Skip to content

Commit

Permalink
clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
khanh1902 committed Jun 8, 2024
1 parent 94011ee commit b5324c1
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 173 deletions.
4 changes: 2 additions & 2 deletions actions/HTTPRequest.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { ComponentDialog, WaterfallDialog } = require('botbuilder-dialogs');
const { REPLACE_ACTION, HTTP_REQUEST } = require('../Constant');
const { HTTP_REQUEST } = require('../Constant');
const { replaceData, replaceObjWithParam, keyValueToObject, arrayKeyValueToObject } = require('../utils/utils');
const { default: axios } = require('axios');

Expand Down Expand Up @@ -43,7 +43,7 @@ class HttpRequest extends ComponentDialog {
);
}
} catch (e) {
console.log(`[HTTP] HTTP request failed`, e.message);
console.log(`HttpRequest run failed - `, e.message);
const nextId = nextActions.find((c) => c.condition == 'failure');
return await step.endDialog({ actionId: nextId && nextId.id });
}
Expand Down
151 changes: 81 additions & 70 deletions actions/Main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,67 +3,66 @@ const {
DialogSet,
DialogTurnStatus,
WaterfallDialog,
} = require("botbuilder-dialogs");
const { CustomActivityTypes } = require("../classes/CustomActivityTypes");
} = require('botbuilder-dialogs');
const { CustomActivityTypes } = require('../classes/CustomActivityTypes');

const {
SEND_TEXT,
PROMPTING,
SET_DATA,
HTTP_REQUEST,
SUB_FLOW,
CHECK_VARIABLE,
SEND_MAIL,
} = require("../Constant");
} = require('../Constant');

const { getFlowByContactId } = require("../services/proxy");
const { SendText } = require("./SendText");
const { Prompting } = require("./Prompting");
const { endConversation, keyValueToObject, replaceSubFlowValueAssigned } = require("../utils/utils");
const { SetData } = require("./SetData");
const { HttpRequest } = require("./HTTPRequest");
const { SubFlow } = require("./SubFlow");
const { CheckVariable } = require("./CheckVariable");
const { SendMail } = require("./SendMail");
const { getFlowByContactId } = require('../services/proxy');
const { SendText } = require('./SendText');
const { Prompting } = require('./Prompting');
const {
endConversation,
keyValueToObject,
replaceSubFlowValueAssigned,
} = require('../utils/utils');
const { HttpRequest } = require('./HTTPRequest');
const { SubFlow } = require('./SubFlow');
const { CheckVariable } = require('./CheckVariable');
const { SendMail } = require('./SendMail');

const CHAT = "CHAT";
const CHAT = 'CHAT';

class MainDialog extends ComponentDialog {
constructor(conversationState, adapter) {
super(CHAT);

this.adapter = adapter;
this.conversationState = conversationState;
this.conversationDataAccessor =
this.conversationState.createProperty("conversationData");
this.dialogState = conversationState.createProperty("DialogState");
this.conversationDataAccessor = this.conversationState.createProperty('conversationData');
this.dialogState = conversationState.createProperty('DialogState');
this.dialogSet = new DialogSet(this.dialogState);
// this.dialogSet = new DialogSet(this.conversationDataAccessor);
this.dialogSet.add(this);

this.addDialog(new SendText(this));
this.addDialog(new Prompting(this));
this.addDialog(new SetData(this));
this.addDialog(new HttpRequest(this));
this.addDialog(new SubFlow(this));
this.addDialog(new CheckVariable(this));
this.addDialog(new SendMail(this));

this.addDialog(
new WaterfallDialog("Main_Water_Fall", [this.ReadFlow.bind(this)])
new WaterfallDialog('Main_Water_Fall', [this.ReadFlow.bind(this)])
);

this.addDialog(
new WaterfallDialog("REDIRECT_FLOW", [
new WaterfallDialog('REDIRECT_FLOW', [
this.RedirectFlow.bind(this),
this.CheckNextFlow.bind(this),
])
);

this.initialDialogId = "Main_Water_Fall";
this.initialDialogId = 'Main_Water_Fall';
}

async run(turnContext, accessor) {
async run(turnContext) {
const dialogContext = await this.dialogSet.createContext(turnContext);

await this.sendTypingIndicator(turnContext, true);
Expand All @@ -82,7 +81,7 @@ class MainDialog extends ComponentDialog {

conversationData.variables = {
...conversationData.variables,
...((typeof context.activity.data == "object" && context.activity.data) ||
...((typeof context.activity.data == 'object' && context.activity.data) ||
{}),
};

Expand All @@ -93,7 +92,7 @@ class MainDialog extends ComponentDialog {
const { activity } = context;
try {
if (!activity) {
throw new Error('Can not find activity');
throw new Error('[Main] handleEvent - Can not find activity');
}

switch (activity.typeName) {
Expand All @@ -104,7 +103,9 @@ class MainDialog extends ComponentDialog {
break;
}
} catch (e) {
console.error(`Handle event ${context.activity.name} error : ${e.message}`);
console.error(
`Handle event ${context.activity.name} error : ${e.message}`
);
console.error(e.stack);
}
}
Expand All @@ -113,7 +114,9 @@ class MainDialog extends ComponentDialog {
const dialogContext = await this.dialogSet.createContext(turnContext);

if (turnContext.activity.typeName == 'endConversation') {
console.log(`[Main] - Run function - handel ${turnContext.activity.typeName} event => end conv`);
console.log(
`[Main] - Run function - handleEventEndConversation event => end conv`
);
return await endConversation(dialogContext);
}
}
Expand Down Expand Up @@ -145,18 +148,18 @@ class MainDialog extends ComponentDialog {
if (!flows) return await endConversation(step, ERROR_MESSAGE);

try {
if (typeof flows == "string") flows = JSON.parse(flows);
if (typeof settings == "string") settings = JSON.parse(settings);
if (typeof attributes == "string")
if (typeof flows == 'string') flows = JSON.parse(flows);
if (typeof settings == 'string') settings = JSON.parse(settings);
if (typeof attributes == 'string')
attributes = keyValueToObject(attributes);
} catch (e) {
// console.log(e)
console.log('[Main] ReadFlow - Parse flow information failed - ' + e.message || e)
}

const language =
settings && settings.find((e) => e.default && e.type === "language");
settings && settings.find((e) => e.default && e.type === 'language');

conversationData.language = (language && language.value) || "en";
conversationData.language = (language && language.value) || 'en';
conversationData.flow = [flows];
conversationData.currentFlow = flows;
conversationData.variables = variables;
Expand All @@ -165,33 +168,33 @@ class MainDialog extends ComponentDialog {
conversationData.botId = recipient.id;
conversationData.testBot = testBot || false;

const firstAction = flows.find((a) => a && a.action == "start");
const firstAction = flows.find((a) => a && a.action == 'start');

if (!firstAction) return await step.context.sendActivity(ERROR_MESSAGE);

const nextAction = flows.find((a) => a.id == firstAction.nextAction);

return await step.replaceDialog("REDIRECT_FLOW", { ...nextAction });
return await step.replaceDialog('REDIRECT_FLOW', { ...nextAction });
}

async RedirectFlow(step) {
console.log(
"--------------------------------------------------------------------"
'--------------------------------------------------------------------'
);

const { action } = step._info.options;

const actions = {
"message": SEND_TEXT,
"prompt-and-collect": PROMPTING,
"http-request": HTTP_REQUEST,
"sub-flow": SUB_FLOW,
"check-variables": CHECK_VARIABLE,
"send-mail": SEND_MAIL,
message: SEND_TEXT,
'prompt-and-collect': PROMPTING,
'http-request': HTTP_REQUEST,
'sub-flow': SUB_FLOW,
'check-variables': CHECK_VARIABLE,
'send-mail': SEND_MAIL,
};

if (!actions[action]) {
console.log("Can can not find next action type => end dialog");
console.log('[Main] RedirectFlow - Can can not find next action type => end dialog');
return await endConversation(step);
}
return await step.beginDialog(actions[action], step._info.options);
Expand All @@ -214,29 +217,33 @@ class MainDialog extends ComponentDialog {
let findVar = conversationData.variables.find(
(x) => x.name === assignUserResponse
);
const value = conversationData.variables.find(x => x.name === 'answer')?.value;
const value = conversationData.variables.find(
(x) => x.name === 'answer'
)?.value;
if (findVar && !findVar.filled && value) {
findVar.value = value;
}
if (assignUserResponse === 'language' && ['en', 'vi'].includes(value)) conversationData[assignUserResponse] = value;
if (assignUserResponse === 'language' && ['en', 'vi'].includes(value))
conversationData[assignUserResponse] = value;
}

let nextAction;

if (checkAction) {
const Case = this.GetNextAction({
attribute: assignUserResponse || "answer",
attribute: assignUserResponse || 'answer',
actions: nextActions || [],
data: conversationData.variables,
});
nextAction = currentFlow.find((a) => a.id == (Case && Case.id));

if (nextAction && Case) {
console.log(`Pass case option : ${Case.condition}`);
console.log(`[Main] CheckNextFlow - Pass case option : ${Case.condition}`);
}

if (!nextAction) {
const OtherCase = nextActions && nextActions.find((c) => c.condition == "otherwise");
const OtherCase =
nextActions && nextActions.find((c) => c.condition == 'otherwise');

nextAction = currentFlow.find(
(a) => a.id == (OtherCase && OtherCase.id)
Expand All @@ -251,7 +258,10 @@ class MainDialog extends ComponentDialog {

if (conversationData.flow.length) {
conversationData.currentFlow = conversationData.flow[0];
conversationData.variables = replaceSubFlowValueAssigned(conversationData.variables, conversationData.subFlowOutput);
conversationData.variables = replaceSubFlowValueAssigned(
conversationData.variables,
conversationData.subFlowOutput
);
conversationData.subFlowOutput = [];
} else {
conversationData.currentFlow = [];
Expand All @@ -262,7 +272,7 @@ class MainDialog extends ComponentDialog {
);
}

return await step.replaceDialog("REDIRECT_FLOW", nextAction);
return await step.replaceDialog('REDIRECT_FLOW', nextAction);
}

GetNextAction({ attribute, actions, data }) {
Expand All @@ -276,54 +286,55 @@ class MainDialog extends ComponentDialog {
const { condition, value, id } = Case;

switch (condition) {
case "empty":
if (typeof checkData == "object") {
if (value == "true" && !Object.keys(checkData).length) return Case;
if (value == "false" && Object.keys(checkData).length) return Case;
case 'empty':
if (typeof checkData == 'object') {
if (value == 'true' && !Object.keys(checkData).length) return Case;
if (value == 'false' && Object.keys(checkData).length) return Case;
}
if (
(typeof checkData == "string" || typeof checkData == "array") &&
(typeof checkData == 'string' || typeof checkData == 'array') &&
checkData.length
) {
return Case;
}
continue;
case "equal":
case 'equal':
if (checkData == value) return Case;
if (
typeof checkData == "string" &&
typeof checkData == 'string' &&
checkData.toLocaleLowerCase() == value.toLocaleLowerCase()
)
return Case;
continue;
case "not_equal":
if (checkData.toLocaleLowerCase() != value.toLocaleLowerCase()) return Case;
case 'not_equal':
if (checkData.toLocaleLowerCase() != value.toLocaleLowerCase())
return Case;
continue;
case "less_than":
case 'less_than':
if (parseInt(checkData) < parseInt(value)) return Case;
continue;
case "less_than_or_equal":
case 'less_than_or_equal':
if (parseInt(checkData) <= parseInt(value)) return Case;
continue;
case "greater_than":
case 'greater_than':
if (parseInt(checkData) > parseInt(value)) return Case;
continue;
case "greater_than_or_equal":
case 'greater_than_or_equal':
if (parseInt(checkData) >= parseInt(value)) return Case;
continue;
case "Starts with":
if (typeof checkData === "string" && checkData.startsWith(value))
case 'Starts with':
if (typeof checkData === 'string' && checkData.startsWith(value))
return Case;
continue;
case "Ends with":
if (typeof checkData === "string" && checkData.endsWith(value))
case 'Ends with':
if (typeof checkData === 'string' && checkData.endsWith(value))
return Case;
continue;
case "contains":
if (typeof checkData === "string" && checkData.includes(value))
case 'contains':
if (typeof checkData === 'string' && checkData.includes(value))
return Case;
continue;
case "exist":
case 'exist':
if (value && checkData) return Case;
if (!value && !checkData) return Case;
continue;
Expand Down
Loading

0 comments on commit b5324c1

Please sign in to comment.