Atualização para permitir inserção no de informação ao SLM

pull/20/head
adriano 2023-07-06 10:04:26 -03:00
parent 2f9dbff941
commit 306111e037
10 changed files with 406 additions and 367 deletions

View File

@ -14,12 +14,14 @@ import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import { Op, where, Sequelize } from "sequelize";
import ShowTicketServiceByContactId from "../services/TicketServices/ShowTicketServiceByContactId";
import hitPortalMonitoring from "../helpers/HitPortalMonitoring";
import { verifyContact } from "../services/WbotServices/wbotMessageListener";
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 = {
@ -85,187 +87,54 @@ export const hit = async (req: Request, res: Response): Promise<Response> => {
}
let response: any = await hitPortalMonitoring({
'params[n_chamado_web]': req.body['n_chamado_web'],
'method': 'omnihit.consultachamado',
})
if (req.body['action'] === 'atdfechou') {
console.log('FECHOU')
try {
// console.log('atdfechou ----------> THE CONTACT: ', contact)
if (contact) {
let response: any = await hitPortalMonitoring({ 'params[n_chamado_web]': req.body['n_chamado_web'], })
if (!response || response.length == 0) {
console.log('Empty result from hit portal monitoring. Centro_de_custo: ', req.body['cod_web'])
return res.status(200).json({ "message": "Ok" });
}
// let data = req.body
// let str = ''
// let str2 = ''
// str = `*Cliente*: ${contact.name}`
// let historico = data['historico']
// for (const key in historico) {
// const hist = Object.keys(historico[key]);
// hist.forEach((keys, index) => {
// str2 += `*${keys}*: ${historico[key][keys]}\n`
// });
// str2 += '\n'
// }
// console.log('--------------> str: ', str)
// console.log('--------------> str2: ', str2)
const botInfo = await BotIsOnQueue('botqueue')
let ticket = await ShowTicketServiceByContactId(contact.id)
if (ticket.id && ticket.status == 'pending') {
// await sendMessageHitMonitoring(`*Olá. Somos o grupo HIT.*\nO chamado da sua loja ${contact.name} foi fechado. Abaixo seguem informações sobre o incidente.\n\n*Situação do chamado*\n\n*Incidente:*\n\n ${str}\n\n*Atualizações*:\n\n${str2}`, ticket);
await sendMessageHitMonitoring(response, ticket);
}
else if (!ticket.id) {
ticket = await CreateTicketService({ contactId: 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 o grupo HIT.*\nO chamado da sua loja ${contact.name} foi fechado pela operadora. Abaixo seguem informações sobre o incidente.\n\n*Situação do chamado*\n\n*Incidente:*\n\n ${str}\n\n*Atualizações*:\n\n${str2}`, ticket);
await sendMessageHitMonitoring(response, ticket);
}
}
} catch (error) {
console.log(`Error on try sending the monitor message closed: `, error)
}
}
else if (req.body['action'] === 'atdatualizou') {
// console.log('status: atdatualizou --------------> contact: ', contact)
if (contact) {
try {
let response: any = await hitPortalMonitoring({ 'params[n_chamado_web]': req.body['n_chamado_web'], })
console.log('respone: ', response)
if (!response || response.length == 0) {
console.log('Empty result from hit portal monitoring. Centro_de_custo: ', req.body['cod_web'])
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 = await ShowTicketServiceByContactId(contact.id)
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(`*Olá. Somos o grupo HIT.*\nAtualização do chamado para sua loja ${contact.name}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
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 if (!ticket.id) {
ticket = await CreateTicketService({ contactId: 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 o grupo HIT.*\nAtualização do chamado para sua loja ${contact.name}. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
await sendMessageHitMonitoring(response, ticket);
}
} catch (error) {
console.log(`Error on try sending the message monitor: `, error)
}
}
}
else {
console.log('status: atdatabriu ')
if (contact) {
try {
let response: any = await hitPortalMonitoring({ 'params[n_chamado_web]': req.body['n_chamado_web'], })
console.log('response: ', response)
if (!response || response.length == 0) {
console.log('Empty result from hit portal monitoring. n_chamado_web: ', req.body['n_chamado_web'])
return res.status(200).json({ "message": "Ok" });
}
const botInfo = await BotIsOnQueue('botqueue')
let ticket = await ShowTicketServiceByContactId(contact.id)
if (ticket.id && ticket.status == 'pending') {
// await sendMessageHitMonitoring(`*Olá. Somos o grupo HIT.*\nIdentificamos em nossos monitoramentos que há um problema na internet da sua loja ${contact.name} e já estamos resolvendo. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
await sendMessageHitMonitoring(response, ticket);
}
else if (!ticket.id) {
ticket = await CreateTicketService({ contactId: 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 o grupo HIT.*\nIdentificamos em nossos monitoramentos que há um problema na internet da sua loja ${contact.name} e já estamos resolvendo. Abaixo seguem informações sobre o incidente para que possam acompanhar.\n\n*Situação do chamado*\n\n*Incidente*:\n\n ${response[0].header}\n${response[0].body}`, ticket);
await sendMessageHitMonitoring(response, ticket);
}
} catch (error) {
console.log(`Error on try sending the message monitor: `, error)
}
}
}
}
else {
return res.status(401).json({ "message": "Token Inválido!" });

View File

@ -98,6 +98,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
const botInfo = await BotIsOnQueue('botqueue')
if (botInfo) {
ticket = await Ticket.findOne({ where: { contactId, status: 'open', userId: botInfo.userIdBot } });
}
@ -106,13 +107,20 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
}
if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open', userId: userId, }, ticketId: ticket.id });
await ticket.update({ queueId: null })
}
else {
ticket = await CreateTicketService({ contactId, status, userId });
}
const io = getIO();
io.to(ticket.status).emit("ticket", {
action: "update",

View File

@ -32,7 +32,7 @@ const endPointQuery = async (
let payload = {
'auth': '0424bd59b807674191e7d77572075f33',
'jsonrpc': '2.0',
'method': 'omnihit.consultachamado',
// 'method': 'omnihit.consultachamado',
id: '101'
}
@ -49,6 +49,8 @@ const endPointQuery = async (
console.error(`Erro ao consultar endpoint ${url}: ${error}`);
}
// console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> response: ', response)
return response
}

View File

@ -8,8 +8,7 @@ import WhatsQueueIndex from "./WhatsQueueIndex";
const hitPortalMonitoring = async (params: object) => {
let response = await endPointQuery('http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php', 'post', params)
let response = await endPointQuery('http://177.107.192.247:8095/labs/monitoramentohit/api/api.php', 'post', params)
if (response && response.data.result.trim().length > 0) {
return response.data.result
@ -21,90 +20,6 @@ const hitPortalMonitoring = async (params: object) => {
return null
}
// let msg_endpoint: any = []
// let response2 = await endPointQuery('http://177.107.193.124:8095/labs/zabbix-frontend/api/api.php', 'post', 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++) {
// const 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
}
export default hitPortalMonitoring

View File

@ -34,7 +34,6 @@ const FindOrCreateTicketService = async (
// const botInfo = { isOnQueue: false }
if (ticket) {
await ticket.update({ unreadMessages });
}

View File

@ -0,0 +1,119 @@
import { subHours, subMinutes, subSeconds } from "date-fns";
import { Op } from "sequelize";
import BotIsOnQueue from "../../helpers/BotIsOnQueue";
import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError";
import { userInfo } from "os";
const FindOrCreateTicketServiceBot = async (
contact: Contact,
whatsappId: number,
unreadMessages: number,
groupContact?: Contact
): Promise<any> => {
try {
let ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id
}
});
const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId);
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue')
// const botInfo = { isOnQueue: false }
if (ticket) {
await ticket.update({ unreadMessages });
}
// if (!ticket && groupContact) {
// ticket = await Ticket.findOne({
// where: {
// contactId: groupContact.id
// },
// order: [["updatedAt", "DESC"]]
// });
// if (ticket) {
// await ticket.update({
// status: "pending",
// userId: null,
// unreadMessages
// });
// }
// }
if (!ticket && !groupContact) {
console.log('BOT CREATING OR REOPENING THE TICKET')
ticket = await Ticket.findOne({
where: {
contactId: contact.id,
userId: botInfo.userIdBot
},
order: [["updatedAt", "DESC"]]
});
if (ticket) {
await ticket.update({
status: "open",
userId: botInfo.userIdBot,
unreadMessages
});
}
}
let created = false
if (!ticket) {
created = true
let status = "open"
if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice"
}
ticket = await Ticket.create({
contactId: groupContact ? groupContact.id : contact.id,
status: status,
userId: botInfo.userIdBot,
isGroup: !!groupContact,
unreadMessages,
whatsappId
});
}
ticket = await ShowTicketService(ticket.id);
return {ticket, created};
} catch (error: any) {
console.error('===> Error on FindOrCreateTicketServiceBot.ts file: \n', error)
throw new AppError(error.message);
}
};
export default FindOrCreateTicketServiceBot;

View File

@ -29,26 +29,22 @@ function paramsQuery(params: string[]) {
//Report by user, startDate, endDate
const ShowTicketMessage = async (
ticketId: string | number,
onlyNumber: boolean = false,
params: string[],
fromMe?: boolean,
limit?: number,
limit: number,
fromMe: boolean,
params?: string[],
onlyNumber?: boolean,
regexp?: string): Promise<Message[]> => {
let where_clause = {}
if (onlyNumber) {
where_clause = {
ticketId: ticketId,
fromMe: fromMe ? fromMe : 0,
//body: {[Op.regexp]: '^[0-9]*$'},
// body: {[Op.regexp]: '^[0-3]$'},
body: { [Op.regexp]: regexp },
}
}
else if (params.length > 0) {
else if (params && params.length > 0) {
where_clause = {
ticketId: ticketId,
fromMe: fromMe ? fromMe : 0,
@ -60,22 +56,20 @@ const ShowTicketMessage = async (
}
}
}
else if (params.length === 0) {
else {
where_clause = {
ticketId: ticketId,
fromMe: fromMe ? fromMe : 0,
}
}
const ticket = await Message.findAll({
where: where_clause,
limit: limit ? limit : 10000,
limit: limit,
raw: true,
attributes: ['body', 'read', 'mediaType', 'fromMe', 'mediaUrl', [Sequelize.fn("DATE_FORMAT", Sequelize.col("createdAt"), "%d/%m/%Y %H:%i:%s"), "createdAt"]],

View File

@ -27,7 +27,7 @@ const ShowTicketService = async (id: string | number): Promise<Ticket> => {
]
});
console.log('>>>>>>>>>>>>>>>>>>>>>>>> ShowTicketService: ',ticket?.whatsappId)
// console.log('>>>>>>>>>>>>>>>>>>>>>>>> ShowTicketService: ',ticket?.whatsappId)
if (!ticket) {
throw new AppError("ERR_NO_TICKET_FOUND", 404);

View File

@ -36,7 +36,7 @@ import UpdateTicketService from "../TicketServices/UpdateTicketService";
import { date } from "faker";
import ShowQueueService from "../QueueService/ShowQueueService";
// import ShowTicketMessage from "../TicketServices/ShowTicketMessage"
import ShowTicketMessage from "../TicketServices/ShowTicketMessage"
import BotIsOnQueue from "../../helpers/BotIsOnQueue"
import Queue from "../../models/Queue";
@ -71,9 +71,9 @@ import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl";
import SendWhatsAppMedia from "./SendWhatsAppMedia";
import AppError from "../../errors/AppError";
import hitPortalMonitoring from "../../helpers/HitPortalMonitoring";
import { tr } from "date-fns/locale";
import mostRepeatedPhrase from "../../helpers/MostRepeatedPhrase";
import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot";
@ -356,7 +356,7 @@ const monitoramento_response2 = async (response: any | null, wbot: any, contact:
async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Contact, message: string, _msg?: WbotMessage) {
async function sendDelayedMessages(wbot: any, ticket: Ticket, contact: Contact, message: string, _msg?: WbotMessage) {
const body = message.replace(/\\n/g, '\n');
if (body.search('dialog_actions') != -1) {
@ -367,10 +367,6 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
if (msgAction.actions[0] == 'request_endpoint') {
// 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` })
@ -391,56 +387,95 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
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]}*\n_Digite *0* sair dessa operação e voltar ao menu principal._`)
}
else if (valid && valid.data.result == 'notfound') {
botSendMessage(ticket, `Protocolo *${params[1]}* não encontrado!\n_Digite *0* para voltar ao menu principal._`)
}
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 voltar ao menu principal._`)
}
}
if (params[0] === 'validate_n_chamado_web') return
if (params[0] === 'cod_web') {
response = await hitPortalMonitoring({ 'params[cod_web]': params[1], })
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 hitPortalMonitoring({ 'params[n_chamado_web]': params[1], })
response = await endPointQuery('http://177.107.192.247:8095/labs/monitoramentohit/api/api.php',
'post',
{
'params[n_chamado_web]': params[1],
'method': 'omnihit.consultachamado',
})
}
console.log('~~~~~~~~~~~~~~~~~~~~~~>response: ', response, ' | response.trim().length: ', response.trim().length)
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, contact, wbot, `Não existe nenhum chamado para essa consulta!\n _Digite *0* para voltar ao menu principal._`)
botSendMessage(ticket, `Não existe nenhum chamado para essa operação!\n _Digite *0* para voltar ao menu principal._`)
}
else if (response.trim().length > 0) {
await SendWhatsAppMessage({ body: response, ticket });
}
} catch (error) {
botSendMessage(ticket, contact, wbot, `Houve um erro ao realizar a consulta!\n _Digite *0* para voltar ao menu principal._`)
botSendMessage(ticket, `Houve um erro ao realizar a consulta!\n _Digite *0* para voltar ao menu principal._`)
}
} 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` })
await transferTicket(+msgAction.actions[1], wbot, ticket, contact)
await transferTicket(+msgAction.actions[1], wbot, ticket)
}
else if (msgAction.actions[0] == 'send_file') {
@ -491,12 +526,17 @@ const extractCallCode = (str: string) => {
}
const sendDialogflowAwswer = async (
wbot: Session,
wbot: any,
ticket: Ticket,
msg: any,
contact: Contact,
chat: Chat
send: boolean = true
// chat: Chat
) => {
console.log('-----------> msg.from: ', msg.from)
// return
const session = await createDialogflowSessionWithModel(ticket.queue.dialogflow);
if (session === undefined) {
return;
@ -504,12 +544,12 @@ const sendDialogflowAwswer = async (
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._`)
botSendMessage(ticket, `Desculpe, nao compreendi!\nEnvie apenas texto quando estiver interagindo com o bot!\n _Digite *0* para voltar ao menu principal._`)
return
}
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._`)
botSendMessage(ticket, `Desculpe, nao compreendi!\nTexto acima de 120 caracteres!\n _Digite *0* para voltar ao menu principal._`)
return
}
@ -524,6 +564,8 @@ const sendDialogflowAwswer = async (
return;
}
if (!send) return
// Make disponible later from session out
// chat.sendStateTyping();
@ -612,12 +654,10 @@ const verifyQueue = async (
});
const _ticket = await ShowTicketService(ticket.id);
// const chat = await msg.getChat();
const chat = wbot.chat
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat);
// const chat = wbot.chat
await sendDialogflowAwswer(wbot, _ticket, msg, contact);
return
}
//
@ -630,9 +670,6 @@ 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)
}
@ -678,7 +715,7 @@ const verifyQueue = async (
}
};
const transferTicket = async (queueIndex: number, wbot: Session, ticket: Ticket, contact: Contact) => {
const transferTicket = async (queueIndex: number, wbot: any, ticket: Ticket) => {
const botInfo = await BotIsOnQueue('botqueue')
@ -688,7 +725,7 @@ const transferTicket = async (queueIndex: number, wbot: Session, ticket: Ticket,
// console.log('queues ---> ', queues)
await botTransferTicket(queues[queueIndex], ticket, contact, wbot)
await botTransferTicket(queues[queueIndex], ticket)
}
@ -734,7 +771,7 @@ const isValidMsg = (msg: WbotMessage): boolean => {
};
const queuesOutBot = async (wbot: Session, botId: string | number) => {
const queuesOutBot = async (wbot: any, botId: string | number) => {
const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!);
@ -748,7 +785,9 @@ const queuesOutBot = async (wbot: Session, botId: string | number) => {
}
const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: Session) => {
const botTransferTicket = async (queues: Queue, ticket: Ticket) => {
console.log('>>>>>>>>>>>>>>>>> queues.id: ', queues.id)
await ticket.update({ userId: null });
@ -756,7 +795,7 @@ const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact
}
const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, mediaPath: string, fileNameExtension: string) => {
const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: any, mediaPath: string, fileNameExtension: string) => {
const debouncedSentMessage = debounce(
@ -785,7 +824,7 @@ const botSendMedia = async (ticket: Ticket, contact: Contact, wbot: Session, med
}
const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: string) => {
const botSendMessage = (ticket: Ticket, msg: string) => {
const debouncedSentMessage = debounce(
@ -945,13 +984,55 @@ const handleMessage = async (
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
const ticket = await FindOrCreateTicketService(
let ticket
const _botInfo = await BotIsOnQueue('botqueue')
if (_botInfo.isOnQueue) {
let ticket_obj: any = await FindOrCreateTicketServiceBot(
contact,
wbot.id!,
unreadMessages,
// groupContact
);
ticket = ticket_obj.ticket
if (ticket_obj.created) {
let queue = await ShowQueueService(_botInfo.botQueueId);
await UpdateTicketService({
ticketData: { queueId: queue.id },
ticketId: ticket.id
});
ticket = await ShowTicketService(ticket.id);
}
}
else {
ticket = await FindOrCreateTicketService(
contact,
wbot.id!,
unreadMessages,
// groupContact
);
}
// const ticket = await FindOrCreateTicketService(
// contact,
// wbot.id!,
// unreadMessages,
// // groupContact
// );
//
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1007,7 +1088,7 @@ const handleMessage = async (
if (repet.occurrences > 4) {
await transferTicket(0, wbot, ticket, contact)
await transferTicket(0, wbot, ticket)
await SendWhatsAppMessage({
body: `Seu atendimento foi transferido para um agente!\n\nPara voltar ao menu principal digite *0*
@ -1016,7 +1097,59 @@ const handleMessage = async (
}
else {
await sendDialogflowAwswer(wbot, ticket, msg, contact, chat);
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 voltar ao menu principal._`)
await SendWhatsAppMessage({ body: `Aguarde, inserindo informação...\n_Digite *0* para voltar ao menu principal._`, 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}\n_Digite *0* para voltar ao menu principal._`)
}
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 voltar ao menu principal._`)
}
}
else {
await sendDialogflowAwswer(wbot, ticket, msg, contact,);
}
}
}
else if (botInfo.isOnQueue && !msg.fromMe && msg.body == '0' && ticket.status == 'pending' && ticket.queueId) {
@ -1033,7 +1166,7 @@ const handleMessage = async (
// const chat = await msg.getChat();
const chat = wbot.chat
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat);
await sendDialogflowAwswer(wbot, _ticket, msg, contact,);
return
}
@ -1086,19 +1219,19 @@ const handleMsgAck = async (msg_id: any, ack: any) => {
}
};
const wbotMessageListener = (wbot: Session): void => {
const wbotMessageListener = (wbot: any): void => {
wbot.on("message_create", async msg => {
wbot.on("message_create", async (msg: any) => {
handleMessage(msg, wbot);
});
wbot.on("media_uploaded", async msg => {
wbot.on("media_uploaded", async (msg: any) => {
handleMessage(msg, wbot);
});
wbot.on("message_ack", async (msg, ack) => {
wbot.on("message_ack", async (msg: any, ack: any) => {
handleMsgAck(msg, ack);
});
};
export { wbotMessageListener, handleMessage, handleMsgAck, lst, verifyContact };
export { wbotMessageListener, handleMessage, handleMsgAck, lst, verifyContact, sendDialogflowAwswer };