From 95bec1f92e057dc135d90353593dbda8b4824e2e Mon Sep 17 00:00:00 2001 From: adriano Date: Mon, 17 Jul 2023 13:01:05 -0300 Subject: [PATCH] ajustes slm --- backend/src/controllers/HitController.ts | 32 ++++++++++++++----- .../helpers/whatsappQueueMatchingUserQueue.ts | 26 +++++++++++++++ .../TicketServices/CreateTicketService.ts | 19 +++++++---- .../WbotServices/wbotMessageListener.ts | 22 ++++++------- 4 files changed, 73 insertions(+), 26 deletions(-) create mode 100644 backend/src/helpers/whatsappQueueMatchingUserQueue.ts diff --git a/backend/src/controllers/HitController.ts b/backend/src/controllers/HitController.ts index 53faacb..7480237 100644 --- a/backend/src/controllers/HitController.ts +++ b/backend/src/controllers/HitController.ts @@ -64,7 +64,7 @@ export const hit = async (req: Request, res: Response): Promise => { return res.status(200).json({ "message": "Ok" }); } - validNumber = req.body['cod_web']==='0001' ? validNumber : '5517988325936' + validNumber = req.body['cod_web'] === '0001' ? validNumber : '5517988325936' let contact = await Contact.findOne({ where: { number: validNumber } }); // let contact = await Contact.findOne({ where: { number: '5517988325936' } }); @@ -87,6 +87,7 @@ export const hit = async (req: Request, res: Response): Promise => { } + // let response: any = `*Olá!*\r\n\r\n*Esperamos que esteja tudo bem com você. Somos o grupo HIT e estamos aqui para mantê-lo atualizado sobre o chamado referente à unidade 0001 - Hit World Teste. Queremos garantir que você esteja informado sobre o incidente e possa acompanhar tudo de perto.*\r\n\r\nPrezado cliente, se deseja adicionar alguma informação no protocolo 200-322442 digite 2\r\n\r\n\r\n*Protocolo:* 200-322442\r\n*Data de abertura:* 07/07/2023 16:51:29\r\n*Nome do cliente:* Hit World Teste\r\n*Nome da filial:* Hit World Teste\r\n*Código do cliente:* 0001\r\n\r\n*Informação de abertura:* teste de ativação Contato: Felipe Telefone: 11983534545\r\n*Data de abertura:* 07/07/2023 16:51:29\r\n\r\n` let response: any = await hitPortalMonitoring({ 'params[n_chamado_web]': req.body['n_chamado_web'], @@ -100,8 +101,8 @@ export const hit = async (req: Request, res: Response): Promise => { const botInfo = await BotIsOnQueue('botqueue') - let ticket: any = await ShowTicketServiceByContactId(contact.id) - + let ticket: any = await ShowTicketServiceByContactId(contact.id) + if (!ticket.dataValues.id) { const defaultWhatsapp = await GetDefaultWhatsApp(); @@ -112,29 +113,33 @@ export const hit = async (req: Request, res: Response): Promise => { 0, ); - ticket = ticket_obj.ticket + ticket = ticket_obj.ticket } - + if (ticket.id && ticket.status == 'pending') { await sendMessageHitMonitoring(response, ticket); + await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou']); + } else if (ticket.id && ticket.userId == botInfo.userIdBot) { let queue = await ShowQueueService(botInfo.botQueueId); - await UpdateTicketService({ ticketData: { queueId: queue.id }, ticketId: ticket.id }); + await UpdateTicketService({ ticketData: { queueId: queue.id }, ticketId: ticket.id }); - ticket = await ShowTicketService(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 sendDialogflowAwswer(ticket.whatsappId, ticket, msg, contact, false); await sendMessageHitMonitoring(response, ticket); + await sendMessageInsertInfoSLM(req, ticket, ['atdabriu', 'atdatualizou']); + } } else { @@ -146,6 +151,17 @@ export const hit = async (req: Request, res: Response): Promise => { }; +async function sendMessageInsertInfoSLM(req: Request, ticket: any, params: any[]) { + + if (params.includes(req.body['action'])) { + + await new Promise(f => setTimeout(f, 1000)); + + await sendMessageHitMonitoring(`Se deseja adicionar alguma informação ao protocolo acima, digite 2.`, ticket); + + } +} + async function sendMessageHitMonitoring(msg: any, ticket: Ticket) { if (msg && msg.length > 0) { 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/services/TicketServices/CreateTicketService.ts b/backend/src/services/TicketServices/CreateTicketService.ts index 376a90c..fe8066d 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,23 +23,28 @@ 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 => { - - - console.log('========> queueId: ', queueId) + 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); + queueId = matchingQueue ? matchingQueue.queueId : undefined + } await CheckContactOpenTickets(contactId); diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index e050577..5b33ddf 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -401,12 +401,12 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, 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]}*`) + botSendMessage(ticket, `✅ Protocolo validado, agora digite a informação que deseja adicionar.`) } else if (valid && valid.data.result == 'notfound') { - botSendMessage(ticket, `Protocolo *${params[1]}* não encontrado!\n_Digite *0* para falar com a HIT._`) + botSendMessage(ticket, `Protocolo *${params[1]}* não encontrado!`) } else if (valid && valid.data.result == 'close') { @@ -754,7 +754,7 @@ const transferTicket = async (queueIndex: number, wbot: any, ticket: Ticket) => const botMsgActions = (params: string) => { let lstActions = params.split('dialog_actions=') - let bodyMsg = lstActions[0] + let bodyMsg = lstActions[0].trim() let obj = {} console.log('lstActions: ', lstActions[1].split('=')) @@ -1109,11 +1109,8 @@ const handleMessage = async ( 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] @@ -1139,12 +1136,13 @@ const handleMessage = async ( if (response && response.data.result) { - botSendMessage(ticket, `${response.data.result}`) + // botSendMessage(ticket, `${response.data.result}`) + botSendMessage(ticket, `✅ A informação foi adicionada com sucesso e será armazenada no histórico do protocolo.`) } 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._`) + 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.`) } @@ -1177,13 +1175,13 @@ const handleMessage = async ( return } - - if (msg && !msg.fromMe && ticket.status == 'pending') { - + + if (msg && !msg.fromMe && ticket.status == 'pending') { + await setMessageAsRead(ticket) } - + } catch (err) { Sentry.captureException(err);