From 2c9ae18a363089351d855bd090f0a075e5dcc1a1 Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 27 Apr 2023 10:18:27 -0300 Subject: [PATCH] =?UTF-8?q?Vers=C3=A3o=20com=20ajustes=20para=20producao?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/BotIsOnQueue.ts | 36 ++-- backend/src/models/Contact.ts | 4 + .../ContactServices/CreateContactService.ts | 2 +- .../CreateSessionDialogflow.ts | 5 + .../FindOrCreateTicketService.ts | 2 +- .../WbotServices/wbotMessageListener.ts | 154 ++++++++++++------ 6 files changed, 139 insertions(+), 64 deletions(-) diff --git a/backend/src/helpers/BotIsOnQueue.ts b/backend/src/helpers/BotIsOnQueue.ts index 4a531f9..82d1351 100644 --- a/backend/src/helpers/BotIsOnQueue.ts +++ b/backend/src/helpers/BotIsOnQueue.ts @@ -3,9 +3,13 @@ import dir from 'path'; import fs from 'fs'; import os from 'os'; -import ListUsersService from "../services/UserServices/ListUsersService" +import ListUsersService from "../services/UserServices/ListUsersService" -const _botIsOnQueue = async (botName: string) => { +const _botIsOnQueue = async (botName: string, accept: boolean = true) => { + + if (!accept) { + return { isOnQueue: false } + } const botInfoFile = dir.join(os.tmpdir(), `botInfo.json`); @@ -17,20 +21,20 @@ const _botIsOnQueue = async (botName: string) => { if (fs.existsSync(botInfoFile)) { console.log('botInfo.json file exists'); - - const botInfo = fs.readFileSync(botInfoFile, {encoding:'utf8', flag:'r'}); - + + const botInfo = fs.readFileSync(botInfoFile, { encoding: 'utf8', flag: 'r' }); + return JSON.parse(botInfo) - + } else { console.log('botInfo.json file not found!'); - } - - + } + + } catch (error) { - console.log('There was an error on try to read the botInfo.json file: ',error) - } - + console.log('There was an error on try to read the botInfo.json file: ', error) + } + const { users, count, hasMore } = await ListUsersService({ searchParam: `${botName}`, pageNumber: 1 }); let botIsOnQueue = false @@ -44,21 +48,21 @@ const _botIsOnQueue = async (botName: string) => { console.log('----------------- bot queue id: ', Object(users)[0]["queues"][0].id) queueId = Object(users)[0]["queues"][0].id; userIdBot = Object(users)[0].id - botIsOnQueue = true + botIsOnQueue = true - fs.writeFileSync(botInfoFile, JSON.stringify({ userIdBot: userIdBot, botQueueId: queueId, isOnQueue: botIsOnQueue }), "utf8"); + fs.writeFileSync(botInfoFile, JSON.stringify({ userIdBot: userIdBot, botQueueId: queueId, isOnQueue: botIsOnQueue }), "utf8"); } catch (err) { console.log('O usuário botqueue não está em nenhuma fila err: ', err) - } + } } else { console.log('Usuário botqueue não existe!') - fs.writeFileSync(botInfoFile, JSON.stringify({ isOnQueue: false, botQueueId: 0, userIdBot: 0 }), "utf8"); + fs.writeFileSync(botInfoFile, JSON.stringify({ isOnQueue: false, botQueueId: 0, userIdBot: 0 }), "utf8"); } diff --git a/backend/src/models/Contact.ts b/backend/src/models/Contact.ts index d2c399e..6892f10 100644 --- a/backend/src/models/Contact.ts +++ b/backend/src/models/Contact.ts @@ -49,6 +49,10 @@ class Contact extends Model { @Column useDialogflow: boolean; + @Default(false) + @Column + accept: boolean; + @CreatedAt createdAt: Date; diff --git a/backend/src/services/ContactServices/CreateContactService.ts b/backend/src/services/ContactServices/CreateContactService.ts index 81a01b9..77f786e 100644 --- a/backend/src/services/ContactServices/CreateContactService.ts +++ b/backend/src/services/ContactServices/CreateContactService.ts @@ -43,7 +43,7 @@ const CreateContactService = async ({ name, number, email, - useDialogflow, + useDialogflow, profilePicUrl, extraInfo }, diff --git a/backend/src/services/DialogflowServices/CreateSessionDialogflow.ts b/backend/src/services/DialogflowServices/CreateSessionDialogflow.ts index 2457b84..4b26ddd 100644 --- a/backend/src/services/DialogflowServices/CreateSessionDialogflow.ts +++ b/backend/src/services/DialogflowServices/CreateSessionDialogflow.ts @@ -8,6 +8,7 @@ import { logger } from "../../utils/logger"; const sessions : Map = new Map(); const createDialogflowSession = async (id:number, projectName:string, jsonContent:string) : Promise => { + if(sessions.has(id)) { return sessions.get(id); } @@ -25,8 +26,12 @@ const createDialogflowSession = async (id:number, projectName:string, jsonConten return session; } + const createDialogflowSessionWithModel = async (model: Dialogflow) : Promise => { + + // console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 0004: ',model) + return createDialogflowSession(model.id, model.projectName, model.jsonContent); } diff --git a/backend/src/services/TicketServices/FindOrCreateTicketService.ts b/backend/src/services/TicketServices/FindOrCreateTicketService.ts index 0eeb67e..3e5126c 100644 --- a/backend/src/services/TicketServices/FindOrCreateTicketService.ts +++ b/backend/src/services/TicketServices/FindOrCreateTicketService.ts @@ -30,7 +30,7 @@ const FindOrCreateTicketService = async ( //Habilitar esse caso queira usar o bot - const botInfo = await BotIsOnQueue('botqueue') + const botInfo = await BotIsOnQueue('botqueue', contact.accept) // const botInfo = { isOnQueue: false } diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 30248e6..0253fb2 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -96,6 +96,8 @@ const verifyContact = async (msgContact: any): Promise => { const contact = CreateOrUpdateContactService(contactData); + // console.log('----------> contact: ', JSON.parse(JSON.stringify(contact))) + return contact; }; @@ -520,17 +522,17 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta console.log('>>>>>>>>>>>>>>> msgAction: ', msgAction, ' | msgAction.actions[1]: ', msgAction.actions[1]) - const contact_custom_field = await ShowContactCustomFieldService(contact.id) + // const contact_custom_field = await ShowContactCustomFieldService(contact.id) - if (contact_custom_field && contact_custom_field.length > 0) { + // if (contact_custom_field && contact_custom_field.length > 0) { - const msg_endpoint = await queryEndPointHit(contact_custom_field[0].value) + // const msg_endpoint = await queryEndPointHit(contact_custom_field[0].value) - await monitoramento_response2(msg_endpoint, wbot, contact, ticket, contact_custom_field[0].value) + // await monitoramento_response2(msg_endpoint, wbot, contact, ticket, contact_custom_field[0].value) - } + // } - console.log('************* contact_custom_field: ', contact_custom_field) + // console.log('************* contact_custom_field: ', contact_custom_field) // OLD // const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); @@ -551,7 +553,7 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta // await new Promise(f => setTimeout(f, 1000)); // // NEW - await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) + await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) await botSendMedia(ticket, contact, wbot, sourcePath, msgAction.actions[1]) @@ -595,33 +597,39 @@ const sendDialogflowAwswer = async ( ticket: Ticket, msg: any, contact: Contact, - chat: Chat + chat: Chat, + startDialog: boolean = false ) => { + + if (startDialog) + msg.body = 'menu' + + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 04') + const session = await createDialogflowSessionWithModel(ticket.queue.dialogflow); if (session === undefined) { return; } // Make disponible later from session out - // wbot.sendPresenceAvailable(); - - // console.log('typeof(msg.type): ', typeof (msg.type), ' | msg.type: ', msg.type) - - - // console.log('KKKKKKKKK msg: ', msg) - // console.log('KKKKKKKKK msg2: ', msg['body']) + // wbot.sendPresenceAvailable(); + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 4') if (msg.type != 'chat') { botSendMessage(ticket, contact, wbot, `Desculpe, nao compreendi!\nEnvie apenas texto quando estiver interagindo com o bot!\n _Digite *0* para voltar ao menu principal._`) return } + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 5') + if (msg.type == 'chat' && String(msg.body).length > 120) { botSendMessage(ticket, contact, wbot, `Desculpe, nao compreendi!\nTexto acima de 120 caracteres!\n _Digite *0* para voltar ao menu principal._`) return } + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 6') + let dialogFlowReply = await queryDialogFlow( session, ticket.queue.dialogflow.projectName, @@ -668,15 +676,16 @@ const verifyQueue = async ( let choosenQueue = null //Habilitar esse caso queira usar o bot - const botInfo = await BotIsOnQueue('botqueue') + let botInfo = await BotIsOnQueue('botqueue', contact.accept) // const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 } + console.log('::::::::::::> contact.accept: ', contact.accept) + if (botInfo.isOnQueue) { choosenQueue = await ShowQueueService(botInfo.botQueueId); } - else if (queues.length === 1) { selectedOption = 1; choosenQueue = queues[+selectedOption - 1]; @@ -689,13 +698,40 @@ const verifyQueue = async ( selectedOption = selectedOption.replace(/[^1-9]/g, '') /////////////////////////////////// - choosenQueue = queues[+selectedOption - 1]; + if (+selectedOption == 1 || +selectedOption == 2) + choosenQueue = queues[+selectedOption - 1]; } if (choosenQueue) { + // console.log('---------------> choosendQueue: ', choosenQueue) + + if (choosenQueue.name == 'sim') { + + await contact.update({ accept: true }); + + botInfo = await BotIsOnQueue('botqueue') + + choosenQueue = await ShowQueueService(botInfo.botQueueId); + + } + else if (choosenQueue.name == 'nao') { + + await SendWhatsAppMessage({ body: `\u200e${choosenQueue.greetingMessage}`, ticket }); + + await UpdateTicketService({ + ticketData: { status: 'closed' }, + ticketId: ticket.id + }); + + console.log('QUEUE NAO') + + return + + } + // Atualizando o status do ticket para mostrar notificação para o atendente da fila escolhida pelo usuário. De queueChoice para pending if (queues.length > 1 && !botInfo.isOnQueue) { @@ -715,21 +751,32 @@ const verifyQueue = async ( // O bot abre a mensagem na fila para atender o usuario if (botInfo.isOnQueue) { + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 1') + await UpdateTicketService({ ticketData: { status: 'open', userId: botInfo.userIdBot }, ticketId: ticket.id }); + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 2') + const _ticket = await ShowTicketService(ticket.id); // const chat = await msg.getChat(); + + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3') + const chat = wbot.chat - await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat); + await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat, true); + + console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 03') return } // + + let body = '' if (botOptions.length > 0) { @@ -744,13 +791,15 @@ const verifyQueue = async ( sendWhatsAppMessageSocket(ticket, body) + // console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3 body: ',body) + } else { //test del transfere o atendimento se entrar na ura infinita let ticket_message = await ShowTicketMessage(ticket.id, false); - if (ticket_message.length > 10) { + if (ticket_message.length > 20) { await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id }); @@ -760,7 +809,10 @@ const verifyQueue = async ( let options = ""; queues.forEach((queue, index) => { - options += `*${index + 1}* - ${queue.name}\n`; + + if (queue.name == 'sim' || queue.name == 'nao') + options += `*${index + 1}* - ${queue.name}\n`; + }); const body = `\u200e${greetingMessage}\n${options}`; @@ -773,7 +825,6 @@ const verifyQueue = async ( sendWhatsAppMessageSocket(ticket, body) - }, 3000, ticket.id @@ -790,7 +841,7 @@ const verifyQueue = async ( const transferTicket = async (queueIndex: number, wbot: Session, ticket: Ticket, contact: Contact) => { - const botInfo = await BotIsOnQueue('botqueue') + const botInfo = await BotIsOnQueue('botqueue', contact.accept) const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId) @@ -975,6 +1026,24 @@ const handleMessage = async ( if (msg.fromMe) { + if (/\u200e/.test(msg.body[0])) { + + // remove this in the future because impact have process impact + const queue = await Queue.findOne( + { + where: { name: 'nao' }, + raw: true, + attributes: ['name', 'greetingMessage'] + }); + + if (queue && queue.greetingMessage.trim() == msg.body.replace(/\u200e/, '').trim()) { + return + } + + } + + console.log('PASSOU -------------') + // console.log('FROM ME: ', msg.fromMe, ' | /\u200e/.test(msg.body[0]: ', (/\u200e/.test(msg.body[0]))) // messages sent automatically by wbot have a special character in front of it @@ -1043,8 +1112,19 @@ const handleMessage = async ( const contact = await verifyContact(msgContact); + // console.log('----------> contact: ', JSON.parse(JSON.stringify(contact))) + // let contactAux = JSON.parse(JSON.stringify(contact)) + + // console.log('contactAux.accept: ',contactAux.accept) + + // if(contactAux && !contactAux.accept){ + + // return + + // } + if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return; @@ -1056,9 +1136,6 @@ const handleMessage = async ( // groupContact ); - console.log('okkkkkkkkkkkkkkkkkk 1') - - // // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) @@ -1075,8 +1152,6 @@ const handleMessage = async ( throw new AppError(error.message); } - - } // @@ -1089,10 +1164,6 @@ const handleMessage = async ( } - console.log('okkkkkkkkkkkkkkkkkk 2') - - - if ( !ticket.queue && !chat.isGroup && @@ -1100,28 +1171,21 @@ const handleMessage = async ( !ticket.userId && whatsapp.queues.length >= 1 ) { + await verifyQueue(wbot, msg, ticket, contact); + } - - - console.log('okkkkkkkkkkkkkkkkkk 3') - - // O bot interage com o cliente e encaminha o atendimento para fila de atendende quando o usuário escolhe a opção falar com atendente //Habilitar esse caso queira usar o bot - const botInfo = await BotIsOnQueue('botqueue') + const botInfo = await BotIsOnQueue('botqueue', contact.accept) // const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 } if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) { - console.log('okkkkkkkkkkkkkkkkkk 4') - // TEST DEL let test: any = await ShowTicketMessage(ticket.id, false, true, 5); - console.log('okkkkkkkkkkkkkkkkkk 5 test: ', test) - if (test && test.length > 0 && test[0].body.includes('Se deseja solicitar atendimento de urgência, digite *1*') && msg.body == '1') { console.log('===================================> ENDPOINT REQUEST') @@ -1149,9 +1213,7 @@ const handleMessage = async ( return } - // - - console.log('okkkkkkkkkkkkkkkkkk 6') + // await sendDialogflowAwswer(wbot, ticket, msg, contact, chat); @@ -1166,7 +1228,7 @@ const handleMessage = async ( }); const _ticket = await ShowTicketService(ticket.id); - + // const chat = await msg.getChat(); const chat = wbot.chat