124 lines
2.9 KiB
TypeScript
124 lines
2.9 KiB
TypeScript
import { subHours, subMinutes, subSeconds } from "date-fns";
|
|
import { Op } from "sequelize";
|
|
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 AppError from "../../errors/AppError";
|
|
|
|
|
|
const FindOrCreateTicketService = async (
|
|
contact: Contact,
|
|
whatsappId: number,
|
|
unreadMessages: number,
|
|
groupContact?: Contact
|
|
): Promise<Ticket> => {
|
|
|
|
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
|
|
const botInfo = await BotIsOnQueue('botqueue')
|
|
// const botInfo = { isOnQueue: false }
|
|
|
|
|
|
if (ticket) {
|
|
await ticket.update({ unreadMessages });
|
|
}
|
|
|
|
if (!ticket && groupContact) {
|
|
ticket = await Ticket.findOne({
|
|
where: {
|
|
contactId: groupContact.id
|
|
},
|
|
order: [["updatedAt", "DESC"]]
|
|
});
|
|
|
|
|
|
|
|
if (ticket) {
|
|
|
|
await ticket.update({
|
|
status: "pending",
|
|
userId: null,
|
|
unreadMessages
|
|
});
|
|
}
|
|
}
|
|
|
|
if (!ticket && !groupContact) {
|
|
|
|
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()]
|
|
},
|
|
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);
|
|
}
|
|
};
|
|
|
|
export default FindOrCreateTicketService;
|