From 42784ac37570a652ca857aeee7a7a23a09bc02ef Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 13 Jul 2023 15:28:40 -0300 Subject: [PATCH] Controller ominihit da hit deletado --- backend/src/controllers/HitController.ts | 159 ------ .../helpers/whatsappQueueMatchingUserQueue.ts | 26 + backend/src/routes/hitRoutes.ts | 9 - backend/src/routes/index.ts | 6 +- .../TicketServices/CreateTicketService.ts | 15 +- .../FindOrCreateTicketServiceBot.ts | 7 +- .../WbotServices/SendWhatsAppMessage.ts | 3 +- .../WbotServices/wbotMessageListener.ts | 459 ++++-------------- 8 files changed, 127 insertions(+), 557 deletions(-) delete mode 100644 backend/src/controllers/HitController.ts create mode 100644 backend/src/helpers/whatsappQueueMatchingUserQueue.ts delete mode 100644 backend/src/routes/hitRoutes.ts diff --git a/backend/src/controllers/HitController.ts b/backend/src/controllers/HitController.ts deleted file mode 100644 index 53faacb..0000000 --- a/backend/src/controllers/HitController.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { Request, Response } from "express"; -import BotIsOnQueue from "../helpers/BotIsOnQueue"; -import GetDefaultWhatsApp from "../helpers/GetDefaultWhatsApp"; -import { getIO } from "../libs/socket"; -import { getWbot } from "../libs/wbot"; -import Ticket from "../models/Ticket"; -import ContactByCustomField from "../services/HitServices/ShowContactByCustomFieldValueService"; -import ShowQueueService from "../services/QueueService/ShowQueueService"; -import CreateTicketService from "../services/TicketServices/CreateTicketService"; -import ShowTicketService from "../services/TicketServices/ShowTicketService"; -import UpdateTicketService from "../services/TicketServices/UpdateTicketService"; -import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage"; - -import { Op, where, Sequelize } from "sequelize"; -import ShowTicketServiceByContactId from "../services/TicketServices/ShowTicketServiceByContactId"; -import hitPortalMonitoring from "../helpers/HitPortalMonitoring"; -import { sendDialogflowAwswer, verifyContact } from "../services/WbotServices/wbotMessageListener"; -import CheckIsValidContact from "../services/WbotServices/CheckIsValidContact"; -import Contact from "../models/Contact"; -import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl"; -import CreateContactService from "../services/ContactServices/CreateContactService"; -import { resourceUsage } from "process"; -import FindOrCreateTicketServiceBot from "../services/TicketServices/FindOrCreateTicketServiceBot"; - - - -// type IndexQuery = { -// cod_web: string; -// }; - -export const hit = async (req: Request, res: Response): Promise => { - - // const { - // cod_web, - // } = req.body as IndexQuery; - - console.log('req.boy: ', req.body) - console.log("req.body['cod_web']: ", req.body['cod_web']) - console.log("req.body['action']: ", req.body['action']) - console.log("req.body['phone']: ", req.body['phone']) - console.log("req.body['name']: ", req.body['name']) - - - if (req.headers["auth"] === '0424bd59b807674191e7d77572075f33') { - - let phone = req.body['phone'] - let name = req.body['name'] - - if (!phone) return res.status(200).json({ "message": "Ok" }); - - const regex = /^55/; - - phone = phone.match(/\d+/g).join(''); - - if (!regex.test(phone)) { - phone = '55' + phone; - } - - if (phone.length < 7) return res.status(200).json({ "message": "Ok" }); - - let validNumber = await CheckIsValidContact(phone); - - if (!validNumber) { - return res.status(200).json({ "message": "Ok" }); - } - - validNumber = req.body['cod_web']==='0001' ? validNumber : '5517988325936' - - let contact = await Contact.findOne({ where: { number: validNumber } }); - // let contact = await Contact.findOne({ where: { number: '5517988325936' } }); - - if (!contact) { - - const profilePicUrl = await GetProfilePicUrl(validNumber); - - contact = await CreateContactService({ - name: name || phone, - number: validNumber, - profilePicUrl: profilePicUrl, - }); - - const io = getIO(); - io.emit("contact", { - action: "create", - contact - }); - - } - - - let response: any = await hitPortalMonitoring({ - 'params[n_chamado_web]': req.body['n_chamado_web'], - 'method': 'omnihit.consultachamado', - }) - - if (!response || response.length == 0 || !contact) { - console.log('Empty result from hit portal monitoring to n_chamado_web: ', req.body['n_chamado_web']) - return res.status(200).json({ "message": "Ok" }); - } - - const botInfo = await BotIsOnQueue('botqueue') - - let ticket: any = await ShowTicketServiceByContactId(contact.id) - - if (!ticket.dataValues.id) { - - const defaultWhatsapp = await GetDefaultWhatsApp(); - - let ticket_obj: any = await FindOrCreateTicketServiceBot( - contact, - defaultWhatsapp.id!, - 0, - ); - - ticket = ticket_obj.ticket - } - - - if (ticket.id && ticket.status == 'pending') { - - await sendMessageHitMonitoring(response, ticket); - - } - else if (ticket.id && ticket.userId == botInfo.userIdBot) { - - let queue = await ShowQueueService(botInfo.botQueueId); - - await UpdateTicketService({ ticketData: { queueId: queue.id }, ticketId: ticket.id }); - - ticket = await ShowTicketService(ticket.id); - - let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' } - - await sendDialogflowAwswer(ticket.whatsappId, ticket, msg, contact, false); - - await sendMessageHitMonitoring(response, ticket); - - } - } - else { - return res.status(401).json({ "message": "Token Inválido!" }); - } - - - return res.status(200).json({ "message": "Ok" }); - -}; - -async function sendMessageHitMonitoring(msg: any, ticket: Ticket) { - - if (msg && msg.length > 0) { - - console.log('MESSAGE WILL BE SENT!') - - await SendWhatsAppMessage({ body: msg, ticket }); - - } - -} diff --git a/backend/src/helpers/whatsappQueueMatchingUserQueue.ts b/backend/src/helpers/whatsappQueueMatchingUserQueue.ts new file mode 100644 index 0000000..af54cd5 --- /dev/null +++ b/backend/src/helpers/whatsappQueueMatchingUserQueue.ts @@ -0,0 +1,26 @@ +import Whatsapp from "../models/Whatsapp"; +import ShowQueuesByUser from "../services/UserServices/ShowQueuesByUser"; +import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; + +async function whatsappQueueMatchingUserQueue(userId: number, whatsapp: Whatsapp, userProfile: string = 'user') { + + const userQueues = await ShowQueuesByUser({ profile: userProfile, userId: userId }); + + if (!userQueues || userQueues && userQueues.length == 0) return + + // console.log('-----> userQueues: ', userQueues); + + let whats: any = await ShowWhatsAppService(whatsapp.id); + + if (!whats.queues || whats.queues && whats.queues.length == 0) return + + const whatsappQueues = whats.queues.map((e: any) => e.dataValues.name); + + // console.log('-----> whatsappQueues: ', whatsappQueues); + + const matchingQueue = userQueues.find(queue => whatsappQueues.includes(queue.name)); + + return matchingQueue +} + +export default whatsappQueueMatchingUserQueue \ No newline at end of file diff --git a/backend/src/routes/hitRoutes.ts b/backend/src/routes/hitRoutes.ts deleted file mode 100644 index b4e649b..0000000 --- a/backend/src/routes/hitRoutes.ts +++ /dev/null @@ -1,9 +0,0 @@ -import express from "express"; - -import * as HitController from "../controllers/HitController"; - -const hitRoutes = express.Router(); - -hitRoutes.post("/omnihit/incidente", HitController.hit); - -export default hitRoutes; diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index f959997..697856e 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -13,8 +13,7 @@ import quickAnswerRoutes from "./quickAnswerRoutes"; import reportRoutes from "./reportRoutes"; import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes"; import statusChatEndRoutes from "./statusChatEndRoutes"; -import dialogflowRoutes from "./dialogflowRoutes"; -import hitRoutes from "./hitRoutes"; +import dialogflowRoutes from "./dialogflowRoutes"; import wbotMonitorRoutes from "./wbotMonitorRoutes"; const routes = Router(); @@ -34,8 +33,7 @@ routes.use(quickAnswerRoutes); routes.use(schedulingNotifiyRoutes); routes.use(reportRoutes); routes.use(statusChatEndRoutes); -routes.use(dialogflowRoutes); -routes.use(hitRoutes); +routes.use(dialogflowRoutes); routes.use(wbotMonitorRoutes); export default routes; diff --git a/backend/src/services/TicketServices/CreateTicketService.ts b/backend/src/services/TicketServices/CreateTicketService.ts index 376a90c..f8b4d00 100644 --- a/backend/src/services/TicketServices/CreateTicketService.ts +++ b/backend/src/services/TicketServices/CreateTicketService.ts @@ -14,6 +14,8 @@ import { splitDateTime } from "../../helpers/SplitDateTime"; import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser"; import { createOrUpdateTicketCache } from '../../helpers/TicketCache' +import User from "../../models/User"; +import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue"; let flatten = require('flat') @@ -21,14 +23,14 @@ let flatten = require('flat') interface Request { contactId: number; status: string; - userId: number; + userId: number; queueId?: number | undefined; } const CreateTicketService = async ({ contactId, status, - userId, + userId, queueId = undefined }: Request): Promise => { @@ -37,7 +39,14 @@ const CreateTicketService = async ({ try { - const defaultWhatsapp = await GetDefaultWhatsApp(userId); + const defaultWhatsapp = await GetDefaultWhatsApp(userId); + + if (!queueId) { + const user = await User.findByPk(userId, { raw: true, }) + const matchingQueue = await whatsappQueueMatchingUserQueue(userId, defaultWhatsapp, user?.profile); + console.log('matchingQueue: ', matchingQueue) + queueId = matchingQueue ? matchingQueue.queueId : undefined + } await CheckContactOpenTickets(contactId); diff --git a/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts b/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts index 57593c2..dcbb9bb 100644 --- a/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts +++ b/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts @@ -7,7 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowTicketService from "./ShowTicketService"; import AppError from "../../errors/AppError"; import { userInfo } from "os"; -import { sendDialogflowAwswer } from "../WbotServices/wbotMessageListener"; +import { sendDialogflowAnswer } from "../WbotServices/wbotMessageListener"; import ShowQueueService from "../QueueService/ShowQueueService"; import UpdateTicketService from "./UpdateTicketService"; @@ -34,7 +34,7 @@ const FindOrCreateTicketServiceBot = async ( //Habilitar esse caso queira usar o bot - const botInfo = await BotIsOnQueue('botqueue') + const botInfo = await BotIsOnQueue('botqueue', contact.accept) // const botInfo = { isOnQueue: false } @@ -142,6 +142,7 @@ async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: ticket = await ShowTicketService(ticket.id); - await sendDialogflowAwswer(ticket.whatsappId, ticket, msg, contact, false); + // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false); + } diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index 183aaf3..1d662ec 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -49,7 +49,8 @@ const SendWhatsAppMessage = async ({ let timestamp = Date.now() + String(Math.floor(Math.random() * 1000)) var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`; - console.time(timetaken) + console.time(timetaken) + let quotedMsgSerializedId: string | undefined; diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index c6912dd..617ed9e 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -60,8 +60,7 @@ import bot_actions from './BotActions' import ShowTicketService from "../TicketServices/ShowTicketService"; import { updateTicketCacheByTicketId } from '../../helpers/TicketCache' - -import endPointQuery from "../../helpers/EndpointQuery"; + import { Console } from "console"; import ShowContactCustomFieldService from "../ContactServices/ShowContactCustomFieldsService"; import { insertMessageContactCache, getLastId } from '../../helpers/LastMessageIdByContactCache' @@ -71,7 +70,6 @@ import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl"; import SendWhatsAppMedia from "./SendWhatsAppMedia"; import AppError from "../../errors/AppError"; -import { tr } from "date-fns/locale"; import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase"; import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot"; import { setMessageAsRead } from "../../helpers/SetMessageAsRead"; @@ -221,97 +219,7 @@ const verifyMessage = async ( await CreateMessageService({ messageData }); }; - - -const queryEndPointHit = async (centro_de_custo: string) => { - - let msg_endpoint: any = [] - - let response2 = await endPointQuery('http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php', 'post', { 'params[cod_web]': centro_de_custo.trim(), }) - - if (response2 && response2.data.result) { - - response2 = response2.data.result; - - - for (let i = 0; i < response2.length; i++) { - - let data = '' - let sub_data = '*Atualizações:*\n\n' - - let properties: any = Object.entries(response2[i]); - - for (let x = 0; x < properties.length; x++) { - - if (typeof (properties[x][1]) != 'object') { - - if (properties[x][0] === 'n_chamado_web') { - properties[x][0] = 'Protocolo' - } - else if (properties[x][0] === 'nome_cliente') { - properties[x][0] = 'Nome do cliente' - } - else if (properties[x][0] === 'quando_inicio') { - properties[x][0] = 'Data de abertura' - } - else if (properties[x][0] === 'nome_filial') { - properties[x][0] = 'Nome da filial' - } - else if (properties[x][0] === 'cod_web') { - properties[x][0] = 'Codigo do cliente' - } - else if (properties[x][0] === 'id' || properties[x][0] === 'cliente_id') { - continue - } - - - data += `*${properties[x][0]}*: ${properties[x][1].replace(/(\r\n|\n|\r)/gm, "")}\n` - - } - else if (typeof (properties[x][1]) == 'object') { - - const sub_properties = properties[x][1]; - - for (let k = 0; k < sub_properties.length; k++) { - - let inner_properties: any = Object.entries(sub_properties[k]); - - for (let y = 0; y < inner_properties.length; y++) { - - if (inner_properties[y][0] === 'texto') { - inner_properties[y][0] = 'Informação' - } - else if (inner_properties[y][0] === 'quando') { - inner_properties[y][0] = 'Data da Informação' - } - else if (inner_properties[y][0] === 'login') { - continue - } - - sub_data += `*${inner_properties[y][0]}*: ${inner_properties[y][1].replace(/(\r\n|\n|\r)/gm, "")}\n` - - } - - sub_data += '\n' - - } - - } - - } - - msg_endpoint.push({ header: data, body: sub_data }) - - } - - } - else { - msg_endpoint = null - } - - return msg_endpoint - -} + const monitoramento_response2 = async (response: any | null, wbot: any, contact: any, ticket: any, centro_de_custo: any, final_message: string = '', send_empty_incident?: boolean) => { @@ -368,140 +276,13 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, // console.log('gggggggggggggggggggggggggggggggggg msgAction: ', msgAction) - if (msgAction.actions[0] == 'request_endpoint') { - - - // NEW - await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) - - // const url = 'http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php/99383' - - let aux = msgAction.actions[1].split('/') - - let cod_web - - if (aux && aux.length > 0) { - cod_web = aux[aux.length - 1] - } - - let params = msgAction.actions[1].split('api.php')[1].slice(1).split('/') - - let url = msgAction.actions[1].replace(/\.php.*/, '.php') - - let response: any = '' - - if (params[0] === 'validate_n_chamado_web') { - - let valid = await endPointQuery( - 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', - 'post', - { - 'params[n_chamado_web]': params[1], - 'method': 'omnihit.consultachamadostatus' - }) - - - if (valid && valid.data.result == 'open') { - - botSendMessage(ticket, `Protocolo validado, por favor, pode digitar o texto a ser adicionado no histórico do protocolo *${params[1]}*`) - - } - else if (valid && valid.data.result == 'notfound') { - - botSendMessage(ticket, `Protocolo *${params[1]}* não encontrado!\n_Digite *0* para falar com a HIT._`) - - } - else if (valid && valid.data.result == 'close') { - - botSendMessage( - ticket, - `O protocolo *${params[1]}* foi encerrado. Não é mais possível adicionar informação. Se desejar consultar o historico digite *1*`) - - // - - } - else { - - botSendMessage(ticket, `Ops! Não foi possível validar seu protocolo devido a um erro na comunicação com o servidor.Tente novamente mais tarde.\n_Digite *0* para falar com a HIT._`) - - } - - } - - if (params[0] === 'validate_n_chamado_web') return - - if (params[0] === 'cod_web') { - - response = await endPointQuery('http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', - 'post', { - 'params[cod_web]': params[1], - 'method': 'omnihit.consultachamado' - }) - - - } - else if (params[0] === 'n_chamado_web') { - - response = await endPointQuery('http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', - 'post', - { - 'params[n_chamado_web]': params[1], - 'method': 'omnihit.consultachamado', - }) - - - } - - try { - - if (response && response.data.result.trim().length > 0) { - response = response.data.result - } - else if (response && response.data.result.trim().length === 0) { - response = '' - } - else { - response = null - } - - // response = response.data.result - - if (response.trim().length == 0) { - - botSendMessage(ticket, `Não existe nenhum chamado para essa operação!\n _Digite *0* para falar com a HIT._`) - - } - else if (response.trim().length > 0) { - - await SendWhatsAppMessage({ body: response, ticket }); - - } - - } catch (error) { - botSendMessage(ticket, `Houve um erro ao realizar a consulta!\n _Digite *0* para falar com a HIT._`) - } + if (msgAction.actions[0] == 'request_endpoint') { + } else if (msgAction.actions[0] == 'queue_transfer') { console.log('>>>>>>>>>>>>>>> msgAction: ', msgAction, ' | msgAction.actions[1]: ', msgAction.actions[1]) - - const contact_custom_field = await ShowContactCustomFieldService(contact.id) - - if (contact_custom_field && contact_custom_field.length > 0) { - - const msg_endpoint = await queryEndPointHit(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) - - // OLD - // const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); - // await verifyMessage(msg, ticket, contact); - // await new Promise(f => setTimeout(f, 1000)); - + // NEW await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) @@ -524,24 +305,9 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, } } - else { - // const linesOfBody = body.split('\n'); - - // OLD - // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); - // await verifyMessage(sentMessage, ticket, contact); - // await new Promise(f => setTimeout(f, 1000)); - + else { // NEW - sendWhatsAppMessageSocket(ticket, body) - - - - // for(let message of linesOfBody) { - // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, message); - // await verifyMessage(sentMessage, ticket, contact); - // await new Promise(f => setTimeout(f, 1000)); - // } + sendWhatsAppMessageSocket(ticket, body) } @@ -555,15 +321,13 @@ const extractCallCode = (str: string) => { return '' } -const sendDialogflowAnswer = async ( - wbot: any, +const sendDialogflowAnswer = async ( + wbot:any, ticket: Ticket, msg: any, contact: Contact, chat: Chat, - startDialog: boolean = false, - send: boolean = true - // chat: Chat + startDialog: boolean = false ) => { if (startDialog) { @@ -585,14 +349,14 @@ const sendDialogflowAnswer = async ( console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 4') if (msg.type != 'chat') { - botSendMessage(ticket, `Desculpe, nao compreendi!\nEnvie apenas texto quando estiver interagindo com o bot!\n _Digite *0* para falar com a HIT._`) + botSendMessage(ticket, `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, `Desculpe, nao compreendi!\nTexto acima de 120 caracteres!\n _Digite *0* para falar com a HIT._`) + botSendMessage(ticket, `Desculpe, nao compreendi!\nTexto acima de 120 caracteres!\n _Digite *0* para voltar ao menu principal._`) return } @@ -609,10 +373,8 @@ const sendDialogflowAnswer = async ( return; } - if (!send) return - // Make disponible later from session out - // chat.sendStateTyping(); + // chat.sendStateTyping(); await new Promise(f => setTimeout(f, 1000)); @@ -744,6 +506,7 @@ const verifyQueue = async ( console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 03') return + } // @@ -758,6 +521,9 @@ const verifyQueue = async ( body = `\u200e${choosenQueue.greetingMessage}`; } + // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); + // await verifyMessage(sentMessage, ticket, contact); + sendWhatsAppMessageSocket(ticket, body) // console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3 body: ',body) @@ -765,6 +531,8 @@ const verifyQueue = async ( } else { + + //test del transfere o atendimento se entrar na ura infinita const repet: any = await mostRepeatedPhrase(ticket.id) if (repet.occurrences > 4) { @@ -830,13 +598,10 @@ const transferTicket = async (queueIndex: number, wbot: any, ticket: Ticket, con // console.log('queues ---> ', queues) - await botTransferTicket(queues[queueIndex], ticket) + await botTransferTicket(queues[queueIndex], ticket, contact, wbot) } - - - // const botMsgActions = (params: string) => { // let lstActions = params.split('dialog_actions=') @@ -893,9 +658,7 @@ const queuesOutBot = async (wbot: any, botId: string | number) => { } -const botTransferTicket = async (queues: Queue, ticket: Ticket) => { - - console.log('>>>>>>>>>>>>>>>>> queues.id: ', queues.id) +const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: any) => { await ticket.update({ userId: null }); @@ -932,7 +695,7 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: any, mediaPa } -const botSendMessage = (ticket: Ticket, msg: string) => { +const botSendMessage = (ticket: Ticket, msg: string) => { const debouncedSentMessage = debounce( @@ -966,13 +729,15 @@ const _clear_lst = () => { setWhatsappId(whatsappIdsSplited, true) -} +} + const handleMessage = async ( msg: any, wbot: any ): Promise => { + if (!msg.fromMe) { _clear_lst() @@ -983,7 +748,7 @@ const handleMessage = async ( if (index == -1) { - // console.log('-----------------> LST: ', lst):q + // console.log('-----------------> LST: ', lst) lst.push({ id: msg.id.id }) @@ -1074,12 +839,6 @@ const handleMessage = async ( // const chat = await msg.getChat(); const chat = wbot.chat - // if(chat.isGroup){ - - // console.log('This message is from a Group and will be ignored!') - // return - // } - // console.log('----------> chat: ', JSON.parse(JSON.stringify(chat))) // if (chat.isGroup) { @@ -1102,7 +861,7 @@ const handleMessage = async ( const unreadMessages = msg.fromMe ? 0 : chat.unreadCount; - const contact: any = await verifyContact(msgContact); + const contact = await verifyContact(msgContact); // console.log('----------> contact: ', JSON.parse(JSON.stringify(contact))) @@ -1118,9 +877,12 @@ const handleMessage = async ( // } + + if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return; + let ticket - const _botInfo = await BotIsOnQueue('botqueue') + const _botInfo = await BotIsOnQueue('botqueue', contact.accept) if (_botInfo.isOnQueue) { @@ -1156,16 +918,6 @@ const handleMessage = async ( ); } - - - // const ticket = await FindOrCreateTicketService( - // contact, - // wbot.id!, - // unreadMessages, - // // groupContact - // ); - - // // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) @@ -1201,7 +953,9 @@ const handleMessage = async ( !ticket.userId && whatsapp.queues.length >= 1 ) { + await verifyQueue(wbot, msg, ticket, contact); + } // 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 @@ -1217,7 +971,7 @@ const handleMessage = async ( if (repet.occurrences > 4) { - await transferTicket(0, wbot, ticket, contact.accept) + await transferTicket(0, wbot, ticket, contact) await SendWhatsAppMessage({ body: `Seu atendimento foi transferido para um agente!\n\nPara voltar ao menu principal digite *0* @@ -1227,59 +981,11 @@ const handleMessage = async ( } else { - let last_messages = await ShowTicketMessage(ticket.id, 2, true) - - if (last_messages.length > 0 && last_messages[0].body.includes('validado') && msg.body.trim() != '0') { - - // botSendMessage(ticket,`Aguarde, inserindo informação...\n_Digite *0* para falar com a HIT._`) - - await SendWhatsAppMessage({ body: `Aguarde inserindo informação, em breve te atualizaremos`, ticket }) - - - let aux_msg = last_messages[0].body - - aux_msg = aux_msg.split('\n')[0] - - let index = aux_msg.indexOf('do protocolo ') - - aux_msg = aux_msg.substring(index, aux_msg.length) - - let regex = /[0-9-]+/g; - - let matches: any = aux_msg.match(regex); - - console.log("~~~~~~~~~~~~~~~~~~~~~~> matches.join(''): ", matches.join('')); - - let response = await endPointQuery( - 'http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', - 'post', - { - 'params[n_chamado_web]': matches.join(''), - 'method': 'omnihit.chamadoaddobs', - 'params[obs]': msg.body - }) - - if (response && response.data.result) { - - botSendMessage(ticket, `${response.data.result}`) - - } - else { - - botSendMessage(ticket, `Ops! Houve um erro ao tentar inserir sua informação devido a um erro na comunicação com o servidor.Tente novamente mais tarde.\n_Digite *0* para falar com a HIT._`) - - } - - - } - else { - - await sendDialogflowAnswer(wbot, ticket, msg, contact, chat, contact.accept); - - } - + await sendDialogflowAnswer(wbot, ticket, msg, contact, chat); } + + } else if (botInfo.isOnQueue && !msg.fromMe && msg.body == '0' && ticket.status == 'pending' && ticket.queueId) { @@ -1295,7 +1001,7 @@ const handleMessage = async ( // const chat = await msg.getChat(); const chat = wbot.chat - await sendDialogflowAnswer(wbot, _ticket, msg, contact, chat, contact.aceppt); + await sendDialogflowAnswer(wbot, _ticket, msg, contact, chat); return } @@ -1306,63 +1012,60 @@ const handleMessage = async ( } - } catch (err) { + console.log('xxxxxxxxxxxxxxxxxxxx err: ', err) Sentry.captureException(err); - console.log('xxxxxxxxxxxxx err: ', err) logger.error(`Error handling whatsapp message: Err: ${err}`); - } -}; + }; +} -const handleMsgAck = async (msg_id: any, ack: any) => { + const handleMsgAck = async (msg_id: any, ack: any) => { + await new Promise(r => setTimeout(r, 500)); - await new Promise(r => setTimeout(r, 4000)); + const io = getIO(); - const io = getIO(); + try { + const messageToUpdate = await Message.findByPk(msg_id, { + include: [ + "contact", + { + model: Message, + as: "quotedMsg", + include: ["contact"] + } + ] + }); + if (!messageToUpdate) { + return; + } + await messageToUpdate.update({ ack }); - try { - const messageToUpdate = await Message.findByPk(msg_id, { - include: [ - "contact", - { - model: Message, - as: "quotedMsg", - include: ["contact"] - } - ] - }); - if (!messageToUpdate) { - console.log(`Not found the MESSAGE ID ${msg_id}to change the ACK into the Message table`) - return; + // console.log('ACK messageToUpdate: ', JSON.parse(JSON.stringify(messageToUpdate))) + + io.to(messageToUpdate.ticketId.toString()).emit("appMessage", { + action: "update", + message: messageToUpdate + }); + + } catch (err) { + Sentry.captureException(err); + logger.error(`Error handling message ack. Err: ${err}`); } - await messageToUpdate.update({ ack }); + }; - // console.log('ACK messageToUpdate: ', JSON.parse(JSON.stringify(messageToUpdate))) + const wbotMessageListener = (wbot: any): void => { - io.to(messageToUpdate.ticketId.toString()).emit("appMessage", { - action: "update", - message: messageToUpdate + wbot.on("message_create", async (msg: any) => { + handleMessage(msg, wbot); }); - } catch (err) { - Sentry.captureException(err); - logger.error(`Error handling message ack. Err: ${err}`); - } -}; + wbot.on("media_uploaded", async (msg: any) => { + handleMessage(msg, wbot); + }); -const wbotMessageListener = (wbot: any): void => { + wbot.on("message_ack", async (msg: any, ack: any) => { + handleMsgAck(msg, ack); + }); + }; - wbot.on("message_create", async (msg: any) => { - handleMessage(msg, wbot); - }); - - wbot.on("media_uploaded", async (msg: any) => { - handleMessage(msg, wbot); - }); - - wbot.on("message_ack", async (msg: any, ack: any) => { - handleMsgAck(msg, ack); - }); -}; - -export { wbotMessageListener, handleMessage, handleMsgAck, lst, verifyContact, sendDialogflowAnswer }; + export { wbotMessageListener, handleMessage, handleMsgAck, lst, sendDialogflowAnswer };