Controller ominihit da hit deletado

adriano 2023-07-13 15:28:40 -03:00
parent 77b7ed393f
commit 42784ac375
8 changed files with 127 additions and 557 deletions

View File

@ -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<Response> => {
// 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 });
}
}

View File

@ -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

View File

@ -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;

View File

@ -14,7 +14,6 @@ import reportRoutes from "./reportRoutes";
import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes"; import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes";
import statusChatEndRoutes from "./statusChatEndRoutes"; import statusChatEndRoutes from "./statusChatEndRoutes";
import dialogflowRoutes from "./dialogflowRoutes"; import dialogflowRoutes from "./dialogflowRoutes";
import hitRoutes from "./hitRoutes";
import wbotMonitorRoutes from "./wbotMonitorRoutes"; import wbotMonitorRoutes from "./wbotMonitorRoutes";
const routes = Router(); const routes = Router();
@ -35,7 +34,6 @@ routes.use(schedulingNotifiyRoutes);
routes.use(reportRoutes); routes.use(reportRoutes);
routes.use(statusChatEndRoutes); routes.use(statusChatEndRoutes);
routes.use(dialogflowRoutes); routes.use(dialogflowRoutes);
routes.use(hitRoutes);
routes.use(wbotMonitorRoutes); routes.use(wbotMonitorRoutes);
export default routes; export default routes;

View File

@ -14,6 +14,8 @@ import { splitDateTime } from "../../helpers/SplitDateTime";
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser"; import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache' import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
import User from "../../models/User";
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
let flatten = require('flat') let flatten = require('flat')
@ -39,6 +41,13 @@ const CreateTicketService = async ({
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); await CheckContactOpenTickets(contactId);
const { isGroup } = await ShowContactService(contactId); const { isGroup } = await ShowContactService(contactId);

View File

@ -7,7 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService"; import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import { userInfo } from "os"; import { userInfo } from "os";
import { sendDialogflowAwswer } from "../WbotServices/wbotMessageListener"; import { sendDialogflowAnswer } from "../WbotServices/wbotMessageListener";
import ShowQueueService from "../QueueService/ShowQueueService"; import ShowQueueService from "../QueueService/ShowQueueService";
import UpdateTicketService from "./UpdateTicketService"; import UpdateTicketService from "./UpdateTicketService";
@ -34,7 +34,7 @@ const FindOrCreateTicketServiceBot = async (
//Habilitar esse caso queira usar o bot //Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue') const botInfo = await BotIsOnQueue('botqueue', contact.accept)
// const botInfo = { isOnQueue: false } // const botInfo = { isOnQueue: false }
@ -142,6 +142,7 @@ async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo:
ticket = await ShowTicketService(ticket.id); ticket = await ShowTicketService(ticket.id);
await sendDialogflowAwswer(ticket.whatsappId, ticket, msg, contact, false); // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false);
} }

View File

@ -52,6 +52,7 @@ const SendWhatsAppMessage = async ({
console.time(timetaken) console.time(timetaken)
let quotedMsgSerializedId: string | undefined; let quotedMsgSerializedId: string | undefined;
if (quotedMsg) { if (quotedMsg) {

View File

@ -61,7 +61,6 @@ import ShowTicketService from "../TicketServices/ShowTicketService";
import { updateTicketCacheByTicketId } from '../../helpers/TicketCache' import { updateTicketCacheByTicketId } from '../../helpers/TicketCache'
import endPointQuery from "../../helpers/EndpointQuery";
import { Console } from "console"; import { Console } from "console";
import ShowContactCustomFieldService from "../ContactServices/ShowContactCustomFieldsService"; import ShowContactCustomFieldService from "../ContactServices/ShowContactCustomFieldsService";
import { insertMessageContactCache, getLastId } from '../../helpers/LastMessageIdByContactCache' import { insertMessageContactCache, getLastId } from '../../helpers/LastMessageIdByContactCache'
@ -71,7 +70,6 @@ import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl"; import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl";
import SendWhatsAppMedia from "./SendWhatsAppMedia"; import SendWhatsAppMedia from "./SendWhatsAppMedia";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import { tr } from "date-fns/locale";
import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase"; import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase";
import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot"; import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot";
import { setMessageAsRead } from "../../helpers/SetMessageAsRead"; import { setMessageAsRead } from "../../helpers/SetMessageAsRead";
@ -223,96 +221,6 @@ const verifyMessage = async (
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) => { const monitoramento_response2 = async (response: any | null, wbot: any, contact: any, ticket: any, centro_de_custo: any, final_message: string = '', send_empty_incident?: boolean) => {
@ -371,137 +279,10 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact,
if (msgAction.actions[0] == 'request_endpoint') { 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._`)
}
} else if (msgAction.actions[0] == 'queue_transfer') { } else if (msgAction.actions[0] == 'queue_transfer') {
console.log('>>>>>>>>>>>>>>> msgAction: ', msgAction, ' | msgAction.actions[1]: ', msgAction.actions[1]) 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 // NEW
await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` }) await SendWhatsAppMessage({ body: msgAction.msgBody, ticket, number: `${contact.number}@c.us` })
@ -525,23 +306,8 @@ async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact,
} }
else { 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));
// NEW // NEW
sendWhatsAppMessageSocket(ticket, body) 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));
// }
} }
@ -556,14 +322,12 @@ const extractCallCode = (str: string) => {
} }
const sendDialogflowAnswer = async ( const sendDialogflowAnswer = async (
wbot: any, wbot:any,
ticket: Ticket, ticket: Ticket,
msg: any, msg: any,
contact: Contact, contact: Contact,
chat: Chat, chat: Chat,
startDialog: boolean = false, startDialog: boolean = false
send: boolean = true
// chat: Chat
) => { ) => {
if (startDialog) { if (startDialog) {
@ -585,14 +349,14 @@ const sendDialogflowAnswer = async (
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 4') console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 4')
if (msg.type != 'chat') { 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 return
} }
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 5') console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 5')
if (msg.type == 'chat' && String(msg.body).length > 120) { 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 return
} }
@ -609,8 +373,6 @@ const sendDialogflowAnswer = async (
return; return;
} }
if (!send) return
// Make disponible later from session out // Make disponible later from session out
// chat.sendStateTyping(); // chat.sendStateTyping();
@ -744,6 +506,7 @@ const verifyQueue = async (
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 03') console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 03')
return return
} }
// //
@ -758,6 +521,9 @@ const verifyQueue = async (
body = `\u200e${choosenQueue.greetingMessage}`; body = `\u200e${choosenQueue.greetingMessage}`;
} }
// const sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, body);
// await verifyMessage(sentMessage, ticket, contact);
sendWhatsAppMessageSocket(ticket, body) sendWhatsAppMessageSocket(ticket, body)
// console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3 body: ',body) // console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3 body: ',body)
@ -765,6 +531,8 @@ const verifyQueue = async (
} }
else { else {
//test del transfere o atendimento se entrar na ura infinita
const repet: any = await mostRepeatedPhrase(ticket.id) const repet: any = await mostRepeatedPhrase(ticket.id)
if (repet.occurrences > 4) { if (repet.occurrences > 4) {
@ -830,13 +598,10 @@ const transferTicket = async (queueIndex: number, wbot: any, ticket: Ticket, con
// console.log('queues ---> ', queues) // console.log('queues ---> ', queues)
await botTransferTicket(queues[queueIndex], ticket) await botTransferTicket(queues[queueIndex], ticket, contact, wbot)
} }
// const botMsgActions = (params: string) => { // const botMsgActions = (params: string) => {
// let lstActions = params.split('dialog_actions=') // 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) => { const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: any) => {
console.log('>>>>>>>>>>>>>>>>> queues.id: ', queues.id)
await ticket.update({ userId: null }); await ticket.update({ userId: null });
@ -968,11 +731,13 @@ const _clear_lst = () => {
} }
const handleMessage = async ( const handleMessage = async (
msg: any, msg: any,
wbot: any wbot: any
): Promise<void> => { ): Promise<void> => {
if (!msg.fromMe) { if (!msg.fromMe) {
_clear_lst() _clear_lst()
@ -983,7 +748,7 @@ const handleMessage = async (
if (index == -1) { if (index == -1) {
// console.log('-----------------> LST: ', lst):q // console.log('-----------------> LST: ', lst)
lst.push({ id: msg.id.id }) lst.push({ id: msg.id.id })
@ -1074,12 +839,6 @@ const handleMessage = async (
// const chat = await msg.getChat(); // const chat = await msg.getChat();
const chat = wbot.chat 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))) // console.log('----------> chat: ', JSON.parse(JSON.stringify(chat)))
// if (chat.isGroup) { // if (chat.isGroup) {
@ -1102,7 +861,7 @@ const handleMessage = async (
const unreadMessages = msg.fromMe ? 0 : chat.unreadCount; 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))) // 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 let ticket
const _botInfo = await BotIsOnQueue('botqueue') const _botInfo = await BotIsOnQueue('botqueue', contact.accept)
if (_botInfo.isOnQueue) { 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}) // await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1201,7 +953,9 @@ const handleMessage = async (
!ticket.userId && !ticket.userId &&
whatsapp.queues.length >= 1 whatsapp.queues.length >= 1
) { ) {
await verifyQueue(wbot, msg, ticket, contact); 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 // 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) { if (repet.occurrences > 4) {
await transferTicket(0, wbot, ticket, contact.accept) await transferTicket(0, wbot, ticket, contact)
await SendWhatsAppMessage({ await SendWhatsAppMessage({
body: `Seu atendimento foi transferido para um agente!\n\nPara voltar ao menu principal digite *0* body: `Seu atendimento foi transferido para um agente!\n\nPara voltar ao menu principal digite *0*
@ -1227,59 +981,11 @@ const handleMessage = async (
} }
else { else {
let last_messages = await ShowTicketMessage(ticket.id, 2, true) await sendDialogflowAnswer(wbot, ticket, msg, contact, chat);
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);
}
}
} }
else if (botInfo.isOnQueue && !msg.fromMe && msg.body == '0' && ticket.status == 'pending' && ticket.queueId) { 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 = await msg.getChat();
const chat = wbot.chat const chat = wbot.chat
await sendDialogflowAnswer(wbot, _ticket, msg, contact, chat, contact.aceppt); await sendDialogflowAnswer(wbot, _ticket, msg, contact, chat);
return return
} }
@ -1306,17 +1012,15 @@ const handleMessage = async (
} }
} catch (err) { } catch (err) {
console.log('xxxxxxxxxxxxxxxxxxxx err: ', err)
Sentry.captureException(err); Sentry.captureException(err);
console.log('xxxxxxxxxxxxx err: ', err)
logger.error(`Error handling whatsapp message: 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();
@ -1332,7 +1036,6 @@ const handleMsgAck = async (msg_id: any, ack: any) => {
] ]
}); });
if (!messageToUpdate) { if (!messageToUpdate) {
console.log(`Not found the MESSAGE ID ${msg_id}to change the ACK into the Message table`)
return; return;
} }
await messageToUpdate.update({ ack }); await messageToUpdate.update({ ack });
@ -1348,9 +1051,9 @@ const handleMsgAck = async (msg_id: any, ack: any) => {
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`Error handling message ack. Err: ${err}`); logger.error(`Error handling message ack. Err: ${err}`);
} }
}; };
const wbotMessageListener = (wbot: any): void => { const wbotMessageListener = (wbot: any): void => {
wbot.on("message_create", async (msg: any) => { wbot.on("message_create", async (msg: any) => {
handleMessage(msg, wbot); handleMessage(msg, wbot);
@ -1363,6 +1066,6 @@ const wbotMessageListener = (wbot: any): void => {
wbot.on("message_ack", async (msg: any, ack: any) => { wbot.on("message_ack", async (msg: any, ack: any) => {
handleMsgAck(msg, ack); handleMsgAck(msg, ack);
}); });
}; };
export { wbotMessageListener, handleMessage, handleMsgAck, lst, verifyContact, sendDialogflowAnswer }; export { wbotMessageListener, handleMessage, handleMsgAck, lst, sendDialogflowAnswer };