Merge branch 'whats_session_out' into dialogflow_sessions_out

pull/20/head
adriano 2023-04-24 14:30:42 -03:00
commit b08fbbf56f
20 changed files with 957 additions and 847 deletions

View File

@ -561,7 +561,7 @@ app.post('/api/DeleteWhatsAppMessage', async (req, res) => {
} catch (error) { } catch (error) {
console.log('There was an error on try disconnect the whatsapp: ', error) console.log('There was an error on try delete the massage: ', error)
res.status(500).json({ message: "There was an error on trying delete the message" }); res.status(500).json({ message: "There was an error on trying delete the message" });
return return

View File

@ -28,35 +28,44 @@ const CreateContactService = async ({
extraInfo = [] extraInfo = []
}: Request): Promise<Contact> => { }: Request): Promise<Contact> => {
const numberExists = await Contact.findOne({ try {
where: { number }
});
if (numberExists) { const numberExists = await Contact.findOne({
throw new AppError("ERR_DUPLICATED_CONTACT"); where: { number }
});
if (numberExists) {
throw new AppError("ERR_DUPLICATED_CONTACT");
}
const contact = await Contact.create(
{
name,
number,
email,
useDialogflow,
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);
} }
const contact = await Contact.create(
{
name,
number,
email,
useDialogflow,
profilePicUrl,
extraInfo
},
{
include: ["extraInfo"]
}
);
// TEST DEL
await createOrUpdateContactCache(`contact:${contact.id}`, {id: contact.id, name, number, profilePicUrl, isGroup:'false', extraInfo, email })
//
return contact;
}; };
export default CreateContactService; export default CreateContactService;

View File

@ -2,6 +2,8 @@ import { getIO } from "../../libs/socket";
import Contact from "../../models/Contact"; import Contact from "../../models/Contact";
import { createOrUpdateContactCache } from '../../helpers/ContactsCache' import { createOrUpdateContactCache } from '../../helpers/ContactsCache'
import { tr } from "date-fns/locale";
import AppError from "../../errors/AppError";
interface ExtraInfo { interface ExtraInfo {
name: string; name: string;
@ -25,47 +27,56 @@ const CreateOrUpdateContactService = async ({
email = "", email = "",
extraInfo = [] extraInfo = []
}: Request): Promise<Contact> => { }: Request): Promise<Contact> => {
const number = isGroup ? rawNumber : rawNumber.replace(/[^0-9]/g, "");
const io = getIO(); try {
let contact: Contact | null;
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) { if (contact) {
contact.update({ profilePicUrl }); contact.update({ profilePicUrl });
// TEST DEL // TEST DEL
await createOrUpdateContactCache(`contact:${contact.id}`, { profilePicUrl }) await createOrUpdateContactCache(`contact:${contact.id}`, { profilePicUrl })
// //
io.emit("contact", { io.emit("contact", {
action: "update", action: "update",
contact contact
}); });
} else { } else {
contact = await Contact.create({ contact = await Contact.create({
name, name,
number, number,
profilePicUrl, profilePicUrl,
email, email,
isGroup, isGroup,
extraInfo extraInfo
}); });
// TEST DEL // TEST DEL
await createOrUpdateContactCache(`contact:${contact.id}`, {id: contact.id, name, number, profilePicUrl, isGroup, extraInfo, email }) await createOrUpdateContactCache(`contact:${contact.id}`, { id: contact.id, name, number, profilePicUrl, isGroup, extraInfo, email })
// //
io.emit("contact", { io.emit("contact", {
action: "create", action: "create",
contact 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; export default CreateOrUpdateContactService;

View File

@ -4,6 +4,7 @@ import ContactCustomField from "../../models/ContactCustomField";
import { updateTicketsByContactsCache } from '../../helpers/TicketCache' import { updateTicketsByContactsCache } from '../../helpers/TicketCache'
import { updateContactCacheById } from '../../helpers/ContactsCache' import { updateContactCacheById } from '../../helpers/ContactsCache'
import { tr } from "date-fns/locale";
interface ExtraInfo { interface ExtraInfo {
id?: number; id?: number;
@ -27,78 +28,87 @@ const UpdateContactService = async ({
contactData, contactData,
contactId contactId
}: Request): Promise<Contact> => { }: Request): Promise<Contact> => {
const { email, name, number, extraInfo } = contactData;
// console.log('email, name, number, extraInfo: ', email, name, number, extraInfo) try {
const contact = await Contact.findOne({ const { email, name, number, extraInfo } = contactData;
where: { id: contactId },
attributes: ["id", "name", "number", "email", "profilePicUrl"],
include: ["extraInfo"]
});
if (!contact) { // console.log('email, name, number, extraInfo: ', email, name, number, extraInfo)
throw new AppError("ERR_NO_CONTACT_FOUND", 404);
}
if (extraInfo) { const contact = await Contact.findOne({
await Promise.all( where: { id: contactId },
extraInfo.map(async info => { attributes: ["id", "name", "number", "email", "profilePicUrl"],
await ContactCustomField.upsert({ ...info, contactId: contact.id }); include: ["extraInfo"]
})
);
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) { if (!contact) {
throw new AppError("ERR_DUPLICATED_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 && 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; export default UpdateContactService;

View File

@ -1,3 +1,4 @@
import AppError from "../../errors/AppError";
import { updateTicketCacheByTicketId } from "../../helpers/TicketCache"; import { updateTicketCacheByTicketId } from "../../helpers/TicketCache";
import { getIO } from "../../libs/socket"; import { getIO } from "../../libs/socket";
import Message from "../../models/Message"; import Message from "../../models/Message";
@ -21,7 +22,9 @@ const CreateMessageService = async ({ messageData }: Request): Promise<Message>
// console.log('UPSERT MESSAGE messageData: ', messageData) // console.log('UPSERT MESSAGE messageData: ', messageData)
await Message.upsert(messageData); try {
await Message.upsert(messageData);
const message = await Message.findByPk(messageData.id, { const message = await Message.findByPk(messageData.id, {
include: [ include: [
@ -75,6 +78,13 @@ const CreateMessageService = async ({ messageData }: Request): Promise<Message>
return message; return message;
} catch (error: any) {
console.error('===> Error on CreateMessageService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default CreateMessageService; export default CreateMessageService;

View File

@ -10,7 +10,10 @@ interface QueueData {
} }
const CreateQueueService = async (queueData: QueueData): Promise<Queue> => { const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
const { color, name } = queueData;
try {
const { color, name } = queueData;
const queueSchema = Yup.object().shape({ const queueSchema = Yup.object().shape({
name: Yup.string() name: Yup.string()
@ -56,7 +59,7 @@ const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
try { try {
await queueSchema.validate({ color, name }); await queueSchema.validate({ color, name });
} catch (err) { } catch (err: any) {
throw new AppError(err.message); throw new AppError(err.message);
} }
@ -65,6 +68,12 @@ const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
deleteFileFromTMP(`botInfo.json`) deleteFileFromTMP(`botInfo.json`)
return queue; return queue;
} catch (error: any) {
console.error('===> Error on CreateQueueService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default CreateQueueService; export default CreateQueueService;

View File

@ -15,62 +15,71 @@ const UpdateQueueService = async (
queueId: number | string, queueId: number | string,
queueData: QueueData queueData: QueueData
): Promise<Queue> => { ): Promise<Queue> => {
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 { 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); 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);
deleteFileFromTMP(`botInfo.json`) deleteFileFromTMP(`botInfo.json`)
return queue; return queue;
} catch (error: any) {
console.error('===> Error on UpdateQueueService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default UpdateQueueService; export default UpdateQueueService;

View File

@ -22,19 +22,21 @@ const CreateSchedulingNotifyService = async ({
message message
}: Request): Promise<SchedulingNotify> => { }: Request): Promise<SchedulingNotify> => {
let schedulingNotify = null; try {
if(schedulingNotifyId){ let schedulingNotify = null;
if (schedulingNotifyId) {
schedulingNotify = await SchedulingNotify.findOne({ where: { id: schedulingNotifyId } }); schedulingNotify = await SchedulingNotify.findOne({ where: { id: schedulingNotifyId } });
if(schedulingNotify){ if (schedulingNotify) {
try{ try {
await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message}); await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message });
}catch(err){ } catch (err) {
throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404); throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404);
@ -46,7 +48,7 @@ const CreateSchedulingNotifyService = async ({
} }
if(!schedulingNotify){ if (!schedulingNotify) {
schedulingNotify = await SchedulingNotify.create( schedulingNotify = await SchedulingNotify.create(
{ {
@ -63,7 +65,13 @@ const CreateSchedulingNotifyService = async ({
return schedulingNotify return schedulingNotify
}
} catch (error: any) {
console.error('===> Error on CreateSchedulingNotifyService.ts file: \n', error)
throw new AppError(error.message);
}
}
@ -85,4 +93,4 @@ const CreateSchedulingNotifyService = async ({
// return schedulingNotify // return schedulingNotify
// } // }
export default CreateSchedulingNotifyService export default CreateSchedulingNotifyService

View File

@ -3,37 +3,46 @@ import SchedulingNotify from "../../models/SchedulingNotify";
interface SchedulingData { interface SchedulingData {
name?: string name?: string
} }
interface Request { interface Request {
schedulingData: SchedulingData schedulingData: SchedulingData
schedulingDataId: string schedulingDataId: string
} }
const UpdateSchedulingNotify = async ({ const UpdateSchedulingNotify = async ({
schedulingData, schedulingData,
schedulingDataId schedulingDataId
}: Request): Promise<SchedulingNotify> => { }: Request): Promise<SchedulingNotify> => {
const { name } = schedulingData;
const updateScheduling = await SchedulingNotify.findOne({ try {
where: { id: schedulingDataId },
attributes: ["id", "name"]
});
if (!updateScheduling) { const { name } = schedulingData;
const updateScheduling = await SchedulingNotify.findOne({
where: { id: schedulingDataId },
attributes: ["id", "name"]
});
if (!updateScheduling) {
//console.log('NOT FOUND SCHEDULING NOTIFY') //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; export default UpdateSchedulingNotify;

View File

@ -10,17 +10,24 @@ const UpdateSettingService = async ({
key, key,
value value
}: Request): Promise<Setting | undefined> => { }: Request): Promise<Setting | undefined> => {
const setting = await Setting.findOne({
where: { key }
});
if (!setting) { try {
throw new AppError("ERR_NO_SETTING_FOUND", 404); 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; export default UpdateSettingService;

View File

@ -29,57 +29,66 @@ const CreateTicketService = async ({
status, status,
userId userId
}: Request): Promise<Ticket> => { }: Request): Promise<Ticket> => {
const defaultWhatsapp = await GetDefaultWhatsApp(userId);
await CheckContactOpenTickets(contactId);
const { isGroup } = await ShowContactService(contactId);
const { id }: Ticket = await defaultWhatsapp.$create("ticket", {
contactId,
status,
isGroup,
userId
});
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 { try {
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data const defaultWhatsapp = await GetDefaultWhatsApp(userId);
let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo']
ticket_obj = flatten(ticket_obj) await CheckContactOpenTickets(contactId);
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj) const { isGroup } = await ShowContactService(contactId);
} catch (error) { const { id }: Ticket = await defaultWhatsapp.$create("ticket", {
console.log('There was an error on UpdateTicketService.ts on createTicketCache from user: ', error) contactId,
status,
isGroup,
userId
});
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)
}
//
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate)
const io = getIO();
io.emit("ticketStatus", {
action: "update",
ticketStatus: { ticketId: ticket.id, status: ticket.status }
});
return ticket;
} catch (error: any) {
console.error('===> Error on CreateTicketService.ts file: \n', error)
throw new AppError(error.message);
} }
//
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate)
const io = getIO();
io.emit("ticketStatus", {
action: "update",
ticketStatus: {ticketId: ticket.id, status: ticket.status}
});
return ticket;
}; };
export default CreateTicketService; export default CreateTicketService;

View File

@ -5,6 +5,7 @@ import Contact from "../../models/Contact";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService"; import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError";
const FindOrCreateTicketService = async ( const FindOrCreateTicketService = async (
@ -13,16 +14,19 @@ const FindOrCreateTicketService = async (
unreadMessages: number, unreadMessages: number,
groupContact?: Contact groupContact?: Contact
): Promise<Ticket> => { ): Promise<Ticket> => {
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 {
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 //Habilitar esse caso queira usar o bot
@ -31,86 +35,90 @@ const FindOrCreateTicketService = async (
if (ticket) {
await ticket.update({ unreadMessages });
}
if (!ticket && groupContact) {
ticket = await Ticket.findOne({
where: {
contactId: groupContact.id
},
order: [["updatedAt", "DESC"]]
});
if (ticket) { if (ticket) {
await ticket.update({ unreadMessages });
await ticket.update({
status: "pending",
userId: null,
unreadMessages
});
} }
}
if (!ticket && !groupContact) { if (!ticket && groupContact) {
ticket = await Ticket.findOne({
ticket = await Ticket.findOne({ where: {
where: { contactId: groupContact.id
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()]
}, },
contactId: contact.id order: [["updatedAt", "DESC"]]
},
order: [["updatedAt", "DESC"]]
});
if (ticket) {
await ticket.update({
status: "pending",
userId: null,
unreadMessages
}); });
}
}
if (!ticket) {
let status = "pending"
if (queues.length > 1 && !botInfo.isOnQueue) { if (ticket) {
status = "queueChoice"
await ticket.update({
status: "pending",
userId: null,
unreadMessages
});
}
} }
ticket = await Ticket.create({ if (!ticket && !groupContact) {
contactId: groupContact ? groupContact.id : contact.id,
status: status,
isGroup: !!groupContact,
unreadMessages,
whatsappId
});
// TEST DEL ticket = await Ticket.findOne({
where: {
updatedAt: {
//[Op.between]: [+subHours(new Date(), 2), +new Date()]
// const { name } = await ShowContactService(contact.id); // Tempo osioso para a ura responder thuanny
// console.log('FIND OR CREATE TICKET SERVICE NAME: ', contact.name, ' STATUS: ', status) //[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; export default FindOrCreateTicketService;

View File

@ -7,6 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService"; import ShowTicketService from "./ShowTicketService";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache' import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
import AppError from "../../errors/AppError";
var flatten = require('flat') var flatten = require('flat')
@ -33,7 +34,10 @@ const UpdateTicketService = async ({
ticketData, ticketData,
ticketId ticketId
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const { status, userId, queueId, statusChatEnd } = ticketData;
try {
const { status, userId, queueId, statusChatEnd } = ticketData;
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
// await SetTicketMessagesAsRead(ticket); // await SetTicketMessagesAsRead(ticket);
@ -99,6 +103,12 @@ const UpdateTicketService = async ({
return { ticket, oldStatus, oldUserId }; return { ticket, oldStatus, oldUserId };
} catch (error: any) {
console.error('===> Error on UpdateTicketService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default UpdateTicketService; export default UpdateTicketService;

View File

@ -34,146 +34,152 @@ const CreateOrUpdateUserOnlineTime = async ({
status, status,
}: Request): Promise<UserOnlineTime> => { }: Request): Promise<UserOnlineTime> => {
try {
const io = getIO();
let userOnlineTime: any = null;
const io = getIO(); const user = await User.findOne({ where: { id: userId } });
let userOnlineTime: any = null;
const user = await User.findOne({ where: { id: userId } }); if (!user) {
if (!user) { return userOnlineTime
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}`)
},
]
} }
});
if (userOnlineTime) {
try {
let oldStatus = userOnlineTime.status
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
userOnlineTime = await UserOnlineTime.findOne({
if (oldStatus == 'online' && status === 'offline') { where: {
//updatedAt [Op.and]: [
let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date() }) {
userId: userId
},
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${dateTime.fullDate}`)
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)
} }
}); });
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
} }

View File

@ -28,61 +28,70 @@ const CreateUserService = async ({
queueIds = [], queueIds = [],
profile = "master" profile = "master"
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
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 { try {
await schema.validate({ email, password, name });
} catch (err:any) {
throw new AppError(err.message);
}
const user = await User.create( const schema = Yup.object().shape({
{ name: Yup.string().required().min(2),
email,
password,
name,
profile
},
{ include: ["queues"] }
);
await user.$set("queues", queueIds); 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;
}
),
await user.reload(); // 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;
// }
// ),
const serializedUser = SerializeUser(user); 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);
deleteFileFromTMP(`botInfo.json`) deleteFileFromTMP(`botInfo.json`)
return serializedUser; return serializedUser;
} catch (error: any) {
console.error('===> Error on CreateUserService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default CreateUserService; export default CreateUserService;

View File

@ -30,66 +30,76 @@ const UpdateUserService = async ({
userData, userData,
userId userId
}: Request): Promise<Response | undefined> => { }: Request): Promise<Response | undefined> => {
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 { try {
await schema.validate({ email, password, profile, name });
} catch (err: any) { const user = await ShowUserService(userId);
throw new AppError(err.message);
} 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({ await user.update({
email, email,
password, password,
profile, profile,
name name
}); });
await user.$set("queues", queueIds); await user.$set("queues", queueIds);
await user.reload(); await user.reload();
const serializedUser = { const serializedUser = {
id: user.id, id: user.id,
name: user.name, name: user.name,
email: user.email, email: user.email,
profile: user.profile, profile: user.profile,
queues: user.queues queues: user.queues
}; };
deleteFileFromTMP(`botInfo.json`) deleteFileFromTMP(`botInfo.json`)
return serializedUser; return serializedUser;
} catch (error: any) {
console.error('===> Error on UpdateUserService.ts file: \n', error)
throw new AppError(error.message);
}
}; };
export default UpdateUserService; export default UpdateUserService;

View File

@ -43,152 +43,106 @@ const SendWhatsAppMessage = async ({
number number
}: Request): Promise<WbotMessage | any> => { }: Request): Promise<WbotMessage | any> => {
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 { try {
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 });
}
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, number); sendWhatsAppMessageSocket(ticket, body, quotedMsgSerializedId, number);
await ticket.update({ lastMessage: body }); await ticket.update({ lastMessage: body });
await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() }) await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() })
console.timeEnd(timetaken)
} catch (err: any) {
// const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, body, { quotedMessageId: quotedMsgSerializedId, linkPreview: false }); console.error('0 ===> Error on SendWhatsAppMessage.ts file: \n', err)
throw new AppError("ERR_SENDING_WAPP_MSG");
// await ticket.update({ lastMessage: body }); }
// await updateTicketCacheByTicketId(ticket.id, { lastMessage: body, updatedAt: new Date(ticket.updatedAt).toISOString() }) } catch (error: any) {
console.error('===> Error on SendWhatsAppMessage.ts file: \n', error)
// return sentMessage; throw new AppError(error.message);
console.timeEnd(timetaken)
} catch (err) {
// const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
throw new AppError("ERR_SENDING_WAPP_MSG");
} }
}; };
export default SendWhatsAppMessage; export default SendWhatsAppMessage;

View File

@ -70,6 +70,7 @@ import { _restore } from "../../helpers/RestoreControll";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl"; import { getWhatsappIds, setWhatsappId } from "../../helpers/WhatsappIdMultiSessionControl";
import SendWhatsAppMedia from "./SendWhatsAppMedia"; import SendWhatsAppMedia from "./SendWhatsAppMedia";
import AppError from "../../errors/AppError";
@ -964,11 +965,6 @@ const handleMessage = async (
} }
if (!isValidMsg(msg)) { if (!isValidMsg(msg)) {
return; return;
} }
@ -1072,7 +1068,14 @@ const handleMessage = async (
// console.log('PARA RESPONDER PELO MEMOS WHATSAPP wbot.id: ', wbot.id, ' | wbot.status: ', wbot.status) // console.log('PARA RESPONDER PELO MEMOS WHATSAPP wbot.id: ', wbot.id, ' | wbot.status: ', wbot.status)
// console.log('WHATSAPP STATUS ticket.whatsappId: ', ticket.whatsappId) // 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);
}
} }
// //

View File

@ -30,67 +30,77 @@ const CreateWhatsAppService = async ({
farewellMessage, farewellMessage,
isDefault = false, isDefault = false,
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
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 { try {
await schema.validate({ name, status, isDefault, urlApi });
} catch (err: any) {
throw new AppError(err.message);
}
const whatsappFound = await Whatsapp.findOne(); const schema = Yup.object().shape({
name: Yup.string()
isDefault = !whatsappFound; .required()
.min(2)
let oldDefaultWhatsapp: Whatsapp | null = null; .test(
"Check-name",
if (isDefault) { "This whatsapp name is already used.",
oldDefaultWhatsapp = await Whatsapp.findOne({ async value => {
where: { isDefault: true } 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; export default CreateWhatsAppService;

View File

@ -37,80 +37,89 @@ const UpdateWhatsAppService = async ({
whatsappData, whatsappData,
whatsappId whatsappId
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
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 { try {
await schema.validate({ name, status, isDefault });
} catch (err: any) {
throw new AppError(err.message);
}
if (queueIds.length > 1 && !greetingMessage) { const schema = Yup.object().shape({
throw new AppError("ERR_WAPP_GREETING_REQUIRED"); name: Yup.string().min(2),
} status: Yup.string(),
isDefault: Yup.boolean()
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 {
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 };
} catch (error: any) {
console.error('===> Error on UpdateWhatsAppService.ts file: \n', error)
throw new AppError(error.message);
} }
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 };
}; };
export default UpdateWhatsAppService; export default UpdateWhatsAppService;