modulo canpanha em desenvolvimento

pull/21/head
adriano 2023-07-26 17:24:10 -03:00
parent 417f947263
commit 4ee65ad300
8 changed files with 339 additions and 257 deletions

View File

@ -8,24 +8,22 @@ import ShowTicketService from "../services/TicketServices/ShowTicketService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService"; import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage"; import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import ShowStatusChatEndService from '../services/StatusChatEndService/ShowStatusChatEndService' import ShowStatusChatEndService from "../services/StatusChatEndService/ShowStatusChatEndService";
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService"; import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService"; import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import { isScheduling } from "../helpers/CheckSchedulingReminderNotify" import { isScheduling } from "../helpers/CheckSchedulingReminderNotify";
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from "date-fns/locale/pt-BR";
import { splitDateTime } from "../helpers/SplitDateTime"; import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format'; import format from "date-fns/format";
import ListTicketsServiceCache from "../services/TicketServices/ListTicketServiceCache"; import ListTicketsServiceCache from "../services/TicketServices/ListTicketServiceCache";
import { searchTicketCache, loadTicketsCache, } from '../helpers/TicketCache' import { searchTicketCache, loadTicketsCache } from "../helpers/TicketCache";
import { Op } from "sequelize"; import { Op } from "sequelize";
type IndexQuery = { type IndexQuery = {
searchParam: string; searchParam: string;
pageNumber: string; pageNumber: string;
@ -35,7 +33,7 @@ type IndexQuery = {
withUnreadMessages: string; withUnreadMessages: string;
queueIds: string; queueIds: string;
unlimited?: string; unlimited?: string;
searchParamContent?: string searchParamContent?: string;
}; };
interface TicketData { interface TicketData {
@ -43,13 +41,12 @@ interface TicketData {
status: string; status: string;
queueId: number; queueId: number;
userId: number; userId: number;
whatsappId?: string | number whatsappId?: string | number;
msg?: string, msg?: string;
transfer?: boolean | undefined, transfer?: boolean | undefined;
fromMe?: boolean fromMe?: boolean;
} }
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService"; import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport"; import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
@ -60,7 +57,6 @@ import ShowUserService from "../services/UserServices/ShowUserService";
import axios from "axios"; import axios from "axios";
import User from "../models/User"; import User from "../models/User";
import CheckContactOpenTickets from "../helpers/CheckContactOpenTickets"; import CheckContactOpenTickets from "../helpers/CheckContactOpenTickets";
import QueuesByUser from "../services/UserServices/ShowQueuesByUser";
import GetDefaultWhatsApp from "../helpers/GetDefaultWhatsApp"; import GetDefaultWhatsApp from "../helpers/GetDefaultWhatsApp";
import { getWbot } from "../libs/wbot"; import { getWbot } from "../libs/wbot";
import endPointQuery from "../helpers/old_EndPointQuery"; import endPointQuery from "../helpers/old_EndPointQuery";
@ -69,7 +65,6 @@ import BotIsOnQueue from "../helpers/BotIsOnQueue";
import { setMessageAsRead } from "../helpers/SetMessageAsRead"; import { setMessageAsRead } from "../helpers/SetMessageAsRead";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { const {
pageNumber, pageNumber,
status, status,
@ -82,7 +77,6 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
searchParamContent searchParamContent
} = req.query as IndexQuery; } = req.query as IndexQuery;
const userId = req.user.id; const userId = req.user.id;
let queueIds: number[] = []; let queueIds: number[] = [];
@ -110,22 +104,23 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { contactId, status, userId, msg, queueId }: TicketData = req.body; const { contactId, status, userId, msg, queueId }: TicketData = req.body;
const botInfo = await BotIsOnQueue('botqueue') // const botInfo = await BotIsOnQueue("botqueue");
let ticket = await Ticket.findOne({ let ticket = await Ticket.findOne({
where: { where: {
[Op.or]: [ [Op.or]: [
{ contactId, status: 'queueChoice' }, { contactId, status: "queueChoice" }
{ contactId, status: 'open', userId: botInfo.userIdBot } // { contactId, status: "open", userId: botInfo.userIdBot }
] ]
} }
}); });
if (ticket) { if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open', userId: userId, queueId }, ticketId: ticket.id }); await UpdateTicketService({
ticketData: { status: "open", userId: userId, queueId },
} ticketId: ticket.id
else { });
} else {
ticket = await CreateTicketService({ contactId, status, userId, queueId }); ticket = await CreateTicketService({ contactId, status, userId, queueId });
} }
@ -134,8 +129,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
action: "update", action: "update",
ticket ticket
}); });
// //
// const ticket = await CreateTicketService({ contactId, status, userId }); // const ticket = await CreateTicketService({ contactId, status, userId });
@ -148,58 +142,65 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json(ticket); return res.status(200).json(ticket);
}; };
export const show = async (req: Request, res: Response): Promise<Response> => { export const show = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const contact = await ShowTicketService(ticketId); const contact = await ShowTicketService(ticketId);
const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" }); const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({
searchParam: "",
pageNumber: "1"
});
////////////////// //////////////////
const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number); const schedulesContact = await ListSchedulingNotifyContactService(
contact.contact.number
);
///////////////// /////////////////
return res.status(200).json({ contact, statusChatEnd, schedulesContact }); return res.status(200).json({ contact, statusChatEnd, schedulesContact });
}; };
export const count = async (req: Request, res: Response): Promise<Response> => { export const count = async (req: Request, res: Response): Promise<Response> => {
// type indexQ = { status: string; date?: string; }; // type indexQ = { status: string; date?: string; };
const { status, date } = req.query as IndexQuery const { status, date } = req.query as IndexQuery;
const ticketCount = await CountTicketService(status, date); const ticketCount = await CountTicketService(status, date);
return res.status(200).json(ticketCount); return res.status(200).json(ticketCount);
}; };
export const update = async (
export const update = async (req: Request, res: Response): Promise<Response> => { req: Request,
res: Response
console.log('ENTROU NO UPDATE TICKET CONTROLLER') ): Promise<Response> => {
console.log("ENTROU NO UPDATE TICKET CONTROLLER");
const { ticketId } = req.params; const { ticketId } = req.params;
const userOldInfo = await Ticket.findByPk(ticketId) const userOldInfo = await Ticket.findByPk(ticketId);
let ticket2 = {} let ticket2 = {};
if (req.body['status'] === "closed") {
if (req.body["status"] === "closed") {
const { status, userId, schedulingNotifyData } = req.body; const { status, userId, schedulingNotifyData } = req.body;
// lembrete // lembrete
const scheduleData = JSON.parse(schedulingNotifyData) const scheduleData = JSON.parse(schedulingNotifyData);
const statusChatEndName = await ShowStatusChatEndService(scheduleData.statusChatEndId) const statusChatEndName = await ShowStatusChatEndService(
scheduleData.statusChatEndId
);
const { ticket } = await UpdateTicketService({ const { ticket } = await UpdateTicketService({
ticketData: { 'status': status, 'userId': userId, 'statusChatEnd': statusChatEndName.name }, ticketData: {
status: status,
userId: userId,
statusChatEnd: statusChatEndName.name
},
ticketId ticketId
}); });
if (scheduleData.farewellMessage) { if (scheduleData.farewellMessage) {
const whatsapp = await ShowWhatsAppService(ticket.whatsappId); const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
@ -210,37 +211,33 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
} }
} }
// lembrete // agendamento // lembrete // agendamento
if (scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3') { if (
scheduleData.statusChatEndId === "2" ||
scheduleData.statusChatEndId === "3"
if (isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)) { ) {
console.log('*** É AGENDAMENTO!') if (
} isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)
else { ) {
console.log('*** É LEMBRETE!') console.log("*** É AGENDAMENTO!");
} else {
console.log("*** É LEMBRETE!");
} }
const schedulingNotifyCreate = await CreateSchedulingNotifyService( const schedulingNotifyCreate = await CreateSchedulingNotifyService({
{ ticketId: scheduleData.ticketId,
ticketId: scheduleData.ticketId, statusChatEndId: scheduleData.statusChatEndId,
statusChatEndId: scheduleData.statusChatEndId, schedulingDate: scheduleData.schedulingDate,
schedulingDate: scheduleData.schedulingDate, schedulingTime: scheduleData.schedulingTime,
schedulingTime: scheduleData.schedulingTime, message: scheduleData.message
message: scheduleData.message });
}
)
} }
ticket2 = ticket ticket2 = ticket;
} else {
}
else {
// Para aparecer pendente para todos usuarios que estao na fila // Para aparecer pendente para todos usuarios que estao na fila
if (req.body.transfer) { if (req.body.transfer) {
req.body.userId = null req.body.userId = null;
} }
let ticketData: TicketData = req.body; let ticketData: TicketData = req.body;
@ -250,75 +247,75 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
// return res.send() // return res.send()
if (1 == 1 + 1) {
} else {
if (ticketData.transfer) {
const defaultWhatsapp: any = await GetDefaultWhatsApp(
ticketData.userId
);
// if (ticketData.transfer) { const _ticket: any = await Ticket.findByPk(ticketId);
// const defaultWhatsapp: any = await GetDefaultWhatsApp(ticketData.userId); if (defaultWhatsapp && ticketData.status != "open") {
await CheckContactOpenTickets(
_ticket.dataValues.contactId,
defaultWhatsapp.dataValues.id
);
}
// const _ticket: any = await Ticket.findByPk(ticketId) ticketData.whatsappId = defaultWhatsapp.dataValues.id;
}
// if (defaultWhatsapp && ticketData.status != 'open') { }
// await CheckContactOpenTickets(_ticket.dataValues.contactId, defaultWhatsapp.dataValues.id)
// }
// ticketData.whatsappId = defaultWhatsapp.dataValues.id
// }
console.log('--------> ticketData.status: ', ticketData.status, ' | ticketData.fromMe: ', ticketData.fromMe)
console.log(
"--------> ticketData.status: ",
ticketData.status,
" | ticketData.fromMe: ",
ticketData.fromMe
);
const { ticket } = await UpdateTicketService({ const { ticket } = await UpdateTicketService({
ticketData, ticketData,
ticketId, ticketId
}); });
if (ticketData.status == "open" && !ticketData.fromMe) {
if (ticketData.status == 'open' && !ticketData.fromMe) {
await setMessageAsRead(ticket); await setMessageAsRead(ticket);
} }
console.log('ticket.unreadMessages: ', ticket.unreadMessages) console.log("ticket.unreadMessages: ", ticket.unreadMessages);
if (ticketData.userId) { if (ticketData.userId) {
const dateToday = splitDateTime(
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
TicketEmiterSumOpenClosedByUser(ticketData.userId.toString(), dateToday.fullDate, dateToday.fullDate) );
TicketEmiterSumOpenClosedByUser(
ticketData.userId.toString(),
dateToday.fullDate,
dateToday.fullDate
);
} }
ticket2 = ticket ticket2 = ticket;
} }
if (userOldInfo) { if (userOldInfo) {
const dateToday = splitDateTime(
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
);
if (userOldInfo.userId) { if (userOldInfo.userId) {
TicketEmiterSumOpenClosedByUser(
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate) userOldInfo.userId.toString(),
dateToday.fullDate,
dateToday.fullDate
);
} }
} }
return res.status(200).json(ticket2); return res.status(200).json(ticket2);
}; };
// export const update = async ( // export const update = async (
// req: Request, // req: Request,
// res: Response // res: Response
@ -341,7 +338,6 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
// } // }
// } // }
// return res.status(200).json(ticket); // return res.status(200).json(ticket);
// }; // };
@ -354,13 +350,10 @@ export const remove = async (
const ticket = await DeleteTicketService(ticketId); const ticket = await DeleteTicketService(ticketId);
const io = getIO(); const io = getIO();
io.to(ticket.status) io.to(ticket.status).to(ticketId).to("notification").emit("ticket", {
.to(ticketId) action: "delete",
.to("notification") ticketId: +ticketId
.emit("ticket", { });
action: "delete",
ticketId: +ticketId
});
return res.status(200).json({ message: "ticket deleted" }); return res.status(200).json({ message: "ticket deleted" });
}; };
@ -371,4 +364,3 @@ export const remove = async (
// await endPointQuery(`${wbot_url}/api/sendSeen`, { number: `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us` }); // await endPointQuery(`${wbot_url}/api/sendSeen`, { number: `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us` });
// } // }

View File

@ -1,11 +1,31 @@
import { Op } from "sequelize"; import { Op } from "sequelize";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
const CheckContactOpenTickets = async (contactId: number): Promise<void> => { const CheckContactOpenTickets = async (
const ticket = await Ticket.findOne({ contactId: number,
where: { contactId, status: { [Op.or]: ["open", "pending"] } } whatsappId: number | string
}); ): Promise<void> => {
let ticket;
if (1 == 1 + 1) {
ticket = await Ticket.findOne({
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
});
} else {
let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({
where: {
[Op.and]: [
{ contactId: contactId },
{ whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) } },
{ status: { [Op.or]: ["open", "pending"] } }
]
}
});
}
if (ticket) { if (ticket) {
throw new AppError("ERR_OTHER_OPEN_TICKET"); throw new AppError("ERR_OTHER_OPEN_TICKET");

View File

@ -0,0 +1,34 @@
import Whatsapp from "../models/Whatsapp";
import ShowQueuesByUser from "../services/UserServices/ShowQueuesByUser";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
async function whatsappQueueMatchingUserQueue(
userId: number,
whatsapp: Whatsapp,
userProfile: string = "user"
) {
const userQueues = await ShowQueuesByUser({
profile: userProfile,
userId: userId
});
if (!userQueues || (userQueues && userQueues.length == 0)) return;
// console.log('-----> userQueues: ', userQueues);
let whats: any = await ShowWhatsAppService(whatsapp.id);
if (!whats.queues || (whats.queues && whats.queues.length == 0)) return;
const whatsappQueues = whats.queues.map((e: any) => e.dataValues.name);
// console.log('-----> whatsappQueues: ', whatsappQueues);
const matchingQueue = userQueues.find(queue =>
whatsappQueues.includes(queue.name)
);
return matchingQueue;
}
export default whatsappQueueMatchingUserQueue;

View File

@ -4,42 +4,50 @@ import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import ShowContactService from "../ContactServices/ShowContactService"; import ShowContactService from "../ContactServices/ShowContactService";
import { getIO } from "../../libs/socket"; import { getIO } from "../../libs/socket";
import ShowUserServiceReport from "../UserServices/ShowUserServiceReport"; import ShowUserServiceReport from "../UserServices/ShowUserServiceReport";
import format from 'date-fns/format'; import format from "date-fns/format";
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from "date-fns/locale/pt-BR";
import { splitDateTime } from "../../helpers/SplitDateTime"; import { splitDateTime } from "../../helpers/SplitDateTime";
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser"; import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";
import { createOrUpdateTicketCache } from '../../helpers/TicketCache' import { createOrUpdateTicketCache } from "../../helpers/TicketCache";
let flatten = require('flat') import User from "../../models/User";
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
let flatten = require("flat");
interface Request { interface Request {
contactId: number; contactId: number;
status: string; status: string;
userId: number; userId: number;
queueId?: number | undefined; queueId?: number | undefined;
} }
const CreateTicketService = async ({ const CreateTicketService = async ({
contactId, contactId,
status, status,
userId, userId,
queueId = undefined queueId = undefined
}: Request): Promise<Ticket> => { }: Request): Promise<Ticket> => {
console.log("========> queueId: ", queueId);
console.log('========> queueId: ', queueId)
try { try {
const defaultWhatsapp = await GetDefaultWhatsApp(userId);
const defaultWhatsapp = await GetDefaultWhatsApp(userId); const user = await User.findByPk(userId, { raw: true });
await CheckContactOpenTickets(contactId); if (!queueId) {
const matchingQueue = await whatsappQueueMatchingUserQueue(
userId,
defaultWhatsapp,
user?.profile
);
queueId = matchingQueue ? matchingQueue.queueId : undefined;
}
await CheckContactOpenTickets(contactId, defaultWhatsapp.id);
const { isGroup } = await ShowContactService(contactId); const { isGroup } = await ShowContactService(contactId);
@ -59,27 +67,32 @@ const CreateTicketService = async ({
// console.log('CONTACT ticket.id: ', ticket.id) // console.log('CONTACT ticket.id: ', ticket.id)
// TEST DEL
// TEST DEL
try { try {
let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
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 let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo'] delete ticket_obj["contact"]["extraInfo"];
ticket_obj = flatten(ticket_obj) ticket_obj = flatten(ticket_obj);
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
} catch (error) { } catch (error) {
console.log('There was an error on UpdateTicketService.ts on createTicketCache from user: ', 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 }))
);
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) TicketEmiterSumOpenClosedByUser(
userId.toString(),
TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate) dateToday.fullDate,
dateToday.fullDate
);
const io = getIO(); const io = getIO();
io.emit("ticketStatus", { io.emit("ticketStatus", {
@ -87,14 +100,11 @@ const CreateTicketService = async ({
ticketStatus: { ticketId: ticket.id, status: ticket.status } ticketStatus: { ticketId: ticket.id, status: ticket.status }
}); });
return ticket; return ticket;
} catch (error: any) { } catch (error: any) {
console.error('===> Error on CreateTicketService.ts file: \n', error) console.error("===> Error on CreateTicketService.ts file: \n", error);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };
export default CreateTicketService; export default CreateTicketService;

View File

@ -6,7 +6,7 @@ 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"; import AppError from "../../errors/AppError";
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
const FindOrCreateTicketService = async ( const FindOrCreateTicketService = async (
contact: Contact, contact: Contact,
@ -14,26 +14,37 @@ const FindOrCreateTicketService = async (
unreadMessages: number, unreadMessages: number,
groupContact?: Contact groupContact?: Contact
): Promise<Ticket> => { ): Promise<Ticket> => {
try { try {
let ticket;
let ticket = await Ticket.findOne({ if (1 == 1 + 1) {
where: { ticket = await Ticket.findOne({
status: { where: {
[Op.or]: ["open", "pending", "queueChoice"] status: {
}, [Op.or]: ["open", "pending", "queueChoice"]
contactId: groupContact ? groupContact.id : contact.id },
} contactId: groupContact ? groupContact.id : contact.id
}); }
});
} else {
let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id,
whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) }
}
});
}
const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId); const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId);
//Habilitar esse caso queira usar o bot //Habilitar esse caso queira usar o bot
// const botInfo = await BotIsOnQueue('botqueue') // const botInfo = await BotIsOnQueue('botqueue')
const botInfo = { isOnQueue: false } const botInfo = { isOnQueue: false };
if (ticket) { if (ticket) {
await ticket.update({ unreadMessages }); await ticket.update({ unreadMessages });
@ -47,10 +58,7 @@ const FindOrCreateTicketService = async (
order: [["updatedAt", "DESC"]] order: [["updatedAt", "DESC"]]
}); });
if (ticket) { if (ticket) {
await ticket.update({ await ticket.update({
status: "pending", status: "pending",
userId: null, userId: null,
@ -60,7 +68,6 @@ const FindOrCreateTicketService = async (
} }
if (!ticket && !groupContact) { if (!ticket && !groupContact) {
ticket = await Ticket.findOne({ ticket = await Ticket.findOne({
where: { where: {
updatedAt: { updatedAt: {
@ -78,7 +85,6 @@ const FindOrCreateTicketService = async (
}); });
if (ticket) { if (ticket) {
await ticket.update({ await ticket.update({
status: "pending", status: "pending",
userId: null, userId: null,
@ -88,11 +94,10 @@ const FindOrCreateTicketService = async (
} }
if (!ticket) { if (!ticket) {
let status = "pending";
let status = "pending"
if (queues.length > 1 && !botInfo.isOnQueue) { if (queues.length > 1 && !botInfo.isOnQueue) {
status = "queueChoice" status = "queueChoice";
} }
ticket = await Ticket.create({ ticket = await Ticket.create({
@ -114,9 +119,8 @@ const FindOrCreateTicketService = async (
ticket = await ShowTicketService(ticket.id); ticket = await ShowTicketService(ticket.id);
return ticket; return ticket;
} catch (error: any) { } catch (error: any) {
console.error('===> Error on FindOrCreateTicketService.ts file: \n', error) console.error("===> Error on FindOrCreateTicketService.ts file: \n", error);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };

View File

@ -6,25 +6,24 @@ import SendWhatsAppMessage from "../WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService"; 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"; import AppError from "../../errors/AppError";
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket"; import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
var flatten = require('flat') var flatten = require("flat");
interface TicketData { interface TicketData {
status?: string; status?: string;
userId?: number; userId?: number;
queueId?: number; queueId?: number;
statusChatEnd?: string; statusChatEnd?: string;
unreadMessages?: number; unreadMessages?: number;
whatsappId?: string | number;
} }
interface Request { interface Request {
ticketData: TicketData; ticketData: TicketData;
ticketId: string | number; ticketId: string | number;
msg?: string msg?: string;
} }
interface Response { interface Response {
@ -35,13 +34,18 @@ interface Response {
const UpdateTicketService = async ({ const UpdateTicketService = async ({
ticketData, ticketData,
ticketId, ticketId,
msg='' msg = ""
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
try { try {
const {
const { status, userId, queueId, statusChatEnd, unreadMessages } = ticketData; status,
userId,
queueId,
statusChatEnd,
unreadMessages,
whatsappId
} = ticketData;
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
// await SetTicketMessagesAsRead(ticket); // await SetTicketMessagesAsRead(ticket);
@ -50,7 +54,7 @@ const UpdateTicketService = async ({
const oldUserId = ticket.user?.id; const oldUserId = ticket.user?.id;
if (oldStatus === "closed") { if (oldStatus === "closed") {
await CheckContactOpenTickets(ticket.contact.id); await CheckContactOpenTickets(ticket.contact.id, ticket.whatsappId);
} }
await ticket.update({ await ticket.update({
@ -58,36 +62,35 @@ const UpdateTicketService = async ({
queueId, queueId,
userId, userId,
unreadMessages, unreadMessages,
statusChatEnd statusChatEnd,
whatsappId
}); });
await ticket.reload(); await ticket.reload();
if (msg.length > 0) { if (msg.length > 0) {
setTimeout(async () => { setTimeout(async () => {
sendWhatsAppMessageSocket(ticket, msg);
sendWhatsAppMessageSocket(ticket, msg) }, 2000);
}, 2000)
} }
// TEST DEL // TEST DEL
try { try {
// const { name, number } = await ShowContactService(ticket.contactId)
// const { name, number } = await ShowContactService(ticket.contactId) let jsonString = JSON.stringify(ticket); //convert to string to remove the sequelize specific meta data
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 let ticket_obj = JSON.parse(jsonString); //to make plain json
delete ticket_obj['contact']['extraInfo'] delete ticket_obj["contact"]["extraInfo"];
delete ticket_obj['user'] delete ticket_obj["user"];
ticket_obj = flatten(ticket_obj) ticket_obj = flatten(ticket_obj);
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
} catch (error) { } catch (error) {
console.log('There was an error on UpdateTicketService.ts on createTicketCache: ', error) console.log(
"There was an error on UpdateTicketService.ts on createTicketCache: ",
error
);
} }
// //
@ -100,7 +103,6 @@ const UpdateTicketService = async ({
}); });
} }
io.to(ticket.status) io.to(ticket.status)
.to("notification") .to("notification")
.to(ticketId.toString()) .to(ticketId.toString())
@ -109,20 +111,16 @@ const UpdateTicketService = async ({
ticket ticket
}); });
io.emit("ticketStatus", { io.emit("ticketStatus", {
action: "update", action: "update",
ticketStatus: { ticketId: ticket.id, status: ticket.status } ticketStatus: { ticketId: ticket.id, status: ticket.status }
}); });
return { ticket, oldStatus, oldUserId }; return { ticket, oldStatus, oldUserId };
} catch (error: any) { } catch (error: any) {
console.error('===> Error on UpdateTicketService.ts file: \n', error) console.error("===> Error on UpdateTicketService.ts file: \n", error);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };
export default UpdateTicketService; export default UpdateTicketService;

View File

@ -1,40 +1,62 @@
import { Sequelize } from "sequelize";
import { Sequelize, } from "sequelize";
const dbConfig = require("../../config/database"); const dbConfig = require("../../config/database");
const sequelize = new Sequelize(dbConfig); const sequelize = new Sequelize(dbConfig);
const { QueryTypes } = require('sequelize'); const { QueryTypes } = require("sequelize");
interface Request { interface Request {
profile: string; profile?: string;
userId?: string | number; userId?: string | number;
} }
const QueuesByUser = async ({ profile, userId }: Request): Promise<any[]> => { const QueuesByUser = async ({ profile, userId }: Request): Promise<any[]> => {
let queueByUsersInfo: any = [];
let queueByUsersInfo = [] if (userId && profile) {
// CONSULTANDO FILAS PELO ID DO USUARIO
if (userId) { queueByUsersInfo = await sequelize.query(
// CONSULTANDO FILAS PELO ID DO USUARIO `select UserQueues.userId, UserQueues.queueId, Users.name,
queueByUsersInfo = await sequelize.query(`select UserQueues.userId, UserQueues.queueId, Users.name,
Queues.name, Queues.color from UserQueues inner join Users inner join Queues on Queues.name, Queues.color from UserQueues inner join Users inner join Queues on
UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.id = '${userId}' and Users.profile = '${profile}' order by userId, queueId;`, { type: QueryTypes.SELECT }); UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.id = '${userId}' and Users.profile = '${profile}' order by userId, queueId;`,
{ type: QueryTypes.SELECT }
} else { );
} else if (profile) {
// CONSULTANDO FILAS PELO USUARIO // CONSULTANDO FILAS PELO USUARIO
queueByUsersInfo = await sequelize.query(`select UserQueues.userId, UserQueues.queueId, Users.name, queueByUsersInfo = await sequelize.query(
`select UserQueues.userId, UserQueues.queueId, Users.name,
Queues.name, Queues.color from UserQueues inner join Users inner join Queues on Queues.name, Queues.color from UserQueues inner join Users inner join Queues on
UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.profile = '${profile}' order by userId, queueId;`, { type: QueryTypes.SELECT }); UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.profile = '${profile}' order by userId, queueId;`,
{ type: QueryTypes.SELECT }
);
} else if (userId) {
queueByUsersInfo = await sequelize.query(
`select UserQueues.userId, UserQueues.queueId, Users.name,
Queues.name, Queues.color from UserQueues inner join Users inner join Queues on
UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.id = '${userId}' order by userId, queueId;`,
{ type: QueryTypes.SELECT }
);
}
} // if (userId) {
// // CONSULTANDO FILAS PELO ID DO USUARIO
// queueByUsersInfo = await sequelize.query(
// `select UserQueues.userId, UserQueues.queueId, Users.name,
// Queues.name, Queues.color from UserQueues inner join Users inner join Queues on
// UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.id = '${userId}' and Users.profile = '${profile}' order by userId, queueId;`,
// { type: QueryTypes.SELECT }
// );
// } else {
// // CONSULTANDO FILAS PELO USUARIO
// queueByUsersInfo = await sequelize.query(
// `select UserQueues.userId, UserQueues.queueId, Users.name,
// Queues.name, Queues.color from UserQueues inner join Users inner join Queues on
// UserQueues.queueId = Queues.id and UserQueues.userId = Users.id and Users.profile = '${profile}' order by userId, queueId;`,
// { type: QueryTypes.SELECT }
// );
// }
return queueByUsersInfo; return queueByUsersInfo;
}; };
export default QueuesByUser; export default QueuesByUser;

View File

@ -1,30 +1,32 @@
import Whatsapp from "../../models/Whatsapp"; import Whatsapp from "../../models/Whatsapp";
const ListWhatsAppsNumber = async (whatsappId: string | number, status: string): Promise<Whatsapp[] | any> => { const ListWhatsAppsNumber = async (
whatsappId: string | number,
status?: string
): Promise<Whatsapp[] | any> => {
const whatsapp = await Whatsapp.findByPk(whatsappId, { raw: true });
// const whatsapp = await Whatsapp.findOne({ let whatsapps: any = [];
// raw: true,
// where: { id: whatsappId }
// })
const whatsapp = await Whatsapp.findByPk(whatsappId, { raw: true })
if (whatsapp) {
const whatsapps = await Whatsapp.findAll({
raw: true,
where: { number: whatsapp.number, status: status },
attributes: ['id', 'number', 'status', 'isDefault', 'url']
});
return { whatsapps, whatsapp };
if (whatsapp) {
if (status) {
whatsapps = await Whatsapp.findAll({
raw: true,
where: { number: whatsapp.number, status: status },
attributes: ["id", "number", "status", "isDefault", "url"]
});
} else {
whatsapps = await Whatsapp.findAll({
raw: true,
where: { number: whatsapp.number },
attributes: ["id", "number", "status", "isDefault", "url"]
});
} }
return { whatsapps: [], whatsapp: null } return { whatsapps, whatsapp };
}
return { whatsapps: [], whatsapp: null };
}; };
export default ListWhatsAppsNumber; export default ListWhatsAppsNumber;