asksuite-core
Version:
95 lines (82 loc) • 2.68 kB
JavaScript
const fallbackIntent = require('./fallbackIntent');
const Util = require('../util');
const _ = require('lodash');
class IntentResolver {
constructor(intents, companyId, text) {
this.intents = intents;
this.companyId = companyId;
this.text = text || '';
}
findDialogByIntent(intent) {
let fallbackReason = null;
const intentMapped = this.intents.find(this.isTheSame(intent));
let intentBot = _.cloneDeep(
intentMapped || this.intents.find(this.isIntentForIDidntUnderstand),
);
if (intentBot) {
if (!intentMapped && intent) {
fallbackReason = 'intent_not_mapped';
} else if (this.isIntentForIDidntUnderstand(intentBot)) {
fallbackReason = 'intent_not_found';
} else if (!intentBot.dialog) {
fallbackReason = 'dialog_empty';
}
}
if (!intentBot || this.isIntentForIDidntUnderstand(intentBot)) {
let msg = Util.replaceIfIsPhrase(this.text);
msg = !msg ? this.text.toLowerCase() : msg;
const notUnderstandable =
(msg.length <= 2 && !Util.isNumeric(msg)) || Util.existsletterCount(msg, 3);
if (notUnderstandable) {
intentBot = this.intents.find(IntentResolver.isIntentForNotUnderstandable) || {};
fallbackReason = 'text_not_understandable';
} else if (!intentBot || !intentBot.dialog) {
// Fallback
intentBot = {
intent: fallbackIntent.normal.intent,
dialog: this.companyId + fallbackIntent.normal.dialogSuffix,
};
}
}
intentBot.processingStep = {
fallbackReason,
intentFound: !intent ? null : intent,
};
return intentBot;
}
isTheSame(intent) {
return (item) => {
return item && intent && item.intent === intent;
};
}
isIntentForIDidntUnderstand(item) {
return (
item && [fallbackIntent.normal.intent, fallbackIntent.grande.intent].includes(item.intent)
);
}
static isIntentForNotUnderstandable(item) {
return item && item.intent === fallbackIntent.naoentendivel.intent;
}
static queryTextMaxLengthExceededDialog(companyId) {
return {
intent: fallbackIntent.grande.intent,
dialog: companyId + fallbackIntent.grande.dialogSuffix,
processingStep: {
fallbackReason: 'max_length_exceeded',
intentFound: null,
},
};
}
static textNotDefinedDialog(companyId) {
return {
intent: fallbackIntent.normal.intent,
dialog: companyId + fallbackIntent.normal.dialogSuffix,
processingStep: {
fallbackReason: 'intent_not_found',
text: '',
intentFound: null,
},
};
}
}
module.exports = IntentResolver;