From 69da69089ab909378f18c67041915a83de02ed24 Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 20 Apr 2023 15:48:42 -0300 Subject: [PATCH] Inclusao de try catch para rastrear a origem do tcp_wrap.cc erro --- .../ContactServices/CreateContactService.ts | 63 +++-- .../CreateOrUpdateContactService.ts | 71 +++-- .../ContactServices/UpdateContactService.ts | 136 +++++----- .../MessageServices/CreateMessageService.ts | 12 +- .../QueueService/CreateQueueService.ts | 13 +- .../QueueService/UpdateQueueService.ts | 109 ++++---- .../CreateSchedulingNotifyService.ts | 86 +++--- .../UpdateSchedulingNotifyService.ts | 49 ++-- .../SettingServices/UpdateSettingService.ts | 25 +- .../TicketServices/CreateTicketService.ts | 89 +++--- .../FindOrCreateTicketService.ts | 172 ++++++------ .../TicketServices/UpdateTicketService.ts | 12 +- .../CreateOrUpdateOnlineUserService.ts | 256 +++++++++--------- .../UserServices/CreateUserService.ts | 107 ++++---- .../UserServices/UpdateUserService.ts | 116 ++++---- .../WbotServices/SendWhatsAppMessage.ts | 214 ++++++--------- .../WbotServices/wbotMessageListener.ts | 35 +-- .../WhatsappService/CreateWhatsAppService.ts | 118 ++++---- .../WhatsappService/UpdateWhatsAppService.ts | 151 ++++++----- 19 files changed, 972 insertions(+), 862 deletions(-) diff --git a/backend/src/services/ContactServices/CreateContactService.ts b/backend/src/services/ContactServices/CreateContactService.ts index c09bc33..692be06 100644 --- a/backend/src/services/ContactServices/CreateContactService.ts +++ b/backend/src/services/ContactServices/CreateContactService.ts @@ -24,36 +24,45 @@ const CreateContactService = async ({ profilePicUrl='', extraInfo = [] }: Request): Promise => { - - const numberExists = await Contact.findOne({ - where: { number } - }); - if (numberExists) { - throw new AppError("ERR_DUPLICATED_CONTACT"); - } + try { - const contact = await Contact.create( - { - name, - number, - email, - profilePicUrl, - extraInfo - }, - { - include: ["extraInfo"] + const numberExists = await Contact.findOne({ + where: { number } + }); + + if (numberExists) { + throw new AppError("ERR_DUPLICATED_CONTACT"); } - ); - - - - // TEST DEL - await createOrUpdateContactCache(`contact:${contact.id}`, {id: contact.id, name, number, profilePicUrl, isGroup:'false', extraInfo, email }) - // - - - return contact; + + const contact = await Contact.create( + { + name, + number, + email, + profilePicUrl, + extraInfo + }, + { + include: ["extraInfo"] + } + ); + + + + // TEST DEL + await createOrUpdateContactCache(`contact:${contact.id}`, {id: contact.id, name, number, profilePicUrl, isGroup:'false', extraInfo, email }) + // + + + return contact; + + } catch (error: any) { + console.error('===> Error on CreateContactService.ts file: \n', error) + throw new AppError(error.message); + } + + }; export default CreateContactService; diff --git a/backend/src/services/ContactServices/CreateOrUpdateContactService.ts b/backend/src/services/ContactServices/CreateOrUpdateContactService.ts index 380cf9c..50d5d5f 100644 --- a/backend/src/services/ContactServices/CreateOrUpdateContactService.ts +++ b/backend/src/services/ContactServices/CreateOrUpdateContactService.ts @@ -2,6 +2,8 @@ import { getIO } from "../../libs/socket"; import Contact from "../../models/Contact"; import { createOrUpdateContactCache } from '../../helpers/ContactsCache' +import { tr } from "date-fns/locale"; +import AppError from "../../errors/AppError"; interface ExtraInfo { name: string; @@ -25,47 +27,56 @@ const CreateOrUpdateContactService = async ({ email = "", extraInfo = [] }: Request): Promise => { - const number = isGroup ? rawNumber : rawNumber.replace(/[^0-9]/g, ""); - const io = getIO(); - let contact: Contact | null; + try { + + const number = isGroup ? rawNumber : rawNumber.replace(/[^0-9]/g, ""); + + const io = getIO(); + let contact: Contact | null; - contact = await Contact.findOne({ where: { number } }); + contact = await Contact.findOne({ where: { number } }); - if (contact) { - contact.update({ profilePicUrl }); + if (contact) { + contact.update({ profilePicUrl }); - // TEST DEL - await createOrUpdateContactCache(`contact:${contact.id}`, { profilePicUrl }) - // + // TEST DEL + await createOrUpdateContactCache(`contact:${contact.id}`, { profilePicUrl }) + // - io.emit("contact", { - action: "update", - contact - }); - } else { - contact = await Contact.create({ - name, - number, - profilePicUrl, - email, - isGroup, - extraInfo - }); + io.emit("contact", { + action: "update", + contact + }); + } else { + contact = await Contact.create({ + name, + number, + profilePicUrl, + email, + isGroup, + extraInfo + }); - // TEST DEL - await createOrUpdateContactCache(`contact:${contact.id}`, {id: contact.id, name, number, profilePicUrl, isGroup, extraInfo, email }) - // + // TEST DEL + await createOrUpdateContactCache(`contact:${contact.id}`, { id: contact.id, name, number, profilePicUrl, isGroup, extraInfo, email }) + // - io.emit("contact", { - action: "create", - contact - }); + io.emit("contact", { + action: "create", + contact + }); + } + + return contact; + + } catch (error: any) { + console.error('===> Error on CreateOrUpdateContactService.ts file: \n', error) + throw new AppError(error.message); } - return contact; }; export default CreateOrUpdateContactService; diff --git a/backend/src/services/ContactServices/UpdateContactService.ts b/backend/src/services/ContactServices/UpdateContactService.ts index a4963e5..3478743 100644 --- a/backend/src/services/ContactServices/UpdateContactService.ts +++ b/backend/src/services/ContactServices/UpdateContactService.ts @@ -4,6 +4,7 @@ import ContactCustomField from "../../models/ContactCustomField"; import { updateTicketsByContactsCache } from '../../helpers/TicketCache' import { updateContactCacheById } from '../../helpers/ContactsCache' +import { tr } from "date-fns/locale"; interface ExtraInfo { id?: number; @@ -27,78 +28,87 @@ const UpdateContactService = async ({ contactData, contactId }: Request): Promise => { - const { email, name, number, extraInfo } = contactData; - // console.log('email, name, number, extraInfo: ', email, name, number, extraInfo) + try { - const contact = await Contact.findOne({ - where: { id: contactId }, - attributes: ["id", "name", "number", "email", "profilePicUrl"], - include: ["extraInfo"] - }); + const { email, name, number, extraInfo } = contactData; - if (!contact) { - throw new AppError("ERR_NO_CONTACT_FOUND", 404); - } + // console.log('email, name, number, extraInfo: ', email, name, number, extraInfo) - if (extraInfo) { - await Promise.all( - extraInfo.map(async info => { - await ContactCustomField.upsert({ ...info, contactId: contact.id }); - }) - ); - - await Promise.all( - contact.extraInfo.map(async oldInfo => { - const stillExists = extraInfo.findIndex(info => info.id === oldInfo.id); - - if (stillExists === -1) { - await ContactCustomField.destroy({ where: { id: oldInfo.id } }); - } - }) - ); - } - - const oldNumber = contact.number - - - //Solução para o erro tcp_wrap.cc - // console.log('----------> oldNumber: ', oldNumber) - - if (number) { - const numberExists = await Contact.findOne({ - where: { number } + const contact = await Contact.findOne({ + where: { id: contactId }, + attributes: ["id", "name", "number", "email", "profilePicUrl"], + include: ["extraInfo"] }); - if (numberExists) { - throw new AppError("ERR_DUPLICATED_CONTACT"); + if (!contact) { + throw new AppError("ERR_NO_CONTACT_FOUND", 404); } + + if (extraInfo) { + await Promise.all( + extraInfo.map(async info => { + await ContactCustomField.upsert({ ...info, contactId: contact.id }); + }) + ); + + await Promise.all( + contact.extraInfo.map(async oldInfo => { + const stillExists = extraInfo.findIndex(info => info.id === oldInfo.id); + + if (stillExists === -1) { + await ContactCustomField.destroy({ where: { id: oldInfo.id } }); + } + }) + ); + } + + const oldNumber = contact.number + + + //Solução para o erro tcp_wrap.cc + console.log('----------> oldNumber: ', oldNumber) + if (number) { + const numberExists = await Contact.findOne({ + where: { number } + }); + + if (numberExists && numberExists.id != +contactId) { + throw new AppError("ERR_DUPLICATED_CONTACT"); + } + } + + + await contact.update({ + name, + number, + email + }); + + + + //TEST DEL + await updateTicketsByContactsCache(oldNumber, contact.name, contact.number) + // + + + await contact.reload({ + attributes: ["id", "name", "number", "email", "profilePicUrl"], + include: ["extraInfo"] + }); + + + + // console.log('contactcontactcontactcontact: ',flatten(JSON.parse(JSON.stringify(contact)))) + await updateContactCacheById(contact.id, JSON.parse(JSON.stringify(contact))) + + return contact; + + } catch (error: any) { + console.error('===> Error on UpdateContactService.ts file: \n', error) + throw new AppError(error.message); } - // - - await contact.update({ - name, - number, - email - }); - - //TEST DEL - await updateTicketsByContactsCache(oldNumber, contact.name, contact.number) - // - - - await contact.reload({ - attributes: ["id", "name", "number", "email", "profilePicUrl"], - include: ["extraInfo"] - }); - - - - // console.log('contactcontactcontactcontact: ',flatten(JSON.parse(JSON.stringify(contact)))) - await updateContactCacheById(contact.id, JSON.parse(JSON.stringify(contact))) - - return contact; }; export default UpdateContactService; diff --git a/backend/src/services/MessageServices/CreateMessageService.ts b/backend/src/services/MessageServices/CreateMessageService.ts index 853cd07..11a009b 100644 --- a/backend/src/services/MessageServices/CreateMessageService.ts +++ b/backend/src/services/MessageServices/CreateMessageService.ts @@ -1,3 +1,4 @@ +import AppError from "../../errors/AppError"; import { updateTicketCacheByTicketId } from "../../helpers/TicketCache"; import { getIO } from "../../libs/socket"; import Message from "../../models/Message"; @@ -21,7 +22,9 @@ const CreateMessageService = async ({ messageData }: Request): Promise // console.log('UPSERT MESSAGE messageData: ', messageData) - await Message.upsert(messageData); + try { + + await Message.upsert(messageData); const message = await Message.findByPk(messageData.id, { include: [ @@ -75,6 +78,13 @@ const CreateMessageService = async ({ messageData }: Request): Promise return message; + + } catch (error: any) { + console.error('===> Error on CreateMessageService.ts file: \n', error) + throw new AppError(error.message); + } + + }; export default CreateMessageService; diff --git a/backend/src/services/QueueService/CreateQueueService.ts b/backend/src/services/QueueService/CreateQueueService.ts index 57881e1..b783da8 100644 --- a/backend/src/services/QueueService/CreateQueueService.ts +++ b/backend/src/services/QueueService/CreateQueueService.ts @@ -9,7 +9,10 @@ interface QueueData { } const CreateQueueService = async (queueData: QueueData): Promise => { - const { color, name } = queueData; + + try { + + const { color, name } = queueData; const queueSchema = Yup.object().shape({ name: Yup.string() @@ -55,13 +58,19 @@ const CreateQueueService = async (queueData: QueueData): Promise => { try { await queueSchema.validate({ color, name }); - } catch (err) { + } catch (err: any) { throw new AppError(err.message); } const queue = await Queue.create(queueData); return queue; + + } catch (error: any) { + console.error('===> Error on CreateQueueService.ts file: \n', error) + throw new AppError(error.message); + } + }; export default CreateQueueService; diff --git a/backend/src/services/QueueService/UpdateQueueService.ts b/backend/src/services/QueueService/UpdateQueueService.ts index 8aa2a23..d52da18 100644 --- a/backend/src/services/QueueService/UpdateQueueService.ts +++ b/backend/src/services/QueueService/UpdateQueueService.ts @@ -14,60 +14,69 @@ const UpdateQueueService = async ( queueId: number | string, queueData: QueueData ): Promise => { - const { color, name } = queueData; - - const queueSchema = Yup.object().shape({ - name: Yup.string() - .min(2, "ERR_QUEUE_INVALID_NAME") - .test( - "Check-unique-name", - "ERR_QUEUE_NAME_ALREADY_EXISTS", - async value => { - if (value) { - const queueWithSameName = await Queue.findOne({ - where: { name: value, id: { [Op.not]: queueId } } - }); - - return !queueWithSameName; - } - return true; - } - ), - color: Yup.string() - .required("ERR_QUEUE_INVALID_COLOR") - .test("Check-color", "ERR_QUEUE_INVALID_COLOR", async value => { - if (value) { - const colorTestRegex = /^#[0-9a-f]{3,6}$/i; - return colorTestRegex.test(value); - } - return true; - }) - .test( - "Check-color-exists", - "ERR_QUEUE_COLOR_ALREADY_EXISTS", - async value => { - if (value) { - const queueWithSameColor = await Queue.findOne({ - where: { color: value, id: { [Op.not]: queueId } } - }); - return !queueWithSameColor; - } - return true; - } - ) - }); try { - await queueSchema.validate({ color, name }); - } catch (err) { - throw new AppError(err.message); - } - const queue = await ShowQueueService(queueId); + const { color, name } = queueData; - await queue.update(queueData); - - return queue; + const queueSchema = Yup.object().shape({ + name: Yup.string() + .min(2, "ERR_QUEUE_INVALID_NAME") + .test( + "Check-unique-name", + "ERR_QUEUE_NAME_ALREADY_EXISTS", + async value => { + if (value) { + const queueWithSameName = await Queue.findOne({ + where: { name: value, id: { [Op.not]: queueId } } + }); + + return !queueWithSameName; + } + return true; + } + ), + color: Yup.string() + .required("ERR_QUEUE_INVALID_COLOR") + .test("Check-color", "ERR_QUEUE_INVALID_COLOR", async value => { + if (value) { + const colorTestRegex = /^#[0-9a-f]{3,6}$/i; + return colorTestRegex.test(value); + } + return true; + }) + .test( + "Check-color-exists", + "ERR_QUEUE_COLOR_ALREADY_EXISTS", + async value => { + if (value) { + const queueWithSameColor = await Queue.findOne({ + where: { color: value, id: { [Op.not]: queueId } } + }); + return !queueWithSameColor; + } + return true; + } + ) + }); + + try { + await queueSchema.validate({ color, name }); + } catch (err: any) { + throw new AppError(err.message); + } + + const queue = await ShowQueueService(queueId); + + await queue.update(queueData); + + return queue; + + } catch (error: any) { + console.error('===> Error on UpdateQueueService.ts file: \n', error) + throw new AppError(error.message); + } + }; export default UpdateQueueService; diff --git a/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts b/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts index 6c9d0e8..c6f31ff 100644 --- a/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts +++ b/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts @@ -2,74 +2,82 @@ import AppError from "../../errors/AppError"; import { createSchedulingNotifyCache } from "../../helpers/SchedulingNotifyCache"; import SchedulingNotify from "../../models/SchedulingNotify"; - + interface Request { - schedulingNotifyId?: string, + schedulingNotifyId?: string, ticketId: string, - statusChatEndId: string, - schedulingDate: string, + statusChatEndId: string, + schedulingDate: string, schedulingTime: string, - message: string + message: string } -const CreateSchedulingNotifyService = async ({ +const CreateSchedulingNotifyService = async ({ schedulingNotifyId = '', - ticketId, - statusChatEndId, - schedulingDate, - schedulingTime, - message -}: Request): Promise => { + ticketId, + statusChatEndId, + schedulingDate, + schedulingTime, + message +}: Request): Promise => { - let schedulingNotify = null; + try { + + let schedulingNotify = null; + + if (schedulingNotifyId) { - if(schedulingNotifyId){ - schedulingNotify = await SchedulingNotify.findOne({ where: { id: schedulingNotifyId } }); - - if(schedulingNotify){ - try{ + if (schedulingNotify) { - await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message}); + try { - }catch(err){ + await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message }); + + } catch (err) { throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404); - - } - - + + } + + //await scheduleNotify.reload({attributes: ["id", "name"]}); - } + } } - if(!schedulingNotify){ - + if (!schedulingNotify) { + schedulingNotify = await SchedulingNotify.create( { ticketId, - statusChatEndId, - schedulingDate, + statusChatEndId, + schedulingDate, schedulingTime, - message - - }) + message + + }) } - - await createSchedulingNotifyCache(JSON.parse(JSON.stringify(schedulingNotify))) + + await createSchedulingNotifyCache(JSON.parse(JSON.stringify(schedulingNotify))) return schedulingNotify - } + + } catch (error: any) { + console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error) + throw new AppError(error.message); + } + +} + + - - // const CreateSchedulingNotifyService = async ({ ticketId, statusChatEndId, schedulingDate, schedulingTime, message }: Request): Promise => { // const schedulingNotify = await SchedulingNotify.create( @@ -79,10 +87,10 @@ const CreateSchedulingNotifyService = async ({ // schedulingDate, // schedulingTime, // message - + // }) // return schedulingNotify // } - export default CreateSchedulingNotifyService \ No newline at end of file +export default CreateSchedulingNotifyService \ No newline at end of file diff --git a/backend/src/services/SchedulingNotifyServices/UpdateSchedulingNotifyService.ts b/backend/src/services/SchedulingNotifyServices/UpdateSchedulingNotifyService.ts index cd72b77..fce85dd 100644 --- a/backend/src/services/SchedulingNotifyServices/UpdateSchedulingNotifyService.ts +++ b/backend/src/services/SchedulingNotifyServices/UpdateSchedulingNotifyService.ts @@ -2,38 +2,47 @@ import AppError from "../../errors/AppError"; import SchedulingNotify from "../../models/SchedulingNotify"; -interface SchedulingData { - name?: string - } +interface SchedulingData { + name?: string +} interface Request { - schedulingData: SchedulingData - schedulingDataId: string + schedulingData: SchedulingData + schedulingDataId: string } const UpdateSchedulingNotify = async ({ - schedulingData, - schedulingDataId + schedulingData, + schedulingDataId }: Request): Promise => { - const { name } = schedulingData; - const updateScheduling = await SchedulingNotify.findOne({ - where: { id: schedulingDataId }, - attributes: ["id", "name"] - }); + try { - if (!updateScheduling) { + const { name } = schedulingData; + + const updateScheduling = await SchedulingNotify.findOne({ + where: { id: schedulingDataId }, + attributes: ["id", "name"] + }); + + if (!updateScheduling) { //console.log('NOT FOUND SCHEDULING NOTIFY') - throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404); + throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404); + } + await updateScheduling.update({ name }); + + await updateScheduling.reload({ + attributes: ["id", "name"] + }); + + return updateScheduling; + + } catch (error: any) { + console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error) + throw new AppError(error.message); } - await updateScheduling.update({ name }); - await updateScheduling.reload({ - attributes: ["id", "name"] - }); - - return updateScheduling; }; export default UpdateSchedulingNotify; diff --git a/backend/src/services/SettingServices/UpdateSettingService.ts b/backend/src/services/SettingServices/UpdateSettingService.ts index 9c443a1..59bf6b2 100644 --- a/backend/src/services/SettingServices/UpdateSettingService.ts +++ b/backend/src/services/SettingServices/UpdateSettingService.ts @@ -10,17 +10,24 @@ const UpdateSettingService = async ({ key, value }: Request): Promise => { - const setting = await Setting.findOne({ - where: { key } - }); - if (!setting) { - throw new AppError("ERR_NO_SETTING_FOUND", 404); + try { + const setting = await Setting.findOne({ + where: { key } + }); + + if (!setting) { + throw new AppError("ERR_NO_SETTING_FOUND", 404); + } + + await setting.update({ value }); + + return setting; + + } catch (error: any) { + console.error('===> Error on UpdateSettingService.ts file: \n', error) + throw new AppError(error.message); } - - await setting.update({ value }); - - return setting; }; export default UpdateSettingService; diff --git a/backend/src/services/TicketServices/CreateTicketService.ts b/backend/src/services/TicketServices/CreateTicketService.ts index 936033f..f3bd64a 100644 --- a/backend/src/services/TicketServices/CreateTicketService.ts +++ b/backend/src/services/TicketServices/CreateTicketService.ts @@ -15,8 +15,8 @@ import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfo import { createOrUpdateTicketCache } from '../../helpers/TicketCache' let flatten = require('flat') - - + + interface Request { contactId: number; @@ -29,57 +29,66 @@ const CreateTicketService = async ({ status, userId }: Request): Promise => { - const defaultWhatsapp = await GetDefaultWhatsApp(userId); - await CheckContactOpenTickets(contactId); + try { - const { isGroup } = await ShowContactService(contactId); + const defaultWhatsapp = await GetDefaultWhatsApp(userId); - const { id }: Ticket = await defaultWhatsapp.$create("ticket", { - contactId, - status, - isGroup, - userId - }); + await CheckContactOpenTickets(contactId); - const ticket = await Ticket.findByPk(id, { include: ["contact"] }); + const { isGroup } = await ShowContactService(contactId); - if (!ticket) { - throw new AppError("ERR_CREATING_TICKET"); - } + const { id }: Ticket = await defaultWhatsapp.$create("ticket", { + contactId, + status, + isGroup, + userId + }); - // console.log('CONTACT ticket.id: ', ticket.id) + const ticket = await Ticket.findByPk(id, { include: ["contact"] }); + + if (!ticket) { + throw new AppError("ERR_CREATING_TICKET"); + } + + // console.log('CONTACT ticket.id: ', ticket.id) - // TEST DEL - try { - - let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data - let ticket_obj = JSON.parse(jsonString); //to make plain json - delete ticket_obj['contact']['extraInfo'] - - ticket_obj = flatten(ticket_obj) - - await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj) - - } catch (error) { - console.log('There was an error on UpdateTicketService.ts on createTicketCache from user: ', error) - } - // + // TEST DEL + try { + + let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data + let ticket_obj = JSON.parse(jsonString); //to make plain json + delete ticket_obj['contact']['extraInfo'] + + ticket_obj = flatten(ticket_obj) + + await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj) + + } catch (error) { + console.log('There was an error on UpdateTicketService.ts on createTicketCache from user: ', error) + } + // - const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) - - TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate) + const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) - const io = getIO(); - io.emit("ticketStatus", { - action: "update", - ticketStatus: {ticketId: ticket.id, status: ticket.status} - }); + TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate) + + const io = getIO(); + io.emit("ticketStatus", { + action: "update", + ticketStatus: { ticketId: ticket.id, status: ticket.status } + }); - return ticket; + return ticket; + + } catch (error: any) { + console.error('===> Error on CreateTicketService.ts file: \n', error) + throw new AppError(error.message); + } + }; export default CreateTicketService; diff --git a/backend/src/services/TicketServices/FindOrCreateTicketService.ts b/backend/src/services/TicketServices/FindOrCreateTicketService.ts index 94e7d9b..601a99f 100644 --- a/backend/src/services/TicketServices/FindOrCreateTicketService.ts +++ b/backend/src/services/TicketServices/FindOrCreateTicketService.ts @@ -4,8 +4,9 @@ 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 ShowTicketService from "./ShowTicketService"; +import AppError from "../../errors/AppError"; + const FindOrCreateTicketService = async ( contact: Contact, @@ -13,104 +14,111 @@ const FindOrCreateTicketService = async ( unreadMessages: number, groupContact?: Contact ): Promise => { - let ticket = await Ticket.findOne({ - where: { - status: { - [Op.or]: ["open", "pending", "queueChoice"] - }, - contactId: groupContact ? groupContact.id : contact.id - } - }); - const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId); + try { - - //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({ + let ticket = await Ticket.findOne({ where: { - contactId: groupContact.id - }, - order: [["updatedAt", "DESC"]] - }); - - - - if (ticket) { - - await ticket.update({ - status: "pending", - userId: null, - unreadMessages - }); - } - } - - if (!ticket && !groupContact) { - - ticket = await Ticket.findOne({ - where: { - updatedAt: { - //[Op.between]: [+subHours(new Date(), 2), +new Date()] - - // Tempo osioso para a ura responder thuanny - //[Op.between]: [+subMinutes(new Date(), 30), +new Date()] - - // Sub seconds - [Op.between]: [+subSeconds(new Date(), 0), +new Date()] + status: { + [Op.or]: ["open", "pending", "queueChoice"] }, - contactId: contact.id - }, - order: [["updatedAt", "DESC"]] + 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 }); + } - await ticket.update({ - status: "pending", - userId: null, - unreadMessages + if (!ticket && groupContact) { + ticket = await Ticket.findOne({ + where: { + contactId: groupContact.id + }, + order: [["updatedAt", "DESC"]] }); - } - } - if (!ticket) { - let status = "pending" - if (queues.length > 1 && !botInfo.isOnQueue) { - status = "queueChoice" + if (ticket) { + + await ticket.update({ + status: "pending", + userId: null, + unreadMessages + }); + } } - ticket = await Ticket.create({ - contactId: groupContact ? groupContact.id : contact.id, - status: status, - isGroup: !!groupContact, - unreadMessages, - whatsappId - }); + if (!ticket && !groupContact) { - // TEST DEL + ticket = await Ticket.findOne({ + where: { + updatedAt: { + //[Op.between]: [+subHours(new Date(), 2), +new Date()] - // const { name } = await ShowContactService(contact.id); - // console.log('FIND OR CREATE TICKET SERVICE NAME: ', contact.name, ' STATUS: ', status) + // Tempo osioso para a ura responder thuanny + //[Op.between]: [+subMinutes(new Date(), 30), +new Date()] - // + // Sub seconds + [Op.between]: [+subSeconds(new Date(), 0), +new Date()] + }, + contactId: contact.id + }, + order: [["updatedAt", "DESC"]] + }); + + if (ticket) { + + await ticket.update({ + status: "pending", + userId: null, + unreadMessages + }); + } + } + + if (!ticket) { + + let status = "pending" + + if (queues.length > 1 && !botInfo.isOnQueue) { + status = "queueChoice" + } + + ticket = await Ticket.create({ + contactId: groupContact ? groupContact.id : contact.id, + status: status, + isGroup: !!groupContact, + unreadMessages, + whatsappId + }); + + // TEST DEL + + // const { name } = await ShowContactService(contact.id); + // console.log('FIND OR CREATE TICKET SERVICE NAME: ', contact.name, ' STATUS: ', status) + + // + } + + ticket = await ShowTicketService(ticket.id); + + return ticket; + + } catch (error: any) { + console.error('===> Error on FindOrCreateTicketService.ts file: \n', error) + throw new AppError(error.message); } - - ticket = await ShowTicketService(ticket.id); - - - return ticket; }; export default FindOrCreateTicketService; diff --git a/backend/src/services/TicketServices/UpdateTicketService.ts b/backend/src/services/TicketServices/UpdateTicketService.ts index 34e58dd..3cafa11 100644 --- a/backend/src/services/TicketServices/UpdateTicketService.ts +++ b/backend/src/services/TicketServices/UpdateTicketService.ts @@ -7,6 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowTicketService from "./ShowTicketService"; import { createOrUpdateTicketCache } from '../../helpers/TicketCache' +import AppError from "../../errors/AppError"; var flatten = require('flat') @@ -33,7 +34,10 @@ const UpdateTicketService = async ({ ticketData, ticketId }: Request): Promise => { - const { status, userId, queueId, statusChatEnd } = ticketData; + + try { + + const { status, userId, queueId, statusChatEnd } = ticketData; const ticket = await ShowTicketService(ticketId); // await SetTicketMessagesAsRead(ticket); @@ -99,6 +103,12 @@ const UpdateTicketService = async ({ return { ticket, oldStatus, oldUserId }; + + } catch (error: any) { + console.error('===> Error on UpdateTicketService.ts file: \n', error) + throw new AppError(error.message); + } + }; export default UpdateTicketService; diff --git a/backend/src/services/UserServices/CreateOrUpdateOnlineUserService.ts b/backend/src/services/UserServices/CreateOrUpdateOnlineUserService.ts index 29f03aa..34d2148 100644 --- a/backend/src/services/UserServices/CreateOrUpdateOnlineUserService.ts +++ b/backend/src/services/UserServices/CreateOrUpdateOnlineUserService.ts @@ -34,146 +34,152 @@ const CreateOrUpdateUserOnlineTime = async ({ status, }: Request): Promise => { + try { + const io = getIO(); + let userOnlineTime: any = null; - const io = getIO(); - let userOnlineTime: any = null; + const user = await User.findOne({ where: { id: userId } }); - const user = await User.findOne({ where: { id: userId } }); + if (!user) { - if (!user) { - - return userOnlineTime - } - - - let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) - - userOnlineTime = await UserOnlineTime.findOne({ - where: { - [Op.and]: [ - { - userId: userId - }, - { - "$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${dateTime.fullDate}`) - }, - ] + return userOnlineTime } - }); - - if (userOnlineTime) { - try { - - let oldStatus = userOnlineTime.status + let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) - - if (oldStatus == 'online' && status === 'offline') { - //updatedAt - let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date() }) - - - - - let onlineTime = new Date() - - onlineTime.setUTCHours(userOnlineTime.onlineTime.getHours()) - onlineTime.setUTCMinutes(userOnlineTime.onlineTime.getMinutes()) - onlineTime.setUTCSeconds(userOnlineTime.onlineTime.getSeconds()) - - - - if (newtTime.hours && +newtTime.hours > 0) { - onlineTime = addHours(onlineTime, newtTime.hours) - } - if (newtTime.minutes && +newtTime.minutes > 0) { - onlineTime = addMinutes(onlineTime, newtTime.minutes) - } - if (newtTime.seconds && +newtTime.seconds > 0) { - onlineTime = addSeconds(onlineTime, newtTime.seconds) - } - - - - const isoDate = new Date(onlineTime); - const mySQLDateString = isoDate.toJSON().slice(0, 19).replace('T', ' '); - - - await userOnlineTime.update({ status, onlineTime: mySQLDateString }) - - //test del - - const updatedAtString = formatDateTimeString(userOnlineTime.updatedAt) - const createdAtString = formatDateTimeString(userOnlineTime.createdAt) - - - - // - - - io.emit("onlineStatus", { - action: "update", - userOnlineTime: { - userId: userOnlineTime.userId, - status: userOnlineTime.status, - onlineTime: mySQLDateString, - createdAt: createdAtString, - updatedAt: updatedAtString - } - }); - - } - else if (oldStatus == 'offline' && status === 'online') { - await userOnlineTime.update({ status }) - - io.emit("onlineStatus", { - action: "update", - userOnlineTime: { - userId: userOnlineTime.userId, - status: userOnlineTime.status, - createdAt: formatDateTimeString(userOnlineTime.createdAt), - updatedAt: formatDateTimeString(userOnlineTime.updatedAt) - } - }); - } - else { - console.log('NOT UPDATED THE USER: ', userOnlineTime.userId) - } - - } catch (err) { - - throw new AppError("ERR_NO_USER_ONLINE_FOUND", 404); - - } - } - - if (!userOnlineTime) { - - userOnlineTime = await UserOnlineTime.create( - { - userId, - status, - onlineTime: `${dateTime.fullDate} 00:00:00` - }) - - io.emit("onlineStatus", { - action: "update", - userOnlineTime: { - userId: userOnlineTime.userId, - status: userOnlineTime.status, - createdAt: formatDateTimeString(userOnlineTime.createdAt), - updatedAt: formatDateTimeString(userOnlineTime.updatedAt) + userOnlineTime = await UserOnlineTime.findOne({ + where: { + [Op.and]: [ + { + userId: userId + }, + { + "$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${dateTime.fullDate}`) + }, + ] } }); + if (userOnlineTime) { + try { + + let oldStatus = userOnlineTime.status + + + if (oldStatus == 'online' && status === 'offline') { + //updatedAt + let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date() }) + + + + + let onlineTime = new Date() + + onlineTime.setUTCHours(userOnlineTime.onlineTime.getHours()) + onlineTime.setUTCMinutes(userOnlineTime.onlineTime.getMinutes()) + onlineTime.setUTCSeconds(userOnlineTime.onlineTime.getSeconds()) + + + + if (newtTime.hours && +newtTime.hours > 0) { + onlineTime = addHours(onlineTime, newtTime.hours) + } + if (newtTime.minutes && +newtTime.minutes > 0) { + onlineTime = addMinutes(onlineTime, newtTime.minutes) + } + if (newtTime.seconds && +newtTime.seconds > 0) { + onlineTime = addSeconds(onlineTime, newtTime.seconds) + } + + + + const isoDate = new Date(onlineTime); + const mySQLDateString = isoDate.toJSON().slice(0, 19).replace('T', ' '); + + + await userOnlineTime.update({ status, onlineTime: mySQLDateString }) + + //test del + + const updatedAtString = formatDateTimeString(userOnlineTime.updatedAt) + const createdAtString = formatDateTimeString(userOnlineTime.createdAt) + + + + // + + + io.emit("onlineStatus", { + action: "update", + userOnlineTime: { + userId: userOnlineTime.userId, + status: userOnlineTime.status, + onlineTime: mySQLDateString, + createdAt: createdAtString, + updatedAt: updatedAtString + } + }); + + } + else if (oldStatus == 'offline' && status === 'online') { + await userOnlineTime.update({ status }) + + io.emit("onlineStatus", { + action: "update", + userOnlineTime: { + userId: userOnlineTime.userId, + status: userOnlineTime.status, + createdAt: formatDateTimeString(userOnlineTime.createdAt), + updatedAt: formatDateTimeString(userOnlineTime.updatedAt) + } + }); + } + else { + console.log('NOT UPDATED THE USER: ', userOnlineTime.userId) + } + + } catch (err) { + + throw new AppError("ERR_NO_USER_ONLINE_FOUND", 404); + + } + } + + if (!userOnlineTime) { + + userOnlineTime = await UserOnlineTime.create( + { + userId, + status, + onlineTime: `${dateTime.fullDate} 00:00:00` + }) + + io.emit("onlineStatus", { + action: "update", + userOnlineTime: { + userId: userOnlineTime.userId, + status: userOnlineTime.status, + createdAt: formatDateTimeString(userOnlineTime.createdAt), + updatedAt: formatDateTimeString(userOnlineTime.updatedAt) + } + }); + + + + } + + + return userOnlineTime + + } catch (error: any) { + console.error('===> Error on CreateOrUpdateUserOnlineTime.ts file: \n', error) + throw new AppError(error.message); } - - return userOnlineTime } diff --git a/backend/src/services/UserServices/CreateUserService.ts b/backend/src/services/UserServices/CreateUserService.ts index 22a3c1a..69d7c0d 100644 --- a/backend/src/services/UserServices/CreateUserService.ts +++ b/backend/src/services/UserServices/CreateUserService.ts @@ -26,59 +26,68 @@ const CreateUserService = async ({ queueIds = [], profile = "master" }: Request): Promise => { - const schema = Yup.object().shape({ - name: Yup.string().required().min(2), - - email: Yup.string().required().trim().test( - "Check-email", - "An user with this email already exists.", - async value => { - if (!value) return false; - const emailExists = await User.findOne({ - where: { email: value } - }); - return !emailExists; - } - ), - - // email: Yup.string().email().required().test( - // "Check-email", - // "An user with this email already exists.", - // async value => { - // if (!value) return false; - // const emailExists = await User.findOne({ - // where: { email: value } - // }); - // return !emailExists; - // } - // ), - - password: Yup.string().required().min(5) - }); try { - await schema.validate({ email, password, name }); - } catch (err:any) { - throw new AppError(err.message); + + const schema = Yup.object().shape({ + name: Yup.string().required().min(2), + + email: Yup.string().required().trim().test( + "Check-email", + "An user with this email already exists.", + async value => { + if (!value) return false; + const emailExists = await User.findOne({ + where: { email: value } + }); + return !emailExists; + } + ), + + // email: Yup.string().email().required().test( + // "Check-email", + // "An user with this email already exists.", + // async value => { + // if (!value) return false; + // const emailExists = await User.findOne({ + // where: { email: value } + // }); + // return !emailExists; + // } + // ), + + password: Yup.string().required().min(5) + }); + + try { + await schema.validate({ email, password, name }); + } catch (err: any) { + throw new AppError(err.message); + } + + const user = await User.create( + { + email, + password, + name, + profile + }, + { include: ["queues"] } + ); + + await user.$set("queues", queueIds); + + await user.reload(); + + const serializedUser = SerializeUser(user); + + return serializedUser; + + } catch (error: any) { + console.error('===> Error on CreateUserService.ts file: \n', error) + throw new AppError(error.message); } - const user = await User.create( - { - email, - password, - name, - profile - }, - { include: ["queues"] } - ); - - await user.$set("queues", queueIds); - - await user.reload(); - - const serializedUser = SerializeUser(user); - - return serializedUser; }; export default CreateUserService; diff --git a/backend/src/services/UserServices/UpdateUserService.ts b/backend/src/services/UserServices/UpdateUserService.ts index e3f3127..ed80cc2 100644 --- a/backend/src/services/UserServices/UpdateUserService.ts +++ b/backend/src/services/UserServices/UpdateUserService.ts @@ -28,64 +28,74 @@ const UpdateUserService = async ({ userData, userId }: Request): Promise => { - const user = await ShowUserService(userId); - - const schema = Yup.object().shape({ - name: Yup.string().min(2), - // email: Yup.string().min(2), - profile: Yup.string(), - password: Yup.string(), - - email: Yup.string().trim().required().test( - "Check-email", - "An user with this email already exists.", - async value => { - - if (!value) return false; - - const emailExists = await User.findOne({ where: { email: value }, raw: true, attributes: ['email', 'id'] }); - - if (emailExists && user.id != emailExists?.id) { - - console.error('The email already exists in another user profile!') - return !emailExists; - } - - return true - } - ), - - }); - - const { email, password, profile, name, queueIds = [] } = userData; try { - await schema.validate({ email, password, profile, name }); - } catch (err: any) { - throw new AppError(err.message); + + const user = await ShowUserService(userId); + + const schema = Yup.object().shape({ + name: Yup.string().min(2), + // email: Yup.string().min(2), + profile: Yup.string(), + password: Yup.string(), + + email: Yup.string().trim().required().test( + "Check-email", + "An user with this email already exists.", + async value => { + + if (!value) return false; + + const emailExists = await User.findOne({ where: { email: value }, raw: true, attributes: ['email', 'id'] }); + + if (emailExists && user.id != emailExists?.id) { + + console.error('The email already exists in another user profile!') + return !emailExists; + } + + return true + } + ), + + }); + + const { email, password, profile, name, queueIds = [] } = userData; + + try { + await schema.validate({ email, password, profile, name }); + } catch (err: any) { + throw new AppError(err.message); + } + + + await user.update({ + email, + password, + profile, + name + }); + + await user.$set("queues", queueIds); + + await user.reload(); + + const serializedUser = { + id: user.id, + name: user.name, + email: user.email, + profile: user.profile, + queues: user.queues + }; + + return serializedUser; + + } catch (error: any) { + console.error('===> Error on UpdateUserService.ts file: \n', error) + throw new AppError(error.message); } - await user.update({ - email, - password, - profile, - name - }); - - await user.$set("queues", queueIds); - - await user.reload(); - - const serializedUser = { - id: user.id, - name: user.name, - email: user.email, - profile: user.profile, - queues: user.queues - }; - - return serializedUser; }; export default UpdateUserService; diff --git a/backend/src/services/WbotServices/SendWhatsAppMessage.ts b/backend/src/services/WbotServices/SendWhatsAppMessage.ts index 0dd5734..c48b2fd 100644 --- a/backend/src/services/WbotServices/SendWhatsAppMessage.ts +++ b/backend/src/services/WbotServices/SendWhatsAppMessage.ts @@ -41,151 +41,105 @@ const SendWhatsAppMessage = async ({ quotedMsg }: Request): Promise => { - let timestamp = Math.floor(Date.now() / 1000) - var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`; - - console.time(timetaken) - - let quotedMsgSerializedId: string | undefined; - - if (quotedMsg) { - - await GetWbotMessage(ticket, quotedMsg.id); - - quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg); - } - - console.log('quotedMsgSerializedId: ', quotedMsgSerializedId) - - - let whatsapps: any - - let listWhatsapp = null - - // listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED') - - console.log('ticket.whatsappIdticket.whatsappIdticket.whatsappIdticket: ', ticket.whatsappId) - - if (!listWhatsapp) { - listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') - } - - if (listWhatsapp.whatsapp && listWhatsapp.whatsapp.status != 'CONNECTED' && listWhatsapp.whatsapps.length > 0) { - - console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', listWhatsapp.whatsapps[0].id) - - await ticket.update({ whatsappId: + listWhatsapp.whatsapps[0].id }); - - let _ticket = await Ticket.findByPk(listWhatsapp.whatsapps[0].id) - - } - - - - - if (listWhatsapp.whatsapps.length > 1) { - - const _whatsapp = listWhatsapp.whatsapps[Math.floor(Math.random() * listWhatsapp.whatsapps.length)]; - - await ticket.update({ whatsappId: +_whatsapp.id }); - // await ticket.reload(); - - - } - - // console.log('listWhatsapp.whatsapps.length: ', listWhatsapp.whatsapps.length) - // console.log('listWhatsapp.whatsapp.status: ', listWhatsapp.whatsapp.status) - - - if (listWhatsapp.whatsapps.length == 0 && listWhatsapp.whatsapp.status != 'CONNECTED') { - - console.log('listWhatsapp.whatsapps == 0') - - whatsapps = await wbotByUserQueue(ticket.userId) - - console.log('============> The whatsapps: ', whatsapps) - - if (whatsapps.length > 0) { - - if (whatsapps.length > 1) { - - await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id }); - - } - else { - - await ticket.update({ whatsappId: whatsapps[0].id }); - - } - - } - - } - - console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId) - - // const wbot = await GetTicketWbot(ticket); - - - - - /*const whatsapp = await Whatsapp.findByPk(ticket.whatsappId); - - if (whatsapp && whatsapp.status != 'CONNECTED') { - - let whatsapps = await wbotByUserQueue(ticket.userId) - - if (whatsapps.length > 0) { - - if (whatsapps.length > 1) { - - await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id }); - - } - else { - - await ticket.update({ whatsappId: whatsapps[0].id }); - - } - - } - - } - - const wbot = await GetTicketWbot(ticket); -*/ - - - - - console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId) - try { - sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId); + let timestamp = Math.floor(Date.now() / 1000) + var timetaken = `########################################${timestamp}| TicketId: ${ticket.id} => Time taken to send the message`; - await ticket.update({ lastMessage: body }); + console.time(timetaken) - await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() }) + let quotedMsgSerializedId: string | undefined; + + if (quotedMsg) { + + await GetWbotMessage(ticket, quotedMsg.id); + + quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg); + } + + console.log('quotedMsgSerializedId: ', quotedMsgSerializedId) + let whatsapps: any - // const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false }); + let listWhatsapp = null - // await ticket.update({ lastMessage: body }); + // listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED') - // await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() }) + console.log('ticket.whatsappIdticket.whatsappIdticket.whatsappIdticket: ', ticket.whatsappId) - // return sentMessage; + if (!listWhatsapp) { + listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') + } - console.timeEnd(timetaken) + if (listWhatsapp.whatsapp && listWhatsapp.whatsapp.status != 'CONNECTED' && listWhatsapp.whatsapps.length > 0) { - } catch (err) { + // console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', listWhatsapp.whatsapps[0].id) - // const whatsapp = await ShowWhatsAppService(ticket.whatsappId); + await ticket.update({ whatsappId: + listWhatsapp.whatsapps[0].id }); - throw new AppError("ERR_SENDING_WAPP_MSG"); + let _ticket = await Ticket.findByPk(listWhatsapp.whatsapps[0].id) + + } + + + if (listWhatsapp.whatsapps.length > 1) { + + const _whatsapp = listWhatsapp.whatsapps[Math.floor(Math.random() * listWhatsapp.whatsapps.length)]; + + await ticket.update({ whatsappId: +_whatsapp.id }); + + } + + if (listWhatsapp.whatsapps.length == 0 && listWhatsapp.whatsapp.status != 'CONNECTED') { + + console.log('listWhatsapp.whatsapps == 0') + + whatsapps = await wbotByUserQueue(ticket.userId) + + console.log('============> The whatsapps: ', whatsapps) + + if (whatsapps.length > 0) { + + if (whatsapps.length > 1) { + + await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id }); + + } + else { + + await ticket.update({ whatsappId: whatsapps[0].id }); + + } + + } + + } + + console.log('1 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId) + + try { + + sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId); + + await ticket.update({ lastMessage: body }); + + await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() }) + + console.timeEnd(timetaken) + + } catch (err: any) { + + console.error('0 ===> Error on SendWhatsAppMessage.ts file: \n', err) + throw new AppError("ERR_SENDING_WAPP_MSG"); + + } + + } catch (error: any) { + console.error('===> Error on SendWhatsAppMessage.ts file: \n', error) + throw new AppError(error.message); } + }; export default SendWhatsAppMessage; diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 74a1837..069b3ff 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -59,6 +59,7 @@ import autoRestore from "../../helpers/AutoRestore"; import { _restore } from "../../helpers/RestoreControll"; import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl"; +import AppError from "../../errors/AppError"; @@ -125,8 +126,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}`; @@ -141,13 +142,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}`); @@ -167,7 +168,7 @@ const verifyMediaMessage = async ( }; await ticket.update({ lastMessage: msg.body || media.filename }); - const newMessage = await CreateMessageService({ messageData }); + const newMessage = await CreateMessageService({ messageData }); return newMessage; }; @@ -198,7 +199,7 @@ const verifyMessage = async ( }; - await ticket.update({ lastMessage: msg.body }); + await ticket.update({ lastMessage: msg.body }); await CreateMessageService({ messageData }); }; @@ -407,8 +408,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) @@ -418,7 +419,7 @@ const handleMessage = async ( msg: any, wbot: any ): Promise => { - + if (!msg.fromMe) { _clear_lst() @@ -448,11 +449,6 @@ const handleMessage = async ( } - - - - - if (!isValidMsg(msg)) { return; } @@ -553,12 +549,19 @@ 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 }); + try { + await ticket.update({ whatsappId: wbot.id }); + } catch (error: any) { + console.error('===> Error on wbotMessageListener.ts into handleMessage fuction file: \n', error) + throw new AppError(error.message); + } + + } // - if (msg.hasMedia) { + if (msg.hasMedia) { await verifyMediaMessage(msg, ticket, contact, wbot.media, wbot.quotedMsg); } else { diff --git a/backend/src/services/WhatsappService/CreateWhatsAppService.ts b/backend/src/services/WhatsappService/CreateWhatsAppService.ts index 070c949..91c7370 100644 --- a/backend/src/services/WhatsappService/CreateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/CreateWhatsAppService.ts @@ -30,67 +30,77 @@ const CreateWhatsAppService = async ({ farewellMessage, isDefault = false, }: Request): Promise => { - const schema = Yup.object().shape({ - name: Yup.string() - .required() - .min(2) - .test( - "Check-name", - "This whatsapp name is already used.", - async value => { - if (!value) return false; - const nameExists = await Whatsapp.findOne({ - where: { name: value } - }); - return !nameExists; - } - ), - isDefault: Yup.boolean().required(), - urlApi: Yup.string().required() - }); try { - await schema.validate({ name, status, isDefault, urlApi }); - } catch (err: any) { - throw new AppError(err.message); - } - const whatsappFound = await Whatsapp.findOne(); - - isDefault = !whatsappFound; - - let oldDefaultWhatsapp: Whatsapp | null = null; - - if (isDefault) { - oldDefaultWhatsapp = await Whatsapp.findOne({ - where: { isDefault: true } + const schema = Yup.object().shape({ + name: Yup.string() + .required() + .min(2) + .test( + "Check-name", + "This whatsapp name is already used.", + async value => { + if (!value) return false; + const nameExists = await Whatsapp.findOne({ + where: { name: value } + }); + return !nameExists; + } + ), + isDefault: Yup.boolean().required(), + urlApi: Yup.string().required() }); - if (oldDefaultWhatsapp) { - await oldDefaultWhatsapp.update({ isDefault: false }); - + + try { + await schema.validate({ name, status, isDefault, urlApi }); + } catch (err: any) { + throw new AppError(err.message); } + + const whatsappFound = await Whatsapp.findOne(); + + isDefault = !whatsappFound; + + let oldDefaultWhatsapp: Whatsapp | null = null; + + if (isDefault) { + oldDefaultWhatsapp = await Whatsapp.findOne({ + where: { isDefault: true } + }); + if (oldDefaultWhatsapp) { + await oldDefaultWhatsapp.update({ isDefault: false }); + + } + } + + if (queueIds.length > 1 && !greetingMessage) { + throw new AppError("ERR_WAPP_GREETING_REQUIRED"); + } + + const whatsapp = await Whatsapp.create( + { + name, + status, + url, + urlApi, + greetingMessage, + farewellMessage, + isDefault + }, + { include: ["queues"] } + ); + + await AssociateWhatsappQueue(whatsapp, queueIds); + + return { whatsapp, oldDefaultWhatsapp }; + + } catch (error: any) { + console.error('===> Error on CreateWhatsAppService.ts file: \n', error) + throw new AppError(error.message); } - if (queueIds.length > 1 && !greetingMessage) { - throw new AppError("ERR_WAPP_GREETING_REQUIRED"); - } - - const whatsapp = await Whatsapp.create( - { - name, - status, - url, - urlApi, - greetingMessage, - farewellMessage, - isDefault - }, - { include: ["queues"] } - ); - - await AssociateWhatsappQueue(whatsapp, queueIds); - - return { whatsapp, oldDefaultWhatsapp }; + }; export default CreateWhatsAppService; diff --git a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts index 4c20829..04336df 100644 --- a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts @@ -8,8 +8,8 @@ import AssociateWhatsappQueue from "./AssociateWhatsappQueue"; // import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache"; import { getWbot } from "../../libs/wbot"; import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; - - + + interface WhatsappData { name?: string; @@ -37,80 +37,89 @@ const UpdateWhatsAppService = async ({ whatsappData, whatsappId }: Request): Promise => { - const schema = Yup.object().shape({ - name: Yup.string().min(2), - status: Yup.string(), - isDefault: Yup.boolean() - }); - - const { - name, - status, - isDefault, - url, - urlApi, - session, - greetingMessage, - farewellMessage, - queueIds = [] - } = whatsappData; - - try { - await schema.validate({ name, status, isDefault }); - } catch (err: any) { - throw new AppError(err.message); - } - if (queueIds.length > 1 && !greetingMessage) { - throw new AppError("ERR_WAPP_GREETING_REQUIRED"); - } - - let oldDefaultWhatsapp: Whatsapp | null = null; - - if (isDefault) { - oldDefaultWhatsapp = await Whatsapp.findOne({ - where: { isDefault: true, id: { [Op.not]: whatsappId } } - }); - if (oldDefaultWhatsapp) { - await oldDefaultWhatsapp.update({ isDefault: false }); - } - } - - const whatsapp = await ShowWhatsAppService(whatsappId); - - // console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp))) - - if(name && !name.includes(whatsapp.number) && whatsapp.status === 'CONNECTED'){ - - throw new AppError("ERR_WAPP_WRONG_SESSION_NAME"); - - } + const schema = Yup.object().shape({ + name: Yup.string().min(2), + status: Yup.string(), + isDefault: Yup.boolean() + }); - await whatsapp.update({ - name, - status, - session, - url, - urlApi, - greetingMessage, - farewellMessage, - isDefault - }); + const { + name, + status, + isDefault, + url, + urlApi, + session, + greetingMessage, + farewellMessage, + queueIds = [] + } = whatsappData; + + + + try { + await schema.validate({ name, status, isDefault }); + } catch (err: any) { + throw new AppError(err.message); + } + + if (queueIds.length > 1 && !greetingMessage) { + throw new AppError("ERR_WAPP_GREETING_REQUIRED"); + } + + let oldDefaultWhatsapp: Whatsapp | null = null; + + if (isDefault) { + oldDefaultWhatsapp = await Whatsapp.findOne({ + where: { isDefault: true, id: { [Op.not]: whatsappId } } + }); + if (oldDefaultWhatsapp) { + await oldDefaultWhatsapp.update({ isDefault: false }); + } + } + + const whatsapp = await ShowWhatsAppService(whatsappId); + + // console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp))) + + if (name && !name.includes(whatsapp.number) && whatsapp.status === 'CONNECTED') { + + throw new AppError("ERR_WAPP_WRONG_SESSION_NAME"); + + } + + await whatsapp.update({ + name, + status, + session, + url, + urlApi, + greetingMessage, + farewellMessage, + isDefault + }); + + // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { + // name, + // status, + // session, + // greetingMessage, + // farewellMessage, + // isDefault + // }) + + await AssociateWhatsappQueue(whatsapp, queueIds); + + return { whatsapp, oldDefaultWhatsapp }; - // await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { - // name, - // status, - // session, - // greetingMessage, - // farewellMessage, - // isDefault - // }) - - await AssociateWhatsappQueue(whatsapp, queueIds); - - return { whatsapp, oldDefaultWhatsapp }; + } catch (error: any) { + console.error('===> Error on UpdateWhatsAppService.ts file: \n', error) + throw new AppError(error.message); + } + }; export default UpdateWhatsAppService;