From 626264d5686b360667bb9e08c9835b6c49264601 Mon Sep 17 00:00:00 2001 From: adriano Date: Tue, 18 Apr 2023 16:30:19 -0300 Subject: [PATCH] =?UTF-8?q?Atualiza=C3=A7=C3=A3o=20para=20funcionamento=20?= =?UTF-8?q?com=20varias=20sessoes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/controllers/HitController.ts | 53 +++++- .../src/helpers/SendWhatsappMessageSocket.ts | 4 +- .../WbotServices/SendWhatsAppMedia.ts | 2 +- .../WbotServices/SendWhatsAppMessage.ts | 6 +- .../WbotServices/wbotMessageListener.ts | 174 ++++++++++++------ 5 files changed, 175 insertions(+), 64 deletions(-) diff --git a/backend/src/controllers/HitController.ts b/backend/src/controllers/HitController.ts index 69c16b7..96cf15c 100644 --- a/backend/src/controllers/HitController.ts +++ b/backend/src/controllers/HitController.ts @@ -28,7 +28,7 @@ export const hit = async (req: Request, res: Response): Promise => { console.log('req.boy: ', req.body) console.log('req.boy: ', req.body['centro_custo']) - console.log('ACTION: ', req.body['action']) + console.log('ACTION: ', req.body['action']) if (req.headers["auth"] === '0424bd59b807674191e7d77572075f33') { @@ -50,7 +50,7 @@ export const hit = async (req: Request, res: Response): Promise => { try { - console.log('THE CONTACT: ', contact) + console.log('atdfechou ----------> THE CONTACT: ', contact) if (contact) { @@ -121,12 +121,55 @@ export const hit = async (req: Request, res: Response): Promise => { } } - else if (req.body['action'] === 'atdatualizou'){ - + else if (req.body['action'] === 'atdatualizou') { + + console.log('status: atdatualizou --------------> contact: ', contact) + + if (contact) { + + try { + + let response = await hitPortalMonitoring(req.body['centro_custo']) + + if (!response || response.length == 0) { + console.log('Empty result from hit portal monitoring. Centro_de_custo: ', req.body['centro_custo']) + return res.status(200).json({ "message": "Ok" }); + } + + const botInfo = await BotIsOnQueue('botqueue') + + let ticket = await ShowTicketServiceByContactId(contact['contact.id']) + + if (ticket.id && ticket.status == 'pending') { + + await sendMessageHitMonitoring(`*Olá. Somos a TI Espaçolaser.*\nAtualização do chamado para sua loja ${contact['contact.name']}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket); + + } + else if (!ticket.id) { + + ticket = await CreateTicketService({ contactId: contact['contact.id'], status: 'open', userId: botInfo.userIdBot }); + + console.log('botInfo.botQueueId: ', botInfo.botQueueId) + + await UpdateTicketService({ ticketData: { queueId: botInfo.botQueueId }, ticketId: ticket.id }); + + await sendMessageHitMonitoring(`*Olá. Somos a TI Espaçolaser.*\nAtualização do chamado para sua loja ${contact['contact.name']}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket); + + } + + + } catch (error) { + + console.log(`Error on try sending the message monitor: `, error) + + } + + } + } else { - console.log('--------------> contact: ', contact) + console.log('status: atdatabriu --------------> contact: ', contact) if (contact) { diff --git a/backend/src/helpers/SendWhatsappMessageSocket.ts b/backend/src/helpers/SendWhatsappMessageSocket.ts index 837b343..073384e 100644 --- a/backend/src/helpers/SendWhatsappMessageSocket.ts +++ b/backend/src/helpers/SendWhatsappMessageSocket.ts @@ -2,14 +2,14 @@ import { getIO } from "../libs/socket"; import Ticket from "../models/Ticket"; -function sendWhatsAppMessageSocket(ticket: Ticket, body: string, quotedMsgSerializedId?: string | undefined) { +function sendWhatsAppMessageSocket(ticket: Ticket, body: string, quotedMsgSerializedId?: string | undefined, number?: string ) { const io = getIO(); io.to(`session_${ticket.whatsappId.toString()}`).emit("send_message", { action: "create", msg: { - number: `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, + number: number ? number : `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body: body, quotedMessageId: quotedMsgSerializedId, linkPreview: false diff --git a/backend/src/services/WbotServices/SendWhatsAppMedia.ts b/backend/src/services/WbotServices/SendWhatsAppMedia.ts index f15a9cb..4843dd6 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMedia.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMedia.ts @@ -11,7 +11,7 @@ import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import sendWhatsAppMediaSocket from "../../helpers/SendWhatsappMessageMediaSocket"; interface Request { - media: Express.Multer.File; + media: Express.Multer.File | any; ticket: Ticket; } diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index d70bbd6..07b21ef 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -33,12 +33,14 @@ interface Request { body: string; ticket: Ticket; quotedMsg?: Message; + number?: string } const SendWhatsAppMessage = async ({ body, ticket, - quotedMsg + quotedMsg, + number }: Request): Promise => { let timestamp = Math.floor(Date.now() / 1000) @@ -163,7 +165,7 @@ const SendWhatsAppMessage = async ({ try { - sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId); + sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId, number); await ticket.update({ lastMessage: body }); diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index d5d65f7..a0db1c4 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -69,6 +69,7 @@ import autoRestore from "../../helpers/AutoRestore"; import { _restore } from "../../helpers/RestoreControll"; import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl"; +import SendWhatsAppMedia from "./SendWhatsAppMedia"; @@ -135,8 +136,8 @@ const verifyMediaMessage = async ( if (!media.filename) { - console.log('No file name -----------------------------------------') - + console.log('No file name -----------------------------------------') + const ext = media.mimetype.split("/")[1].split(";")[0]; media.filename = `${new Date().getTime()}.${ext}`; @@ -151,13 +152,13 @@ const verifyMediaMessage = async ( console.log('FROM wbotMessageListener.ts media.filename: ', media.filename) - + await writeFileAsync( join(__dirname, "..", "..", "..", "..", "..", "public", media.filename), media.data, "base64" ); - + } catch (err) { Sentry.captureException(err); logger.error(`There was an error: wbotMessageLitener.ts: ${err}`); @@ -177,7 +178,7 @@ const verifyMediaMessage = async ( }; await ticket.update({ lastMessage: msg.body || media.filename }); - const newMessage = await CreateMessageService({ messageData }); + const newMessage = await CreateMessageService({ messageData }); return newMessage; }; @@ -208,7 +209,7 @@ const verifyMessage = async ( }; - await ticket.update({ lastMessage: msg.body }); + await ticket.update({ lastMessage: msg.body }); await CreateMessageService({ messageData }); }; @@ -279,27 +280,40 @@ const monitoramento_response2 = async (response: any | null, wbot: any, contact: if (!response) { - const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // OLD + // const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`); + // await verifyMessage(msg, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: `Houve um erro ao tentar consultar o monitoramento da Operadora!${final_message}`, ticket, number: `${contact.number}@c.us` }) } else if (response.length > 0) { for (let i = 0; i < response.length; i++) { - const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // OLD + // const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`); + // await verifyMessage(msg, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: `*Situação do chamado na Operadora*\n\n*Incidente*:\n\n ${response[i].header}\n${response[i].body}${final_message}`, ticket, number: `${contact.number}@c.us` }) + } } else if (send_empty_incident) { - const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Conforme Monitoramento a internet da unidade está operacional${final_message}`); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // OLD + // const msg = await wbot.sendMessage(`${contact.number}@c.us`, `Conforme Monitoramento a internet da unidade está operacional${final_message}`); + // await verifyMessage(msg, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: `Conforme Monitoramento a internet da unidade está operacional${final_message}`, ticket, number: `${contact.number}@c.us` }) } @@ -318,9 +332,14 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta if (msgAction.actions[0] == 'request_endpoint') { - const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); - await verifyMessage(sentMessage, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // OLD + // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); + // await verifyMessage(sentMessage, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) + // const url = 'https://sos.espacolaser.com.br/api/whatsapps/ticket/R32656' let endPointResponse = await endPointQuery(msgAction.actions[1], 'get') @@ -368,16 +387,28 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta const itsm_response = async (message1: string = '', message2: string = '') => { - const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + + // OLD + // const msg = await wbot.sendMessage(`${contact.number}@c.us`, `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`); + // await verifyMessage(msg, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: `*Situação do chamado ${extractCallCode(msgAction.msgBody)}:*${message1}${msg_endpoint_response}${message2}\n_Digite *0* para voltar ao menu principal._`, ticket, number: `${contact.number}@c.us` }) + } const sendMessageBot = async (message1: string = '', message2: string = '') => { - const msg = await wbot.sendMessage(`${contact.number}@c.us`, `${message1}${message2}`); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + + // OLD + // const msg = await wbot.sendMessage(`${contact.number}@c.us`, `${message1}${message2}`); + // await verifyMessage(msg, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + await SendWhatsAppMessage({ body: `${message1}${message2}`, ticket, number: `${contact.number}@c.us` }) + } @@ -500,9 +531,13 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta console.log('************* contact_custom_field: ', contact_custom_field) - const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // 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` }) await transferTicket(+msgAction.actions[1], wbot, ticket, contact) } @@ -510,9 +545,13 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta const sourcePath = path.join(__dirname, `../../../public/bot`) - const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody); - await verifyMessage(msg, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + // 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` }) + await botSendMedia(ticket, contact, wbot, sourcePath, msgAction.actions[1]) @@ -521,9 +560,16 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta } else { // const linesOfBody = body.split('\n'); - const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); - await verifyMessage(sentMessage, ticket, contact); - await new Promise(f => setTimeout(f, 1000)); + + // OLD + // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body); + // await verifyMessage(sentMessage, ticket, contact); + // await new Promise(f => setTimeout(f, 1000)); + + // NEW + sendWhatsAppMessageSocket(ticket, body) + + // for(let message of linesOfBody) { // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, message); @@ -555,12 +601,16 @@ const sendDialogflowAwswer = async ( return; } + // Make disponible later from session out // wbot.sendPresenceAvailable(); - // console.log('(msg: ', msg ) - // console.log('typeof(msg.type): ', typeof (msg.type), ' | msg.type: ', msg.type) + + // console.log('KKKKKKKKK msg: ', msg) + // console.log('KKKKKKKKK msg2: ', msg['body']) + + 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 @@ -582,7 +632,8 @@ const sendDialogflowAwswer = async ( return; } - chat.sendStateTyping(); + // Make disponible later from session out + // chat.sendStateTyping(); await new Promise(f => setTimeout(f, 1000)); @@ -820,21 +871,18 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, med async () => { - // const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, newMedia, { sendAudioAsVoice: true }); - const newMedia = MessageMedia.fromFilePath(`${mediaPath}/${fileNameExtension}`); - const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, { caption: 'this is my caption' }); + const media = { path: `${mediaPath}/${fileNameExtension}` } + // OLD + // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia, { caption: 'this is my caption' }); + // await ticket.update({ lastMessage: fileNameExtension }); + // verifyMessage(sentMessage, ticket, contact); + // NEW + await SendWhatsAppMedia({ media: media.path, ticket }) - // client.sendMessage("xxxxxxxx@c.us", media, {caption: "some caption"}); })(); - - // client.sendMessage(msg.from, attachmentData, { caption: 'Here\'s your requested media.' }); - - await ticket.update({ lastMessage: fileNameExtension }); - - verifyMessage(sentMessage, ticket, contact); }, 3000, @@ -851,8 +899,12 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st const debouncedSentMessage = debounce( async () => { - const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, `${msg}`); - verifyMessage(sentMessage, ticket, contact); + //OLD + // const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, `${msg}`); + // verifyMessage(sentMessage, ticket, contact); + + //NEW + await SendWhatsAppMessage({ body: msg, ticket }) }, 3000, ticket.id @@ -871,8 +923,8 @@ const _clear_lst = () => { const chunk: any = Math.floor((lst.length / 2)) lst = lst.slice(chunk, chunk + lst.length); - - let whatsappIdsSplited = lst.map((e)=>`${e.id}`).toString() + + let whatsappIdsSplited = lst.map((e) => `${e.id}`).toString() setWhatsappId(whatsappIdsSplited, true) @@ -882,7 +934,7 @@ const handleMessage = async ( msg: any, wbot: any ): Promise => { - + if (!msg.fromMe) { _clear_lst() @@ -1008,6 +1060,9 @@ const handleMessage = async ( // groupContact ); + console.log('okkkkkkkkkkkkkkkkkk 1') + + // // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl}) @@ -1017,12 +1072,12 @@ const handleMessage = async ( // console.log('PARA RESPONDER PELO MEMOS WHATSAPP wbot.id: ', wbot.id, ' | wbot.status: ', wbot.status) // console.log('WHATSAPP STATUS ticket.whatsappId: ', ticket.whatsappId) - await ticket.update({ whatsappId: wbot.id }); + await ticket.update({ whatsappId: wbot.id }); } // - if (msg.hasMedia) { + if (msg.hasMedia) { await verifyMediaMessage(msg, ticket, contact, wbot.media, wbot.quotedMsg); } else { @@ -1031,6 +1086,10 @@ const handleMessage = async ( } + console.log('okkkkkkkkkkkkkkkkkk 2') + + + if ( !ticket.queue && !chat.isGroup && @@ -1043,6 +1102,7 @@ const handleMessage = async ( + 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 @@ -1052,10 +1112,14 @@ const handleMessage = async ( // 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); - if (test[0].body.includes('Se deseja solicitar atendimento de urgência, digite *1*') && msg.body == '1') { + 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') @@ -1084,6 +1148,8 @@ const handleMessage = async ( } // + console.log('okkkkkkkkkkkkkkkkkk 6') + await sendDialogflowAwswer(wbot, ticket, msg, contact, chat); }