diff --git a/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts b/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts index 38d7f6b..42d7d53 100644 --- a/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts +++ b/backend/src/services/TicketServices/FindOrCreateTicketServiceBot.ts @@ -6,144 +6,162 @@ import Ticket from "../../models/Ticket"; import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowTicketService from "./ShowTicketService"; import AppError from "../../errors/AppError"; -import { userInfo } from "os"; +import { userInfo } from "os"; import ShowQueueService from "../QueueService/ShowQueueService"; import UpdateTicketService from "./UpdateTicketService"; - +import { getSettingValue } from "../../helpers/WhaticketSettings"; +import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber"; const FindOrCreateTicketServiceBot = async ( - contact: Contact, - whatsappId: number, - unreadMessages: number, - groupContact?: Contact + contact: Contact, + whatsappId: number, + unreadMessages: number, + groupContact?: Contact ): Promise => { + try { + // let ticket = await Ticket.findOne({ + // where: { + // status: { + // [Op.or]: ["open", "pending", "queueChoice"] + // }, + // contactId: groupContact ? groupContact.id : contact.id + // } + // }); - try { + let ticket; - let ticket = await Ticket.findOne({ - where: { - status: { - [Op.or]: ["open", "pending", "queueChoice"] - }, - contactId: groupContact ? groupContact.id : contact.id - } + if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") { + let whats = await ListWhatsAppsNumber(whatsappId); + + ticket = await Ticket.findOne({ + where: { + status: { + [Op.or]: ["open", "pending", "queueChoice"] + }, + contactId: groupContact ? groupContact.id : contact.id, + whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) } + } + }); + } else { + ticket = await Ticket.findOne({ + where: { + status: { + [Op.or]: ["open", "pending", "queueChoice"] + }, + contactId: groupContact ? groupContact.id : contact.id + } + }); + } + + const { queues, greetingMessage, phoneNumberId } = + 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, + whatsappId: whatsappId + }, + order: [["updatedAt", "DESC"]] + }); + + if (ticket) { + await ticket.update({ + status: "open", + userId: botInfo.userIdBot, + unreadMessages }); - const { queues, greetingMessage, phoneNumberId } = - await ShowWhatsAppService(whatsappId); + console.log("lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); - - //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 - }); - - console.log('lxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') - - await dialogFlowStartContext(contact, ticket, botInfo); - - } - } - - 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, - phoneNumberId - }); - - console.log('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy') - - await dialogFlowStartContext(contact, ticket, botInfo); - - } - - 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); + await dialogFlowStartContext(contact, ticket, botInfo); + } } + + 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, + phoneNumberId + }); + + console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"); + + await dialogFlowStartContext(contact, ticket, botInfo); + } + + 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; -async function dialogFlowStartContext(contact: Contact, ticket: Ticket, botInfo: any) { +async function dialogFlowStartContext( + contact: Contact, + ticket: Ticket, + botInfo: any +) { + let msg: any = { type: "chat", from: `${contact.number}@c.us`, body: "0" }; - let msg: any = { type: 'chat', from: `${contact.number}@c.us`, body: '0' }; + let queue = await ShowQueueService(botInfo.botQueueId); - 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); - - // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false); - + // await sendDialogflowAnswer(ticket.whatsappId, ticket, msg, contact, false); } - diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 204b03b..c017331 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -184,7 +184,11 @@ const verifyMediaMessage = async ( phoneNumberId: msg?.phoneNumberId, fromAgent: false }; - if(messageData.mediaType === 'video' || messageData.mediaType === 'audio' && getSettingValue('blockAudioVideoMedia')?.value === 'enabled'){ + if ( + messageData.mediaType === "video" || + (messageData.mediaType === "audio" && + getSettingValue("blockAudioVideoMedia")?.value === "enabled") + ) { mediaAuthorized = false; } if (msg?.fromMe) { @@ -201,35 +205,48 @@ const verifyMediaMessage = async ( body: media.filename }; } - if(mediaAuthorized){ + if (mediaAuthorized) { try { await writeFileAsync( - join(__dirname, "..", "..", "..", "..", "..", "public", media.filename), + join( + __dirname, + "..", + "..", + "..", + "..", + "..", + "public", + media.filename + ), media.data, "base64" - ); - } catch (err) { - Sentry.captureException(err); - logger.error(`There was an error: wbotMessageLitener.ts: ${err}`); - } + ); + } catch (err) { + Sentry.captureException(err); + logger.error(`There was an error: wbotMessageLitener.ts: ${err}`); + } } } - if(mediaAuthorized){ + if (mediaAuthorized) { await ticket.update({ lastMessage: msg.body || media.filename }); const newMessage = await CreateMessageService({ messageData }); return newMessage; - }else{ - if (ticket.status !== "queueChoice") { - botSendMessage( - ticket, - `Atenção! Mensagem ignorada, tipo de mídia não suportado.` + } else { + if (ticket.status !== "queueChoice") { + botSendMessage( + ticket, + `Atenção! Mensagem ignorada, tipo de mídia não suportado.` ); } - messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`; - messageData.mediaUrl = ''; - await ticket.update({ lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`}); - const newMessage = await CreateMessageService({ messageData }); - console.log(`--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!`) + messageData.body = `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.`; + messageData.mediaUrl = ""; + await ticket.update({ + lastMessage: `Mensagem de *${messageData.mediaType}* ignorada, tipo de mídia não suportado.` + }); + const newMessage = await CreateMessageService({ messageData }); + console.log( + `--------->>> Mensagem do tipo: ${messageData.mediaType}, ignorada!` + ); } }; @@ -318,12 +335,15 @@ const verifyMessage = async ( quotedMsgId: quotedMsg, phoneNumberId: msg?.phoneNumberId }; - if (msg?.fromMe) { const botInfo = await BotIsOnQueue("botqueue"); if (botInfo.isOnQueue) { - const ura: any = await get({ key: "ura" }); + let whatsapp = await whatsappCache(ticket.whatsappId); + + const ura: any = await get({ + key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + }); if (ura && !ura.includes(JSON.stringify(msg?.body))) { messageData = { ...messageData, fromAgent: true }; @@ -341,7 +361,7 @@ const verifyMessage = async ( } else { messageData = { ...messageData, body: JSON.stringify(msg.vCards) }; } - } + } await CreateMessageService({ messageData }); }; @@ -399,12 +419,17 @@ const verifyQueue = async ( ticketId: ticket.id }); - const data = await get({ key: "ura", parse: true }); + const whatsapp = await whatsappCache(ticket.whatsappId); + + const data = await get({ + key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", + parse: true + }); await createObject({ whatsappId: `${ticket.whatsappId}`, contactId: `${ticket.contactId}`, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: data[1].id, history: `|${data[1].id}` }); @@ -435,7 +460,7 @@ const verifyQueue = async ( body = `\u200e${choosenQueue.greetingMessage}`; } - io.emit('notifyPeding', {data: {ticket, queue: choosenQueue}}); + io.emit("notifyPeding", { data: { ticket, queue: choosenQueue } }); sendWhatsAppMessageSocket(ticket, body); } else { @@ -779,7 +804,7 @@ const handleMessage = async ( unreadMessages // groupContact ); - } + } if (getSettingValue("oneContactChatWithManyWhats")?.value == "disabled") { // Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen @@ -1004,8 +1029,17 @@ const handleMessage = async ( }; const menu = async (userTyped: string, whatsappId: any, contactId: any) => { - let lastId = await findObject(whatsappId, contactId, "ura"); - const data: any = await get({ key: "ura", parse: true }); + let whatsapp = await whatsappCache(whatsappId); + + let lastId = await findObject( + whatsappId, + contactId, + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + ); + const data: any = await get({ + key: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", + parse: true + }); console.log("lastId[0]: ", lastId[0]); @@ -1013,13 +1047,17 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: data[1].id, history: `|${data[1].id}` }); } - lastId = await findObject(whatsappId, contactId, "ura"); + lastId = await findObject( + whatsappId, + contactId, + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + ); console.log("LAST ID: ", lastId); let option: any; @@ -1043,7 +1081,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { let uraOptionSelected = await findObject( whatsappId, contactId, - "ura" + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" ); uraOptionSelected = uraOptionSelected[4].split("|"); @@ -1052,7 +1090,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: data[1].id, history: `|${data[1].id}` }); @@ -1068,7 +1106,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: id, history }); @@ -1091,7 +1129,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: response.id, history }); @@ -1101,7 +1139,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: data[1].id, history: `|${data[1].id}` }); @@ -1121,7 +1159,11 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { } async function mainOptionsMenu(userTyped: any) { - let currentMenu = await findObject(whatsappId, contactId, "ura"); + let currentMenu = await findObject( + whatsappId, + contactId, + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + ); const menuValues = data .filter((m: any) => m.idmaster == currentMenu[3]) @@ -1141,7 +1183,7 @@ const menu = async (userTyped: string, whatsappId: any, contactId: any) => { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: response.id, history }); @@ -1328,7 +1370,13 @@ async function vcard(msg: any) { } async function backUra(whatsappId: any, contactId: any, data: any) { - let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); + let whatsapp = await whatsappCache(whatsappId); + + let uraOptionSelected = await findObject( + whatsappId, + contactId, + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + ); uraOptionSelected = uraOptionSelected[4].split("|").filter(Boolean); @@ -1349,7 +1397,7 @@ async function backUra(whatsappId: any, contactId: any, data: any) { await createObject({ whatsappId, contactId, - identifier: "ura", + identifier: whatsapp?.number ? `ura_${whatsapp?.number}` : "ura", value: id, history }); @@ -1365,7 +1413,13 @@ async function historyUra( id: any, remove?: boolean ) { - let uraOptionSelected = await findObject(whatsappId, contactId, "ura"); + let whatsapp = await whatsappCache(whatsappId); + + let uraOptionSelected = await findObject( + whatsappId, + contactId, + whatsapp?.number ? `ura_${whatsapp?.number}` : "ura" + ); let history = ""; console.log("SELECED OPTION uraOptionSelected: ", uraOptionSelected); @@ -1387,3 +1441,13 @@ async function historyUra( async function whatsappInfo(whatsappId: string | number) { return await Whatsapp.findByPk(whatsappId); } +async function whatsappCache(whatsappId: any) { + let whatsapp = await get({ key: "whatsapp:*", parse: true }); + + let uraByNumber = await get({ key: "ura_*", parse: true }); + // console.log("------------------------> uraByNumber: ", uraByNumber); + + whatsapp = whatsapp.filter((w: any) => +w?.id == +whatsappId); + + if (whatsapp && whatsapp.length > 0 && uraByNumber) return whatsapp[0]; +}