import CheckContactOpenTickets from "../../helpers/CheckContactOpenTickets"; import SetTicketMessagesAsRead from "../../helpers/SetTicketMessagesAsRead"; import { getIO } from "../../libs/socket"; import Ticket from "../../models/Ticket"; import SendWhatsAppMessage from "../WbotServices/SendWhatsAppMessage"; import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; import ShowTicketService from "./ShowTicketService"; import { createOrUpdateTicketCache } from '../../helpers/TicketCache' var flatten = require('flat') interface TicketData { status?: string; userId?: number; queueId?: number; statusChatEnd?: string } interface Request { ticketData: TicketData; ticketId: string | number; } interface Response { ticket: Ticket; oldStatus: string; oldUserId: number | undefined; } const UpdateTicketService = async ({ ticketData, ticketId }: Request): Promise => { const { status, userId, queueId, statusChatEnd } = ticketData; const ticket = await ShowTicketService(ticketId); await SetTicketMessagesAsRead(ticket); const oldStatus = ticket.status; const oldUserId = ticket.user?.id; if (oldStatus === "closed") { await CheckContactOpenTickets(ticket.contact.id); } await ticket.update({ status, queueId, userId, statusChatEnd }); await ticket.reload(); // TEST DEL try { // const { name, number } = await ShowContactService(ticket.contactId) 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'] delete ticket_obj['user'] 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: ', error) } // let io = getIO(); if (ticket.status !== oldStatus || ticket.user?.id !== oldUserId) { io.to(oldStatus).emit("ticket", { action: "delete", ticketId: ticket.id }); } io.to(ticket.status) .to("notification") .to(ticketId.toString()) .emit("ticket", { action: "update", ticket }); io.emit("ticketStatus", { action: "update", ticketStatus: { ticketId: ticket.id, status: ticket.status } }); return { ticket, oldStatus, oldUserId }; }; export default UpdateTicketService;