From 3640b9ed2214cbd15e19a6e7ccf8b46194afc238 Mon Sep 17 00:00:00 2001 From: Yash Mittal Date: Thu, 13 Jun 2024 11:58:18 +0530 Subject: [PATCH 1/8] fix: scheme --- src/app.controller.ts | 778 ++++--- src/common/utils.ts | 348 +-- src/modules/aiTools/ai-tools.service.ts | 234 ++- src/modules/user/user.service.ts | 203 +- src/xstate/prompt/prompt.gaurds.ts | 34 +- src/xstate/prompt/prompt.machine.ts | 2563 ++++++++++++----------- src/xstate/prompt/prompt.service.ts | 491 +++-- src/xstate/prompt/prompt.utils.ts | 1 + 8 files changed, 2526 insertions(+), 2126 deletions(-) create mode 100644 src/xstate/prompt/prompt.utils.ts diff --git a/src/app.controller.ts b/src/app.controller.ts index dd1b6c0..ff64e1a 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -1,27 +1,40 @@ -import { Controller, Get, Post, Headers, Body, Param, CACHE_MANAGER, Inject } from "@nestjs/common"; +import { + Controller, + Get, + Post, + Headers, + Body, + Param, + CACHE_MANAGER, + Inject, +} from "@nestjs/common"; import { AppService, Prompt } from "./app.service"; -import { IsNotEmpty,IsUUID, IsOptional } from 'class-validator'; +import { IsNotEmpty, IsUUID, IsOptional } from "class-validator"; import { interpret } from "xstate"; import { Language } from "./language"; import { ConfigService } from "@nestjs/config"; import { AiToolsService } from "./modules/aiTools/ai-tools.service"; -import { formatStringsToTable, removeLinks, wordToNumber } from "./common/utils"; +import { + formatStringsToTable, + removeLinks, + wordToNumber, +} from "./common/utils"; import { ConversationService } from "./modules/conversation/conversation.service"; import { PrismaService } from "./global-services/prisma.service"; import { CustomLogger } from "./common/logger"; import { MonitoringService } from "./modules/monitoring/monitoring.service"; import { PromptServices } from "./xstate/prompt/prompt.service"; import { TelemetryService } from "./modules/telemetry/telemetry.service"; -import { Cache } from 'cache-manager' -const uuid = require('uuid'); -const path = require('path'); -const filePath = path.resolve(__dirname, './common/en.json'); +import { Cache } from "cache-manager"; +const uuid = require("uuid"); +const path = require("path"); +const filePath = path.resolve(__dirname, "./common/en.json"); const engMessage = require(filePath); -const argon2 = require('argon2'); +const argon2 = require("argon2"); export class PromptDto { @IsNotEmpty() - type: "Text"|"Audio" ; + type: "Text" | "Audio"; @IsNotEmpty() text: string; @IsNotEmpty() @@ -54,24 +67,36 @@ export class PromptDto { @Controller() export class AppController { - private configService : ConfigService - private aiToolsService: AiToolsService - private conversationService: ConversationService - private prismaService: PrismaService - private promptService: PromptServices - private logger: CustomLogger - + private configService: ConfigService; + private aiToolsService: AiToolsService; + private conversationService: ConversationService; + private prismaService: PrismaService; + private promptService: PromptServices; + private logger: CustomLogger; + constructor( private readonly appService: AppService, private readonly monitoringService: MonitoringService, private readonly telemetryService: TelemetryService, @Inject(CACHE_MANAGER) private readonly cacheManager: Cache ) { - this.prismaService = new PrismaService() - this.configService = new ConfigService() - this.aiToolsService = new AiToolsService(this.configService,this.monitoringService, this.cacheManager) - this.conversationService = new ConversationService(this.prismaService,this.configService) - this.promptService = new PromptServices(this.prismaService,this.configService,this.aiToolsService, this.monitoringService) + this.prismaService = new PrismaService(); + this.configService = new ConfigService(); + this.aiToolsService = new AiToolsService( + this.configService, + this.monitoringService, + this.cacheManager + ); + this.conversationService = new ConversationService( + this.prismaService, + this.configService + ); + this.promptService = new PromptServices( + this.prismaService, + this.configService, + this.aiToolsService, + this.monitoringService + ); this.logger = new CustomLogger("AppController"); } @@ -81,51 +106,61 @@ export class AppController { } @Post("/prompt/:configid") - async prompt(@Body() promptDto: any, @Headers() headers, @Param("configid") configid: string): Promise { - let startTime = Date.now() + async prompt( + @Body() promptDto: any, + @Headers() headers, + @Param("configid") configid: string + ): Promise { + let startTime = Date.now(); //get userId from headers - const userId = headers["user-id"] - const sessionId = headers["session-id"] - console.log("userId =",userId) - console.log("sessionId =", sessionId) - if(!userId){ + const userId = headers["user-id"]; + const sessionId = headers["session-id"]; + console.log("userId =", userId); + console.log("sessionId =", sessionId); + if (!userId) { return { - "text":"", - "error": "'user-id' should not be empty" - } + text: "", + error: "'user-id' should not be empty", + }; } - if(!sessionId) { + if (!sessionId) { return { - "text": "", - "error": "'session-id' should not be empty" - } + text: "", + error: "'session-id' should not be empty", + }; } - let messageType = 'intermediate_response' + let messageType = "intermediate_response"; //setup loggers - let verboseLogger = this.logger.logWithCustomFields({ - userId: userId, - flowId: configid - },"verbose") - let errorLogger = this.logger.logWithCustomFields({ - userId: userId, - flowId: configid - },"error") + let verboseLogger = this.logger.logWithCustomFields( + { + userId: userId, + flowId: configid, + }, + "verbose" + ); + let errorLogger = this.logger.logWithCustomFields( + { + userId: userId, + flowId: configid, + }, + "error" + ); // verboseLogger("User input", promptDto) //create or get user and conversation let user; - try{ + try { user = await this.prismaService.user.findUnique({ - where:{ - id: userId - } - }) - }catch{ - this.monitoringService.incrementTotalSessionsCount() + where: { + id: userId, + }, + }); + } catch { + this.monitoringService.incrementTotalSessionsCount(); // verboseLogger("creating new user with id =",userId) await this.telemetryService.capture({ eventName: "Conversation start", eventType: "START_CONVERSATION", - producer:{ + producer: { channel: "Bot", deviceID: null, producerID: userId, @@ -139,7 +174,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - startTime}`, audioURL: null, questionGenerated: null, @@ -150,42 +185,44 @@ export class AppController { errorData: undefined, }, errorType: null, - tags: ['bot','conversation_start'] - }) + tags: ["bot", "conversation_start"], + }); } - if(!user) { + if (!user) { user = await this.prismaService.user.create({ - data:{ - id: userId - } - }) + data: { + id: userId, + }, + }); } //input setup let prompt: Prompt = { - input: promptDto - } + input: promptDto, + }; let userInput = promptDto.text; - let type = "text" + let type = "text"; let defaultContext = { sessionId, userId, - userQuestion:'', - query: '', - queryType: '', - response: '', - userAadhaarNumber: user.identifier && configid=='3' ? user.identifier : '', - otp: '', - error: '', + userQuestion: "", + query: "", + queryType: "", + response: "", + userAadhaarNumber: + user.identifier && configid == "3" ? user.identifier : "", + otp: "", + error: "", currentState: "getUserQuestion", - type: '', + type: "", inputType: type, inputLanguage: prompt.inputLanguage, - lastAadhaarDigits:'', - state:'onGoing', - isOTPVerified: false - } + lastAadhaarDigits: "", + state: "onGoing", + isOTPVerified: false, + schemeName: promptDto.schemeName, + }; let conversation = await this.conversationService.getConversationState( sessionId, @@ -196,11 +233,11 @@ export class AppController { // console.log("fetched conversation: ", conversation) //handle text and audio - if(promptDto.text){ - type = "Text" + if (promptDto.text) { + type = "Text"; let detectLanguageStartTime = Date.now(); - if(/^\d+$/.test(userInput)){ - prompt.inputLanguage = Language.en + if (/^\d+$/.test(userInput)) { + prompt.inputLanguage = Language.en; } else { // console.log("IN ELSE....") try { @@ -210,7 +247,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Detect language error", eventType: "DETECT_LANGUAGE", - producer:{ + producer: { channel: "Bot", deviceID: null, producerID: userId, @@ -224,7 +261,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - detectLanguageStartTime}`, audioURL: null, questionGenerated: null, @@ -234,17 +271,17 @@ export class AppController { logData: undefined, errorData: { input: userInput, - error: error + error: error, }, }, errorType: "DETECT_LANGUAGE", - tags: ['bot','detect_language','error'] - }) + tags: ["bot", "detect_language", "error"], + }); } // console.log("LANGUAGE DETECTED...") //@ts-ignore - if(prompt.inputLanguage == 'unk'){ - prompt.inputLanguage = prompt.input.inputLanguage as Language + if (prompt.inputLanguage == "unk") { + prompt.inputLanguage = prompt.input.inputLanguage as Language; } // verboseLogger("Detected Language =", prompt.inputLanguage) } @@ -252,7 +289,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Detect language", eventType: "DETECT_LANGUAGE", - producer:{ + producer: { channel: "Bot", deviceID: null, producerID: userId, @@ -266,7 +303,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - detectLanguageStartTime}`, audioURL: null, questionGenerated: null, @@ -274,27 +311,27 @@ export class AppController { comparisonScore: 0, answer: prompt.inputLanguage, logData: undefined, - errorData: undefined + errorData: undefined, }, errorType: null, - tags: ['bot','detect_language'] - }) - } else if (promptDto.media){ + tags: ["bot", "detect_language"], + }); + } else if (promptDto.media) { let audioStartTime = Date.now(); - if(promptDto.media.category=="base64audio" && promptDto.media.text){ - type = "Audio" - prompt.inputLanguage = promptDto.inputLanguage as Language + if (promptDto.media.category == "base64audio" && promptDto.media.text) { + type = "Audio"; + prompt.inputLanguage = promptDto.inputLanguage as Language; let response; if(['askingAadhaarNumber','askingOTP','askLastAaadhaarDigits','confirmInput2','confirmInput3','confirmInput4'].indexOf(conversation?.currentState) != -1) response = await this.aiToolsService.speechToText(promptDto.media.text,Language.en,userId,sessionId) else response = await this.aiToolsService.speechToText(promptDto.media.text,prompt.inputLanguage,userId,sessionId) - if(response.error) { + if (response.error) { await this.telemetryService.capture({ eventName: "Speech to text error", eventType: "SPEECH_TO_TEXT_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -308,7 +345,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: null, @@ -318,27 +355,27 @@ export class AppController { logData: undefined, errorData: { language: prompt.inputLanguage, - error: response.error + error: response.error, }, }, errorType: "SPEECH_TO_TEXT", - tags: ['bot','speech_to_text','error'] - }) - errorLogger(response.error) - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementSomethingWentWrongTryAgainCount() - return{ - text:"", + tags: ["bot", "speech_to_text", "error"], + }); + errorLogger(response.error); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementSomethingWentWrongTryAgainCount(); + return { + text: "", error: "Something went wrong, please try again.", - conversationId: conversation?.id - } + conversationId: conversation?.id, + }; } - userInput = response["text"] + userInput = response["text"]; // verboseLogger("speech to text =",userInput) await this.telemetryService.capture({ eventName: "Speech to text", eventType: "SPEECH_TO_TEXT", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -352,7 +389,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: userInput, @@ -360,21 +397,21 @@ export class AppController { comparisonScore: 0, answer: null, logData: undefined, - errorData: null + errorData: null, }, errorType: "SPEECH_TO_TEXT", - tags: ['bot','speech_to_text'] - }) + tags: ["bot", "speech_to_text"], + }); } else { - this.monitoringService.incrementUnsupportedMediaCount() - errorLogger("Unsupported media") + this.monitoringService.incrementUnsupportedMediaCount(); + errorLogger("Unsupported media"); return { text: "", media: promptDto.media, mediaCaption: "", error: "Unsupported media", - conversationId: conversation?.id - } + conversationId: conversation?.id, + }; } } @@ -382,29 +419,33 @@ export class AppController { // console.log("CP 1...") //get flow let botFlowMachine; - switch(configid){ - case '1': - botFlowMachine = this.promptService.getXstateMachine("botFlowMachine1") - break - case '2': - botFlowMachine = this.promptService.getXstateMachine("botFlowMachine2") - break - case '3': - botFlowMachine = this.promptService.getXstateMachine("botFlowMachine3") - break + switch (configid) { + case "1": + botFlowMachine = this.promptService.getXstateMachine("botFlowMachine1"); + break; + case "2": + botFlowMachine = this.promptService.getXstateMachine("botFlowMachine2"); + break; + case "3": + botFlowMachine = this.promptService.getXstateMachine("botFlowMachine3"); + break; default: - botFlowMachine = this.promptService.getXstateMachine("botFlowMachine3") + botFlowMachine = this.promptService.getXstateMachine("botFlowMachine3"); } - - - let botFlowService = interpret(botFlowMachine.withContext(conversation || defaultContext)).start(); + let botFlowService = interpret( + botFlowMachine.withContext(conversation || defaultContext) + ).start(); // verboseLogger("current state when API hit =", botFlowService.state.context.currentState) - if((botFlowService.state.context.currentState == "askingAadhaarNumber" || botFlowService.state.context.currentState == "confirmInput2") && type=="Text" ){ + if ( + (botFlowService.state.context.currentState == "askingAadhaarNumber" || + botFlowService.state.context.currentState == "confirmInput2") && + type == "Text" + ) { let hashedAadhaar = await argon2.hash(promptDto.text); - console.log("you have entered aadhaar", hashedAadhaar) + console.log("you have entered aadhaar", hashedAadhaar); await this.prismaService.message.create({ - data:{ + data: { text: hashedAadhaar, // audio: type=="Audio"?promptDto.media.text:null, audio: null, @@ -417,22 +458,26 @@ export class AppController { }else { // console.log("creating a new message in Message table...") await this.prismaService.message.create({ - data:{ - text: type=="Text"?promptDto.text:null, + data: { + text: type == "Text" ? promptDto.text : null, // audio: type=="Audio"?promptDto.media.text:null, audio: null, type: "User", userId, - flowId: configid || '3', - messageType - } - }) + flowId: configid || "3", + messageType, + }, + }); } let isNumber = false; - if(type == 'Audio' && (botFlowService.state.context.currentState == 'confirmInput1' || botFlowService.state.context.currentState == 'getUserQuestion')) { + if ( + type == "Audio" && + (botFlowService.state.context.currentState == "confirmInput1" || + botFlowService.state.context.currentState == "getUserQuestion") + ) { let audioStartTime = Date.now(); - let res = { + let res = { text: userInput, textInEnglish: "", error: null @@ -442,7 +487,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Text to speech error", eventType: "TEXT_TO_SPEECH_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -456,7 +501,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: null, @@ -465,19 +510,19 @@ export class AppController { answer: prompt.inputLanguage, logData: undefined, errorData: { - input:res.text, + input: res.text, language: prompt.inputLanguage, - error: res['audio']['error'] + error: res["audio"]["error"], }, }, errorType: "TEXT_TO_SPEECH", - tags: ['bot','text_to_speech','error'] - }) + tags: ["bot", "text_to_speech", "error"], + }); } else { await this.telemetryService.capture({ eventName: "Text to speech", eventType: "TEXT_TO_SPEECH", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -491,7 +536,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: null, @@ -502,20 +547,20 @@ export class AppController { errorData: undefined, }, errorType: "TEXT_TO_SPEECH", - tags: ['bot','text_to_speech'] - }) + tags: ["bot", "text_to_speech"], + }); } - res['messageId'] = uuid.v4() - res['conversationId'] = conversation?.id - return res + res["messageId"] = uuid.v4(); + res["conversationId"] = conversation?.id; + return res; } else { //translate to english // console.log("Translating to English...") let translateStartTime = Date.now(); - if(userInput == 'resend OTP'){ - this.monitoringService.incrementResentOTPCount() + if (userInput == "resend OTP") { + this.monitoringService.incrementResentOTPCount(); } - if(prompt.inputLanguage != Language.en && userInput != 'resend OTP') { + if (prompt.inputLanguage != Language.en && userInput != "resend OTP") { try { let response = await this.aiToolsService.translate( prompt.inputLanguage as Language, @@ -528,7 +573,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -542,7 +587,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -551,28 +596,31 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: response['error'] + error: response["error"], }, }, errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger("Sorry, We are unable to translate given input, please try again") - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - return { - error: "Sorry, We are unable to translate given input, please try again", - conversationId: conversation?.id - } + tags: ["bot", "translate", "error"], + }); + errorLogger( + "Sorry, We are unable to translate given input, please try again" + ); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + return { + error: + "Sorry, We are unable to translate given input, please try again", + conversationId: conversation?.id, + }; } - prompt.inputTextInEnglish = response["text"] + prompt.inputTextInEnglish = response["text"]; // verboseLogger("translated english text =", prompt.inputTextInEnglish) await this.telemetryService.capture({ eventName: "Translate", eventType: "TRANSLATE", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -586,7 +634,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -594,16 +642,16 @@ export class AppController { comparisonScore: 0, answer: prompt.inputTextInEnglish, logData: undefined, - errorData: undefined + errorData: undefined, }, errorType: null, - tags: ['bot','translate'] - }) - } catch(error){ + tags: ["bot", "translate"], + }); + } catch (error) { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -617,7 +665,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -626,33 +674,56 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: error + error: error, }, }, - errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger("Sorry, We are unable to translate given input, please try again") - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - return { - error: "Sorry, We are unable to translate given input, please try again", - conversationId: conversation?.id - } + errorType: "TRANSLATE", + tags: ["bot", "translate", "error"], + }); + errorLogger( + "Sorry, We are unable to translate given input, please try again" + ); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + return { + error: + "Sorry, We are unable to translate given input, please try again", + conversationId: conversation?.id, + }; } } else { - prompt.inputTextInEnglish = userInput + prompt.inputTextInEnglish = userInput; } - if(type == 'Audio' && ['askingAadhaarNumber','askingOTP','askLastAaadhaarDigits','confirmInput2','confirmInput3','confirmInput4'].indexOf(botFlowService.state.context.currentState) != -1) { - let isOTP = ['askingOTP','askLastAaadhaarDigits','confirmInput3','confirmInput4'].indexOf(botFlowService.state.context.currentState) != -1 - let number = wordToNumber(prompt.inputTextInEnglish, isOTP ? 'otp':'benId') + if ( + type == "Audio" && + [ + "askingAadhaarNumber", + "askingOTP", + "askLastAaadhaarDigits", + "confirmInput2", + "confirmInput3", + "confirmInput4", + ].indexOf(botFlowService.state.context.currentState) != -1 + ) { + let isOTP = + [ + "askingOTP", + "askLastAaadhaarDigits", + "confirmInput3", + "confirmInput4", + ].indexOf(botFlowService.state.context.currentState) != -1; + let number = wordToNumber( + prompt.inputTextInEnglish, + isOTP ? "otp" : "benId" + ); // let number = prompt.inputTextInEnglish.replace(/\s/g, '') - prompt.inputTextInEnglish = number.toUpperCase() - if(prompt.inputTextInEnglish == "") prompt.inputTextInEnglish = isOTP ? '1111' : 'AB123123123' - isNumber = true + prompt.inputTextInEnglish = number.toUpperCase(); + if (prompt.inputTextInEnglish == "") + prompt.inputTextInEnglish = isOTP ? "1111" : "AB123123123"; + isNumber = true; // if(/\d/.test(number)){ // isNumber = true // prompt.inputTextInEnglish = number.toUpperCase() @@ -661,16 +732,15 @@ export class AppController { } } - const currentContext = botFlowService.state.context; let updatedContext = { ...currentContext, inputType: type, - type:"" + type: "", }; botFlowService.state.context = updatedContext; - botFlowService.send('USER_INPUT', { data: prompt.inputTextInEnglish }); + botFlowService.send("USER_INPUT", { data: prompt.inputTextInEnglish }); await new Promise((resolve) => { botFlowService.subscribe((state) => { @@ -678,25 +748,25 @@ export class AppController { updatedContext = { ...state.context, //@ts-ignore - currentState: state.value + currentState: state.value, }; botFlowService.state.context = updatedContext; // console.log('Current context:', state.context); - if(state.context.type=="pause"){ + if (state.context.type == "pause") { // verboseLogger("paused state", state.value) - resolve(state) + resolve(state); } }); - botFlowService.onDone((state)=>{ + botFlowService.onDone((state) => { const currentContext = botFlowService.state.context; let updatedContext = { ...currentContext, - state:'Done' + state: "Done", }; botFlowService.state.context = updatedContext; // verboseLogger("state done") - resolve(state) - }) + resolve(state); + }); }); // verboseLogger("final response",botFlowService.getSnapshot().context.response) @@ -706,45 +776,39 @@ export class AppController { text: botFlowService.getSnapshot().context.response, error: null, audio: null, - } - if(botFlowService.getSnapshot().context.error){ + }; + if (botFlowService.getSnapshot().context.error) { const currentContext = botFlowService.state.context; let updatedContext = { ...currentContext, - state:'Done' + state: "Done", }; botFlowService.state.context = updatedContext; - result.textInEnglish = null - result.text = null - result.error = botFlowService.getSnapshot().context.error + result.textInEnglish = null; + result.text = null; + result.error = botFlowService.getSnapshot().context.error; } - prompt.inputLanguage = promptDto.inputLanguage + prompt.inputLanguage = promptDto.inputLanguage; - if(result.text){ + if (result.text) { let placeholder; - if( - result.text==engMessage["label.popUpTitle"] || - result.text==engMessage["label.popUpTitleValid"] || - result.text==engMessage["label.noRecordsFound"] - ){ - placeholder = engMessage["label.popUpTitle.short"] - } else if( - result.text==engMessage["label.popUpTitle2"] - ){ - placeholder = engMessage["label.popUpTitle2.short"] - }else if( - result.text==engMessage["label.popUpTitle3"] - ){ - placeholder = engMessage["label.popUpTitle3.short"] - }else if( - result.text==engMessage["label.invalid_question"] - ){ - placeholder = engMessage["label.popUpTitle.short"] + if ( + result.text == engMessage["label.popUpTitle"] || + result.text == engMessage["label.popUpTitleValid"] || + result.text == engMessage["label.noRecordsFound"] + ) { + placeholder = engMessage["label.popUpTitle.short"]; + } else if (result.text == engMessage["label.popUpTitle2"]) { + placeholder = engMessage["label.popUpTitle2.short"]; + } else if (result.text == engMessage["label.popUpTitle3"]) { + placeholder = engMessage["label.popUpTitle3.short"]; + } else if (result.text == engMessage["label.invalid_question"]) { + placeholder = engMessage["label.popUpTitle.short"]; } - if(prompt.inputLanguage != Language.en && !isNumber) { + if (prompt.inputLanguage != Language.en && !isNumber) { let translateStartTime = Date.now(); try { - let inp = result.text + let inp = result.text; let response = await this.aiToolsService.translate( Language.en, prompt.inputLanguage as Language, @@ -756,7 +820,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -770,7 +834,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -779,25 +843,28 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: response['error'] + error: response["error"], }, }, - errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger("Sorry, We are unable to translate given input, please try again") - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - result.error = "Sorry, We are unable to translate given input, please try again" + errorType: "TRANSLATE", + tags: ["bot", "translate", "error"], + }); + errorLogger( + "Sorry, We are unable to translate given input, please try again" + ); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + result.error = + "Sorry, We are unable to translate given input, please try again"; } - result.text = response["text"] + result.text = response["text"]; // verboseLogger("input language translated text =",result.text) await this.telemetryService.capture({ eventName: "Translate", eventType: "TRANSLATE", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -811,7 +878,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -819,16 +886,16 @@ export class AppController { comparisonScore: 0, answer: result.text, logData: undefined, - errorData: undefined + errorData: undefined, }, errorType: null, - tags: ['bot','translate'] - }) - } catch(error){ + tags: ["bot", "translate"], + }); + } catch (error) { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -842,7 +909,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -851,24 +918,25 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: error + error: error, }, }, errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger(error) - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - return { - error: "Sorry, We are unable to translate given input, please try again", - conversationId: conversation?.id - } + tags: ["bot", "translate", "error"], + }); + errorLogger(error); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + return { + error: + "Sorry, We are unable to translate given input, please try again", + conversationId: conversation?.id, + }; } } - if(prompt.inputLanguage != Language.en && placeholder){ + if (prompt.inputLanguage != Language.en && placeholder) { let translateStartTime = Date.now(); try { let response = await this.aiToolsService.translate( @@ -882,7 +950,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -896,7 +964,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -905,24 +973,27 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: response['error'] + error: response["error"], }, }, errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger("Sorry, We are unable to translate given input, please try again") - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - result.error = "Sorry, We are unable to translate given input, please try again" + tags: ["bot", "translate", "error"], + }); + errorLogger( + "Sorry, We are unable to translate given input, please try again" + ); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + result.error = + "Sorry, We are unable to translate given input, please try again"; } - result['placeholder'] = response["text"] + result["placeholder"] = response["text"]; await this.telemetryService.capture({ eventName: "Translate", eventType: "TRANSLATE", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -936,24 +1007,24 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, questionSubmitted: placeholder, comparisonScore: 0, - answer: result['placeholder'], + answer: result["placeholder"], logData: undefined, - errorData: undefined + errorData: undefined, }, errorType: null, - tags: ['bot','translate'] - }) - } catch(error){ + tags: ["bot", "translate"], + }); + } catch (error) { await this.telemetryService.capture({ eventName: "Translate error", eventType: "TRANSLATE_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -967,7 +1038,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - translateStartTime}`, audioURL: null, questionGenerated: null, @@ -976,30 +1047,31 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:userInput, + input: userInput, language: prompt.inputLanguage, - error: error + error: error, }, }, errorType: "TRANSLATE", - tags: ['bot','translate','error'] - }) - errorLogger(error) - this.monitoringService.incrementTotalFailureSessionsCount() - this.monitoringService.incrementUnableToTranslateCount() - return { - error: "Sorry, We are unable to translate given input, please try again", - conversationId: conversation?.id - } + tags: ["bot", "translate", "error"], + }); + errorLogger(error); + this.monitoringService.incrementTotalFailureSessionsCount(); + this.monitoringService.incrementUnableToTranslateCount(); + return { + error: + "Sorry, We are unable to translate given input, please try again", + conversationId: conversation?.id, + }; } - } else if(placeholder) { - result['placeholder'] = placeholder + } else if (placeholder) { + result["placeholder"] = placeholder; } - try{ - let textToaudio = result.text - if(botFlowService.state.context.currentState == 'endFlow'){ + try { + let textToaudio = result.text; + if (botFlowService.state.context.currentState == "endFlow") { this.monitoringService.incrementTotalSuccessfullSessionsCount(); - switch(prompt.inputLanguage){ + switch (prompt.inputLanguage) { case Language.hi: this.monitoringService.incrementTotalSessionsInHindiCount(); break; @@ -1008,7 +1080,7 @@ export class AppController { break; case Language.or: this.monitoringService.incrementTotalSessionsInOdiaCount(); - break; + break; case Language.te: this.monitoringService.incrementTotalSessionsInTeluguCount(); break; @@ -1025,17 +1097,22 @@ export class AppController { this.monitoringService.incrementTotalSessionsInEnglishCount(); break; } - messageType = botFlowService.state.context.queryType == "convo" ? "convo_response" : "final_response" - if(botFlowService.state.context.isWadhwaniResponse == 'false'){ - let resArray = result.text.split("\n") - let compareText = result.textInEnglish.split('\n') - if(compareText[compareText.length-1].slice(0,12)=="Registration"){ - textToaudio = "" + messageType = + botFlowService.state.context.queryType == "convo" + ? "convo_response" + : "final_response"; + if (botFlowService.state.context.isWadhwaniResponse == "false") { + let resArray = result.text.split("\n"); + let compareText = result.textInEnglish.split("\n"); + if ( + compareText[compareText.length - 1].slice(0, 12) == "Registration" + ) { + textToaudio = ""; } else { - textToaudio = resArray.pop() + textToaudio = resArray.pop(); } // verboseLogger("Array to convert",resArray) - result.text = `${formatStringsToTable(resArray)}\n${textToaudio}` + result.text = `${formatStringsToTable(resArray)}\n${textToaudio}`; } } // verboseLogger("textToaudio =",textToaudio) @@ -1046,7 +1123,7 @@ export class AppController { await this.telemetryService.capture({ eventName: "Text to speech error", eventType: "TEXT_TO_SPEECH_ERROR", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -1060,7 +1137,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: null, @@ -1069,19 +1146,19 @@ export class AppController { answer: null, logData: undefined, errorData: { - input:textToaudio, + input: textToaudio, language: prompt.inputLanguage, - error: result['audio']['error'] + error: result["audio"]["error"], }, }, errorType: "TEXT_TO_SPEECH", - tags: ['bot','text_to_speech','error'] - }) + tags: ["bot", "text_to_speech", "error"], + }); } else { await this.telemetryService.capture({ eventName: "Text to speech", eventType: "TEXT_TO_SPEECH", - producer:{ + producer: { channel: "Bhashini", deviceID: null, producerID: userId, @@ -1095,7 +1172,7 @@ export class AppController { pageID: null, rollup: undefined, }, - eventData:{ + eventData: { duration: `${Date.now() - audioStartTime}`, audioURL: null, questionGenerated: null, @@ -1103,14 +1180,14 @@ export class AppController { comparisonScore: 0, answer: null, logData: undefined, - errorData: undefined + errorData: undefined, }, errorType: null, - tags: ['bot','text_to_speech'] - }) + tags: ["bot", "text_to_speech"], + }); } - } catch(error){ - result['audio'] = {text: "",error: error.message} + } catch (error) { + result["audio"] = { text: "", error: error.message }; } } // console.log("Saving conversation..") @@ -1120,39 +1197,42 @@ export class AppController { botFlowService.getSnapshot().context, botFlowService.state.context.state, configid - ) + ); let msg = await this.prismaService.message.create({ - data:{ - text: result?.text ? result?.text : result.error? result.error : null, + data: { + text: result?.text ? result?.text : result.error ? result.error : null, // audio: result?.audio?.text ? result?.audio?.text : null, audio: null, type: "System", userId, - flowId: configid || '3', - messageType - } - }) - result["messageId"] = msg.id - result["messageType"] = messageType - result["conversationId"] = conversation.id - verboseLogger("current state while returning response =", botFlowService.state.context.currentState) - switch(botFlowService.state.context.currentState){ - case 'askingAadhaarNumber': - this.monitoringService.incrementStage3Count() + flowId: configid || "3", + messageType, + }, + }); + result["messageId"] = msg.id; + result["messageType"] = messageType; + result["conversationId"] = conversation.id; + verboseLogger( + "current state while returning response =", + botFlowService.state.context.currentState + ); + switch (botFlowService.state.context.currentState) { + case "askingAadhaarNumber": + this.monitoringService.incrementStage3Count(); break; - case 'askingOTP': - this.monitoringService.incrementStage4Count() + case "askingOTP": + this.monitoringService.incrementStage4Count(); break; - case 'endFlow': - if(!result.error){ - this.monitoringService.incrementStage5Count() + case "endFlow": + if (!result.error) { + this.monitoringService.incrementStage5Count(); } break; default: break; } - + // verboseLogger("response text", result.text) // verboseLogger("response textInEnglish", result.textInEnglish) // verboseLogger("response error", result.error) diff --git a/src/common/utils.ts b/src/common/utils.ts index 199690a..d09a114 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -1,202 +1,233 @@ -const fetch = require('node-fetch'); +const fetch = require("node-fetch"); const { Headers } = fetch; export function isMostlyEnglish(text: string): boolean { - const englishCharacterCount = (text.match(/[a-zA-Z0-9\s.,!?'"`~@#$%^&*()-_=+[\]{};:\\|<>/?]/g) || []).length; + const englishCharacterCount = ( + text.match(/[a-zA-Z0-9\s.,!?'"`~@#$%^&*()-_=+[\]{};:\\|<>/?]/g) || [] + ).length; const totalCharacters = text.length; - const englishCharacterPercentage = (englishCharacterCount / totalCharacters) * 100; + const englishCharacterPercentage = + (englishCharacterCount / totalCharacters) * 100; return englishCharacterPercentage >= 90; } -export const wordToNumber = (input,type='benId') => { - input = input.toLowerCase() - // Map of words to numbers - const wordToNum = { - 'zero': 0, - 'one': 1, - 'two': 2, - 'three': 3, - 'four': 4, - 'five': 5, - 'six': 6, - 'seven': 7, - 'eight': 8, - 'nine': 9, - 'a': 'A', - 'b': 'B', - 'c': 'C', - 'd': 'D', - 'e': 'E', - 'f': 'F', - 'g': 'G', - 'h': 'H', - 'i': 'I', - 'j': 'J', - 'k': 'K', - 'l': 'L', - 'm': 'M', - 'n': 'N', - 'o': 'O', - 'p': 'P', - 'q': 'Q', - 'r': 'R', - 's': 'S', - 't': 'T', - 'u': 'U', - 'v': 'V', - 'w': 'W', - 'x': 'X', - 'y': 'Y', - 'z': 'Z' +export const wordToNumber = (input, type = "benId") => { + input = input.toLowerCase(); + // Map of words to numbers + const wordToNum = { + zero: 0, + one: 1, + two: 2, + three: 3, + four: 4, + five: 5, + six: 6, + seven: 7, + eight: 8, + nine: 9, + a: "A", + b: "B", + c: "C", + d: "D", + e: "E", + f: "F", + g: "G", + h: "H", + i: "I", + j: "J", + k: "K", + l: "L", + m: "M", + n: "N", + o: "O", + p: "P", + q: "Q", + r: "R", + s: "S", + t: "T", + u: "U", + v: "V", + w: "W", + x: "X", + y: "Y", + z: "Z", }; // Remove punctuation, extra spaces, and common noise words - input = input.replace(/[.,:;?!-]/g, '').replace(/\s+/g, ' ').trim().replace(/(and|is|the|this|with|for|it|its|ok|sure|yes|please|use|enter|login|received|needed|code|verify|access|confirm|your|needed|remember|need|forget)/gi, ''); + input = input + .replace(/[.,:;?!-]/g, "") + .replace(/\s+/g, " ") + .trim() + .replace( + /(and|is|the|this|with|for|it|its|ok|sure|yes|please|use|enter|login|received|needed|code|verify|access|confirm|your|needed|remember|need|forget)/gi, + "" + ); // Convert "double", "triple" (and their misspellings) followed by a word or a number const repetitionReplacement = (match, count, word) => { - let repeatCount = 1; - if (count.toLowerCase().startsWith('dou')) repeatCount = 2; - if (count.toLowerCase().startsWith('tri') || - count.toLowerCase().startsWith('ter') || - count.toLowerCase() === 'thriple') { - repeatCount = 3; - } - - if (wordToNum[word.toLowerCase()] !== undefined) { - return wordToNum[word.toLowerCase()].toString().repeat(repeatCount); - } - if (!isNaN(parseInt(word))) { - return word.repeat(repeatCount); - } - return match; // if it's neither a word nor a number, return the match as is + let repeatCount = 1; + if (count.toLowerCase().startsWith("dou")) repeatCount = 2; + if ( + count.toLowerCase().startsWith("tri") || + count.toLowerCase().startsWith("ter") || + count.toLowerCase() === "thriple" + ) { + repeatCount = 3; + } + + if (wordToNum[word.toLowerCase()] !== undefined) { + return wordToNum[word.toLowerCase()].toString().repeat(repeatCount); + } + if (!isNaN(parseInt(word))) { + return word.repeat(repeatCount); + } + return match; // if it's neither a word nor a number, return the match as is }; - input = input.replace(/(double|triple|trible|trouble|terrible|terribel|terribal|thriple|single)\s+(\w+)/gi, repetitionReplacement); + input = input.replace( + /(double|triple|trible|trouble|terrible|terribel|terribal|thriple|single)\s+(\w+)/gi, + repetitionReplacement + ); - // Convert words directly followed by digits (like "One234") + // Convert words directly followed by digits (like "One234") for (let word in wordToNum) { - const regex = new RegExp(word + "(\\d+)", "gi"); - input = input.replace(regex, (_, digits) => wordToNum[word] + digits); - input = input.replace(word,wordToNum[word]) + const regex = new RegExp(word + "(\\d+)", "gi"); + input = input.replace(regex, (_, digits) => wordToNum[word] + digits); + input = input.replace(word, wordToNum[word]); } - if(type=='benId'){ + if (type == "benId") { // Convert standalone words to numbers or alphabets - let sanitizedStr = input.split(' ').map(word => { + let sanitizedStr = input + .split(" ") + .map((word) => { if (wordToNum[word.toLowerCase()] !== undefined) { - return wordToNum[word.toLowerCase()]; + return wordToNum[word.toLowerCase()]; } return word; - }).join(''); + }) + .join(""); // Ensure the format: <2 alphabets><9 digits> const formatRegex = /^([a-zA-Z]{2})(\d{9})$/; if (!formatRegex.test(sanitizedStr)) { - - if(/[a-zA-Z]+/.test(sanitizedStr.slice(0,2))) { - sanitizedStr = sanitizedStr.slice(0,2) + sanitizedStr.slice(2).replace(/[^0-9]/g, '');; - return sanitizedStr + if (/[a-zA-Z]+/.test(sanitizedStr.slice(0, 2))) { + sanitizedStr = + sanitizedStr.slice(0, 2) + + sanitizedStr.slice(2).replace(/[^0-9]/g, ""); + return sanitizedStr; // if(sanitizedStr.slice(2).length == 9) { // return sanitizedStr // } } - return sanitizedStr.replace(/[^\d]/g, '') + return sanitizedStr.replace(/[^\d]/g, ""); } return sanitizedStr; - }else{ - // Convert standalone words to numbers - let numStr = input.split(' ').map(word => { + } else { + // Convert standalone words to numbers + let numStr = input + .split(" ") + .map((word) => { if (wordToNum[word.toLowerCase()] !== undefined) { return wordToNum[word.toLowerCase()]; } return word; - }).join(''); + }) + .join(""); - // Remove any non-numeric characters - numStr = numStr.replace(/[^\d]/g, ''); + // Remove any non-numeric characters + numStr = numStr.replace(/[^\d]/g, ""); - if(type=='otp') - numStr = `${numStr}`.slice(0,4) + if (type == "otp") numStr = `${numStr}`.slice(0, 4); - return numStr; + return numStr; } -} - - export const encryptRequest = async (text:string) => { - try { - var myHeaders = new Headers(); - myHeaders.append("Content-Type", "application/json"); - - var raw = JSON.stringify({ - "EncryptedRequest": text - }); - - var requestOptions: any = { - method: 'POST', - headers: myHeaders, - body: raw, - redirect: 'follow' - }; - - let response:any = await fetch(`${process.env.PM_KISAN_ENC_DEC_API}/EncryptedRequest`, requestOptions) - response = await response.json() - return response - }catch(error){ - return { - error: "Error while encrypting the message." - } - } +}; + +export const encryptRequest = async (text: string) => { + try { + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + console.log("text: ", text); + var raw = JSON.stringify({ + EncryptedRequest: text, + }); + + var requestOptions: any = { + method: "POST", + headers: myHeaders, + body: raw, + redirect: "follow", + }; + + let response: any = await fetch( + `${process.env.PM_KISAN_ENC_DEC_API}/EncryptedRequest`, + requestOptions + ); + response = await response.json(); + return response; + } catch (error) { + return { + error: "Error while encrypting the message.", + }; } - - export const decryptRequest = async (text:string,token:string) => { - try{ - var myHeaders = new Headers(); - myHeaders.append("Content-Type", "application/json"); - - var raw = JSON.stringify({ - "DecryptedRequest": `${text}@${token}` - }); - - var requestOptions: any = { - method: 'POST', - headers: myHeaders, - body: raw, - redirect: 'follow' - }; - - let response = await fetch(`${process.env.PM_KISAN_ENC_DEC_API}/DecryptedRequest`, requestOptions) - response = await response.json() - return response - }catch(error){ - return { - error: "Error while decrypting the message." - } - } +}; + +export const decryptRequest = async (text: string, token: string) => { + try { + var myHeaders = new Headers(); + myHeaders.append("Content-Type", "application/json"); + + var raw = JSON.stringify({ + DecryptedRequest: `${text}@${token}`, + }); + + var requestOptions: any = { + method: "POST", + headers: myHeaders, + body: raw, + redirect: "follow", + }; + + let response = await fetch( + `${process.env.PM_KISAN_ENC_DEC_API}/DecryptedRequest`, + requestOptions + ); + response = await response.json(); + return response; + } catch (error) { + return { + error: "Error while decrypting the message.", + }; } - - export const formatStringsToTable = (tableData: Array) => { - let formattedString = `` - tableData.forEach((text)=>{ - let td = text.split('-') - formattedString+= `` - }) - formattedString+=`
${td[0].trim()} :${td.slice(1).join("-").trim()}
` - return formattedString; +}; + +export const formatStringsToTable = (tableData: Array) => { + let formattedString = ``; + tableData.forEach((text) => { + let td = text.split("-"); + formattedString += ``; + }); + formattedString += `
${td[0].trim()} :${td + .slice(1) + .join("-") + .trim()}
`; + return formattedString; +}; + +export const titleCase = (str) => { + var splitStr = str.toLowerCase().split(" "); + for (var i = 0; i < splitStr.length; i++) { + // You do not need to check if i is larger than splitStr length, as your for does that for you + // Assign it back to the array + splitStr[i] = + splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } + // Directly return the joined string + return splitStr.join(" "); +}; - export const titleCase = (str) => { - var splitStr = str.toLowerCase().split(' '); - for (var i = 0; i < splitStr.length; i++) { - // You do not need to check if i is larger than splitStr length, as your for does that for you - // Assign it back to the array - splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); - } - // Directly return the joined string - return splitStr.join(' '); - } - - export const addOrdinalSuffix = (number) => { +export const addOrdinalSuffix = (number) => { if (number % 100 >= 11 && number % 100 <= 13) { return number + "th"; } else { @@ -211,12 +242,13 @@ export const wordToNumber = (input,type='benId') => { return number + "th"; } } -} +}; export const removeLinks = (inputString) => { // Define a regular expression pattern for identifying links - var linkPattern = /http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/g; + var linkPattern = + /http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+/g; // Use the replace() method to replace all links with an empty string - var resultString = inputString.replace(linkPattern, ''); + var resultString = inputString.replace(linkPattern, ""); return resultString; -} \ No newline at end of file +}; diff --git a/src/modules/aiTools/ai-tools.service.ts b/src/modules/aiTools/ai-tools.service.ts index 07f5878..91efee7 100644 --- a/src/modules/aiTools/ai-tools.service.ts +++ b/src/modules/aiTools/ai-tools.service.ts @@ -1,14 +1,14 @@ -import { Injectable, CACHE_MANAGER, Inject } from '@nestjs/common'; -import { Cache } from 'cache-manager'; -import { ConfigService } from '@nestjs/config'; -import { Language } from '../../language'; -import { isMostlyEnglish } from 'src/common/utils'; -import { MonitoringService } from '../monitoring/monitoring.service'; -const fetch = require('../../common/fetch'); -const nodefetch = require('node-fetch'); -const { Headers } = require('node-fetch'); -const path = require('path'); -const filePath = path.resolve(__dirname, '../../common/en.json'); +import { Injectable, CACHE_MANAGER, Inject } from "@nestjs/common"; +import { Cache } from "cache-manager"; +import { ConfigService } from "@nestjs/config"; +import { Language } from "../../language"; +import { isMostlyEnglish } from "src/common/utils"; +import { MonitoringService } from "../monitoring/monitoring.service"; +const fetch = require("../../common/fetch"); +const nodefetch = require("node-fetch"); +const { Headers } = require("node-fetch"); +const path = require("path"); +const filePath = path.resolve(__dirname, "../../common/en.json"); const engMessage = require(filePath); @Injectable() @@ -16,7 +16,7 @@ export class AiToolsService { constructor( private configService: ConfigService, private readonly monitoringService: MonitoringService, - @Inject(CACHE_MANAGER) private readonly cacheManager: Cache, + @Inject(CACHE_MANAGER) private readonly cacheManager: Cache ) {} async detectLanguage(text: string, userId: string, sessionId: string): Promise { // console.log("DETECTING LANGUAGE....") @@ -59,18 +59,18 @@ export class AiToolsService { } } } catch (error) { - this.monitoringService.incrementBhashiniFailureCount() - if(isMostlyEnglish(text?.replace("?","")?.trim())) { - return { - language: Language.en, - error: error.message - } - } else { - return { - language: 'unk', - error: error.message - } - } + this.monitoringService.incrementBhashiniFailureCount(); + if (isMostlyEnglish(text?.replace("?", "")?.trim())) { + return { + language: Language.en, + error: error.message, + }; + } else { + return { + language: "unk", + error: error.message, + }; + } } } @@ -85,8 +85,8 @@ export class AiToolsService { const urlRegex = /(https?:\/\/[^\s]+)|(www\.[^\s]+)/g; const urls = text.match(urlRegex) || []; - const placeHolder = "9814567092798090023722437987555212294" //placeholder which stays the same across languages after translation - const textWithoutUrls = text.replace(urlRegex, placeHolder) + const placeHolder = "9814567092798090023722437987555212294"; //placeholder which stays the same across languages after translation + const textWithoutUrls = text.replace(urlRegex, placeHolder); let config = { "language": { "sourceLanguage": source, @@ -104,7 +104,7 @@ export class AiToolsService { bhashiniConfig?.pipelineInferenceAPIEndPoint?.callbackUrl, config, { - "input":[ + input: [ { // "source": text?.replace("\n",".") "source": textArray[i] @@ -118,19 +118,21 @@ export class AiToolsService { console.log(response["error"]) throw new Error(response["error"]) } - textArray[i]=response?.pipelineResponse[0]?.output[0]?.target + textArray[i] = response?.pipelineResponse[0]?.output[0]?.target; } - const translatedText = textArray.join('\n').replace(new RegExp(placeHolder, 'g'), () => urls.shift() || ''); + const translatedText = textArray + .join("\n") + .replace(new RegExp(placeHolder, "g"), () => urls.shift() || ""); return { text: translatedText, - error: null - } - } catch(error){ - console.log(error) + error: null, + }; + } catch (error) { + console.log(error); return { - text:"", - error: error - } + text: "", + error: error, + }; } } @@ -147,16 +149,14 @@ export class AiToolsService { } },userId,sessionId) let requestConfig = { - "language": { - "sourceLanguage": language - } - } - if(['kn', 'ur', 'ml', 'gu', 'pa'].indexOf(`${language}`)==-1){ - requestConfig["postProcessors"] = [ - "itn" - ] + language: { + sourceLanguage: language, + }, + }; + if (["kn", "ur", "ml", "gu", "pa"].indexOf(`${language}`) == -1) { + requestConfig["postProcessors"] = ["itn"]; } - + let response: any = await this.computeBhashini( config?.pipelineInferenceAPIEndPoint?.inferenceApiKey?.value, "asr", @@ -164,7 +164,7 @@ export class AiToolsService { config?.pipelineInferenceAPIEndPoint?.callbackUrl, requestConfig, { - "audio":[ + audio: [ { "audioContent": base64audio } @@ -179,14 +179,14 @@ export class AiToolsService { } return { text: response?.pipelineResponse[0]?.output[0]?.source, - error: null - } - } catch(error){ - console.log(error) + error: null, + }; + } catch (error) { + console.log(error); return { - text:"", - error: error - } + text: "", + error: error, + }; } } @@ -209,12 +209,12 @@ export class AiToolsService { config?.pipelineResponseConfig[0].config[0].serviceId, config?.pipelineInferenceAPIEndPoint?.callbackUrl, { - "language": { - "sourceLanguage": language - } + language: { + sourceLanguage: language, + }, }, { - "input":[ + input: [ { "source": text } @@ -229,19 +229,19 @@ export class AiToolsService { } return { text: response?.pipelineResponse[0]?.audio[0]?.audioContent, - error: null - } - } catch(error){ - console.log(error) + error: null, + }; + } catch (error) { + console.log(error); return { - text:"", - error: error - } + text: "", + error: error, + }; } } async textClassification(text: string) { - try{ + try { var myHeaders = new Headers(); myHeaders.append("accept", "application/json"); myHeaders.append("X-API-Key", this.configService.get("WADHWANI_API_KEY")); @@ -255,24 +255,34 @@ export class AiToolsService { // "mode": "cors", // "credentials": "omit" // }); - let response: any = await fetch(`${this.configService.get("WADHWANI_BASE_URL")}/detect_query_intent?query=${text}`, { - headers: myHeaders, - "method": "GET", - "mode": "cors", - "credentials": "omit" - }); - response = await response.text() - return response - } catch(error){ - console.log(error) + let response: any = await fetch( + `${this.configService.get( + "WADHWANI_BASE_URL" + )}/detect_query_intent?query=${text}`, + { + headers: myHeaders, + method: "GET", + mode: "cors", + credentials: "omit", + } + ); + response = await response.text(); + return response; + } catch (error) { + console.log(error); return { - error - } + error, + }; } } - async getResponseViaWadhwani(sessionId: string, userId: string, text: string) { - try{ + async getResponseViaWadhwani( + sessionId: string, + userId: string, + text: string, + schemeName: string + ) { + try { var myHeaders = new Headers(); myHeaders.append("accept", "application/json"); myHeaders.append("X-API-Key", this.configService.get("WADHWANI_API_KEY")); @@ -291,8 +301,8 @@ export class AiToolsService { } catch(error){ console.log(error) return { - error - } + error, + }; } } @@ -309,23 +319,23 @@ export class AiToolsService { myHeaders.append("Content-Type", "application/json"); var raw = JSON.stringify({ - "pipelineTasks": [ + pipelineTasks: [ { - "taskType": task, - "config": config - } + taskType: task, + config: config, + }, ], - "pipelineRequestConfig": { - "pipelineId": "64392f96daac500b55c543cd" - } + pipelineRequestConfig: { + pipelineId: "64392f96daac500b55c543cd", + }, }); var requestOptions: any = { - method: 'POST', + method: "POST", headers: myHeaders, body: raw, - redirect: 'follow', - retry: 4, + redirect: "follow", + retry: 4, pause: 0, url: this.configService.get("ULCA_CONFIG_URL"), userId, @@ -353,13 +363,13 @@ export class AiToolsService { console.log(`${endDate}: userId: ${userId} sessionId: ${sessionId} URL: ${this.configService.get("ULCA_CONFIG_URL")} (config API) Responded succesfully in ${endDate.getTime()-startDate.getTime()} ms.`) this.monitoringService.incrementBhashiniSuccessCount() await this.cacheManager.set(cacheKey, response, 86400); - return response - } catch(error) { - this.monitoringService.incrementBhashiniFailureCount() + return response; + } catch (error) { + this.monitoringService.incrementBhashiniFailureCount(); console.log(error); return { - error - } + error, + }; } } @@ -375,23 +385,23 @@ export class AiToolsService { myHeaders.append("Accept", " */*"); myHeaders.append("Authorization", authorization); myHeaders.append("Content-Type", "application/json"); - config['serviceId']=serviceId - if(task == 'tts'){ - config['gender']='male' - config['samplingRate']=8000 + config["serviceId"] = serviceId; + if (task == "tts") { + config["gender"] = "male"; + config["samplingRate"] = 8000; } var raw = JSON.stringify({ - "pipelineTasks": [ + pipelineTasks: [ { - "taskType": task, - "config": config - } + taskType: task, + config: config, + }, ], - "inputData": input + inputData: input, }); var requestOptions: any = { - method: 'POST', + method: "POST", headers: myHeaders, body: raw, redirect: 'follow', @@ -427,13 +437,13 @@ export class AiToolsService { if(task != 'asr') { await this.cacheManager.set(cacheKey, response, 7200); } - return response - } catch(error) { - this.monitoringService.incrementBhashiniFailureCount() + return response; + } catch (error) { + this.monitoringService.incrementBhashiniFailureCount(); console.log(error); return { - error - } + error, + }; } } -} \ No newline at end of file +} diff --git a/src/modules/user/user.service.ts b/src/modules/user/user.service.ts index 623b734..a4dca6b 100644 --- a/src/modules/user/user.service.ts +++ b/src/modules/user/user.service.ts @@ -7,7 +7,6 @@ import { decryptRequest, encryptRequest } from "../../common/utils"; import { Message } from "@prisma/client"; import { MonitoringService } from "../monitoring/monitoring.service"; - @Injectable() export class UserService { private logger: CustomLogger; @@ -19,173 +18,197 @@ export class UserService { this.logger = new CustomLogger("UserService"); } - async sendOTP( - mobileNumber: string, - type: string = 'Mobile' - ): Promise { + async sendOTP(mobileNumber: string, type: string = "Mobile"): Promise { try { - let encryptedData = await encryptRequest(`{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"Token\":\"${this.configService.get("PM_KISSAN_TOKEN")}\"}`) + let encryptedData = await encryptRequest( + `{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"Token\":\"${this.configService.get( + "PM_KISSAN_TOKEN" + )}\"}` + ); + console.log("encrypted data: ", encryptedData); let data = JSON.stringify({ - "EncryptedRequest": `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}` + EncryptedRequest: `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}`, }); - + let config = { - method: 'post', + method: "post", maxBodyLength: Infinity, url: `${this.configService.get("PM_KISAN_BASE_URL")}/chatbototp`, - headers: { - 'Content-Type': 'application/json' + headers: { + "Content-Type": "application/json", }, - data : data + data: data, }; - let response: any = await axios.request(config) - console.log("sendOTP",response.status) + let response: any = await axios.request(config); + console.log("sendOTP", response.status); if (response.status >= 200 && response.status < 300) { - response = await response.data - let decryptedData: any = await decryptRequest(response.d.output,encryptedData.d.token) - response.d.output = JSON.parse(decryptedData.d.decryptedvalue) - response["status"] = response.d.output.Rsponce != "False" ? "OK" : "NOT_OK" - return response + response = await response.data; + let decryptedData: any = await decryptRequest( + response.d.output, + encryptedData.d.token + ); + response.d.output = JSON.parse(decryptedData.d.decryptedvalue); + response["status"] = + response.d.output.Rsponce != "False" ? "OK" : "NOT_OK"; + return response; } else { return { d: { output: { - status: 'False', - Message: 'Try again' - } - } - } + status: "False", + Message: "Try again", + }, + }, + }; } } catch (error) { - console.log(error) + console.log(error); return { d: { output: { - status: 'False', - Message: 'Try again' - } - } - } + status: "False", + Message: "Try again", + }, + }, + }; } } async verifyOTP( mobileNumber: string, otp: string, - type: string = 'Mobile' + type: string = "Mobile" ): Promise { - try { - let encryptedData = await encryptRequest(`{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"OTP\":\"${otp}\",\"Token\":\"${this.configService.get("PM_KISSAN_TOKEN")}\"}`) + let encryptedData = await encryptRequest( + `{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"OTP\":\"${otp}\",\"Token\":\"${this.configService.get( + "PM_KISSAN_TOKEN" + )}\"}` + ); let data = JSON.stringify({ - "EncryptedRequest": `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}` + EncryptedRequest: `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}`, }); - + let config = { - method: 'post', + method: "post", maxBodyLength: Infinity, - url: `${this.configService.get("PM_KISAN_BASE_URL")}/ChatbotOTPVerified`, - headers: { - 'Content-Type': 'application/json' + url: `${this.configService.get( + "PM_KISAN_BASE_URL" + )}/ChatbotOTPVerified`, + headers: { + "Content-Type": "application/json", }, - data : data + data: data, }; - let response: any = await axios.request(config) - console.log("verifyOTP",response.status) + let response: any = await axios.request(config); + console.log("verifyOTP", response.status); if (response.status >= 200 && response.status < 300) { - response = await response.data - let decryptedData: any = await decryptRequest(response.d.output,encryptedData.d.token) - console.log(decryptedData) - response.d.output = JSON.parse(decryptedData.d.decryptedvalue) - response["status"] = response.d.output.Rsponce != "False" ? "OK" : "NOT_OK" - return response + response = await response.data; + let decryptedData: any = await decryptRequest( + response.d.output, + encryptedData.d.token + ); + console.log(decryptedData); + response.d.output = JSON.parse(decryptedData.d.decryptedvalue); + response["status"] = + response.d.output.Rsponce != "False" ? "OK" : "NOT_OK"; + return response; } else { return { d: { output: { - status: 'False', - Message: 'Try again' - } - } - } + status: "False", + Message: "Try again", + }, + }, + }; } } catch (error) { - console.log(error) + console.log(error); return { d: { output: { - status: 'False', - Message: 'Try again' - } - } - } + status: "False", + Message: "Try again", + }, + }, + }; } } async getUserData( mobileNumber: string, - type: string = 'Mobile' + type: string = "Mobile" ): Promise { let res: any; try { - let encryptedData = await encryptRequest(`{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"Token\":\"${this.configService.get("PM_KISSAN_TOKEN")}\"}`) + let encryptedData = await encryptRequest( + `{\"Types\":\"${type}\",\"Values\":\"${mobileNumber}\",\"Token\":\"${this.configService.get( + "PM_KISSAN_TOKEN" + )}\"}` + ); let data = JSON.stringify({ - "EncryptedRequest": `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}` + EncryptedRequest: `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}`, }); - + let config = { - method: 'post', + method: "post", maxBodyLength: Infinity, - url: `${this.configService.get("PM_KISAN_BASE_URL")}/ChatbotUserDetails`, - headers: { - 'Content-Type': 'application/json' + url: `${this.configService.get( + "PM_KISAN_BASE_URL" + )}/ChatbotUserDetails`, + headers: { + "Content-Type": "application/json", }, - data : data + data: data, }; - res = await axios.request(config) - console.log("getUserData",res.status) + res = await axios.request(config); + console.log("getUserData", res.status); if (res.status >= 200 && res.status < 300) { - res = await res.data - let decryptedData: any = await decryptRequest(res.d.output,encryptedData.d.token) - res.d.output = JSON.parse(decryptedData.d.decryptedvalue) - res["status"] = res.d.output.Rsponce != "False" ? "OK" : "NOT_OK" + res = await res.data; + let decryptedData: any = await decryptRequest( + res.d.output, + encryptedData.d.token + ); + res.d.output = JSON.parse(decryptedData.d.decryptedvalue); + res["status"] = res.d.output.Rsponce != "False" ? "OK" : "NOT_OK"; } else { - this.monitoringService.incrementUnableToGetUserDetailsCount() + this.monitoringService.incrementUnableToGetUserDetailsCount(); res = { d: { output: { - status: 'False', - Message: 'Unable to get user details' - } - } - } + status: "False", + Message: "Unable to get user details", + }, + }, + }; } } catch (error) { - this.monitoringService.incrementUnableToGetUserDetailsCount() + this.monitoringService.incrementUnableToGetUserDetailsCount(); return { d: { output: { - status: 'False', - Message: 'Unable to get user details' - } - } - } + status: "False", + Message: "Unable to get user details", + }, + }, + }; } - return res + return res; } async likeQuery(id): Promise { // try { - await this.prisma.$queryRawUnsafe(` + await this.prisma.$queryRawUnsafe(` UPDATE "Message" SET "reaction" = 1 WHERE "id" = '${id}'`); // } catch { // return null; // } - this.monitoringService.incrementPositveFeedbackCount() + this.monitoringService.incrementPositveFeedbackCount(); return this.prisma.$queryRawUnsafe(` SELECT * from "Message" where id = '${id}' `); @@ -197,7 +220,7 @@ export class UserService { UPDATE "Message" SET "reaction" = -1 WHERE "id" = '${id}'`); - this.monitoringService.incrementNegativeFeedbackCount() + this.monitoringService.incrementNegativeFeedbackCount(); } catch { return null; } diff --git a/src/xstate/prompt/prompt.gaurds.ts b/src/xstate/prompt/prompt.gaurds.ts index 8607c5d..ca11193 100644 --- a/src/xstate/prompt/prompt.gaurds.ts +++ b/src/xstate/prompt/prompt.gaurds.ts @@ -1,27 +1,33 @@ export const promptGuards = { + ifText: (_, event) => event.data.prompt.input.type == "Text", - ifText: (_,event) => event.data.prompt.input.type == "Text", + ifAudio: (_, event) => event.data.inputType == "Audio", - ifAudio: (_,event) => event.data.inputType == "Audio", + ifMultipleAadhaar: (_, event) => + event.data == "This mobile number taged with multiple records.", - ifMultipleAadhaar: (_,event) => event.data == "This mobile number taged with multiple records.", + ifInValidScheme: (_, event) => + !VALID_SCHEMES.includes(event.data.prompt.input.schemeName), - ifNoRecordsFound: (context,event)=> event.data == `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.`, + ifNoRecordsFound: (context, event) => + event.data == + `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.`, - ifOTPSend: (_,event)=> event.data == 'OTP send successfully!', + ifOTPSend: (_, event) => event.data == "OTP send successfully!", - ifTryAgain: (_,event)=> event.data == 'Try again', + ifTryAgain: (_, event) => event.data == "Try again", - ifNotValidAadhaar: (_,event) => event.data == "Please enter a valid Beneficiary ID/Aadhaar Number/Phone number", + ifNotValidAadhaar: (_, event) => + event.data == + "Please enter a valid Beneficiary ID/Aadhaar Number/Phone number", - ifInvalidOTP: (_,event) => event.data == "OTP not verified", - - resendOTP: (_,event) => event.data.query == "resend OTP", + ifInvalidOTP: (_, event) => event.data == "OTP not verified", - ifOTPHasBeenVerified: (context,_) => context.isOTPVerified, + resendOTP: (_, event) => event.data.query == "resend OTP", - ifInvalidClassifier: (_,event) => event.data.class == "invalid", + ifOTPHasBeenVerified: (context, _) => context.isOTPVerified, - ifConvoStarterOrEnder: (_,event) => event.data.class == "convo" + ifInvalidClassifier: (_, event) => event.data.class == "invalid", -} \ No newline at end of file + ifConvoStarterOrEnder: (_, event) => event.data.class == "convo", +}; diff --git a/src/xstate/prompt/prompt.machine.ts b/src/xstate/prompt/prompt.machine.ts index 76a173c..e66c1b9 100644 --- a/src/xstate/prompt/prompt.machine.ts +++ b/src/xstate/prompt/prompt.machine.ts @@ -1,1329 +1,1508 @@ // @ts-nocheck -import { assign } from 'xstate'; -const path = require('path'); -const filePath = path.resolve(__dirname, '../../common/en.json'); +import { assign } from "xstate"; +const path = require("path"); +const filePath = path.resolve(__dirname, "../../common/en.json"); const engMessage = require(filePath); -export const botFlowMachine1:any = - { - /** @xstate-layout N4IgpgJg5mDOIC5QCMD2AXAYgG1QdwDoZ0BVWMAJwEUBXOdAS1QDsBiEgZQFEAlAfQCSAOQAKJACoBtAAwBdRKAAOqWA0YsFIAB6IAjAA4AzAQAsukwDZDAVhMAma3f26ANCACeiALR2DBXQCc0sHWAboWugDsutIWAL5xbmhYuIQAjnSw6swAwtgAhrCqAGYMlKwQLGAEDMwAbqgA1tXJOPgEGfRMuQVFDKWUCLUNAMb52TKyk5rKqtmaOgi61rqmJtb61tbS+hYm0tFunghmBNJ2VvoHAfrRJobmCUkYbemZ2XmFJWUUrJQUqAoBEUBXQxUBAFsCK1Uh13t1Pn0BhQhvVUGMJnJpkgQLM1N0Ft5ItYCE57BtDBZNtYLNYjt59PoCLtrJFdmELoZDHZIk8QDD2oVGrUoABBfIQAAW+XyFCENAhyHKnF4glEEmxShU+I0OMWUSZ4UsFgcPOCAXW9IQdhMkVJkQdhluFxWtmsfIFhDq+WwDAg4xF4qlMrlCqVv0qzGqwyaLResO9vv9jGYYol0tl8sVgxjGO6k01uO18z13kcFgIAQsARWkUpGyc+itjmkBGs3K5gQdkRr+g98faib9AdTQYzoezEaqNTRzWhA69PuHKbTwczYZzaLzLALunkOLxJdA+p2qx25cZ5gCDmbdlb7bsnYC3d7-ZSg6XycD6ZDWfDFWnGM509Aghy-Ucf3XSdUVGAMdyxOx9y1OYCVLBAaQCStpF0QxIhtW1OxMW97w7B5nwdV9En5BdQM-EdV3HP9ykjaNZzjd9FyTeix1-DcUVzODmALQwkKLFDdWPRAwlMXCbTsfDNktDxEBbNtSK7CiNjfV5aK4lceKg-9-kBYFQXBCgoRAsDuMgidwxg9FBILOQZmLVDJIQHxpBJQwax2fQa0MWILB2K1fLsNtIhNFZOWrbD3SokChRFAB5cQRHYbh+GEMQpBcg83Ik7Q9CMUxzBpHYnF0AxQuUhArmMJ0NnbbzOwsXlEpo6yVzSjKWJnBpgK6uievShztyErF8uQnVmEJE4HUrZ8LV8ewHBwq1qpsNSTHuRxNP0ExtITEbUvSgCowG2N5w43TlzOkRxqcrE91c8S5rQ6qIp5fZuWwmJIh2CxNuWJkVmkKsAhrKlGWOj89Iev4KABIEQXGczLOGhHU16p7MSmaaxNm+avHCJk72JJ0q0iXblhB7b212mweR7DYjs627ijAdARklEUyEoAARcZ8gu1jBvYnSuZ5vnUwFihhfQfI8fzKbRMPdziqWELTA2NkWw2KlpEMTbLGMVkeQMB0bQpOHCGl3n+fIBWRaRlHTPRyEbql7nHbl53FeVgT8cLDWisWUmosrfZiUh58IjsTaOwIWOQqCdtNgCO2CGMqdLqAyXYVzlX4IJ9XCo+jzSdZAhCKBu8HlpOk6uWaSNmWW1duiXCEio5hUAgOBNE9N7ibQrxWRMStq1ret9EbK0vCdCstlZXQLnuExr1sbPiHl2guiKsPK61o1TAdcILSCAGLkXuwobOLY8MfGtAaMeIOZ0zosgRXpvkoUeR5T64UrEFBwZsqyxUXkEZkAVfB4QtDYB02dkoQTXHZABBV3rzXMBFK4YR448j2GyTa7Z-BmBrL4K41VwjZ26t+dBTEKCAM1vqPwJhGSbHng8YKPIwrVjONeAi7UQoxGfCg2AwocbpRYeHPQ15a7tR7NyHkVZHCJzqoDYwsQjAWkcFvYIhg6GnWkSIWRJ99TbFMBvKIyx6xBGBnVZ8xhnC3ACpnahdhs4O1llAeWgdzE4MsNHB42xcJVmwgEJOvgU6UhwsSdq88jDZ1zoE8eURWyHUBpvSwDYmwt0sKsWwQi8K7HsMSFJzAICvDSR5AwRSoi4XuNFf6m1aStgiEFTha1QgJQSEAA */ - id: 'botFlow', - predictableActionArguments: true, - initial: 'checkStateAndJump', - context: { - userQuestion:'', - query: '', - queryType: '', - response: '', - userAadhaarNumber: '', - otp: '', - error: '', - currentState: "getUserQuestion", - type: '', - inputType:'', - inputLanguage: '', - lastAadhaarDigits: '', - state:'onGoing', - userId:"", - isOTPVerified: false +export const botFlowMachine1: any = { + /** @xstate-layout N4IgpgJg5mDOIC5QCMD2AXAYgG1QdwDoZ0BVWMAJwEUBXOdAS1QDsBiEgZQFEAlAfQCSAOQAKJACoBtAAwBdRKAAOqWA0YsFIAB6IAjAA4AzAQAsukwDZDAVhMAma3f26ANCACeiALR2DBXQCc0sHWAboWugDsutIWAL5xbmhYuIQAjnSw6swAwtgAhrCqAGYMlKwQLGAEDMwAbqgA1tXJOPgEGfRMuQVFDKWUCLUNAMb52TKyk5rKqtmaOgi61rqmJtb61tbS+hYm0tFunghmBNJ2VvoHAfrRJobmCUkYbemZ2XmFJWUUrJQUqAoBEUBXQxUBAFsCK1Uh13t1Pn0BhQhvVUGMJnJpkgQLM1N0Ft5ItYCE57BtDBZNtYLNYjt59PoCLtrJFdmELoZDHZIk8QDD2oVGrUoABBfIQAAW+XyFCENAhyHKnF4glEEmxShU+I0OMWUSZ4UsFgcPOCAXW9IQdhMkVJkQdhluFxWtmsfIFhDq+WwDAg4xF4qlMrlCqVv0qzGqwyaLResO9vv9jGYYol0tl8sVgxjGO6k01uO18z13kcFgIAQsARWkUpGyc+itjmkBGs3K5gQdkRr+g98faib9AdTQYzoezEaqNTRzWhA69PuHKbTwczYZzaLzLALunkOLxJdA+p2qx25cZ5gCDmbdlb7bsnYC3d7-ZSg6XycD6ZDWfDFWnGM509Aghy-Ucf3XSdUVGAMdyxOx9y1OYCVLBAaQCStpF0QxIhtW1OxMW97w7B5nwdV9En5BdQM-EdV3HP9ykjaNZzjd9FyTeix1-DcUVzODmALQwkKLFDdWPRAwlMXCbTsfDNktDxEBbNtSK7CiNjfV5aK4lceKg-9-kBYFQXBCgoRAsDuMgidwxg9FBILOQZmLVDJIQHxpBJQwax2fQa0MWILB2K1fLsNtIhNFZOWrbD3SokChRFAB5cQRHYbh+GEMQpBcg83Ik7Q9CMUxzBpHYnF0AxQuUhArmMJ0NnbbzOwsXlEpo6yVzSjKWJnBpgK6uievShztyErF8uQnVmEJE4HUrZ8LV8ewHBwq1qpsNSTHuRxNP0ExtITEbUvSgCowG2N5w43TlzOkRxqcrE91c8S5rQ6qIp5fZuWwmJIh2CxNuWJkVmkKsAhrKlGWOj89Iev4KABIEQXGczLOGhHU16p7MSmaaxNm+avHCJk72JJ0q0iXblhB7b212mweR7DYjs627ijAdARklEUyEoAARcZ8gu1jBvYnSuZ5vnUwFihhfQfI8fzKbRMPdziqWELTA2NkWw2KlpEMTbLGMVkeQMB0bQpOHCGl3n+fIBWRaRlHTPRyEbql7nHbl53FeVgT8cLDWisWUmosrfZiUh58IjsTaOwIWOQqCdtNgCO2CGMqdLqAyXYVzlX4IJ9XCo+jzSdZAhCKBu8HlpOk6uWaSNmWW1duiXCEio5hUAgOBNE9N7ibQrxWRMStq1ret9EbK0vCdCstlZXQLnuExr1sbPiHl2guiKsPK61o1TAdcILSCAGLkXuwobOLY8MfGtAaMeIOZ0zosgRXpvkoUeR5T64UrEFBwZsqyxUXkEZkAVfB4QtDYB02dkoQTXHZABBV3rzXMBFK4YR448j2GyTa7Z-BmBrL4K41VwjZ26t+dBTEKCAM1vqPwJhGSbHng8YKPIwrVjONeAi7UQoxGfCg2AwocbpRYeHPQ15a7tR7NyHkVZHCJzqoDYwsQjAWkcFvYIhg6GnWkSIWRJ99TbFMBvKIyx6xBGBnVZ8xhnC3ACpnahdhs4O1llAeWgdzE4MsNHB42xcJVmwgEJOvgU6UhwsSdq88jDZ1zoE8eURWyHUBpvSwDYmwt0sKsWwQi8K7HsMSFJzAICvDSR5AwRSoi4XuNFf6m1aStgiEFTha1QgJQSEAA */ + id: "botFlow", + predictableActionArguments: true, + initial: "checkStateAndJump", + context: { + userQuestion: "", + query: "", + queryType: "", + response: "", + userAadhaarNumber: "", + otp: "", + error: "", + currentState: "getUserQuestion", + type: "", + inputType: "", + inputLanguage: "", + lastAadhaarDigits: "", + state: "onGoing", + userId: "", + isOTPVerified: false, + }, + states: { + checkStateAndJump: { + always: [ + { + target: "getUserQuestion", + cond: (context) => context.currentState === "getUserQuestion", + }, + { + target: "questionClassifier", + cond: (context) => context.currentState === "questionClassifier", + }, + { + target: "askingAadhaarNumber", + cond: (context) => context.currentState === "askingAadhaarNumber", + }, + { + target: "validatingAadhaarNumber", + cond: (context) => context.currentState === "validatingAadhaarNumber", + }, + { + target: "askingOTP", + cond: (context) => context.currentState === "askingOTP", + }, + { + target: "validatingOTP", + cond: (context) => context.currentState === "validatingOTP", + }, + { + target: "fetchingUserData", + cond: (context) => context.currentState === "fetchingUserData", + }, + { + target: "error", + cond: (context) => context.currentState === "error", + }, + { + target: "endFlow", + cond: (context) => context.currentState === "endFlow", + }, + ], }, - states: { - checkStateAndJump: { - always: [ - { target: 'getUserQuestion', cond: (context) => context.currentState === 'getUserQuestion' }, - { target: 'questionClassifier', cond: (context) => context.currentState === 'questionClassifier' }, - { target: 'askingAadhaarNumber', cond: (context) => context.currentState === 'askingAadhaarNumber' }, - { target: 'validatingAadhaarNumber', cond: (context) => context.currentState === 'validatingAadhaarNumber' }, - { target: 'askingOTP', cond: (context) => context.currentState === 'askingOTP' }, - { target: 'validatingOTP', cond: (context) => context.currentState === 'validatingOTP' }, - { target: 'fetchingUserData', cond: (context) => context.currentState === 'fetchingUserData' }, - { target: 'error', cond: (context) => context.currentState === 'error' }, - { target: 'endFlow', cond: (context) => context.currentState === 'endFlow' } - ] + getUserQuestion: { + on: { + USER_INPUT: { + target: "questionClassifier", + actions: [ + assign({ + query: (_, event) => event.data, + }), + ], + }, }, - getUserQuestion: { - on: { - USER_INPUT: { - target: 'questionClassifier', + }, + questionClassifier: { + invoke: { + src: "questionClassifier", + onDone: [ + { + cond: "ifInvalidClassifier", + target: "getUserQuestion", actions: [ assign({ - query: (_,event) => event.data - }) - ] - } - } + response: () => engMessage["message.invalid_question"], + type: "pause", + }), + ], + }, + { + target: "askingAadhaarNumber", + actions: [ + assign({ + response: () => engMessage["label.popUpTitle"], + queryType: (_, event) => event.data, + type: "pause", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - questionClassifier: { - invoke: { - src: "questionClassifier", - onDone: [ - { - cond: "ifInvalidClassifier", - target: "getUserQuestion", - actions: [ - assign({ - response: () => engMessage["message.invalid_question"], - type:"pause" - }) - ] - }, - { - target: 'askingAadhaarNumber', - actions: [ - assign({ - response: () => engMessage["label.popUpTitle"], - queryType: (_,event) => event.data, - type: 'pause' - }) - ] - } + }, + askingAadhaarNumber: { + on: { + USER_INPUT: { + target: "validatingAadhaarNumber", + actions: [ + assign({ + userAadhaarNumber: (context, event) => + `${context.userAadhaarNumber}${event.data}`, + type: "", + }), ], - onError: { - target: 'error', + }, + }, + }, + validatingAadhaarNumber: { + invoke: { + src: "validateAadhaarNumber", + onDone: [ + { + cond: "ifNotValidAadhaar", + target: "askingAadhaarNumber", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - askingAadhaarNumber: { - on: { - USER_INPUT: { - target: 'validatingAadhaarNumber', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifMultipleAadhaar", + target: "askingAadhaarNumber", actions: [ assign({ - userAadhaarNumber: (context, event) => `${context.userAadhaarNumber}${event.data}`, - type: '' - }) - ] - } - } - }, - validatingAadhaarNumber: { - invoke: { - src: 'validateAadhaarNumber', - onDone: [ - { - cond: "ifNotValidAadhaar", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifMultipleAadhaar", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle2"], - type: 'pause' - }) - ] - }, - { - cond: "ifNoRecordsFound", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: (context) => `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifOTPSend", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: "error", - actions: [ - assign({ - error: (_, event) => event.data, - type: '' - }) - ] - } - ], - onError: { - target: 'error', + response: () => engMessage["label.popUpTitle2"], + type: "pause", + }), + ], + }, + { + cond: "ifNoRecordsFound", + target: "askingAadhaarNumber", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - askingOTP: { - on: { - USER_INPUT: { - target: 'validatingOTP', + response: (context) => + `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifTryAgain", + target: "askingAadhaarNumber", actions: [ assign({ - otp: (_, event) => event.data, - type: '' - }) - ] - } - } - }, - validatingOTP: { - invoke: { - src: 'validateOTP', - onDone: [ - { - cond: "ifInvalidOTP", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["message.invalid_otp"], - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: 'fetchingUserData', - } - ], - onError: { - target: 'error', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifOTPSend", + target: "askingOTP", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - fetchingUserData: { - invoke: { - src: 'fetchUserData', - onDone: { - target: 'endFlow', + }, + askingOTP: { + on: { + USER_INPUT: { + target: "validatingOTP", + actions: [ + assign({ + otp: (_, event) => event.data, + type: "", + }), + ], + }, + }, + }, + validatingOTP: { + invoke: { + src: "validateOTP", + onDone: [ + { + cond: "ifInvalidOTP", + target: "askingOTP", actions: [ assign({ - response: (_, event) => event.data, - type: '' - }) - ] + response: () => engMessage["message.invalid_otp"], + type: "pause", + }), + ], }, - onError: { - target: 'error', + { + cond: "ifTryAgain", + target: "askingOTP", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "fetchingUserData", + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - error: { - invoke: { - src: 'logError', - onDone: 'endFlow', - } + }, + fetchingUserData: { + invoke: { + src: "fetchUserData", + onDone: { + target: "endFlow", + actions: [ + assign({ + response: (_, event) => event.data, + type: "", + }), + ], + }, + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - endFlow: { - type: 'final' - } - } - } - + }, + error: { + invoke: { + src: "logError", + onDone: "endFlow", + }, + }, + endFlow: { + type: "final", + }, + }, +}; -export const botFlowMachine2: any = - { - /** @xstate-layout N4IgpgJg5mDOIC5QCMD2AXAYgG1QdwDoZ0BVWMAJwEUBXOdAS1QDsBiEgZQFEAlAfQCSAOQAKJACoBtAAwBdRKAAOqWA0YsFIAB6IAjAFZdBaQHZ9ANgBMATmsAOO-vsmANCACeiALS6zlggAsurbS1haWptIBAL7RbmhYuIQAxgAWYMkA1uLuimC6rBAsYAQMzABuqJklCTj4BGkZ2bn5CGWVyQCG6swysn2ayqo9mjoIXpYmAQS+AMzWlo6Ls9Lm5vpunuMGNgQmdpYBYfZHi+ax8Rh1KelZOXkFRcwl7VU1V0kNt80PbRWoXR6fUkunkSBAQzUTGYo0Q1iMln0+lmljW0kMdnM9k23l0KOmhnh0gcxN0dgClguIFqn0adxaBUoFFQFAIimw3QAZiyALYEGn1Ok-VqvQHQ4FyQYqKEacFjLx2EwmAjWFbo4k2XS6LE47ZWawERaKxX6AIBcwmKJUgUpFichgUHkCZiKGjoAqcXiCUQSAbgyEjOXeWb6GZ2FGWAzSWbmaSmay6nxBaSG6wmNbmsIWmPWj71ACOdFgPQAwhzYKp7ZRCsVSv9qvy84RC-RoWXOhWGFWKH8Ot1xXI-UppYHQGMtQbdKtMSZJhYtboAomp4q9gEnJbDpaAujc4kC0XS+XKwxq0yWWyOehuY7G-vm4e28eu6ee6L+ywJWDh8NobDxtYqwqtY5hmpagGTGYy7BAaAThlO8zwuYswmLMe7XAQHaZGUUAAIKdBAqSdJ0FBCDQPLINWnr8MIYhSJK-ojn+QYIAYRimOEtgOE4mJ2ImdggXsBxRIcMYhvo6G0t89xgJYNbPHWlQNjaXxNDJli9gCH69IODE-jKMIsRMUwzKhCxLOGqzrImSrKrMIYCYc9gHCY1iSYK0ktHJTwvPW7z3qp9J5Bp75AoOoJSr+spjnCCJIiiaIYpauiJhYKYrIuU7wgYYTuTcaleaw56suyXK8neGFCupmlip+unfhCTHRdo3iKsqqpxvoGrZeYfEeN4tkEPZ+h2KE6ZIjuElxNSTYNHaDpOi6bpydR3p0UOjVRYZMXjCGYYRlGMZxqNGz9eMoF2KZqHpqhxImMEeUEOUnTYAwED9sweEEURJFkRR1Y+YpbwVZ8z2ve9jCffhhHEaR5GUW+-y1Tp-R6ZtBn-l4pxDQl9lahiAnLmsQkLNqqKzHi5JodNKlg29H1fTDv3wwDtavMps10xDOHQz9cP-YjfZhf0EWMVt-4hv4qoZfZ9mWLMdiLkT5gk5GVjIZTATU5cAVcwzvOw39CPyb5Sn+RheuQ4zfNG5QNXacClgNQGzE7a50yWJMpgGA44amsrqtkxrCta49ls899hssxQJtAxzusvfTVsG8zAv28LkizM7TXbS1rGHAi4ZwZisbSIifVbD4xP7KT6sUyH2szQn4P65HqfG4D7Pm6Difc1Dbf8wj6cDv0ATZ+LLHagrBDmGSabSME5pdadlfairNeIumNj7BEJhh73rdM4PrMKV3IP1OH-dH7bgtaRn+jjxjRknMY8sHMhXHwpYAcb-oW9pgcfeLdk4DxvkVCgzISpXhvHyWmB8QHX2jsPOqqNH6jjzl4BYKstb7CcMiT+CYzpY0WAQfQNgsRWFNA4UONNZpYQADIdnQPhAeAARBgUA1CwHYNwGiPp6JoNdnnI4Bo8bmlGq5OM8tdSzGmGmJwZcAhKmjBEGItCApVRaAEWOZ8VKaLyAEZBKMNou2auOaeZdtR4gtEoyY1glxnTYqQ8I9k1gOBsArR6+iwDaM7n5c++Ugo+KMcCUW+l0FjC1gaQwWpQJYiRIBf2Z15hGBQhEPEURUKokpOoyqnkDHgMgZeMqt49H5OCaFEeJic6YzaiqNUXUDg9QrnoQwzirCuN6k03QOSdaVXmo6Z0rp0DaNWrRX0aNTG5zGDGZUo08Ra2OhSOCK9EArA9qBXB9itSRjsI9LCOEADy4gRA8K9OMgRkUn47V8KBVMmIpzIiUesQhWxZ4ElnMmewU51ZePKbMHR-iykFTyLMEJ9UrkRL0EES6cZ0y9TTGYLBupUIexRGmNYSoEWN2BUEgFfizYBMCsKMFlSUEgkEWY7wvUPbJgtKqbUSoUpnTTAaVYhglHIjLlYNRfSpIgrAPitmQLZreNJUjB2g4naQqEeObcgR9grHuoYEMDitisuMOsRcZgVjZJxaK-5hSLylWvOVXFJLwWoJlVS8YdSOrqm6dqV5iBUWGjEZGM05M3K5NpAMxawyAVjP4dUieNy4kqmRAcIIs5dXMq2AJUMZc2rcR2WsIBScjknMBYSuBwDM0iEtSG65edEQLBmNmdlHSLC6h6fMPY89fA9PXCNPZPqL7wPzdm4GuaM2fWOQWslxiwnoyhQgB5MwbCK06rOXqswa3ywNK5ZK91DhIgcOmvuUB+1dvjhbDtfaTmFulWLYt44sSzBmH-bKZpnAHHnVYPYqFTRl1MArYkG6GbbuKsU01pTOb7q3YewdX5rXTNagJQ0XUxJLpWH-XUI0VYU2CDYUwWIKTer5fUTkYB0BpBwmQSgrDuidB3d3LDOG8OfQIxQIj6BOiFsmTUyeUx-DIXXLOtWIE1WtIpDMHcqwwgmh3HvNthBsO4dSPh8gNHiNGqgSU2Bs1xOUagNR2j9HgMQpPaOhUgksS3Ncn-OMc7HHzGmNGYIDyyTiKmphwgxVSNEuKgxylYGEBkIRCBb53tGWuEcfdFM4ZFjRjjOueErbprMFQBAOAmgbSgcxghfwZcFZevsPCEzq9AIplnFBrW4ReqPWINR2grZmpTP-BEZLaxGXogEiBTL4GjD2IXpaDilkMNNzyQK3QCXJ6yJnn-DMBhMWAXMETCmQ0emTAOI4U4ra7NzWYPaQZS13R9Z2hMREpC4LmXxvPNMy5UuXvWOGBWs4F6dZUi2YsT4OwnkoBtvOjzSFf1RGQhwUxFTLnSaQ9lyIYwjR9vs2A2Er422jk98cBg9jpPO6qSYWJnUAV6oEASbGghhCQ38gVlgod6F2DGYIKJTQGBnS08YSpRFOAaasGMqIvF+qGctfH4xPYq1jETiIPKkKJkoYaY6yILq7lE09ADKdj4UFZ5iPj3zhNIQLomRZziKYiR5chkHmRGHFhYUfdhnD0DwG07KxA5oL0UjxOixEs9iTcd2heheQRUQ7nJDS-VGjykBFZ3BKWeIuqeyURqdMNajikPRcSMzQPAGi+SEztbXvjc2rJKGCMk0lQKzEjIyYhoggrAgmZzxouDkHpEKz3wqFIONqycZ1y8GpykPunBIIvUpgGBx3isvUw5mjVAoHxY5pv5nSyQLkCHLoxmjbzHuPAay9LyGhyiIri8Se11OF4w6JzRTE6vLXpXWe55pL53mMpDOcU1ResKYNafkEEcCoxUSijiPWU5Jqj0n1Od92FqX2VgI9TxrfMZLW3LHLFc0R6YqVnXTFMHiOMDWZvLUGtc9QIRCHpZPdMRUMA5gCAa4TvZCGeBlVENMbUU4GtZVGeerU0SYOxU0WIWIIAA */ - id: 'botFlow', - predictableActionArguments: true, - initial: 'checkStateAndJump', - context: { - userQuestion:'', - query: '', - queryType: '', - response: '', - userAadhaarNumber: '', - otp: '', - error: '', - currentState: "getUserQuestion", - type: '', - inputType:'', - inputLanguage: '', - lastAadhaarDigits:'', - state:'onGoing', - userId:"", - isOTPVerified: false +export const botFlowMachine2: any = { + /** @xstate-layout N4IgpgJg5mDOIC5QCMD2AXAYgG1QdwDoZ0BVWMAJwEUBXOdAS1QDsBiEgZQFEAlAfQCSAOQAKJACoBtAAwBdRKAAOqWA0YsFIAB6IAjAFZdBaQHZ9ANgBMATmsAOO-vsmANCACeiALS6zlggAsurbS1haWptIBAL7RbmhYuIQAxgAWYMkA1uLuimC6rBAsYAQMzABuqJklCTj4BGkZ2bn5CGWVyQCG6swysn2ayqo9mjoIXpYmAQS+AMzWlo6Ls9Lm5vpunuMGNgQmdpYBYfZHi+ax8Rh1KelZOXkFRcwl7VU1V0kNt80PbRWoXR6fUkunkSBAQzUTGYo0Q1iMln0+lmljW0kMdnM9k23l0KOmhnh0gcxN0dgClguIFqn0adxaBUoFFQFAIimw3QAZiyALYEGn1Ok-VqvQHQ4FyQYqKEacFjLx2EwmAjWFbo4k2XS6LE47ZWawERaKxX6AIBcwmKJUgUpFichgUHkCZiKGjoAqcXiCUQSAbgyEjOXeWb6GZ2FGWAzSWbmaSmay6nxBaSG6wmNbmsIWmPWj71ACOdFgPQAwhzYKp7ZRCsVSv9qvy84RC-RoWXOhWGFWKH8Ot1xXI-UppYHQGMtQbdKtMSZJhYtboAomp4q9gEnJbDpaAujc4kC0XS+XKwxq0yWWyOehuY7G-vm4e28eu6ee6L+ywJWDh8NobDxtYqwqtY5hmpagGTGYy7BAaAThlO8zwuYswmLMe7XAQHaZGUUAAIKdBAqSdJ0FBCDQPLINWnr8MIYhSJK-ojn+QYIAYRimOEtgOE4mJ2ImdggXsBxRIcMYhvo6G0t89xgJYNbPHWlQNjaXxNDJli9gCH69IODE-jKMIsRMUwzKhCxLOGqzrImSrKrMIYCYc9gHCY1iSYK0ktHJTwvPW7z3qp9J5Bp75AoOoJSr+spjnCCJIiiaIYpauiJhYKYrIuU7wgYYTuTcaleaw56suyXK8neGFCupmlip+unfhCTHRdo3iKsqqpxvoGrZeYfEeN4tkEPZ+h2KE6ZIjuElxNSTYNHaDpOi6bpydR3p0UOjVRYZMXjCGYYRlGMZxqNGz9eMoF2KZqHpqhxImMEeUEOUnTYAwED9sweEEURJFkRR1Y+YpbwVZ8z2ve9jCffhhHEaR5GUW+-y1Tp-R6ZtBn-l4pxDQl9lahiAnLmsQkLNqqKzHi5JodNKlg29H1fTDv3wwDtavMps10xDOHQz9cP-YjfZhf0EWMVt-4hv4qoZfZ9mWLMdiLkT5gk5GVjIZTATU5cAVcwzvOw39CPyb5Sn+RheuQ4zfNG5QNXacClgNQGzE7a50yWJMpgGA44amsrqtkxrCta49ls899hssxQJtAxzusvfTVsG8zAv28LkizM7TXbS1rGHAi4ZwZisbSIifVbD4xP7KT6sUyH2szQn4P65HqfG4D7Pm6Difc1Dbf8wj6cDv0ATZ+LLHagrBDmGSabSME5pdadlfairNeIumNj7BEJhh73rdM4PrMKV3IP1OH-dH7bgtaRn+jjxjRknMY8sHMhXHwpYAcb-oW9pgcfeLdk4DxvkVCgzISpXhvHyWmB8QHX2jsPOqqNH6jjzl4BYKstb7CcMiT+CYzpY0WAQfQNgsRWFNA4UONNZpYQADIdnQPhAeAARBgUA1CwHYNwGiPp6JoNdnnI4Bo8bmlGq5OM8tdSzGmGmJwZcAhKmjBEGItCApVRaAEWOZ8VKaLyAEZBKMNou2auOaeZdtR4gtEoyY1glxnTYqQ8I9k1gOBsArR6+iwDaM7n5c++Ugo+KMcCUW+l0FjC1gaQwWpQJYiRIBf2Z15hGBQhEPEURUKokpOoyqnkDHgMgZeMqt49H5OCaFEeJic6YzaiqNUXUDg9QrnoQwzirCuN6k03QOSdaVXmo6Z0rp0DaNWrRX0aNTG5zGDGZUo08Ra2OhSOCK9EArA9qBXB9itSRjsI9LCOEADy4gRA8K9OMgRkUn47V8KBVMmIpzIiUesQhWxZ4ElnMmewU51ZePKbMHR-iykFTyLMEJ9UrkRL0EES6cZ0y9TTGYLBupUIexRGmNYSoEWN2BUEgFfizYBMCsKMFlSUEgkEWY7wvUPbJgtKqbUSoUpnTTAaVYhglHIjLlYNRfSpIgrAPitmQLZreNJUjB2g4naQqEeObcgR9grHuoYEMDitisuMOsRcZgVjZJxaK-5hSLylWvOVXFJLwWoJlVS8YdSOrqm6dqV5iBUWGjEZGM05M3K5NpAMxawyAVjP4dUieNy4kqmRAcIIs5dXMq2AJUMZc2rcR2WsIBScjknMBYSuBwDM0iEtSG65edEQLBmNmdlHSLC6h6fMPY89fA9PXCNPZPqL7wPzdm4GuaM2fWOQWslxiwnoyhQgB5MwbCK06rOXqswa3ywNK5ZK91DhIgcOmvuUB+1dvjhbDtfaTmFulWLYt44sSzBmH-bKZpnAHHnVYPYqFTRl1MArYkG6GbbuKsU01pTOb7q3YewdX5rXTNagJQ0XUxJLpWH-XUI0VYU2CDYUwWIKTer5fUTkYB0BpBwmQSgrDuidB3d3LDOG8OfQIxQIj6BOiFsmTUyeUx-DIXXLOtWIE1WtIpDMHcqwwgmh3HvNthBsO4dSPh8gNHiNGqgSU2Bs1xOUagNR2j9HgMQpPaOhUgksS3Ncn-OMc7HHzGmNGYIDyyTiKmphwgxVSNEuKgxylYGEBkIRCBb53tGWuEcfdFM4ZFjRjjOueErbprMFQBAOAmgbSgcxghfwZcFZevsPCEzq9AIplnFBrW4ReqPWINR2grZmpTP-BEZLaxGXogEiBTL4GjD2IXpaDilkMNNzyQK3QCXJ6yJnn-DMBhMWAXMETCmQ0emTAOI4U4ra7NzWYPaQZS13R9Z2hMREpC4LmXxvPNMy5UuXvWOGBWs4F6dZUi2YsT4OwnkoBtvOjzSFf1RGQhwUxFTLnSaQ9lyIYwjR9vs2A2Er422jk98cBg9jpPO6qSYWJnUAV6oEASbGghhCQ38gVlgod6F2DGYIKJTQGBnS08YSpRFOAaasGMqIvF+qGctfH4xPYq1jETiIPKkKJkoYaY6yILq7lE09ADKdj4UFZ5iPj3zhNIQLomRZziKYiR5chkHmRGHFhYUfdhnD0DwG07KxA5oL0UjxOixEs9iTcd2heheQRUQ7nJDS-VGjykBFZ3BKWeIuqeyURqdMNajikPRcSMzQPAGi+SEztbXvjc2rJKGCMk0lQKzEjIyYhoggrAgmZzxouDkHpEKz3wqFIONqycZ1y8GpykPunBIIvUpgGBx3isvUw5mjVAoHxY5pv5nSyQLkCHLoxmjbzHuPAay9LyGhyiIri8Se11OF4w6JzRTE6vLXpXWe55pL53mMpDOcU1ResKYNafkEEcCoxUSijiPWU5Jqj0n1Od92FqX2VgI9TxrfMZLW3LHLFc0R6YqVnXTFMHiOMDWZvLUGtc9QIRCHpZPdMRUMA5gCAa4TvZCGeBlVENMbUU4GtZVGeerU0SYOxU0WIWIIAA */ + id: "botFlow", + predictableActionArguments: true, + initial: "checkStateAndJump", + context: { + userQuestion: "", + query: "", + queryType: "", + response: "", + userAadhaarNumber: "", + otp: "", + error: "", + currentState: "getUserQuestion", + type: "", + inputType: "", + inputLanguage: "", + lastAadhaarDigits: "", + state: "onGoing", + userId: "", + isOTPVerified: false, + }, + states: { + checkStateAndJump: { + always: [ + { + target: "getUserQuestion", + cond: (context) => context.currentState === "getUserQuestion", + }, + { + target: "checkType1", + cond: (context) => context.currentState === "checkType1", + }, + { + target: "confirmInput1", + cond: (context) => context.currentState === "confirmInput1", + }, + { + target: "questionClassifier", + cond: (context) => context.currentState === "questionClassifier", + }, + { + target: "askingAadhaarNumber", + cond: (context) => context.currentState === "askingAadhaarNumber", + }, + { + target: "checkType2", + cond: (context) => context.currentState === "checkType2", + }, + { + target: "confirmInput2", + cond: (context) => context.currentState === "confirmInput2", + }, + { + target: "validatingAadhaarNumber", + cond: (context) => context.currentState === "validatingAadhaarNumber", + }, + { + target: "askLastAaadhaarDigits", + cond: (context) => context.currentState === "askLastAaadhaarDigits", + }, + { + target: "checkType4", + cond: (context) => context.currentState === "checkType4", + }, + { + target: "confirmInput4", + cond: (context) => context.currentState === "confirmInput4", + }, + { + target: "askingOTP", + cond: (context) => context.currentState === "askingOTP", + }, + { + target: "checkType3", + cond: (context) => context.currentState === "checkType3", + }, + { + target: "confirmInput3", + cond: (context) => context.currentState === "confirmInput3", + }, + { + target: "validatingOTP", + cond: (context) => context.currentState === "validatingOTP", + }, + { + target: "fetchingUserData", + cond: (context) => context.currentState === "fetchingUserData", + }, + { + target: "error", + cond: (context) => context.currentState === "error", + }, + { + target: "endFlow", + cond: (context) => context.currentState === "endFlow", + }, + ], }, - states: { - checkStateAndJump: { - always: [ - { target: 'getUserQuestion', cond: (context) => context.currentState === 'getUserQuestion' }, - { target: 'checkType1', cond: (context) => context.currentState === 'checkType1' }, - { target: 'confirmInput1', cond: (context) => context.currentState === 'confirmInput1' }, - { target: 'questionClassifier', cond: (context) => context.currentState === 'questionClassifier' }, - { target: 'askingAadhaarNumber', cond: (context) => context.currentState === 'askingAadhaarNumber' }, - { target: 'checkType2', cond: (context) => context.currentState === 'checkType2' }, - { target: 'confirmInput2', cond: (context) => context.currentState === 'confirmInput2' }, - { target: 'validatingAadhaarNumber', cond: (context) => context.currentState === 'validatingAadhaarNumber' }, - { target: 'askLastAaadhaarDigits', cond: (context) => context.currentState === 'askLastAaadhaarDigits' }, - { target: 'checkType4', cond: (context) => context.currentState === 'checkType4' }, - { target: 'confirmInput4', cond: (context) => context.currentState === 'confirmInput4' }, - { target: 'askingOTP', cond: (context) => context.currentState === 'askingOTP' }, - { target: 'checkType3', cond: (context) => context.currentState === 'checkType3' }, - { target: 'confirmInput3', cond: (context) => context.currentState === 'confirmInput3' }, - { target: 'validatingOTP', cond: (context) => context.currentState === 'validatingOTP' }, - { target: 'fetchingUserData', cond: (context) => context.currentState === 'fetchingUserData' }, - { target: 'error', cond: (context) => context.currentState === 'error' }, - { target: 'endFlow', cond: (context) => context.currentState === 'endFlow' } - ] + getUserQuestion: { + on: { + USER_INPUT: { + target: "checkType1", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, }, - getUserQuestion: { - on: { - USER_INPUT: { - target: 'checkType1', + }, + checkType1: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput1", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + type: "pause", + }), + ], + }, + { + target: "questionClassifier", + actions: [ + assign({ + userQuestion: (_, event) => event.data.query, + query: (_, event) => event.data.query, + response: engMessage["label.popUpTitle"], + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - checkType1: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput1", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"questionClassifier", - actions:[ - assign({ - userQuestion: (_,event) => event.data.query, - query: (_,event) => event.data.query, - response: engMessage["label.popUpTitle"] - }) - ] - } + }, + confirmInput1: { + on: { + USER_INPUT: { + target: "checkType1", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + questionClassifier: { + invoke: { + src: "questionClassifier", + onDone: [ + { + cond: "ifInvalidClassifier", + target: "getUserQuestion", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput1:{ - on: { - USER_INPUT: { - target: 'checkType1', + response: () => engMessage["message.invalid_question"], + type: "pause", + }), + ], + }, + { + target: "askingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + response: () => engMessage["label.popUpTitle"], + queryType: (_, event) => { + console.log(`assigning queryType = ${event.data}`); + return event.data; + }, + type: "pause", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - questionClassifier: { - invoke: { - src: "questionClassifier", - onDone: [ - { - cond: "ifInvalidClassifier", - target: "getUserQuestion", - actions: [ - assign({ - response: () => engMessage["message.invalid_question"], - type:"pause" - }) - ] - }, - { - target: 'askingAadhaarNumber', - actions: [ - assign({ - response: () => engMessage["label.popUpTitle"], - queryType: (_,event) => {console.log(`assigning queryType = ${event.data}`); return event.data}, - type: 'pause' - }) - ] - } + }, + askingAadhaarNumber: { + on: { + USER_INPUT: { + target: "checkType2", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType2: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput2", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - askingAadhaarNumber: { - on: { - USER_INPUT: { - target: 'checkType2', + type: "pause", + }), + ], + }, + { + target: "validatingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + query: (_, event) => event.data.query, + userAadhaarNumber: (_, event) => { + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - checkType2: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput2", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"validatingAadhaarNumber", - actions:[ - assign({ - query: (_,event) => event.data.query, - userAadhaarNumber: (_, event) => {return `${event.data.query}`}, - type:'' - }) - ] - } + }, + confirmInput2: { + on: { + USER_INPUT: { + target: "checkType2", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', - actions: [ - assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } + }, }, - confirmInput2:{ - on: { - USER_INPUT: { - target: 'checkType2', + }, + validatingAadhaarNumber: { + invoke: { + src: "validateAadhaarNumber", + onDone: [ + { + cond: "ifNotValidAadhaar", + target: "askingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - validatingAadhaarNumber: { - invoke: { - src: 'validateAadhaarNumber', - onDone: [ - { - cond: "ifNotValidAadhaar", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifMultipleAadhaar", - target: "askLastAaadhaarDigits", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle2"], - type: 'pause' - }) - ] - }, - { - cond: "ifNoRecordsFound", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: (context) => `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifOTPSend", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: "error", - actions: [ - assign({ - error: (_, event) => event.data, - type: '' - }) - ] - } - ], - onError: { - target: 'error', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifMultipleAadhaar", + target: "askLastAaadhaarDigits", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - askLastAaadhaarDigits:{ - on: { - USER_INPUT: { - target: 'checkType4', + response: () => engMessage["label.popUpTitle2"], + type: "pause", + }), + ], + }, + { + cond: "ifNoRecordsFound", + target: "askingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - checkType4: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput4", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"validatingAadhaarNumber", - actions:[ - assign({ - query: (_,event) => event.data.query, - lastAadhaarDigits: (_context, event) => {return `${event.data.query}`}, - type:'' - }) - ] - } - ], - onError: { - target: 'error', + response: (context) => + `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifTryAgain", + target: "askingAadhaarNumber", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput4:{ - on: { - USER_INPUT: { - target: 'checkType4', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifOTPSend", + target: "askingOTP", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - askingOTP: { - on: { - USER_INPUT: { - target: 'checkType3', + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "error", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + error: (_, event) => event.data, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - checkType3: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput3", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - cond:"resendOTP", - target:"validatingAadhaarNumber", - actions: [ - assign({ - response: engMessage["label.popUpTitle3"] - }) - ] - }, - { - target:"validatingOTP", - actions:[ - assign({ - query: (_,event) => event.data.query, - otp: (_context, event) => {console.log("setting user otp"); return `${event.data.query}`}, - type:'' - }) - ] - } + }, + askLastAaadhaarDigits: { + on: { + USER_INPUT: { + target: "checkType4", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType4: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput4", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput3:{ - on: { - USER_INPUT: { - target: 'checkType3', + type: "pause", + }), + ], + }, + { + target: "validatingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + query: (_, event) => event.data.query, + lastAadhaarDigits: (_context, event) => { + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - validatingOTP: { - invoke: { - src: 'validateOTP', - onDone: [ - { - cond: "ifInvalidOTP", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["message.invalid_otp"], - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: 'fetchingUserData', - } + }, + confirmInput4: { + on: { + USER_INPUT: { + target: "checkType4", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, + }, + }, + askingOTP: { + on: { + USER_INPUT: { + target: "checkType3", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType3: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput3", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - fetchingUserData: { - invoke: { - src: 'fetchUserData', - onDone: { - target: 'endFlow', + type: "pause", + }), + ], + }, + { + cond: "resendOTP", + target: "validatingAadhaarNumber", actions: [ assign({ - response: (_, event) => event.data, - userAadhaarNumber: "", - type: '' - }) - ] + response: engMessage["label.popUpTitle3"], + }), + ], }, - onError: { - target: 'error', + { + target: "validatingOTP", actions: [ assign({ - error: (_, event) => event.data.message, - userAadhaarNumber: "", - type: '' - }) - ] - } - } + query: (_, event) => event.data.query, + otp: (_context, event) => { + console.log("setting user otp"); + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, + }, + }, + confirmInput3: { + on: { + USER_INPUT: { + target: "checkType3", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, }, - error: { - invoke: { - src: 'logError', - onDone: { - target: 'endFlow', + }, + validatingOTP: { + invoke: { + src: "validateOTP", + onDone: [ + { + cond: "ifInvalidOTP", + target: "askingOTP", actions: [ assign({ - userAadhaarNumber: "" - }) - ] - } - } + response: () => engMessage["message.invalid_otp"], + type: "pause", + }), + ], + }, + { + cond: "ifTryAgain", + target: "askingOTP", + actions: [ + assign({ + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "fetchingUserData", + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - endFlow: { - type: 'final' - } - } - } - + }, + fetchingUserData: { + invoke: { + src: "fetchUserData", + onDone: { + target: "endFlow", + actions: [ + assign({ + response: (_, event) => event.data, + userAadhaarNumber: "", + type: "", + }), + ], + }, + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + userAadhaarNumber: "", + type: "", + }), + ], + }, + }, + }, + error: { + invoke: { + src: "logError", + onDone: { + target: "endFlow", + actions: [ + assign({ + userAadhaarNumber: "", + }), + ], + }, + }, + }, + endFlow: { + type: "final", + }, + }, +}; -export const botFlowMachine3:any = - { - id: 'botFlow3', - predictableActionArguments: true, - initial: 'checkStateAndJump', - context: { - userQuestion:'', - query: '', - queryType: '', - response: '', - userAadhaarNumber: '', - otp: '', - error: '', - currentState: "getUserQuestion", - type: '', - inputType:'', - inputLanguage: '', - lastAadhaarDigits:'', - state:'onGoing', - userId:'', - isOTPVerified: false, - isWadhwaniResponse: "false" +export const botFlowMachine3: any = { + id: "botFlow3", + predictableActionArguments: true, + initial: "checkStateAndJump", + context: { + userQuestion: "", + query: "", + queryType: "", + response: "", + userAadhaarNumber: "", + otp: "", + error: "", + currentState: "getUserQuestion", + type: "", + inputType: "", + inputLanguage: "", + lastAadhaarDigits: "", + state: "onGoing", + userId: "", + isOTPVerified: false, + isWadhwaniResponse: "false", + }, + states: { + checkStateAndJump: { + always: [ + { + target: "getUserQuestion", + cond: (context) => context.currentState === "getUserQuestion", + }, + { + target: "checkType1", + cond: (context) => context.currentState === "checkType1", + }, + { + target: "confirmInput1", + cond: (context) => context.currentState === "confirmInput1", + }, + { + target: "questionClassifier", + cond: (context) => context.currentState === "questionClassifier", + }, + { + target: "askingAadhaarNumber", + cond: (context) => context.currentState === "askingAadhaarNumber", + }, + { + target: "checkType2", + cond: (context) => context.currentState === "checkType2", + }, + { + target: "confirmInput2", + cond: (context) => context.currentState === "confirmInput2", + }, + { + target: "validatingAadhaarNumber", + cond: (context) => context.currentState === "validatingAadhaarNumber", + }, + { + target: "askLastAaadhaarDigits", + cond: (context) => context.currentState === "askLastAaadhaarDigits", + }, + { + target: "checkType4", + cond: (context) => context.currentState === "checkType4", + }, + { + target: "confirmInput4", + cond: (context) => context.currentState === "confirmInput4", + }, + { + target: "askingOTP", + cond: (context) => context.currentState === "askingOTP", + }, + { + target: "checkType3", + cond: (context) => context.currentState === "checkType3", + }, + { + target: "confirmInput3", + cond: (context) => context.currentState === "confirmInput3", + }, + { + target: "validatingOTP", + cond: (context) => context.currentState === "validatingOTP", + }, + { + target: "fetchingUserData", + cond: (context) => context.currentState === "fetchingUserData", + }, + { + target: "error", + cond: (context) => context.currentState === "error", + }, + { + target: "endFlow", + cond: (context) => context.currentState === "endFlow", + }, + ], }, - states: { - checkStateAndJump: { - always: [ - { target: 'getUserQuestion', cond: (context) => context.currentState === 'getUserQuestion' }, - { target: 'checkType1', cond: (context) => context.currentState === 'checkType1' }, - { target: 'confirmInput1', cond: (context) => context.currentState === 'confirmInput1' }, - { target: 'questionClassifier', cond: (context) => context.currentState === 'questionClassifier' }, - { target: 'askingAadhaarNumber', cond: (context) => context.currentState === 'askingAadhaarNumber' }, - { target: 'checkType2', cond: (context) => context.currentState === 'checkType2' }, - { target: 'confirmInput2', cond: (context) => context.currentState === 'confirmInput2' }, - { target: 'validatingAadhaarNumber', cond: (context) => context.currentState === 'validatingAadhaarNumber' }, - { target: 'askLastAaadhaarDigits', cond: (context) => context.currentState === 'askLastAaadhaarDigits' }, - { target: 'checkType4', cond: (context) => context.currentState === 'checkType4' }, - { target: 'confirmInput4', cond: (context) => context.currentState === 'confirmInput4' }, - { target: 'askingOTP', cond: (context) => context.currentState === 'askingOTP' }, - { target: 'checkType3', cond: (context) => context.currentState === 'checkType3' }, - { target: 'confirmInput3', cond: (context) => context.currentState === 'confirmInput3' }, - { target: 'validatingOTP', cond: (context) => context.currentState === 'validatingOTP' }, - { target: 'fetchingUserData', cond: (context) => context.currentState === 'fetchingUserData' }, - { target: 'error', cond: (context) => context.currentState === 'error' }, - { target: 'endFlow', cond: (context) => context.currentState === 'endFlow' } - ] + getUserQuestion: { + on: { + USER_INPUT: { + target: "checkType1", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, }, - getUserQuestion: { - on: { - USER_INPUT: { - target: 'checkType1', + }, + checkType1: { + invoke: { + src: "getInput", + onDone: [ + // { + // cond: "ifInValidScheme", + // target: "endFlow", + // actions: [ + // assign({ + // response: "Invalid Scheme, please send a valid scheme.", + // type: "pause", + // }), + // ], + // }, + { + cond: "ifAudio", + target: "confirmInput1", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - checkType1: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput1", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"questionClassifier", - actions:[ - assign({ - userQuestion: (_,event) => event.data.query, - query: (_,event) => event.data.query, - response: engMessage["label.popUpTitle"] - }) - ] - } - ], - onError: { - target: 'error', + type: "pause", + }), + ], + }, + { + cond: "ifAudio", + target: "confirmInput1", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput1:{ - on: { - USER_INPUT: { - target: 'checkType1', + type: "pause", + }), + ], + }, + { + cond: "ifAudio", + target: "confirmInput1", + actions: [ + assign({ + type: "pause", + }), + ], + }, + { + target: "questionClassifier", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + userQuestion: (_, event) => event.data.query, + query: (_, event) => event.data.query, + response: engMessage["label.popUpTitle"], + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - questionClassifier: { - invoke: { - src: "questionClassifier", - onDone: [ - { - cond: "ifConvoStarterOrEnder", - target: "endFlow", - actions: [ - assign({ - queryType: (_,event) => event.data, - response: (_,event) => event.data.response, - isWadhwaniResponse: "true" - }) - ] - }, - { - cond: "ifInvalidClassifier", - target: "endFlow", - actions: [ - assign({ - response: (_,event) => event.data.response, - isWadhwaniResponse: "true" - }) - ] - }, - { - target: 'checkIfOTPHasBeenVerified', - actions: [ - assign({ - queryType: (_,event) => event.data, - isWadhwaniResponse: "false" - }) - ] - } + }, + confirmInput1: { + on: { + USER_INPUT: { + target: "checkType1", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + questionClassifier: { + invoke: { + src: "questionClassifier", + onDone: [ + { + cond: "ifConvoStarterOrEnder", + target: "endFlow", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - wadhwaniClassifier: { - invoke: { - src: "wadhwaniClassifier", - onDone: { - target: 'endFlow', + queryType: (_, event) => event.data, + response: (_, event) => event.data.response, + isWadhwaniResponse: "true", + }), + ], + }, + { + cond: "ifInvalidClassifier", + target: "endFlow", actions: [ assign({ - response: (_, event) => event.data, - userAadhaarNumber: "", - lastAadhaarDigits: "", - isOTPVerified: false, - type: '' - }) - ] + response: (_, event) => event.data.response, + isWadhwaniResponse: "true", + }), + ], }, - onError: { - target: 'error', + { + target: "checkIfOTPHasBeenVerified", actions: [ assign({ - userAadhaarNumber: "", - lastAadhaarDigits: "", - isOTPVerified: false, - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } + queryType: (_, event) => event.data, + isWadhwaniResponse: "false", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - checkIfOTPHasBeenVerified: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifOTPHasBeenVerified", - target:"fetchingUserData" - }, - { - target:"askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle"], - type: 'pause' - }) - ] - } - ] - } + }, + wadhwaniClassifier: { + invoke: { + src: "wadhwaniClassifier", + onDone: { + target: "endFlow", + actions: [ + assign({ + response: (_, event) => event.data, + userAadhaarNumber: "", + lastAadhaarDigits: "", + isOTPVerified: false, + type: "", + }), + ], + }, + onError: { + target: "error", + actions: [ + assign({ + userAadhaarNumber: "", + lastAadhaarDigits: "", + isOTPVerified: false, + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - askingAadhaarNumber: { - on: { - USER_INPUT: { - target: 'checkType2', + }, + checkIfOTPHasBeenVerified: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifOTPHasBeenVerified", + target: "fetchingUserData", + }, + { + target: "askingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + response: () => engMessage["label.popUpTitle"], + type: "pause", + }), + ], + }, + ], }, - checkType2: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput2", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"validatingAadhaarNumber", - actions:[ - assign({ - query: (_,event) => event.data.query, - userAadhaarNumber: (_, event) => {return `${event.data.query}`}, - type:'' - }) - ] - } + }, + askingAadhaarNumber: { + on: { + USER_INPUT: { + target: "checkType2", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType2: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput2", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput2:{ - on: { - USER_INPUT: { - target: 'checkType2', + type: "pause", + }), + ], + }, + { + target: "validatingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + query: (_, event) => event.data.query, + userAadhaarNumber: (_, event) => { + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - validatingAadhaarNumber: { - invoke: { - src: 'validateAadhaarNumber', - onDone: [ - { - cond: "ifNotValidAadhaar", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifMultipleAadhaar", - target: "askLastAaadhaarDigits", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle2"], - type: 'pause' - }) - ] - }, - { - cond: "ifNoRecordsFound", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: (context) => `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingAadhaarNumber", - actions: [ - assign({ - response: () => engMessage["label.popUpTitleValid"], - userAadhaarNumber: "", - type: 'pause' - }) - ] - }, - { - cond: "ifOTPSend", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: "error", - actions: [ - assign({ - error: (_, event) => event.data, - type: '' - }) - ] - } + }, + confirmInput2: { + on: { + USER_INPUT: { + target: "checkType2", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + validatingAadhaarNumber: { + invoke: { + src: "validateAadhaarNumber", + onDone: [ + { + cond: "ifNotValidAadhaar", + target: "askingAadhaarNumber", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - askLastAaadhaarDigits:{ - on: { - USER_INPUT: { - target: 'checkType4', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifMultipleAadhaar", + target: "askLastAaadhaarDigits", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - checkType4: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput4", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - target:"validatingAadhaarNumber", - actions:[ - assign({ - query: (_,event) => event.data.query, - lastAadhaarDigits: (_context, event) => {return `${event.data.query}`}, - type:'' - }) - ] - } - ], - onError: { - target: 'error', + response: () => engMessage["label.popUpTitle2"], + type: "pause", + }), + ], + }, + { + cond: "ifNoRecordsFound", + target: "askingAadhaarNumber", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput4:{ - on: { - USER_INPUT: { - target: 'checkType4', + response: (context) => + `No records were found for ${context.userAadhaarNumber}, Please enter valid Mobile/Aadhaar/Benificiary Id again.`, + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifTryAgain", + target: "askingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } - }, - askingOTP: { - on: { - USER_INPUT: { - target: 'checkType3', + response: () => engMessage["label.popUpTitleValid"], + userAadhaarNumber: "", + type: "pause", + }), + ], + }, + { + cond: "ifOTPSend", + target: "askingOTP", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - checkType3: { - invoke: { - src: "getInput", - onDone: [ - { - cond:"ifAudio", - target: "confirmInput3", - actions: [ - assign({ - type: "pause" - }) - ] - }, - { - cond:"resendOTP", - target:"validatingAadhaarNumber", - actions: [ - assign({ - response: engMessage["label.popUpTitle3"] - }) - ] - }, - { - target:"validatingOTP", - actions:[ - assign({ - query: (_,event) => event.data.query, - otp: (_context, event) => {console.log("setting user otp"); return `${event.data.query}`}, - type:'' - }) - ] - } + }, + askLastAaadhaarDigits: { + on: { + USER_INPUT: { + target: "checkType4", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType4: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput4", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - confirmInput3:{ - on: { - USER_INPUT: { - target: 'checkType3', + type: "pause", + }), + ], + }, + { + target: "validatingAadhaarNumber", actions: [ assign({ - query: (_,event) => event.data, - response: (_,event) => event.data - }) - ] - } - } + query: (_, event) => event.data.query, + lastAadhaarDigits: (_context, event) => { + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, + }, + }, + confirmInput4: { + on: { + USER_INPUT: { + target: "checkType4", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, }, - validatingOTP: { - invoke: { - src: 'validateOTP', - onDone: [ - { - cond: "ifInvalidOTP", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["message.invalid_otp"], - type: 'pause' - }) - ] - }, - { - cond: "ifTryAgain", - target: "askingOTP", - actions: [ - assign({ - response: () => engMessage["label.popUpTitle3"], - type: 'pause' - }) - ] - }, - { - target: 'fetchingUserData', - // actions: 'updateUserAsValidated' - } + }, + askingOTP: { + on: { + USER_INPUT: { + target: "checkType3", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), ], - onError: { - target: 'error', + }, + }, + }, + checkType3: { + invoke: { + src: "getInput", + onDone: [ + { + cond: "ifAudio", + target: "confirmInput3", actions: [ assign({ - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } - }, - fetchingUserData: { - invoke: { - src: 'fetchUserData', - onDone: { - target: 'endFlow', + type: "pause", + }), + ], + }, + { + cond: "resendOTP", + target: "validatingAadhaarNumber", actions: [ assign({ - response: (_, event) => event.data, - userAadhaarNumber: "", - lastAadhaarDigits: "", - isOTPVerified: false, - type: '' - }) - ] + response: engMessage["label.popUpTitle3"], + }), + ], }, - onError: { - target: 'error', + { + target: "validatingOTP", actions: [ assign({ - userAadhaarNumber: "", - lastAadhaarDigits: "", - isOTPVerified: false, - error: (_, event) => event.data.message, - type: '' - }) - ] - } - } + query: (_, event) => event.data.query, + otp: (_context, event) => { + console.log("setting user otp"); + return `${event.data.query}`; + }, + type: "", + }), + ], + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - error: { - invoke: { - src: 'logError', - onDone: { - target: 'endFlow', + }, + confirmInput3: { + on: { + USER_INPUT: { + target: "checkType3", + actions: [ + assign({ + query: (_, event) => event.data, + response: (_, event) => event.data, + }), + ], + }, + }, + }, + validatingOTP: { + invoke: { + src: "validateOTP", + onDone: [ + { + cond: "ifInvalidOTP", + target: "askingOTP", actions: [ assign({ - userAadhaarNumber: "", - lastAadhaarDigits: "", - isOTPVerified: false, - type: '' - }) - ] - } - } + response: () => engMessage["message.invalid_otp"], + type: "pause", + }), + ], + }, + { + cond: "ifTryAgain", + target: "askingOTP", + actions: [ + assign({ + response: () => engMessage["label.popUpTitle3"], + type: "pause", + }), + ], + }, + { + target: "fetchingUserData", + // actions: 'updateUserAsValidated' + }, + ], + onError: { + target: "error", + actions: [ + assign({ + error: (_, event) => event.data.message, + type: "", + }), + ], + }, }, - endFlow: { - type: 'final' - } - } - } \ No newline at end of file + }, + fetchingUserData: { + invoke: { + src: "fetchUserData", + onDone: { + target: "endFlow", + actions: [ + assign({ + response: (_, event) => event.data, + userAadhaarNumber: "", + lastAadhaarDigits: "", + isOTPVerified: false, + type: "", + }), + ], + }, + onError: { + target: "error", + actions: [ + assign({ + userAadhaarNumber: "", + lastAadhaarDigits: "", + isOTPVerified: false, + error: (_, event) => event.data.message, + type: "", + }), + ], + }, + }, + }, + error: { + invoke: { + src: "logError", + onDone: { + target: "endFlow", + actions: [ + assign({ + userAadhaarNumber: "", + lastAadhaarDigits: "", + isOTPVerified: false, + type: "", + }), + ], + }, + }, + }, + endFlow: { + type: "final", + }, + }, +}; diff --git a/src/xstate/prompt/prompt.service.ts b/src/xstate/prompt/prompt.service.ts index 418912f..6dad23e 100644 --- a/src/xstate/prompt/prompt.service.ts +++ b/src/xstate/prompt/prompt.service.ts @@ -6,36 +6,44 @@ import axios from "axios"; import { decryptRequest, encryptRequest, titleCase } from "../../common/utils"; import { PrismaService } from "src/global-services/prisma.service"; import { Injectable } from "@nestjs/common"; -import { botFlowMachine1, botFlowMachine2, botFlowMachine3 } from "./prompt.machine"; +import { + botFlowMachine1, + botFlowMachine2, + botFlowMachine3, +} from "./prompt.machine"; import { createMachine } from "xstate"; import { promptActions } from "./prompt.actions"; import { promptGuards } from "./prompt.gaurds"; import { MonitoringService } from "src/modules/monitoring/monitoring.service"; -const path = require('path'); -const filePath = path.resolve(__dirname, '../../common/kisanPortalErrors.json'); +const path = require("path"); +const filePath = path.resolve(__dirname, "../../common/kisanPortalErrors.json"); const PMKissanProtalErrors = require(filePath); import * as moment from "moment"; @Injectable() export class PromptServices { - private userService: UserService; - constructor( - private prismaService: PrismaService, - private configService: ConfigService, - private aiToolsService: AiToolsService, - private monitoringService: MonitoringService - ){ - this.userService = new UserService(this.prismaService, this.configService, this.monitoringService) - } + private userService: UserService; + constructor( + private prismaService: PrismaService, + private configService: ConfigService, + private aiToolsService: AiToolsService, + private monitoringService: MonitoringService + ) { + this.userService = new UserService( + this.prismaService, + this.configService, + this.monitoringService + ); + } - async getInput (context) { - return context - } + async getInput(context) { + return context; + } async questionClassifier (context) { // console.log("IN questionclassifier") try{ - let response: any = await this.aiToolsService.getResponseViaWadhwani(context.sessionId, context.userId, context.query) + let response: any = await this.aiToolsService.getResponseViaWadhwani(context.sessionId, context.userId, context.query, context.schemeName) if (response.error) throw new Error(`${response.error}, please try again.`) // { // "user_id": "19877818", @@ -62,215 +70,276 @@ export class PromptServices { } } - async logError (_, event) { - console.log("logError") - console.log(event.data) - return event.data - } + async logError(_, event) { + console.log("logError"); + console.log(event.data); + return event.data; + } - async validateAadhaarNumber (context, event) { - console.log("validate aadhar") - try{ - const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; - let res; - if(/^[6-9]\d{9}$/.test(userIdentifier)) { - this.monitoringService.incrementMobileNumberCount() - res = await this.userService.sendOTP(userIdentifier,"Mobile") - } else if(userIdentifier.length==14 && /^[6-9]\d{9}$/.test(userIdentifier.substring(0,10))){ - res = await this.userService.sendOTP(userIdentifier,"MobileAadhar") - } else if(userIdentifier.length==12 && /^\d+$/.test(userIdentifier)){ - this.monitoringService.incrementAadhaarCount() - res = await this.userService.sendOTP(userIdentifier,"Aadhar") - } else if(userIdentifier.length == 11) { - this.monitoringService.incrementRegistrationIdCount() - res = await this.userService.sendOTP(userIdentifier,"Ben_id") - } else { - return Promise.resolve('Please enter a valid Beneficiary ID/Aadhaar Number/Phone number'); - } - if(res) { - if(res.d.output.Message == `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.`){ - this.monitoringService.incrementNoUserRecordsFoundCount() - } - return Promise.resolve(res.d.output.Message); - } - this.monitoringService.incrementSomethingWentWrongCount() - throw new Error('Something went wrong.') - } catch (error) { - console.log(error) - return Promise.reject(new Error('Something went wrong.')) + async validateAadhaarNumber(context, event) { + console.log("validate aadhar"); + try { + const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; + let res; + if (/^[6-9]\d{9}$/.test(userIdentifier)) { + this.monitoringService.incrementMobileNumberCount(); + res = await this.userService.sendOTP(userIdentifier, "Mobile"); + } else if ( + userIdentifier.length == 14 && + /^[6-9]\d{9}$/.test(userIdentifier.substring(0, 10)) + ) { + res = await this.userService.sendOTP(userIdentifier, "MobileAadhar"); + } else if (userIdentifier.length == 12 && /^\d+$/.test(userIdentifier)) { + this.monitoringService.incrementAadhaarCount(); + res = await this.userService.sendOTP(userIdentifier, "Aadhar"); + } else if (userIdentifier.length == 11) { + this.monitoringService.incrementRegistrationIdCount(); + res = await this.userService.sendOTP(userIdentifier, "Ben_id"); + } else { + return Promise.resolve( + "Please enter a valid Beneficiary ID/Aadhaar Number/Phone number" + ); + } + if (res) { + if ( + res.d.output.Message == + `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.` + ) { + this.monitoringService.incrementNoUserRecordsFoundCount(); } - + return Promise.resolve(res.d.output.Message); + } + this.monitoringService.incrementSomethingWentWrongCount(); + throw new Error("Something went wrong."); + } catch (error) { + console.log(error); + return Promise.reject(new Error("Something went wrong.")); } + } - async validateOTP (context, event) { - console.log("Validate OTP") - const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; - const otp = context.otp; - let res; - // Perform OTP validation logic here - if(/^[6-9]\d{9}$/.test(userIdentifier)) { - res = await this.userService.verifyOTP(userIdentifier,otp,"Mobile") - } else if(userIdentifier.length==14 && /^[6-9]\d{9}$/.test(userIdentifier.substring(0,10))){ - res = await this.userService.verifyOTP(userIdentifier,otp,"MobileAadhar") - } else if(userIdentifier.length==12 && /^\d+$/.test(userIdentifier)){ - res = await this.userService.verifyOTP(userIdentifier,otp,"Aadhar") - } else if(userIdentifier.length == 11) { - res = await this.userService.verifyOTP(userIdentifier,otp,"Ben_id") - } else { - return Promise.reject(new Error('Something went wrong, Please try again by asking your question.')); - } - if(res){ - return Promise.resolve(res.d.output.Message); - } else { - return Promise.reject(new Error('Something went wrong, Please try again by asking your question.')); - } + async validateOTP(context, event) { + console.log("Validate OTP"); + const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; + const otp = context.otp; + let res; + // Perform OTP validation logic here + if (/^[6-9]\d{9}$/.test(userIdentifier)) { + res = await this.userService.verifyOTP(userIdentifier, otp, "Mobile"); + } else if ( + userIdentifier.length == 14 && + /^[6-9]\d{9}$/.test(userIdentifier.substring(0, 10)) + ) { + res = await this.userService.verifyOTP( + userIdentifier, + otp, + "MobileAadhar" + ); + } else if (userIdentifier.length == 12 && /^\d+$/.test(userIdentifier)) { + res = await this.userService.verifyOTP(userIdentifier, otp, "Aadhar"); + } else if (userIdentifier.length == 11) { + res = await this.userService.verifyOTP(userIdentifier, otp, "Ben_id"); + } else { + return Promise.reject( + new Error( + "Something went wrong, Please try again by asking your question." + ) + ); } + if (res) { + return Promise.resolve(res.d.output.Message); + } else { + return Promise.reject( + new Error( + "Something went wrong, Please try again by asking your question." + ) + ); + } + } - async fetchUserData (context, event) { - console.log("Fetch user data"); - const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; - let res; - let type='Mobile' - if(/^[6-9]\d{9}$/.test(userIdentifier)) { - type='Mobile' - res = await this.userService.getUserData(userIdentifier,"Mobile") - } else if(userIdentifier.length==14 && /^[6-9]\d{9}$/.test(userIdentifier.substring(0,10))){ - type='MobileAadhar' - res = await this.userService.getUserData(userIdentifier,"MobileAadhar") - } else if(userIdentifier.length==12 && /^\d+$/.test(userIdentifier)){ - type = "Aadhar" - res = await this.userService.getUserData(userIdentifier,"Aadhar") - } else if(userIdentifier.length == 11) { - type = "Ben_id" - res = await this.userService.getUserData(userIdentifier,"Ben_id") - }else { - return Promise.reject(new Error('Please enter a valid Beneficiary ID/Aadhaar Number/Phone number')); - } - if(res.d.output.Message=='Unable to get user details'){ - return Promise.reject(new Error(res.d.output.Message)) - } - let userDetails = AADHAAR_GREETING_MESSAGE( - titleCase(res.d.output['BeneficiaryName']), - titleCase(res.d.output['FatherName']), - res.d.output['DOB'], - res.d.output['Address'], - res.d.output['DateOfRegistration'], - res.d.output['LatestInstallmentPaid'], - res.d.output['Reg_No'], - titleCase(res.d.output['StateName']), - titleCase(res.d.output['DistrictName']), - titleCase(res.d.output['SubDistrictName']), - titleCase(res.d.output['VillageName']), - res.d.output['eKYC_Status'] + async fetchUserData(context, event) { + console.log("Fetch user data"); + const userIdentifier = `${context.userAadhaarNumber}${context.lastAadhaarDigits}`; + let res; + let type = "Mobile"; + if (/^[6-9]\d{9}$/.test(userIdentifier)) { + type = "Mobile"; + res = await this.userService.getUserData(userIdentifier, "Mobile"); + } else if ( + userIdentifier.length == 14 && + /^[6-9]\d{9}$/.test(userIdentifier.substring(0, 10)) + ) { + type = "MobileAadhar"; + res = await this.userService.getUserData(userIdentifier, "MobileAadhar"); + } else if (userIdentifier.length == 12 && /^\d+$/.test(userIdentifier)) { + type = "Aadhar"; + res = await this.userService.getUserData(userIdentifier, "Aadhar"); + } else if (userIdentifier.length == 11) { + type = "Ben_id"; + res = await this.userService.getUserData(userIdentifier, "Ben_id"); + } else { + return Promise.reject( + new Error( + "Please enter a valid Beneficiary ID/Aadhaar Number/Phone number" ) + ); + } + if (res.d.output.Message == "Unable to get user details") { + return Promise.reject(new Error(res.d.output.Message)); + } + let userDetails = AADHAAR_GREETING_MESSAGE( + titleCase(res.d.output["BeneficiaryName"]), + titleCase(res.d.output["FatherName"]), + res.d.output["DOB"], + res.d.output["Address"], + res.d.output["DateOfRegistration"], + res.d.output["LatestInstallmentPaid"], + res.d.output["Reg_No"], + titleCase(res.d.output["StateName"]), + titleCase(res.d.output["DistrictName"]), + titleCase(res.d.output["SubDistrictName"]), + titleCase(res.d.output["VillageName"]), + res.d.output["eKYC_Status"] + ); - console.log("ChatbotBeneficiaryStatus") - console.log("using...",userIdentifier, type) - let userErrors = []; - try { - let encryptedData = await encryptRequest(`{\"Types\":\"${type}",\"Values\":\"${userIdentifier}\",\"Token\":\"${this.configService.get("PM_KISSAN_TOKEN")}\"}`) - let data = JSON.stringify({ - "EncryptedRequest": `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}` - }); - console.log("body", data) - - let config = { - method: 'post', - maxBodyLength: Infinity, - url: `${this.configService.get("PM_KISAN_BASE_URL")}/ChatbotBeneficiaryStatus`, - headers: { - 'Content-Type': 'application/json' - }, - data : data - }; + console.log("ChatbotBeneficiaryStatus"); + console.log("using...", userIdentifier, type); + let userErrors = []; + try { + let encryptedData = await encryptRequest( + `{\"Types\":\"${type}",\"Values\":\"${userIdentifier}\",\"Token\":\"${this.configService.get( + "PM_KISSAN_TOKEN" + )}\"}` + ); + let data = JSON.stringify({ + EncryptedRequest: `${encryptedData.d.encryptedvalu}@${encryptedData.d.token}`, + }); + console.log("body", data); - let errors: any = await axios.request(config) - errors = await errors.data - console.log("related issues",errors) - let decryptedData: any = await decryptRequest(errors.d.output,encryptedData.d.token) - errors = JSON.parse(decryptedData.d.decryptedvalue) - if(errors.Rsponce == "True"){ - Object.entries(errors).forEach(([key, value]) => { - if(key!="Rsponce" && key != "Message"){ - if(value && PMKissanProtalErrors[`${value}`] && PMKissanProtalErrors[`${value}`]["types"].indexOf(context.queryType)!=-1){ - console.log(`ERRORVALUE: ${key} ${value}`); - userErrors.push(PMKissanProtalErrors[`${value}`]["text"].replace('{{farmer_name}}',titleCase(res.d.output['BeneficiaryName']))) - } + let config = { + method: "post", + maxBodyLength: Infinity, + url: `${this.configService.get( + "PM_KISAN_BASE_URL" + )}/ChatbotBeneficiaryStatus`, + headers: { + "Content-Type": "application/json", + }, + data: data, + }; + + let errors: any = await axios.request(config); + errors = await errors.data; + console.log("related issues", errors); + let decryptedData: any = await decryptRequest( + errors.d.output, + encryptedData.d.token + ); + errors = JSON.parse(decryptedData.d.decryptedvalue); + if (errors.Rsponce == "True") { + Object.entries(errors).forEach(([key, value]) => { + if (key != "Rsponce" && key != "Message") { + if ( + value && + PMKissanProtalErrors[`${value}`] && + PMKissanProtalErrors[`${value}`]["types"].indexOf( + context.queryType + ) != -1 + ) { + console.log(`ERRORVALUE: ${key} ${value}`); + userErrors.push( + PMKissanProtalErrors[`${value}`]["text"].replace( + "{{farmer_name}}", + titleCase(res.d.output["BeneficiaryName"]) + ) + ); } - }); - } - if(!userErrors.length){ - userErrors.push(PMKissanProtalErrors["No Errors"]["text"] - .replace('{{farmer_name}}',titleCase(res.d.output['BeneficiaryName'])) - .replace('{{latest_installment_paid}}',res.d.output['LatestInstallmentPaid']) - .replace('{{Reg_Date (DD-MM-YYYY)}}', moment(res.d.output['DateOfRegistration']).format('DD-MM-YYYY')) + } + }); + } + if (!userErrors.length) { + userErrors.push( + PMKissanProtalErrors["No Errors"]["text"] + .replace( + "{{farmer_name}}", + titleCase(res.d.output["BeneficiaryName"]) ) - } - } catch (error) { - console.log("ChatbotBeneficiaryStatus error") - console.log(error) - } - return `${userDetails}${userErrors.join("\n")}` + .replace( + "{{latest_installment_paid}}", + res.d.output["LatestInstallmentPaid"] + ) + .replace( + "{{Reg_Date (DD-MM-YYYY)}}", + moment(res.d.output["DateOfRegistration"]).format("DD-MM-YYYY") + ) + ); + } + } catch (error) { + console.log("ChatbotBeneficiaryStatus error"); + console.log(error); } + return `${userDetails}${userErrors.join("\n")}`; + } - async wadhwaniClassifier (context) { - console.log("Wadhwani Classifierrr") - try{ - let response: any = await this.aiToolsService.getResponseViaWadhwani(context.sessionId, context.userId,context.query) - if (response.error) throw new Error(`${response.error}, please try again.`) - return response; - } catch (error){ - return Promise.reject(error) - } + async wadhwaniClassifier(context) { + console.log("Wadhwani Classifierrr"); + try { + let response: any = await this.aiToolsService.getResponseViaWadhwani( + context.sessionId, + context.userId, + context.query, + context.schemeName + ); + if (response.error) + throw new Error(`${response.error}, please try again.`); + return response; + } catch (error) { + return Promise.reject(error); } + } - allFunctions() { - return { - getInput: this.getInput.bind(this), - questionClassifier: this.questionClassifier.bind(this), - logError: this.logError.bind(this), - validateAadhaarNumber: this.validateAadhaarNumber.bind(this), - validateOTP: this.validateOTP.bind(this), - fetchUserData: this.fetchUserData.bind(this), - wadhwaniClassifier: this.wadhwaniClassifier.bind(this), - } - } + allFunctions() { + return { + getInput: this.getInput.bind(this), + questionClassifier: this.questionClassifier.bind(this), + logError: this.logError.bind(this), + validateAadhaarNumber: this.validateAadhaarNumber.bind(this), + validateOTP: this.validateOTP.bind(this), + fetchUserData: this.fetchUserData.bind(this), + wadhwaniClassifier: this.wadhwaniClassifier.bind(this), + }; + } - getXstateMachine(name:string){ - let machine - switch(name){ - case "botFlowMachine1": - machine = createMachine( - botFlowMachine1,{ - actions: promptActions, - services: this.allFunctions(), - guards: promptGuards - }) - break - case "botFlowMachine2": - machine = createMachine( - botFlowMachine2,{ - actions: promptActions, - services: this.allFunctions(), - guards: promptGuards - }) - break - case "botFlowMachine3": - machine = createMachine( - botFlowMachine3,{ - actions: promptActions, - services: this.allFunctions(), - guards: promptGuards - }) - break - default: - machine = createMachine( - botFlowMachine3,{ - actions: promptActions, - services: this.allFunctions(), - guards: promptGuards - }) - } - return machine + getXstateMachine(name: string) { + let machine; + switch (name) { + case "botFlowMachine1": + machine = createMachine(botFlowMachine1, { + actions: promptActions, + services: this.allFunctions(), + guards: promptGuards, + }); + break; + case "botFlowMachine2": + machine = createMachine(botFlowMachine2, { + actions: promptActions, + services: this.allFunctions(), + guards: promptGuards, + }); + break; + case "botFlowMachine3": + machine = createMachine(botFlowMachine3, { + actions: promptActions, + services: this.allFunctions(), + guards: promptGuards, + }); + break; + default: + machine = createMachine(botFlowMachine3, { + actions: promptActions, + services: this.allFunctions(), + guards: promptGuards, + }); } -} \ No newline at end of file + return machine; + } +} diff --git a/src/xstate/prompt/prompt.utils.ts b/src/xstate/prompt/prompt.utils.ts new file mode 100644 index 0000000..7e04baf --- /dev/null +++ b/src/xstate/prompt/prompt.utils.ts @@ -0,0 +1 @@ +const VALID_SCHEMES = ["PM Kisan", "Kisan Credit Card", "PM Fasal Bima Yojana"]; From 146f68bce42b5cd5e3b65378e0aa5576d2000c8f Mon Sep 17 00:00:00 2001 From: Yash Mittal Date: Thu, 13 Jun 2024 12:15:00 +0530 Subject: [PATCH 2/8] fix: default scheme to be PM Kisan --- README.md | 5 +++++ src/app.controller.ts | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f945858..5c0ea10 100644 --- a/README.md +++ b/README.md @@ -46,3 +46,8 @@ BFF aims to simplify the development process by providing a robust and extensibl ### Deployment - [Deployment steps](https://github.com/AgrI-Mitra/docs/blob/main/deployment.md) + +along with all existing params only 1 additional param: scheme_name +Possiible scheme names: ['PM Kisan', 'Kisan Credit Card', 'PM Fasal Bima Yojana'] ==> scheme names that are displayed on the top right corner of the chatbot. + +Once the Backend team starts sending scheme_name to WAI API, send only the original user query. Don't append it by the scheme name that we were doing till now. \ No newline at end of file diff --git a/src/app.controller.ts b/src/app.controller.ts index ff64e1a..8dc1d51 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -221,7 +221,10 @@ export class AppController { lastAadhaarDigits: "", state: "onGoing", isOTPVerified: false, - schemeName: promptDto.schemeName, + schemeName: + promptDto.schemeName && promptDto.schemeName.trim() !== "" + ? promptDto.schemeName + : "PM Kisan", }; let conversation = await this.conversationService.getConversationState( From 56162778d53ddcfd90ac820d81d03a58c61e7daa Mon Sep 17 00:00:00 2001 From: Yash Mittal Date: Thu, 13 Jun 2024 17:50:19 +0530 Subject: [PATCH 3/8] fix: guards on decryption --- src/xstate/prompt/prompt.gaurds.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/xstate/prompt/prompt.gaurds.ts b/src/xstate/prompt/prompt.gaurds.ts index ca11193..6d09e64 100644 --- a/src/xstate/prompt/prompt.gaurds.ts +++ b/src/xstate/prompt/prompt.gaurds.ts @@ -6,12 +6,20 @@ export const promptGuards = { ifMultipleAadhaar: (_, event) => event.data == "This mobile number taged with multiple records.", - ifInValidScheme: (_, event) => - !VALID_SCHEMES.includes(event.data.prompt.input.schemeName), - - ifNoRecordsFound: (context, event) => - event.data == - `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.`, + // ifInValidScheme: (_, event) => + // !VALID_SCHEMES.includes(event.data.prompt.input.schemeName), + + ifNoRecordsFound: (context, event) => { + const pattern = + /No Record Found for this \((.*?)\) Aadhar\/Ben_id\/Mobile\./; + return ( + pattern.test(event.data) || + ((event.data as string).startsWith("No Record Found for this") && + (event.data as string).endsWith("Aadhar/Ben_id/Mobile.")) + ); + }, + // event.data == + // `No Record Found for this (${context.userAadhaarNumber}) Aadhar/Ben_id/Mobile.`, ifOTPSend: (_, event) => event.data == "OTP send successfully!", From ae04331f236c041691426ccf07107d8eca403b5a Mon Sep 17 00:00:00 2001 From: AmruthVamshi Date: Tue, 3 Sep 2024 11:18:49 +0530 Subject: [PATCH 4/8] Added genderAudio parameter --- src/app.controller.ts | 6 +++--- src/modules/aiTools/ai-tools.service.ts | 6 +++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/app.controller.ts b/src/app.controller.ts index 8dc1d51..548384b 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -224,7 +224,7 @@ export class AppController { schemeName: promptDto.schemeName && promptDto.schemeName.trim() !== "" ? promptDto.schemeName - : "PM Kisan", + : "All Schemes", }; let conversation = await this.conversationService.getConversationState( @@ -485,7 +485,7 @@ export class AppController { textInEnglish: "", error: null } - res['audio'] = await this.aiToolsService.textToSpeech(res.text,prompt.inputLanguage,userId,sessionId) + res['audio'] = await this.aiToolsService.textToSpeech(res.text,prompt.inputLanguage,promptDto.audioGender,userId,sessionId) if(res['audio']['error']){ await this.telemetryService.capture({ eventName: "Text to speech error", @@ -1121,7 +1121,7 @@ export class AppController { // verboseLogger("textToaudio =",textToaudio) let audioStartTime = Date.now(); textToaudio = removeLinks(textToaudio) - result['audio'] = await this.aiToolsService.textToSpeech(textToaudio,isNumber ? Language.en : prompt.inputLanguage,userId,sessionId) + result['audio'] = await this.aiToolsService.textToSpeech(textToaudio,isNumber ? Language.en : prompt.inputLanguage,promptDto.audioGenderuserId,sessionId) if(result['audio']['error']){ await this.telemetryService.capture({ eventName: "Text to speech error", diff --git a/src/modules/aiTools/ai-tools.service.ts b/src/modules/aiTools/ai-tools.service.ts index 91efee7..e08cd0d 100644 --- a/src/modules/aiTools/ai-tools.service.ts +++ b/src/modules/aiTools/ai-tools.service.ts @@ -193,6 +193,7 @@ export class AiToolsService { async textToSpeech( text: string, language: Language, + audioGender: string = 'male', userId: string, sessionId: string ) { @@ -212,6 +213,7 @@ export class AiToolsService { language: { sourceLanguage: language, }, + gender: audioGender }, { input: [ @@ -387,7 +389,9 @@ export class AiToolsService { myHeaders.append("Content-Type", "application/json"); config["serviceId"] = serviceId; if (task == "tts") { - config["gender"] = "male"; + if(!config["gender"]){ + config["gender"] = "male"; + } config["samplingRate"] = 8000; } var raw = JSON.stringify({ From a5c32b84f40a63bb9f6bc233c2ed78c254ff7d2f Mon Sep 17 00:00:00 2001 From: Amruth-Vamshi <130033232+Amruth-Vamshi@users.noreply.github.com> Date: Tue, 3 Sep 2024 11:20:00 +0530 Subject: [PATCH 5/8] Added genderAudio parameter (#30) --- src/app.controller.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/app.controller.ts b/src/app.controller.ts index 548384b..7e6d466 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -1121,7 +1121,7 @@ export class AppController { // verboseLogger("textToaudio =",textToaudio) let audioStartTime = Date.now(); textToaudio = removeLinks(textToaudio) - result['audio'] = await this.aiToolsService.textToSpeech(textToaudio,isNumber ? Language.en : prompt.inputLanguage,promptDto.audioGenderuserId,sessionId) + result['audio'] = await this.aiToolsService.textToSpeech(textToaudio,isNumber ? Language.en : prompt.inputLanguage,promptDto.audioGender,userId,sessionId) if(result['audio']['error']){ await this.telemetryService.capture({ eventName: "Text to speech error", From 14c975a54ae10efdb12400a4e6184558c070a07c Mon Sep 17 00:00:00 2001 From: AmruthVamshi Date: Tue, 26 Nov 2024 14:31:16 +0530 Subject: [PATCH 6/8] Updated STT processor function to check for valid identifier. --- src/app.controller.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/app.controller.ts b/src/app.controller.ts index 7e6d466..365ed0d 100644 --- a/src/app.controller.ts +++ b/src/app.controller.ts @@ -722,11 +722,20 @@ export class AppController { prompt.inputTextInEnglish, isOTP ? "otp" : "benId" ); + if ( + ((/^[6-9]\d{9}$/.test(number)) || + (number.length == 14 && /^[6-9]\d{9}$/.test(number.substring(0, 10))) || + (number.length == 12 && /^\d+$/.test(number)) || + (number.length == 11)) || + (isOTP && number.length==4) + ) { + prompt.inputTextInEnglish = number.toUpperCase(); + if (prompt.inputTextInEnglish == "") + prompt.inputTextInEnglish = isOTP ? "1111" : "AB123123123"; + isNumber = true; + } // let number = prompt.inputTextInEnglish.replace(/\s/g, '') - prompt.inputTextInEnglish = number.toUpperCase(); - if (prompt.inputTextInEnglish == "") - prompt.inputTextInEnglish = isOTP ? "1111" : "AB123123123"; - isNumber = true; + // if(/\d/.test(number)){ // isNumber = true // prompt.inputTextInEnglish = number.toUpperCase() From 645b4875f0c2ae88958503e737948e7e57795266 Mon Sep 17 00:00:00 2001 From: AmruthVamshi Date: Tue, 26 Nov 2024 15:19:13 +0530 Subject: [PATCH 7/8] added bhashini time out variable --- src/modules/aiTools/ai-tools.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/modules/aiTools/ai-tools.service.ts b/src/modules/aiTools/ai-tools.service.ts index e08cd0d..73b2e88 100644 --- a/src/modules/aiTools/ai-tools.service.ts +++ b/src/modules/aiTools/ai-tools.service.ts @@ -343,7 +343,7 @@ export class AiToolsService { userId, sessionId, callback: null, - timeout: 30000 + timeout: this.configService.get("BHASHINI_API_TIMEOUT") || 30000 }; requestOptions.callback = function (retry) { @@ -417,7 +417,7 @@ export class AiToolsService { userId, sessionId, callback: null, - timeout: 30000 + timeout: this.configService.get("BHASHINI_API_TIMEOUT") || 30000 }; requestOptions.callback = function (retry) { From 8ad73114dd84910e3a0a69d39dc5f83189712414 Mon Sep 17 00:00:00 2001 From: AmruthVamshi Date: Thu, 28 Nov 2024 14:11:25 +0530 Subject: [PATCH 8/8] Sending schemeName to WAI --- src/modules/aiTools/ai-tools.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/modules/aiTools/ai-tools.service.ts b/src/modules/aiTools/ai-tools.service.ts index 73b2e88..60a84fb 100644 --- a/src/modules/aiTools/ai-tools.service.ts +++ b/src/modules/aiTools/ai-tools.service.ts @@ -289,8 +289,8 @@ export class AiToolsService { myHeaders.append("accept", "application/json"); myHeaders.append("X-API-Key", this.configService.get("WADHWANI_API_KEY")); let startDate = new Date(); - console.log(`${startDate}: userId: ${userId} sessionId: ${sessionId} Waiting for ${this.configService.get("WADHWANI_BASE_URL")}/get_bot_response?query=${text}&user_id=${userId}&session_id=${sessionId} to respond ...`) - let response: any = await fetch(`${this.configService.get("WADHWANI_BASE_URL")}/get_bot_response?query=${text}&user_id=${userId}&session_id=${sessionId}`, { + console.log(`${startDate}: userId: ${userId} sessionId: ${sessionId} Waiting for ${this.configService.get("WADHWANI_BASE_URL")}/get_bot_response?query=${text}&user_id=${userId}&session_id=${sessionId}&scheme_name=${schemeName} to respond ...`) + let response: any = await fetch(`${this.configService.get("WADHWANI_BASE_URL")}/get_bot_response?query=${text}&user_id=${userId}&session_id=${sessionId}&scheme_name=${schemeName}`, { headers: myHeaders, "method": "GET", "mode": "cors",