fix: Improve ticket query in backend to resolve high delay issue

feat-scaling-ticket-remote-creation
adriano 2024-03-28 12:20:55 -03:00
parent dc5a6945d2
commit c27770ef02
3 changed files with 63 additions and 53 deletions

View File

@ -262,9 +262,7 @@ export const reportMessagesUserByDateStartDateEnd = async (
data_query_messages[i].fromMe = "Cliente"; data_query_messages[i].fromMe = "Cliente";
} }
data_query_messages[i].id = i + 1; data_query_messages[i].id = i + 1;
console.log("data_query_messages: ", data_query_messages[i]);
} }
return res.status(200).json(data_query_messages); return res.status(200).json(data_query_messages);

View File

@ -18,6 +18,7 @@ import { startOfDay, endOfDay, parseISO, getDate } from "date-fns";
import { string } from "yup/lib/locale"; import { string } from "yup/lib/locale";
import Whatsapp from "../../models/Whatsapp"; import Whatsapp from "../../models/Whatsapp";
import Query from "mysql2/typings/mysql/lib/protocol/sequences/Query"; import Query from "mysql2/typings/mysql/lib/protocol/sequences/Query";
import { te } from "date-fns/locale";
interface Request { interface Request {
userId: string | number; userId: string | number;
@ -43,43 +44,56 @@ const ShowTicketReport = async ({
createdOrUpdated = "created", createdOrUpdated = "created",
queueId queueId
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
let where_clause: any = {}; // let where_clause: any = {};
let query = ""; // let query = "";
if (userId !== "0") { // if (userId !== "0") {
where_clause.userid = userId; // where_clause.userid = userId;
query = `AND t.userId = ${userId}`; // query = `AND t.userId = ${userId}`;
} // }
// if (queueId) {
// where_clause.queueId = queueId;
// query = `AND t.queueId = ${queueId}`;
// }
const createdAtOrUpdatedAt =
createdOrUpdated == "created" ? "createdAt" : "updatedAt";
let where_clause = {};
if (queueId) { if (queueId) {
where_clause.queueId = queueId; where_clause = {
query = `AND t.queueId = ${queueId}`; queueId: queueId,
[createdAtOrUpdatedAt]: {
[Op.gte]: startDate + " 00:00:00.000000",
[Op.lte]: endDate + " 23:59:59.999999"
}
};
} else if (userId == "0") {
where_clause = {
[createdAtOrUpdatedAt]: {
[Op.gte]: startDate + " 00:00:00.000000",
[Op.lte]: endDate + " 23:59:59.999999"
}
};
} else if (userId != "0") {
where_clause = {
userid: userId,
[createdAtOrUpdatedAt]: {
[Op.gte]: startDate + " 00:00:00.000000",
[Op.lte]: endDate + " 23:59:59.999999"
}
};
} }
const limit = 40; const limit = 40;
const offset = limit * (+pageNumber - 1); const offset = limit * (+pageNumber - 1);
const createdAtOrUpdatedAt =
createdOrUpdated == "created" ? "createdAt" : "updatedAt";
const _ticketsId = await sequelize.query(
`SELECT t.id
FROM Tickets t
INNER JOIN (
SELECT DISTINCT ticketId
FROM Messages
WHERE ${createdAtOrUpdatedAt} >= '${startDate} 00:00:00' AND ${createdAtOrUpdatedAt} <= '${endDate} 23:59:59'
) AS m ON m.ticketId = t.id ${query};`,
{ type: QueryTypes.SELECT }
);
let { count, rows: tickets }: any = await Ticket.findAndCountAll({ let { count, rows: tickets }: any = await Ticket.findAndCountAll({
where: { where: where_clause,
id: { [Op.in]: _ticketsId.map((t: any) => t.id) }
},
limit, limit,
offset, offset,
attributes: [ attributes: [
"id", "id",
"status", "status",
@ -151,43 +165,41 @@ const ShowTicketReport = async ({
throw new AppError("ERR_NO_TICKET_FOUND", 404); throw new AppError("ERR_NO_TICKET_FOUND", 404);
} }
const ticketIds = tickets.map((t: any) => t.id); if (tickets.length > 0) {
if (ticketIds.length > 0) {
const waiting_time: any = await sequelize.query( const waiting_time: any = await sequelize.query(
`SELECT t.id as ticketId, t.status, TIME_FORMAT( `SELECT t.id as ticketId, t.status, TIME_FORMAT(
SEC_TO_TIME( SEC_TO_TIME(
TIMESTAMPDIFF( TIMESTAMPDIFF(
SECOND, SECOND,
( (
SELECT createdAt SELECT createdAt
FROM Messages FROM Messages
WHERE ticketId = m.ticketId WHERE ticketId = m.ticketId
AND fromMe = 0 AND fromMe = 0
ORDER BY createdAt ASC ORDER BY createdAt ASC
LIMIT 1 LIMIT 1
), ),
( (
SELECT createdAt SELECT createdAt
FROM Messages FROM Messages
WHERE ticketId = m.ticketId WHERE ticketId = m.ticketId
AND fromAgent = 1 AND fromAgent = 1
ORDER BY createdAt ASC ORDER BY createdAt ASC
LIMIT 1 LIMIT 1
) )
) )
), '%H:%i:%s') AS WAITING_TIME ), '%H:%i:%s') AS WAITING_TIME
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
JOIN Whatsapps w ON t.whatsappId = w.id JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId JOIN Queues q ON q.id = t.queueId
WHERE DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999' WHERE DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND t.id IN (${ticketIds.join()}) AND t.id IN (${tickets.map((t: any) => t.id).join()})
AND m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id) AND m.createdAt = (SELECT MIN(createdAt) FROM Messages WHERE ticketId = t.id)
AND m.fromMe = 0 AND m.fromMe = 0
AND t.status IN ('open', 'closed') AND t.status IN ('open', 'closed')
HAVING WAITING_TIME IS NOT NULL HAVING WAITING_TIME IS NOT NULL
ORDER BY ORDER BY
WAITING_TIME;`, WAITING_TIME;`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );

View File

@ -363,7 +363,7 @@ const Report = () => {
if (reportOption === '1') { if (reportOption === '1') {
const { data } = await api.get("/reports/", { params: { userId, startDate, endDate, pageNumber: pageNumberTickets, createdOrUpdated: selectedValue, queueId }, userQueues: userA.queues }) const { data } = await api.get("/reports/", { params: { userId, startDate, endDate, pageNumber: pageNumberTickets, createdOrUpdated: selectedValue, queueId }, userQueues: userA.queues })
let ticketsQueue = data.tickets let ticketsQueue = data.tickets
let userQueues = userA.queues let userQueues = userA.queues
let filterQueuesTickets = [] let filterQueuesTickets = []