Inclusao de try catch para rastrear a origem do tcp_wrap.cc erro

pull/21/head
adriano 2023-04-20 15:48:42 -03:00
parent 5ab5d8d9c3
commit 69da69089a
19 changed files with 972 additions and 862 deletions

View File

@ -24,36 +24,45 @@ const CreateContactService = async ({
profilePicUrl='',
extraInfo = []
}: Request): Promise<Contact> => {
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;

View File

@ -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<Contact> => {
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;

View File

@ -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<Contact> => {
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;

View File

@ -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<Message>
// 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<Message>
return message;
} catch (error: any) {
console.error('===> Error on CreateMessageService.ts file: \n', error)
throw new AppError(error.message);
}
};
export default CreateMessageService;

View File

@ -9,7 +9,10 @@ interface QueueData {
}
const CreateQueueService = async (queueData: QueueData): Promise<Queue> => {
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<Queue> => {
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;

View File

@ -14,60 +14,69 @@ const UpdateQueueService = async (
queueId: number | string,
queueData: QueueData
): 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 {
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;

View File

@ -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<SchedulingNotify> => {
ticketId,
statusChatEndId,
schedulingDate,
schedulingTime,
message
}: Request): Promise<SchedulingNotify> => {
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<SchedulingNotify> => {
// const schedulingNotify = await SchedulingNotify.create(
@ -79,10 +87,10 @@ const CreateSchedulingNotifyService = async ({
// schedulingDate,
// schedulingTime,
// message
// })
// return schedulingNotify
// }
export default CreateSchedulingNotifyService
export default CreateSchedulingNotifyService

View File

@ -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<SchedulingNotify> => {
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;

View File

@ -10,17 +10,24 @@ const UpdateSettingService = async ({
key,
value
}: Request): Promise<Setting | undefined> => {
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;

View File

@ -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<Ticket> => {
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;

View File

@ -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<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 {
//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;

View File

@ -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<Response> => {
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;

View File

@ -34,146 +34,152 @@ const CreateOrUpdateUserOnlineTime = async ({
status,
}: Request): Promise<UserOnlineTime> => {
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
}

View File

@ -26,59 +26,68 @@ const CreateUserService = async ({
queueIds = [],
profile = "master"
}: 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 {
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;

View File

@ -28,64 +28,74 @@ const UpdateUserService = async ({
userData,
userId
}: 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 {
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;

View File

@ -41,151 +41,105 @@ const SendWhatsAppMessage = async ({
quotedMsg
}: 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 {
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;

View File

@ -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<void> => {
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 {

View File

@ -30,67 +30,77 @@ const CreateWhatsAppService = async ({
farewellMessage,
isDefault = false,
}: 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 {
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;

View File

@ -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<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 {
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;