Compare commits

..

4 Commits

28 changed files with 1082 additions and 331 deletions

View File

@ -30,6 +30,7 @@ type IndexQuery = {
queueId: string; queueId: string;
pageNumber: string; pageNumber: string;
userQueues: []; userQueues: [];
isRemote: string;
}; };
type ReportOnQueue = { type ReportOnQueue = {
@ -302,15 +303,19 @@ export const reportService = async (
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { startDate, endDate, queueId } = req.query as IndexQuery; const { startDate, endDate, queueId, isRemote } = req.query as IndexQuery;
console.log( console.log(
`startDate: ${startDate} | endDate: ${endDate} | queueId: ${queueId}` `startDate: ${startDate} | endDate: ${endDate} | queueId: ${queueId}`
); );
console.log("IS REMOTE: ", isRemote);
console.log("isRemote: ", isRemote && isRemote == "true" ? true : false);
const reportService = await ReportByNumberQueueService({ const reportService = await ReportByNumberQueueService({
startDate, startDate,
endDate endDate,
isRemote: isRemote && isRemote == "true" ? true : false
}); });
return res.status(200).json({ reportService }); return res.status(200).json({ reportService });
@ -328,12 +333,13 @@ export const reportServiceByQueue = async (
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { startDate, endDate, queueId } = req.query as IndexQuery; const { startDate, endDate, queueId, isRemote } = req.query as IndexQuery;
const reportService = await ReportByNumberQueueService({ const reportService = await ReportByNumberQueueService({
startDate, startDate,
endDate, endDate,
queue: true queue: true,
isRemote: isRemote && isRemote == "true" ? true : false
}); });
return res.status(200).json({ reportService }); return res.status(200).json({ reportService });

View File

@ -123,11 +123,12 @@ export const update = async (
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { settingKey: key } = req.params; const { settingKey: key } = req.params;
const { value } = req.body; const { value, obj } = req.body;
const setting = await UpdateSettingService({ const setting = await UpdateSettingService({
key, key,
value value,
obj
}); });
if (key && key == "whatsaAppCloudApi") { if (key && key == "whatsaAppCloudApi") {

View File

@ -75,10 +75,11 @@ import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl";
import CreateContactService from "../services/ContactServices/CreateContactService"; import CreateContactService from "../services/ContactServices/CreateContactService";
import { botSendMessage } from "../services/WbotServices/wbotMessageListener"; import { botSendMessage } from "../services/WbotServices/wbotMessageListener";
import WhatsappQueue from "../models/WhatsappQueue"; import WhatsappQueue from "../models/WhatsappQueue";
import { get } from "../helpers/RedisClient"; import { del, get, set } from "../helpers/RedisClient";
import CountStatusChatEndService from "../services/StatusChatEndService/CountStatusChatEndService"; import CountStatusChatEndService from "../services/StatusChatEndService/CountStatusChatEndService";
import Queue from "../models/Queue"; import Queue from "../models/Queue";
import StatusChatEnd from "../models/StatusChatEnd"; import StatusChatEnd from "../models/StatusChatEnd";
import controllByNumber from "../helpers/controllByNumber";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { const {
@ -101,7 +102,8 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
queueIds = JSON.parse(queueIdsStringified); queueIds = JSON.parse(queueIdsStringified);
} }
const { tickets, count, hasMore } = await ListTicketsService({ const { tickets, count, hasMore, remoteTicketsControll } =
await ListTicketsService({
searchParam, searchParam,
pageNumber, pageNumber,
status, status,
@ -114,7 +116,9 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
searchParamContent searchParamContent
}); });
return res.status(200).json({ tickets, count, hasMore }); return res
.status(200)
.json({ tickets, count, hasMore, remoteTicketsControll });
}; };
export const remoteTicketCreation = async ( export const remoteTicketCreation = async (
@ -232,7 +236,8 @@ export const remoteTicketCreation = async (
const botInfo = await BotIsOnQueue("botqueue"); const botInfo = await BotIsOnQueue("botqueue");
let ticket = await Ticket.findOne({ // ticket from queueChoice or bot
let ticket: any = await Ticket.findOne({
where: { where: {
[Op.or]: [ [Op.or]: [
{ contactId, status: "queueChoice" }, { contactId, status: "queueChoice" },
@ -258,7 +263,25 @@ export const remoteTicketCreation = async (
} }
} }
if (!ticket) { ticket = await Ticket.findOne({
where: {
[Op.or]: [
{ contactId, status: "pending" },
{ contactId, status: "open" }
]
}
});
if (ticket) {
console.log(
`THE CAMPAIGN TICKET WAS NOT CREATED BECAUSE THE TICKET IS PENDING OR OPEN`
);
return res.status(422).json({
msg: `The campaign ticket was not created because the number ${contact_to} already has a ticket open or pending`
});
}
ticket = await FindOrCreateTicketService( ticket = await FindOrCreateTicketService(
contact, contact,
whatsappId, whatsappId,
@ -267,8 +290,22 @@ export const remoteTicketCreation = async (
queueId, queueId,
true true
); );
botSendMessage(ticket, `${msg}`);
} // botSendMessage(ticket, `${msg}`);
await ticket.update({
lastMessage: msg
});
await set(
`remote:ticketId:${ticket.id}`,
JSON.stringify({
id: ticket.id,
createdAt: ticket.createdAt,
updatedAt: ticket.updatedAt,
whatsappId: ticket.whatsappId
})
);
const io = getIO(); const io = getIO();
io.to(ticket.status).emit("ticket", { io.to(ticket.status).emit("ticket", {
@ -276,9 +313,19 @@ export const remoteTicketCreation = async (
ticket ticket
}); });
const obj = await controllByNumber();
if (obj?.tickets) {
io.emit("remoteTickesControll", {
action: "update",
tickets: obj.ticketIds
});
}
console.log( console.log(
`REMOTE TICKET CREATION FROM ENDPOINT | STATUS: 200 | MSG: success` `REMOTE TICKET CREATION FROM ENDPOINT | STATUS: 200 | MSG: success`
); );
return res.status(200).json({ msg: "success" }); return res.status(200).json({ msg: "success" });
} }
@ -648,5 +695,7 @@ export const remove = async (
ticketId: +ticketId ticketId: +ticketId
}); });
await del(`remote:ticketId:${ticketId}`);
return res.status(200).json({ message: "ticket deleted" }); return res.status(200).json({ message: "ticket deleted" });
}; };

View File

@ -0,0 +1,15 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Tickets", "remoteDone", {
type: DataTypes.BOOLEAN,
allowNull: true,
defaultValue: false
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Tickets", "remoteDone");
}
};

View File

@ -0,0 +1,14 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Settings", "obj", {
type: DataTypes.STRING,
allowNull: true
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Settings", "obj");
}
};

View File

@ -0,0 +1,22 @@
import { QueryInterface } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.bulkInsert(
"Settings",
[
{
key: "remoteTicketSendControll",
value: "true",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface: QueryInterface) => {
return queryInterface.bulkDelete("Settings", {});
}
};

View File

@ -0,0 +1,78 @@
import { intervalToDuration } from "date-fns";
import { del, get, set } from "./RedisClient";
import { getIO } from "../libs/socket";
import controllByNumber from "./controllByNumber";
let timer: any;
const AutoRemoteTickets = async () => {
try {
let obj: any = await controllByNumber();
if (!obj?.tickets) return;
for (const ticket of obj.tickets) {
if (!ticket.includes("messageDateTime")) continue;
let match = ticket.match(/"messageDateTime":("[^"]*")/);
let messageDateTime = match ? match[1] : null;
console.log("messageDateTime: ", messageDateTime);
match = ticket.match(/"whatsappId":(\d+)/);
let whatsappId = match ? match[1] : null;
console.log("whatsappId: ", whatsappId);
const whatsapp = await get({
key: `whatsapp:${whatsappId}`
});
match = whatsapp.match(/"number":"(\d+)"/);
let number = match ? match[1] : null;
console.log("number: ", number);
match = ticket.match(/"id":(\d+)/);
let ticketId = match ? match[1] : null;
console.log("ticketId: ", ticketId);
number = JSON.parse(number);
ticketId = JSON.parse(ticketId);
let timeDiff: any = intervalToDuration({
start: new Date(JSON.parse(messageDateTime)),
end: new Date()
});
console.log("______timeDiff: ", timeDiff);
if (timeDiff.seconds > 50) {
del(`remote:ticketId:${ticketId}`);
obj = await controllByNumber();
const io = getIO();
io.emit("remoteTickesControll", {
action: "update",
tickets: obj.ticketIds
});
}
}
} catch (error) {
console.log("There was an error on auto remote tickets service: ", error);
}
};
const schedule = async () => {
try {
clearInterval(timer);
await AutoRemoteTickets();
} catch (error) {
console.log("error on schedule: ", error);
} finally {
timer = setInterval(schedule, 5000);
}
};
timer = setInterval(schedule, 5000);
export default schedule;

View File

@ -31,6 +31,7 @@ export async function get({ key, value, parse }: getData) {
if (key.includes("*")) { if (key.includes("*")) {
const keys = await redis.keys(key); const keys = await redis.keys(key);
if (keys.length > 0) { if (keys.length > 0) {
if (value) {
for (const key of keys) { for (const key of keys) {
const val = await redis.get(key); const val = await redis.get(key);
if (val.includes(value)) { if (val.includes(value)) {
@ -38,6 +39,15 @@ export async function get({ key, value, parse }: getData) {
return val; return val;
} }
} }
} else {
let res: any[] = [];
for (const key of keys) {
const val = await redis.get(key);
if (parse) res.push(JSON.parse(val));
res.push(val);
}
return res;
}
} }
return null; return null;
} else { } else {

View File

@ -0,0 +1,41 @@
import { get, set } from "./RedisClient";
async function controllByNumber() {
let tickets = await get({ key: "remote:ticketId*", parse: false });
if (!tickets) return { ticketIds: [], tickets: null };
let controll: any[] = [];
for (const ticket of tickets) {
let match = ticket.match(/"whatsappId":(\d+)/);
let whatsappId = match ? match[1] : null;
const whatsapp = await get({
key: `whatsapp:${whatsappId}`
});
match = whatsapp.match(/"number":"(\d+)"/);
let number = match ? match[1] : null;
match = ticket.match(/"id":(\d+)/);
let ticketId = match ? match[1] : null;
number = JSON.parse(number);
ticketId = JSON.parse(ticketId);
const index = controll.findIndex((c: any) => c.number == number);
if (index == -1) {
controll.push({ ticketId, number });
}
}
const ticketIds = controll.map((c: any) => c.ticketId);
set(`remote:controll`, JSON.stringify(ticketIds));
return { ticketIds, tickets };
}
export default controllByNumber;

View File

@ -16,6 +16,9 @@ class Setting extends Model<Setting> {
@Column @Column
value: string; value: string;
@Column
obj: string;
@CreatedAt @CreatedAt
createdAt: Date; createdAt: Date;

View File

@ -21,7 +21,7 @@ import User from "./User";
import Whatsapp from "./Whatsapp"; import Whatsapp from "./Whatsapp";
import SchedulingNotify from "./SchedulingNotify"; import SchedulingNotify from "./SchedulingNotify";
import StatusChatEnd from "./StatusChatEnd" import StatusChatEnd from "./StatusChatEnd";
@Table @Table
class Ticket extends Model<Ticket> { class Ticket extends Model<Ticket> {
@ -47,6 +47,10 @@ class Ticket extends Model<Ticket> {
@Column @Column
isRemote: boolean; isRemote: boolean;
@Default(false)
@Column
remoteDone: boolean;
@ForeignKey(() => StatusChatEnd) @ForeignKey(() => StatusChatEnd)
@Column @Column
statusChatEndId: number; statusChatEndId: number;

View File

@ -9,7 +9,7 @@ settingRoutes.get("/settings", SettingController.index);
settingRoutes.get("/settings/ticket/:number", SettingController.ticketSettings); settingRoutes.get("/settings/ticket/:number", SettingController.ticketSettings);
// routes.get("/settings/:settingKey", isAuth, SettingsController.show); // settingRoutes.get("/settings/:settingKey", isAuth, SettingsController.show);
settingRoutes.put( settingRoutes.put(
"/settings/ticket", "/settings/ticket",

View File

@ -13,6 +13,7 @@ import { loadContactsCache } from "./helpers/ContactsCache";
import { loadSchedulesCache } from "./helpers/SchedulingNotifyCache"; import { loadSchedulesCache } from "./helpers/SchedulingNotifyCache";
import { delRestoreControllFile } from "./helpers/RestoreControll"; import { delRestoreControllFile } from "./helpers/RestoreControll";
import "./helpers/AutoCloseTickets"; import "./helpers/AutoCloseTickets";
import "./helpers/AutoRemoteTickets"
import "./helpers/SchedulingNotifySendMessage"; import "./helpers/SchedulingNotifySendMessage";
import axios from "axios"; import axios from "axios";
@ -90,6 +91,17 @@ gracefulShutdown(server);
const { phoneNumberId, id, greetingMessage } = whatsapps[i]; const { phoneNumberId, id, greetingMessage } = whatsapps[i];
if (phoneNumberId) { if (phoneNumberId) {
// await set(
// `whatsapp:${whatsapps[i].dataValues.id}`,
// JSON.stringify({
// number: whatsapps[i].dataValues.number,
// id,
// greetingMessage,
// phoneNumberId
// })
// );
}
await set( await set(
`whatsapp:${whatsapps[i].dataValues.id}`, `whatsapp:${whatsapps[i].dataValues.id}`,
JSON.stringify({ JSON.stringify({
@ -99,7 +111,6 @@ gracefulShutdown(server);
phoneNumberId phoneNumberId
}) })
); );
}
if (phoneNumberId) { if (phoneNumberId) {
continue; continue;

View File

@ -1,4 +1,5 @@
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import { get, set } from "../../helpers/RedisClient";
import { updateTicketCacheByTicketId } from "../../helpers/TicketCache"; import { updateTicketCacheByTicketId } from "../../helpers/TicketCache";
import { getIO } from "../../libs/socket"; import { getIO } from "../../libs/socket";
import Message from "../../models/Message"; import Message from "../../models/Message";
@ -22,9 +23,7 @@ interface Request {
const CreateMessageService = async ({ const CreateMessageService = async ({
messageData messageData
}: Request): Promise<Message> => { }: Request): Promise<Message> => {
try { try {
await Message.upsert(messageData); await Message.upsert(messageData);
const message = await Message.findByPk(messageData.id, { const message = await Message.findByPk(messageData.id, {
@ -47,6 +46,28 @@ const CreateMessageService = async ({
throw new Error("ERR_CREATING_MESSAGE"); throw new Error("ERR_CREATING_MESSAGE");
} }
//////////////////// SETTINGS ///////////////////////////
let ticketRemote = await get({
key: `remote:ticketId:${message.ticket.id}`
});
if (ticketRemote && !ticketRemote.includes("messageDateTime")) {
ticketRemote = JSON.parse(ticketRemote);
ticketRemote = {
...ticketRemote,
...{ messageDateTime: message.createdAt }
};
const ticket = await Ticket.findByPk(message.ticket.id);
ticket?.update({ remoteDone: true });
console.log('MESSAGE SERVICE: XXXXXXXXXXXXXXXXXXXXXXX')
set(`remote:ticketId:${message.ticket.id}`, JSON.stringify(ticketRemote));
}
//////////////////////////////////////////////////////////
if (message.ticket.status != "queueChoice") { if (message.ticket.status != "queueChoice") {
await updateTicketCacheByTicketId(message.ticket.id, { await updateTicketCacheByTicketId(message.ticket.id, {
lastMessage: message.body, lastMessage: message.body,

View File

@ -15,14 +15,17 @@ interface Request {
startDate: string | number; startDate: string | number;
endDate: string; endDate: string;
queue?: boolean; queue?: boolean;
isRemote?: boolean;
} }
const ReportByNumberQueueService = async ({ const ReportByNumberQueueService = async ({
startDate, startDate,
endDate, endDate,
queue = false queue = false,
isRemote = false
}: Request): Promise<any[]> => { }: Request): Promise<any[]> => {
let reportServiceData: any[] = []; let reportServiceData: any[] = [];
const includeIsRemote = isRemote ? "t.isRemote = true AND" : "";
const whatsapps = await Whatsapp.findAll(); const whatsapps = await Whatsapp.findAll();
@ -30,6 +33,11 @@ const ReportByNumberQueueService = async ({
for (const whatsapp of whatsapps) { for (const whatsapp of whatsapps) {
const { id, name, number } = whatsapp; const { id, name, number } = whatsapp;
let startedByClient: any;
let avgChatWaitingTime: any;
let pendingChat: any;
let closedChat: any;
if ( if (
!number || !number ||
reportServiceData.findIndex((w: any) => w?.number == number) != -1 reportServiceData.findIndex((w: any) => w?.number == number) != -1
@ -45,15 +53,16 @@ const ReportByNumberQueueService = async ({
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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
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.fromAgent = 1 AND m.fromAgent = 1
AND w.number = ${number};`, AND w.number = ${number};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
if (!isRemote) {
// CHAT STARTED BY CLIENT // CHAT STARTED BY CLIENT
const startedByClient: any = await sequelize.query( startedByClient = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -65,9 +74,25 @@ const ReportByNumberQueueService = async ({
AND w.number = ${number};`, AND w.number = ${number};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
} else {
// CHAT RESPONSE BY CLIENT
startedByClient = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Messages m ON t.id = m.ticketId
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND m.createdAt = (SELECT MAX(createdAt) FROM Messages WHERE ticketId = t.id)
AND m.fromMe = 0
AND w.number = ${number};`,
{ type: QueryTypes.SELECT }
);
}
if (!isRemote) {
// CHAT CLOSED // CHAT CLOSED
const closedChat: any = await sequelize.query( closedChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -78,9 +103,23 @@ const ReportByNumberQueueService = async ({
AND w.number = ${number};`, AND w.number = ${number};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
} else {
// CHAT CLOSED
closedChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND t.status = 'closed'
AND w.number = ${number};`,
{ type: QueryTypes.SELECT }
);
}
if (!isRemote) {
// CHAT WAINTING TIME // CHAT WAINTING TIME
const avgChatWaitingTime: any = await sequelize.query( avgChatWaitingTime = await sequelize.query(
` `
SELECT TIME_FORMAT( SELECT TIME_FORMAT(
SEC_TO_TIME( SEC_TO_TIME(
@ -119,9 +158,11 @@ const ReportByNumberQueueService = async ({
WAITING_TIME;`, WAITING_TIME;`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
}
if (!isRemote) {
// CHAT PENDING // CHAT PENDING
const pendingChat: any = await sequelize.query( pendingChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -133,21 +174,39 @@ const ReportByNumberQueueService = async ({
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
} else {
// CHAT PENDING REMOTE
pendingChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND t.status = 'pending'
AND w.number = ${number};`,
{ type: QueryTypes.SELECT }
);
}
reportServiceData.push({ reportServiceData.push({
id, id,
name, name,
number, number,
startedByAgent: startedByAgent[0]?.ticket_count, startedByAgent: startedByAgent[0]?.ticket_count,
startedByClient: startedByClient[0]?.ticket_count, startedByClient: startedByClient ? startedByClient[0]?.ticket_count : 0,
closedChat: closedChat[0]?.ticket_count, closedChat: closedChat[0]?.ticket_count,
avgChatWaitingTime: avg(avgChatWaitingTime), avgChatWaitingTime: avgChatWaitingTime ? avg(avgChatWaitingTime) : 0,
pendingChat: pendingChat[0]?.ticket_count pendingChat: pendingChat[0]?.ticket_count
}); });
} }
} else { } else {
for (const whatsapp of whatsapps) { for (const whatsapp of whatsapps) {
const { id, name, number } = whatsapp; const { id, name, number } = whatsapp;
let startedByClient: any;
let avgChatWaitingTime: any;
let pendingChat: any;
let closedChat: any;
if ( if (
!number || !number ||
@ -172,15 +231,16 @@ const ReportByNumberQueueService = async ({
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 ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
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.fromAgent = 1 AND m.fromAgent = 1
AND q.id = ${q.id};`, AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
if (!isRemote) {
// CHAT STARTED BY CLIENT // CHAT STARTED BY CLIENT
const startedByClient: any = await sequelize.query( startedByClient = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -192,9 +252,25 @@ const ReportByNumberQueueService = async ({
AND q.id = ${q.id};`, AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
} else {
// CHAT RESPONSE BY CLIENT
startedByClient = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Messages m ON t.id = m.ticketId
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(m.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND m.createdAt = (SELECT MAX(createdAt) FROM Messages WHERE ticketId = t.id)
AND m.fromMe = 0
AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT }
);
}
if (!isRemote) {
// CHAT CLOSED // CHAT CLOSED
const closedChat: any = await sequelize.query( closedChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -205,9 +281,24 @@ const ReportByNumberQueueService = async ({
AND q.id = ${q.id};`, AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
}
else{
// CHAT CLOSED REMOTE
closedChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND t.status = 'closed'
AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT }
);
}
if (!isRemote) {
// CHAT WAINTING TIME // CHAT WAINTING TIME
const avgChatWaitingTime: any = await sequelize.query( avgChatWaitingTime = await sequelize.query(
`SELECT TIME_FORMAT( `SELECT TIME_FORMAT(
SEC_TO_TIME( SEC_TO_TIME(
TIMESTAMPDIFF( TIMESTAMPDIFF(
@ -244,9 +335,11 @@ const ReportByNumberQueueService = async ({
WAITING_TIME;`, WAITING_TIME;`,
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
}
if (!isRemote) {
// CHAT PENDING // CHAT PENDING
const pendingChat: any = await sequelize.query( pendingChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count `SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t FROM Tickets t
JOIN Messages m ON t.id = m.ticketId JOIN Messages m ON t.id = m.ticketId
@ -258,6 +351,20 @@ const ReportByNumberQueueService = async ({
{ type: QueryTypes.SELECT } { type: QueryTypes.SELECT }
); );
} else {
// CHAT PENDING REMOTE
pendingChat = await sequelize.query(
`SELECT COUNT(DISTINCT t.id) AS ticket_count
FROM Tickets t
JOIN Whatsapps w ON t.whatsappId = w.id
JOIN Queues q ON q.id = t.queueId
WHERE ${includeIsRemote} DATE(t.createdAt) BETWEEN '${startDate} 00:00:00.000000' AND '${endDate} 23:59:59.999999'
AND t.status = 'pending'
AND q.id = ${q.id};`,
{ type: QueryTypes.SELECT }
);
}
reportServiceData.push({ reportServiceData.push({
id, id,
@ -266,9 +373,11 @@ const ReportByNumberQueueService = async ({
queueName: q.name, queueName: q.name,
queueColor: q.color, queueColor: q.color,
startedByAgent: startedByAgent[0]?.ticket_count, startedByAgent: startedByAgent[0]?.ticket_count,
startedByClient: startedByClient[0]?.ticket_count, startedByClient: startedByClient
? startedByClient[0]?.ticket_count
: 0,
closedChat: closedChat[0]?.ticket_count, closedChat: closedChat[0]?.ticket_count,
avgChatWaitingTime: avg(avgChatWaitingTime), avgChatWaitingTime: avgChatWaitingTime ? avg(avgChatWaitingTime) : 0,
pendingChat: pendingChat[0]?.ticket_count pendingChat: pendingChat[0]?.ticket_count
}); });
} }
@ -283,23 +392,23 @@ export default ReportByNumberQueueService;
function avg(avgChatWaitingTime: any) { function avg(avgChatWaitingTime: any) {
let waitingAVG: any = avgChatWaitingTime let waitingAVG: any = avgChatWaitingTime
.filter((t: any) => t?.WAITING_TIME) .filter((t: any) => t?.WAITING_TIME)
.map((t: any) => t.WAITING_TIME) .map((t: any) => t.WAITING_TIME);
if (waitingAVG.length > 0) { if (waitingAVG.length > 0) {
let midIndex = Math.floor((0 + waitingAVG.length) / 2) let midIndex = Math.floor((0 + waitingAVG.length) / 2);
if (waitingAVG.length % 2 == 1) { if (waitingAVG.length % 2 == 1) {
waitingAVG = waitingAVG[midIndex] waitingAVG = waitingAVG[midIndex];
} else { } else {
waitingAVG = calculateAverageTime( waitingAVG = calculateAverageTime(
waitingAVG[midIndex - 1], waitingAVG[midIndex - 1],
waitingAVG[midIndex] waitingAVG[midIndex]
) );
} }
} else { } else {
waitingAVG = 0 waitingAVG = 0;
} }
return waitingAVG return waitingAVG;
} }
function calculateAverageTime(time1: string, time2: string) { function calculateAverageTime(time1: string, time2: string) {

View File

@ -4,12 +4,15 @@ import Setting from "../../models/Setting";
interface Request { interface Request {
key: string; key: string;
value: string; value: string;
obj?: string;
} }
const UpdateSettingService = async ({ const UpdateSettingService = async ({
key, key,
value value,
obj
}: Request): Promise<Setting | undefined> => { }: Request): Promise<Setting | undefined> => {
console.log("key: ", key, " | value: ", value, " | obj: ", obj);
try { try {
const setting = await Setting.findOne({ const setting = await Setting.findOne({
@ -20,12 +23,16 @@ const UpdateSettingService = async ({
throw new AppError("ERR_NO_SETTING_FOUND", 404); throw new AppError("ERR_NO_SETTING_FOUND", 404);
} }
await setting.update({ value }); if (obj) {
obj = JSON.stringify(obj);
}
await setting.update({ value, obj });
await setting.reload();
return setting; return setting;
} catch (error: any) { } catch (error: any) {
console.error('===> Error on UpdateSettingService.ts file: \n', error) console.error("===> Error on UpdateSettingService.ts file: \n", error);
throw new AppError(error.message); throw new AppError(error.message);
} }
}; };

View File

@ -20,6 +20,7 @@ import ListTicketServiceCache from "./ListTicketServiceCache";
import { searchTicketCache, loadTicketsCache } from "../../helpers/TicketCache"; import { searchTicketCache, loadTicketsCache } from "../../helpers/TicketCache";
import { getWbot } from "../../libs/wbot"; import { getWbot } from "../../libs/wbot";
import User from "../../models/User"; import User from "../../models/User";
import { get } from "../../helpers/RedisClient";
interface Request { interface Request {
searchParam?: string; searchParam?: string;
@ -38,6 +39,7 @@ interface Response {
tickets: Ticket[]; tickets: Ticket[];
count: number; count: number;
hasMore: boolean; hasMore: boolean;
remoteTicketsControll?: object[];
} }
const ListTicketsService = async ({ const ListTicketsService = async ({
@ -230,7 +232,7 @@ const ListTicketsService = async ({
console.log("kkkkkkkkk limit: ", limit); console.log("kkkkkkkkk limit: ", limit);
const { count, rows: tickets } = await Ticket.findAndCountAll({ let { count, rows: tickets } = await Ticket.findAndCountAll({
where: whereCondition, where: whereCondition,
include: includeCondition, include: includeCondition,
distinct: true, distinct: true,
@ -241,10 +243,13 @@ const ListTicketsService = async ({
const hasMore = count > offset + tickets.length; const hasMore = count > offset + tickets.length;
const ticketIds = await get({ key: `remote:controll`, parse: true });
return { return {
tickets, tickets,
count, count,
hasMore hasMore,
remoteTicketsControll: ticketIds ? ticketIds : []
}; };
}; };

View File

@ -10,7 +10,7 @@ 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";
import BotIsOnQueue from "../../helpers/BotIsOnQueue"; import BotIsOnQueue from "../../helpers/BotIsOnQueue";
import { deleteObject } from "../../helpers/RedisClient"; import { del, deleteObject, get, set } from "../../helpers/RedisClient";
var flatten = require("flat"); var flatten = require("flat");
interface TicketData { interface TicketData {
@ -71,6 +71,23 @@ const UpdateTicketService = async ({
await CheckContactOpenTickets(ticket.contact.id, ticket.whatsappId); await CheckContactOpenTickets(ticket.contact.id, ticket.whatsappId);
} }
if (status == "closed") {
del(`remote:ticketId:${ticket.id}`);
let ticketsIds = await get({ key: `remote:controll`, parse: true });
const index = ticketsIds.findIndex((t: any) => t == ticket.id);
console.log("ticketsIds 1: ", ticketsIds);
if (index != -1) {
ticketsIds.splice(index, 1);
console.log("ticketsIds 2: ", ticketsIds);
set(`remote:controll`, JSON.stringify(ticketsIds));
}
}
await ticket.update({ await ticket.update({
status, status,
queueId, queueId,

View File

@ -94,7 +94,8 @@ import {
findByContain, findByContain,
findObject, findObject,
get, get,
getSimple getSimple,
set
} from "../../helpers/RedisClient"; } from "../../helpers/RedisClient";
import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot"; import FindOrCreateTicketServiceBot from "../TicketServices/FindOrCreateTicketServiceBot";
import ShowTicketService from "../TicketServices/ShowTicketService"; import ShowTicketService from "../TicketServices/ShowTicketService";
@ -766,9 +767,6 @@ const handleMessage = async (
if (getSettingValue("oneContactChatWithManyWhats")?.value == "disabled") { if (getSettingValue("oneContactChatWithManyWhats")?.value == "disabled") {
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen // Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen
if (wbot.id != ticket.whatsappId) { if (wbot.id != ticket.whatsappId) {
// console.log('PARA RESPONDER PELO MEMOS WHATSAPP wbot.id: ', wbot.id, ' | wbot.status: ', wbot.status)
// console.log('WHATSAPP STATUS ticket.whatsappId: ', ticket.whatsappId)
try { try {
await ticket.update({ whatsappId: wbot.id }); await ticket.update({ whatsappId: wbot.id });
} catch (error: any) { } catch (error: any) {

View File

@ -43,6 +43,7 @@ import { TabTicketContext } from "../../context/TabTicketHeaderOption/TabTicketH
import ModalTemplate from "../ModalTemplate" import ModalTemplate from "../ModalTemplate"
import { render } from '@testing-library/react' import { render } from '@testing-library/react'
import { countTicketMsgContext } from "../../context/CountTicketMsgProvider/CountTicketMsgProvider"
const Mp3Recorder = new MicRecorder({ bitRate: 128 }) const Mp3Recorder = new MicRecorder({ bitRate: 128 })
@ -208,10 +209,12 @@ const useStyles = makeStyles((theme) => ({
}, },
})) }))
const MessageInput = ({ ticketStatus }) => { const MessageInput = ({ ticketStatus, ticketLastMessage, ticketIsRemote }) => {
const { tabOption, setTabOption } = useContext(TabTicketContext) const { tabOption, setTabOption } = useContext(TabTicketContext)
const { countTicketMsg, setCountTicketMsg } = useContext(countTicketMsgContext)
const classes = useStyles() const classes = useStyles()
const { ticketId } = useParams() const { ticketId } = useParams()
@ -233,11 +236,21 @@ const MessageInput = ({ ticketStatus }) => {
const isRun = useRef(false) const isRun = useRef(false)
useEffect(() => { useEffect(() => {
inputRef.current.focus() inputRef.current.focus()
}, [replyingMessage]) }, [replyingMessage])
useEffect(() => {
if (ticketIsRemote && countTicketMsg === 0 && ticketLastMessage && ticketLastMessage.trim().length > 0) {
setInputMessage(ticketLastMessage)
}
else {
setInputMessage("")
}
}, [countTicketMsg, ticketIsRemote, ticketLastMessage])
useEffect(() => { useEffect(() => {
inputRef.current.focus() inputRef.current.focus()
return () => { return () => {
@ -352,6 +365,8 @@ const MessageInput = ({ ticketStatus }) => {
setTemplates(data.data) setTemplates(data.data)
} }
setCountTicketMsg(1)
} catch (err) { } catch (err) {
toastError(err) toastError(err)
} }

View File

@ -34,6 +34,7 @@ import whatsBackground from "../../assets/wa-background.png"
import api from "../../services/api" import api from "../../services/api"
import toastError from "../../errors/toastError" import toastError from "../../errors/toastError"
import { CountTicketMsgProvider, countTicketMsgContext } from "../../context/CountTicketMsgProvider/CountTicketMsgProvider"
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
messagesListWrapper: { messagesListWrapper: {
@ -328,6 +329,8 @@ const MessagesList = ({ ticketId, isGroup }) => {
const { user } = useContext(AuthContext) const { user } = useContext(AuthContext)
const { setCountTicketMsg } = useContext(countTicketMsgContext)
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }) dispatch({ type: "RESET" })
setPageNumber(1) setPageNumber(1)
@ -409,6 +412,11 @@ const MessagesList = ({ ticketId, isGroup }) => {
}) })
if (currentTicketId.current === ticketId) { if (currentTicketId.current === ticketId) {
if (data?.messages) {
setCountTicketMsg(data.messages.length)
}
dispatch({ type: "LOAD_MESSAGES", payload: data.messages }) dispatch({ type: "LOAD_MESSAGES", payload: data.messages })
setHasMore(data.hasMore) setHasMore(data.hasMore)
setLoading(false) setLoading(false)

View File

@ -16,6 +16,7 @@ import MessagesList from "../MessagesList"
import api from "../../services/api" import api from "../../services/api"
import { ReplyMessageProvider } from "../../context/ReplyingMessage/ReplyingMessageContext" import { ReplyMessageProvider } from "../../context/ReplyingMessage/ReplyingMessageContext"
import toastError from "../../errors/toastError" import toastError from "../../errors/toastError"
import { CountTicketMsgProvider } from "../../context/CountTicketMsgProvider/CountTicketMsgProvider"
const drawerWidth = 320 const drawerWidth = 320
@ -192,11 +193,21 @@ const Ticket = () => {
</div> </div>
</TicketHeader> </TicketHeader>
<ReplyMessageProvider> <ReplyMessageProvider>
<CountTicketMsgProvider>
<MessagesList <MessagesList
ticketId={ticketId} ticketId={ticketId}
isGroup={ticket.isGroup} isGroup={ticket.isGroup}
></MessagesList> />
<MessageInput ticketStatus={ticket.status} />
<MessageInput
ticketStatus={ticket.status}
ticketLastMessage={ticket?.lastMessage}
ticketIsRemote={ticket?.isRemote} />
</CountTicketMsgProvider>
</ReplyMessageProvider> </ReplyMessageProvider>
</Paper> </Paper>
<ContactDrawer <ContactDrawer

View File

@ -22,6 +22,7 @@ import MarkdownWrapper from "../MarkdownWrapper"
import { Tooltip } from "@material-ui/core" import { Tooltip } from "@material-ui/core"
import { AuthContext } from "../../context/Auth/AuthContext" import { AuthContext } from "../../context/Auth/AuthContext"
import toastError from "../../errors/toastError" import toastError from "../../errors/toastError"
import openSocket from 'socket.io-client'
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
ticket: { ticket: {
@ -101,13 +102,15 @@ const useStyles = makeStyles(theme => ({
}, },
})) }))
const TicketListItem = ({ ticket }) => { const TicketListItem = ({ ticket, remoteTicketsControll, settings }) => {
const classes = useStyles() const classes = useStyles()
const history = useHistory() const history = useHistory()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const { ticketId } = useParams() const { ticketId } = useParams()
const isMounted = useRef(true) const isMounted = useRef(true)
const { user } = useContext(AuthContext) const { user, getSettingValue } = useContext(AuthContext)
const [_remoteTicketsControll, setRemoteTicketsControll] = useState([])
const [_settings, setSettings] = useState(null)
useEffect(() => { useEffect(() => {
return () => { return () => {
@ -115,6 +118,14 @@ const TicketListItem = ({ ticket }) => {
} }
}, []) }, [])
useEffect(() => {
setSettings(settings)
}, [settings])
useEffect(() => {
setRemoteTicketsControll(remoteTicketsControll)
}, [remoteTicketsControll, settings])
const handleAcepptTicket = async id => { const handleAcepptTicket = async id => {
setLoading(true) setLoading(true)
try { try {
@ -131,8 +142,6 @@ const TicketListItem = ({ ticket }) => {
setLoading(false) setLoading(false)
} }
history.push(`/tickets/${id}`) history.push(`/tickets/${id}`)
} }
@ -140,8 +149,46 @@ const TicketListItem = ({ ticket }) => {
history.push(`/tickets/${id}`) history.push(`/tickets/${id}`)
} }
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
socket.on('remoteTickesControll', (data) => {
console.log('REMOTE TICKETS CONTROLL UPDATE2: ', data.tickets)
if (data.action === 'update') {
setRemoteTicketsControll(data.tickets)
}
})
socket.on('settings', (data) => {
if (data.action === 'update') {
setSettings((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
})
return () => {
socket.disconnect()
}
}, [])
return ( return (
<React.Fragment key={ticket.id}> <React.Fragment key={ticket.id}>
<Tooltip
arrow
placement="right"
title={
(ticket?.isRemote && ticket?.remoteDone && ticket.status === 'pending') ? "Mensagem de campanha enviada" : (ticket?.isRemote && ticket.status === 'pending') ? "Mensagem de campanha ainda não enviada" :
""
}
>
<ListItem <ListItem
dense dense
button button
@ -153,6 +200,11 @@ const TicketListItem = ({ ticket }) => {
className={clsx(classes.ticket, { className={clsx(classes.ticket, {
[classes.pendingTicket]: ticket.status === "pending", [classes.pendingTicket]: ticket.status === "pending",
})} })}
style={((ticket.status === "open" || ticket.status === "closed") && ticket?.isRemote) ? {
border: (ticket.status === "open" || ticket.status === "closed") ? "1px solid rgba(121,123,127,0.9)" : "1px solid transparent",
} : {}}
> >
<Tooltip <Tooltip
arrow arrow
@ -238,28 +290,51 @@ const TicketListItem = ({ ticket }) => {
} }
/> />
{ticket.status === "pending" && ( {ticket.status === "pending" && (
<ButtonWithSpinner <ButtonWithSpinner
color="primary" // color="primary"
{...((ticket?.isRemote) ?
((settings &&
settings.length > 0 &&
getSettingValue('remoteTicketSendControll') &&
getSettingValue('remoteTicketSendControll') === 'enabled') && !ticket?.remoteDone && !_remoteTicketsControll?.includes(+ticket.id)) ?
{ style: { backgroundColor: "rgba(121,123,127,0.5)", color: "white" } } :
{ style: { backgroundColor: "rgba(121,123,127,0.9)", color: "white" } } :
{ color: "primary" })}
variant="contained" variant="contained"
disabled={true ? ((settings &&
settings.length > 0 &&
getSettingValue('remoteTicketSendControll') &&
getSettingValue('remoteTicketSendControll') === 'enabled') && ticket?.isRemote && !ticket?.remoteDone && !_remoteTicketsControll?.includes(+ticket.id)) : false}
className={classes.acceptButton} className={classes.acceptButton}
size="small" size="small"
loading={loading} loading={loading}
onClick={e => handleAcepptTicket(ticket.id)} onClick={e => handleAcepptTicket(ticket.id)}
> >
{/* {i18n.t("ticketsList.buttons.accept")} */}
<>
{/* {i18n.t("ticketsList.buttons.accept")}<br />CAMPANHA */}
{ticket?.isRemote ? ( <>
{(ticket?.isRemote && !ticket?.remoteDone) ? (
<>{i18n.t("ticketsList.buttons.accept")}<br />CAMPANHA</> <>{i18n.t("ticketsList.buttons.accept")}<br />CAMPANHA</>
) : ( ) : (
<>{i18n.t("ticketsList.buttons.accept")}</> <>{i18n.t("ticketsList.buttons.accept")}</>
)} )}
</> </>
</ButtonWithSpinner> </ButtonWithSpinner>
)} )}
</ListItem> </ListItem>
</Tooltip>
<Divider variant="inset" component="li" /> <Divider variant="inset" component="li" />
</React.Fragment> </React.Fragment>
) )

View File

@ -15,6 +15,7 @@ import { i18n } from "../../translate/i18n"
import { AuthContext } from "../../context/Auth/AuthContext" import { AuthContext } from "../../context/Auth/AuthContext"
import { SearchTicketContext } from "../../context/SearchTicket/SearchTicket" import { SearchTicketContext } from "../../context/SearchTicket/SearchTicket"
import { Divider } from "@material-ui/core"
const useStyles = makeStyles(theme => ({ const useStyles = makeStyles(theme => ({
ticketsListWrapper: { ticketsListWrapper: {
@ -181,10 +182,18 @@ const TicketsList = (props) => {
const classes = useStyles() const classes = useStyles()
const [pageNumber, setPageNumber] = useState(1) const [pageNumber, setPageNumber] = useState(1)
const [ticketsList, dispatch] = useReducer(reducer, []) const [ticketsList, dispatch] = useReducer(reducer, [])
const { user } = useContext(AuthContext) const { user, setting, } = useContext(AuthContext)
const { searchTicket } = useContext(SearchTicketContext) const { searchTicket } = useContext(SearchTicketContext)
const [_remoteTicketsControll, setRemoteTicketsControll] = useState([])
const [settings, setSettings] = useState([])
useEffect(() => {
setSettings(setting)
}, [setting])
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }) dispatch({ type: "RESET" })
@ -192,7 +201,7 @@ const TicketsList = (props) => {
}, [status, searchParam, searchParamContent, showAll, selectedQueueIds, searchTicket]) }, [status, searchParam, searchParamContent, showAll, selectedQueueIds, searchTicket])
const { tickets, hasMore, loading } = useTickets({ let { tickets, hasMore, loading, remoteTicketsControll } = useTickets({
pageNumber, pageNumber,
searchParam, searchParam,
searchParamContent, searchParamContent,
@ -203,6 +212,11 @@ const TicketsList = (props) => {
unlimited: status === 'open' ? "all" : "false" unlimited: status === 'open' ? "all" : "false"
}) })
useEffect(() => {
setRemoteTicketsControll(remoteTicketsControll)
}, [remoteTicketsControll])
useEffect(() => { useEffect(() => {
if (!status && !searchParam) return if (!status && !searchParam) return
@ -301,6 +315,27 @@ const TicketsList = (props) => {
} }
}) })
socket.on('remoteTickesControll', (data) => {
console.log('REMOTE TICKETS CONTROLL UPDATE 1: ', data.tickets)
if (data.action === 'update') {
setRemoteTicketsControll(data.tickets)
}
})
socket.on('settings', (data) => {
if (data.action === 'update') {
setSettings((prevState) => {
const aux = [...prevState]
const settingIndex = aux.findIndex((s) => s.key === data.setting.key)
aux[settingIndex].value = data.setting.value
return aux
})
}
})
return () => { return () => {
socket.disconnect() socket.disconnect()
} }
@ -354,7 +389,7 @@ const TicketsList = (props) => {
) : ( ) : (
<> <>
{ticketsList.map(ticket => ( {ticketsList.map(ticket => (
<TicketListItem ticket={ticket} key={ticket.id} /> <TicketListItem ticket={ticket} key={ticket.id} remoteTicketsControll={_remoteTicketsControll} settings={settings} />
))} ))}
</> </>
)} )}

View File

@ -0,0 +1,17 @@
import React, { useState, createContext } from "react"
const countTicketMsgContext = createContext()
const CountTicketMsgProvider = ({ children }) => {
const [countTicketMsg, setCountTicketMsg] = useState(0)
return (
<countTicketMsgContext.Provider value={{ countTicketMsg, setCountTicketMsg }}>
{children}
</countTicketMsgContext.Provider>
)
}
export { countTicketMsgContext, CountTicketMsgProvider }

View File

@ -1,7 +1,7 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react"
import toastError from "../../errors/toastError"; import toastError from "../../errors/toastError"
import api from "../../services/api"; import api from "../../services/api"
const useTickets = ({ const useTickets = ({
searchParam, searchParam,
@ -15,16 +15,16 @@ const useTickets = ({
unlimited, unlimited,
tab tab
}) => { }) => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true)
const [hasMore, setHasMore] = useState(false); const [hasMore, setHasMore] = useState(false)
const [tickets, setTickets] = useState([]); const [tickets, setTickets] = useState([])
const [remoteTicketsControll, setRemoteTicketsControll] = useState([])
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true)
const delayDebounceFn = setTimeout(() => { const delayDebounceFn = setTimeout(() => {
const fetchTickets = async () => { const fetchTickets = async () => {
try { try {
@ -45,24 +45,26 @@ const useTickets = ({
withUnreadMessages, withUnreadMessages,
unlimited unlimited
}, },
}); })
setTickets(data.tickets)
setHasMore(data.hasMore)
setLoading(false)
if (data?.remoteTicketsControll) {
setRemoteTicketsControll(data.remoteTicketsControll.map(t => +t))
}
setTickets(data.tickets);
setHasMore(data.hasMore);
setLoading(false);
} catch (err) { } catch (err) {
setLoading(false); setLoading(false)
toastError(err); toastError(err)
} }
}; }
fetchTickets(); fetchTickets()
}, 500); }, 500)
return () => clearTimeout(delayDebounceFn); return () => clearTimeout(delayDebounceFn)
}, [ }, [
searchParam, searchParam,
searchParamContent, searchParamContent,
@ -74,9 +76,9 @@ const useTickets = ({
withUnreadMessages, withUnreadMessages,
tab, tab,
unlimited unlimited
]); ])
return { tickets, loading, hasMore }; return { tickets, loading, hasMore, remoteTicketsControll }
}; }
export default useTickets; export default useTickets

View File

@ -11,7 +11,7 @@ import { AuthContext } from "../../context/Auth/AuthContext"
import { Can } from "../../components/Can" import { Can } from "../../components/Can"
import FormControlLabel from "@mui/material/FormControlLabel" import FormControlLabel from "@mui/material/FormControlLabel"
import Checkbox from '@mui/material/Checkbox' import Checkbox from '@mui/material/Checkbox'
import { Button } from "@material-ui/core" import { Button, Tooltip } from "@material-ui/core"
import ReportModal from "../../components/ReportModal" import ReportModal from "../../components/ReportModal"
import ReportModalType from "../../components/ReportModalType" import ReportModalType from "../../components/ReportModalType"
import MaterialTable from 'material-table' import MaterialTable from 'material-table'
@ -299,6 +299,7 @@ const Report = () => {
const [csvFile, setCsvFile] = useState() const [csvFile, setCsvFile] = useState()
const [selectedValue, setSelectedValue] = useState('created') const [selectedValue, setSelectedValue] = useState('created')
const [checked, setChecked] = useState(true) const [checked, setChecked] = useState(true)
const [checkedRemote, setCheckedRemote] = useState(false)
const [queues, setQueues] = useState([]) const [queues, setQueues] = useState([])
const [queueId, setQueue] = useState(null) const [queueId, setQueue] = useState(null)
@ -378,7 +379,7 @@ const Report = () => {
messagesToFilter: ticket.messages.map(message => message.body).join(' '), messagesToFilter: ticket.messages.map(message => message.body).join(' '),
})) }))
dispatchQ({ type: "LOAD_QUERY", payload: tickets }) dispatchQ({ type: "LOAD_QUERY", payload: tickets })
console.log(tickets) // console.log(tickets)
setHasMore(data.hasMore) setHasMore(data.hasMore)
setTotalCountTickets(data.count) setTotalCountTickets(data.count)
setLoading(false) setLoading(false)
@ -395,15 +396,13 @@ const Report = () => {
} }
else if (reportOption === '3') { else if (reportOption === '3') {
const dataQuery = await api.get("/reports/services/numbers", { params: { startDate, endDate }, }) const dataQuery = await api.get("/reports/services/numbers", { params: { startDate, endDate, isRemote: checkedRemote }, })
dispatchQ({ type: "RESET" }) dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery?.data?.reportService }) dispatchQ({ type: "LOAD_QUERY", payload: dataQuery?.data?.reportService })
} }
else if (reportOption === '4') { else if (reportOption === '4') {
const dataQuery = await api.get("/reports/services/queues", { params: { startDate, endDate }, }) const dataQuery = await api.get("/reports/services/queues", { params: { startDate, endDate, isRemote: checkedRemote }, })
console.log(' dataQuery?.data?.reportService: ', dataQuery?.data?.reportService)
dispatchQ({ type: "RESET" }) dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery?.data?.reportService }) dispatchQ({ type: "LOAD_QUERY", payload: dataQuery?.data?.reportService })
@ -419,7 +418,7 @@ const Report = () => {
}, 500) }, 500)
return () => clearTimeout(delayDebounceFn) return () => clearTimeout(delayDebounceFn)
}, [userId, queueId, checked, startDate, endDate, reportOption, pageNumberTickets, totalCountTickets, selectedValue]) }, [userId, queueId, checked, checkedRemote, startDate, endDate, reportOption, pageNumberTickets, totalCountTickets, selectedValue])
const handleCheckBoxChange = (value) => { const handleCheckBoxChange = (value) => {
@ -737,6 +736,10 @@ const Report = () => {
setChecked(event.target.checked) setChecked(event.target.checked)
} }
const handleChangeRemote = (event) => {
setCheckedRemote(event.target.checked)
}
return ( return (
<Can <Can
@ -782,6 +785,35 @@ const Report = () => {
</label> </label>
</div> </div>
} }
{(reportOption === '3' || reportOption === '4') &&
<div>
<Tooltip
arrow
placement="top"
title="Todos os tickets incluindo os criados remotamente"
><label>
normal
</label>
</Tooltip>
<Switch
checked={checkedRemote}
onChange={handleChangeRemote}
inputProps={{ 'aria-label': 'controlled' }}
/>
<Tooltip
arrow
placement="top"
title="Apenas tickets criados remotamente"
><label>
remoto
</label>
</Tooltip>
</div>
}
@ -959,7 +991,7 @@ const Report = () => {
title={i18n.t("reports.listTitles.title4_1")} title={i18n.t("reports.listTitles.title4_1")}
columns={ columns={
[ !checkedRemote ? [
{ title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, }, { title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, },
{ title: 'Conversas iniciadas', field: 'startedByAgent', }, { title: 'Conversas iniciadas', field: 'startedByAgent', },
{ title: 'Conversas recebidas', field: 'startedByClient' }, { title: 'Conversas recebidas', field: 'startedByClient' },
@ -967,6 +999,14 @@ const Report = () => {
{ title: `Tempo médio de espera`, field: 'avgChatWaitingTime' }, { title: `Tempo médio de espera`, field: 'avgChatWaitingTime' },
{ title: 'Aguardando', field: 'pendingChat' } { title: 'Aguardando', field: 'pendingChat' }
] :
[
{ title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, },
{ title: 'Conversas iniciadas', field: 'startedByAgent', },
{ title: 'Conversas respondidas', field: 'startedByClient' },
{ title: `Conversas finalizadas`, field: 'closedChat' },
{ title: 'Aguardando', field: 'pendingChat' }
] ]
} }
data={dataRows} data={dataRows}
@ -1003,7 +1043,7 @@ const Report = () => {
title={i18n.t("reports.listTitles.title5_1")} title={i18n.t("reports.listTitles.title5_1")}
columns={ columns={
[ !checkedRemote ? [
{ title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, }, { title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, },
{ {
@ -1023,6 +1063,27 @@ const Report = () => {
{ title: `Tempo médio de espera`, field: 'avgChatWaitingTime' }, { title: `Tempo médio de espera`, field: 'avgChatWaitingTime' },
{ title: 'Aguardando', field: 'pendingChat' } { title: 'Aguardando', field: 'pendingChat' }
] :
[
{ title: 'Unidade', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, },
{
title: 'Fila', field: 'queueName',
cellStyle: (evt, rowData) => {
return {
whiteSpace: 'nowrap',
backgroundColor: rowData?.queueColor || 'inherit',
color: 'white'
}
}
},
{ title: 'Conversas iniciadas', field: 'startedByAgent', },
{ title: 'Conversas respondidas', field: 'startedByClient' },
{ title: `Conversas finalizadas`, field: 'closedChat' },
{ title: 'Aguardando', field: 'pendingChat' }
] ]
} }
data={dataRows} data={dataRows}

View File

@ -12,13 +12,38 @@ import api from '../../services/api'
import { i18n } from '../../translate/i18n.js' import { i18n } from '../../translate/i18n.js'
import toastError from '../../errors/toastError' import toastError from '../../errors/toastError'
import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
//-------- //--------
import { AuthContext } from '../../context/Auth/AuthContext' import { AuthContext } from '../../context/Auth/AuthContext'
import { Can } from '../../components/Can' import { Can } from '../../components/Can'
import { boolean } from 'yup'
// import Button from "@material-ui/core/Button"; // import Button from "@material-ui/core/Button";
const IntegerInput = ({ value, onChange }) => {
const handleChange = (event) => {
const inputValue = event.target.value
// Only allow digits 0-9
if (/^\d{0,3}$/.test(inputValue)) {
onChange(inputValue)
}
}
return (
<TextField
type="text"
variant="outlined"
value={value}
onChange={handleChange}
style={{ marginRight: '10px' }}
/>
)
}
const useStyles = makeStyles((theme) => ({ const useStyles = makeStyles((theme) => ({
root: { root: {
display: 'flex', display: 'flex',
@ -48,11 +73,48 @@ const Settings = () => {
const [settings, setSettings] = useState([]) const [settings, setSettings] = useState([])
const [number1, setNumber1] = useState('')
const [number2, setNumber2] = useState('')
const handleNumber1Change = (value) => {
setNumber1(value)
}
const handleNumber2Change = (value) => {
setNumber2(value)
}
const handleGetValues = () => {
let e = {
target: {
value: 'enabled', name: 'remoteTicketSendControll', obj: (number1.trim().length > 0 && number2.trim().length > 0) ? { seconds1: number1, seconds2: number2 } : null
}
}
handleChangeSetting(e)
}
useEffect(() => { useEffect(() => {
const fetchSession = async () => { const fetchSession = async () => {
try { try {
const { data } = await api.get('/settings') const { data } = await api.get('/settings')
console.log('data.settings: ', data.settings)
setSettings(data.settings) setSettings(data.settings)
if (data?.settings) {
let { obj } = data.settings.find((s) => s.key === 'remoteTicketSendControll')
if (!obj) return
obj = JSON.parse(obj)
console.log('SETTING obj: ', obj)
setNumber1(obj.seconds1)
setNumber2(obj.seconds2)
}
} catch (err) { } catch (err) {
toastError(err) toastError(err)
} }
@ -60,6 +122,7 @@ const Settings = () => {
fetchSession() fetchSession()
}, []) }, [])
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL) const socket = openSocket(process.env.REACT_APP_BACKEND_URL)
@ -81,9 +144,6 @@ const Settings = () => {
} }
}, []) }, [])
// useEffect(() => {
// console.log('------> settings: ', settings)
// }, [settings])
const handleChangeSetting = async (e) => { const handleChangeSetting = async (e) => {
const selectedValue = e.target.value const selectedValue = e.target.value
@ -92,6 +152,7 @@ const Settings = () => {
try { try {
await api.put(`/settings/${settingKey}`, { await api.put(`/settings/${settingKey}`, {
value: selectedValue, value: selectedValue,
// obj: e.target?.obj ? e.target.obj : null
}) })
if (settingKey === 'farewellMessageByQueue' && if (settingKey === 'farewellMessageByQueue' &&
@ -117,12 +178,20 @@ const Settings = () => {
} }
} }
const getSettingValue = (key) => { const getSettingValue = (key, _obj = false) => {
const { value } = settings.find((s) => s.key === key) const { value, obj } = settings.find((s) => s.key === key)
if (_obj)
return obj
return value return value
} }
const isSaveDisabled = (settings &&
settings.length > 0 &&
getSettingValue('remoteTicketSendControll') === 'disabled')
return ( return (
<Can <Can
role={user.profile} role={user.profile}
@ -446,10 +515,57 @@ const Settings = () => {
</Container> </Container>
</div> </div>
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Paper className={classes.paper}>
<Typography variant="body1">
Controle de envio de mensagem de ticket remoto por numero
</Typography>
<Select
margin="dense"
variant="outlined"
native
id="remoteTicketSendControll-setting"
name="remoteTicketSendControll"
value={
settings &&
settings.length > 0 &&
getSettingValue('remoteTicketSendControll')
}
className={classes.settingOption}
onChange={handleChangeSetting}
>
<option value="enabled">Ativado</option>
<option value="disabled">Desativado</option>
</Select>
</Paper>
{/* <Paper>
<div style={{ padding: '10px', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<h3>Tempo aleatorio em segundos</h3>
<div style={{ marginBottom: '20px', display: 'flex' }}>
<IntegerInput title="Number 1" value={number1} onChange={handleNumber1Change} />
<IntegerInput title="Number 2" value={number2} onChange={handleNumber2Change} />
<Button variant="contained" color="primary" onClick={handleGetValues} disabled={
(isSaveDisabled) ? true : false
}>
Save
</Button>
</div>
</div>
</Paper> */}
</Container>
</div>
</div> </div>
)} )}
/> />
) )
} }
export default Settings export default Settings