Versão com ajustes para producao

adriano 2023-04-27 10:18:27 -03:00
parent e6c7a298c4
commit 2c9ae18a36
6 changed files with 139 additions and 64 deletions

View File

@ -5,7 +5,11 @@ import os from 'os';
import ListUsersService from "../services/UserServices/ListUsersService"
const _botIsOnQueue = async (botName: string) => {
const _botIsOnQueue = async (botName: string, accept: boolean = true) => {
if (!accept) {
return { isOnQueue: false }
}
const botInfoFile = dir.join(os.tmpdir(), `botInfo.json`);
@ -18,7 +22,7 @@ const _botIsOnQueue = async (botName: string) => {
console.log('botInfo.json file exists');
const botInfo = fs.readFileSync(botInfoFile, {encoding:'utf8', flag:'r'});
const botInfo = fs.readFileSync(botInfoFile, { encoding: 'utf8', flag: 'r' });
return JSON.parse(botInfo)
@ -28,7 +32,7 @@ const _botIsOnQueue = async (botName: string) => {
} catch (error) {
console.log('There was an error on try to read the botInfo.json file: ',error)
console.log('There was an error on try to read the botInfo.json file: ', error)
}

View File

@ -49,6 +49,10 @@ class Contact extends Model<Contact> {
@Column
useDialogflow: boolean;
@Default(false)
@Column
accept: boolean;
@CreatedAt
createdAt: Date;

View File

@ -8,6 +8,7 @@ import { logger } from "../../utils/logger";
const sessions : Map<number, SessionsClient> = new Map<number, SessionsClient>();
const createDialogflowSession = async (id:number, projectName:string, jsonContent:string) : Promise<SessionsClient | undefined> => {
if(sessions.has(id)) {
return sessions.get(id);
}
@ -26,7 +27,11 @@ const createDialogflowSession = async (id:number, projectName:string, jsonConten
return session;
}
const createDialogflowSessionWithModel = async (model: Dialogflow) : Promise<SessionsClient | undefined> => {
// console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 0004: ',model)
return createDialogflowSession(model.id, model.projectName, model.jsonContent);
}

View File

@ -30,7 +30,7 @@ const FindOrCreateTicketService = async (
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue')
const botInfo = await BotIsOnQueue('botqueue', contact.accept)
// const botInfo = { isOnQueue: false }

View File

@ -96,6 +96,8 @@ const verifyContact = async (msgContact: any): Promise<Contact> => {
const contact = CreateOrUpdateContactService(contactData);
// console.log('----------> contact: ', JSON.parse(JSON.stringify(contact)))
return contact;
};
@ -520,17 +522,17 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
console.log('>>>>>>>>>>>>>>> msgAction: ', msgAction, ' | msgAction.actions[1]: ', msgAction.actions[1])
const contact_custom_field = await ShowContactCustomFieldService(contact.id)
// const contact_custom_field = await ShowContactCustomFieldService(contact.id)
if (contact_custom_field && contact_custom_field.length > 0) {
// if (contact_custom_field && contact_custom_field.length > 0) {
const msg_endpoint = await queryEndPointHit(contact_custom_field[0].value)
// const msg_endpoint = await queryEndPointHit(contact_custom_field[0].value)
await monitoramento_response2(msg_endpoint, wbot, contact, ticket, 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)
// console.log('************* contact_custom_field: ', contact_custom_field)
// OLD
// const msg = await wbot.sendMessage(`${contact.number}@c.us`, msgAction.msgBody);
@ -595,8 +597,15 @@ const sendDialogflowAwswer = async (
ticket: Ticket,
msg: any,
contact: Contact,
chat: Chat
chat: Chat,
startDialog: boolean = false
) => {
if (startDialog)
msg.body = 'menu'
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 04')
const session = await createDialogflowSessionWithModel(ticket.queue.dialogflow);
if (session === undefined) {
return;
@ -605,23 +614,22 @@ const sendDialogflowAwswer = async (
// Make disponible later from session out
// wbot.sendPresenceAvailable();
// console.log('typeof(msg.type): ', typeof (msg.type), ' | msg.type: ', msg.type)
// console.log('KKKKKKKKK msg: ', msg)
// console.log('KKKKKKKKK msg2: ', msg['body'])
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 4')
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
}
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 5')
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._`)
return
}
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 6')
let dialogFlowReply = await queryDialogFlow(
session,
ticket.queue.dialogflow.projectName,
@ -668,15 +676,16 @@ const verifyQueue = async (
let choosenQueue = null
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue')
let botInfo = await BotIsOnQueue('botqueue', contact.accept)
// const botInfo = { isOnQueue: false, botQueueId: 0, userIdBot: 0 }
console.log('::::::::::::> contact.accept: ', contact.accept)
if (botInfo.isOnQueue) {
choosenQueue = await ShowQueueService(botInfo.botQueueId);
}
else if (queues.length === 1) {
selectedOption = 1;
choosenQueue = queues[+selectedOption - 1];
@ -689,6 +698,7 @@ const verifyQueue = async (
selectedOption = selectedOption.replace(/[^1-9]/g, '')
///////////////////////////////////
if (+selectedOption == 1 || +selectedOption == 2)
choosenQueue = queues[+selectedOption - 1];
}
@ -696,6 +706,32 @@ const verifyQueue = async (
if (choosenQueue) {
// console.log('---------------> choosendQueue: ', choosenQueue)
if (choosenQueue.name == 'sim') {
await contact.update({ accept: true });
botInfo = await BotIsOnQueue('botqueue')
choosenQueue = await ShowQueueService(botInfo.botQueueId);
}
else if (choosenQueue.name == 'nao') {
await SendWhatsAppMessage({ body: `\u200e${choosenQueue.greetingMessage}`, ticket });
await UpdateTicketService({
ticketData: { status: 'closed' },
ticketId: ticket.id
});
console.log('QUEUE NAO')
return
}
// Atualizando o status do ticket para mostrar notificação para o atendente da fila escolhida pelo usuário. De queueChoice para pending
if (queues.length > 1 && !botInfo.isOnQueue) {
@ -715,21 +751,32 @@ const verifyQueue = async (
// O bot abre a mensagem na fila para atender o usuario
if (botInfo.isOnQueue) {
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 1')
await UpdateTicketService({
ticketData: { status: 'open', userId: botInfo.userIdBot },
ticketId: ticket.id
});
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 2')
const _ticket = await ShowTicketService(ticket.id);
// const chat = await msg.getChat();
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3')
const chat = wbot.chat
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat);
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat, true);
console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 03')
return
}
//
let body = ''
if (botOptions.length > 0) {
@ -744,13 +791,15 @@ const verifyQueue = async (
sendWhatsAppMessageSocket(ticket, body)
// console.log('uuuuuuuuuuuuuuuuuuuuuuuuuuu 3 body: ',body)
}
else {
//test del transfere o atendimento se entrar na ura infinita
let ticket_message = await ShowTicketMessage(ticket.id, false);
if (ticket_message.length > 10) {
if (ticket_message.length > 20) {
await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id });
@ -760,7 +809,10 @@ const verifyQueue = async (
let options = "";
queues.forEach((queue, index) => {
if (queue.name == 'sim' || queue.name == 'nao')
options += `*${index + 1}* - ${queue.name}\n`;
});
const body = `\u200e${greetingMessage}\n${options}`;
@ -773,7 +825,6 @@ const verifyQueue = async (
sendWhatsAppMessageSocket(ticket, body)
},
3000,
ticket.id
@ -790,7 +841,7 @@ const verifyQueue = async (
const transferTicket = async (queueIndex: number, wbot: Session, ticket: Ticket, contact: Contact) => {
const botInfo = await BotIsOnQueue('botqueue')
const botInfo = await BotIsOnQueue('botqueue', contact.accept)
const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId)
@ -975,6 +1026,24 @@ const handleMessage = async (
if (msg.fromMe) {
if (/\u200e/.test(msg.body[0])) {
// remove this in the future because impact have process impact
const queue = await Queue.findOne(
{
where: { name: 'nao' },
raw: true,
attributes: ['name', 'greetingMessage']
});
if (queue && queue.greetingMessage.trim() == msg.body.replace(/\u200e/, '').trim()) {
return
}
}
console.log('PASSOU -------------')
// console.log('FROM ME: ', msg.fromMe, ' | /\u200e/.test(msg.body[0]: ', (/\u200e/.test(msg.body[0])))
// messages sent automatically by wbot have a special character in front of it
@ -1043,8 +1112,19 @@ const handleMessage = async (
const contact = await verifyContact(msgContact);
// console.log('----------> contact: ', JSON.parse(JSON.stringify(contact)))
// let contactAux = JSON.parse(JSON.stringify(contact))
// console.log('contactAux.accept: ',contactAux.accept)
// if(contactAux && !contactAux.accept){
// return
// }
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
@ -1056,9 +1136,6 @@ const handleMessage = async (
// groupContact
);
console.log('okkkkkkkkkkkkkkkkkk 1')
//
// await updateTicketCacheByTicketId(ticket.id, {'contact.profilePicUrl': ticket.contact.profilePicUrl})
@ -1075,8 +1152,6 @@ const handleMessage = async (
throw new AppError(error.message);
}
}
//
@ -1089,10 +1164,6 @@ const handleMessage = async (
}
console.log('okkkkkkkkkkkkkkkkkk 2')
if (
!ticket.queue &&
!chat.isGroup &&
@ -1100,28 +1171,21 @@ const handleMessage = async (
!ticket.userId &&
whatsapp.queues.length >= 1
) {
await verifyQueue(wbot, msg, ticket, contact);
}
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
//Habilitar esse caso queira usar o bot
const botInfo = await BotIsOnQueue('botqueue')
const botInfo = await BotIsOnQueue('botqueue', contact.accept)
// 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);
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')
@ -1151,8 +1215,6 @@ const handleMessage = async (
}
//
console.log('okkkkkkkkkkkkkkkkkk 6')
await sendDialogflowAwswer(wbot, ticket, msg, contact, chat);
}