Alteração finalizada para que um mesmo numero de cliente seja atendido por multiplos numeros na interface omnihit

adriano 2023-06-24 05:16:04 -03:00
parent 1b79ce1a55
commit 34a0f72ac6
8 changed files with 78 additions and 59 deletions

View File

@ -22,6 +22,7 @@ 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";
@ -41,6 +42,7 @@ interface TicketData {
status: string; status: string;
queueId: number; queueId: number;
userId: number; userId: number;
whatsappId?: string | number
msg?: string, msg?: string,
} }
@ -53,6 +55,11 @@ import CountTicketService from "../services/TicketServices/CountTicketService";
import CountTicketsByUserQueue from "../services/UserServices/CountTicketsByUserQueue"; import CountTicketsByUserQueue from "../services/UserServices/CountTicketsByUserQueue";
import ShowUserService from "../services/UserServices/ShowUserService"; import ShowUserService from "../services/UserServices/ShowUserService";
import axios from "axios"; import axios from "axios";
import User from "../models/User";
import CheckContactOpenTickets from "../helpers/CheckContactOpenTickets";
import QueuesByUser from "../services/UserServices/ShowQueuesByUser";
import GetDefaultWhatsApp from "../helpers/GetDefaultWhatsApp";
import whatsappQueueMatchingUserQueue from "../helpers/whatsappQueueMatchingUserQueue";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
@ -100,7 +107,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } }); let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } });
if (ticket) { if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open', userId: userId,}, ticketId: ticket.id, msg }); await UpdateTicketService({ ticketData: { status: 'open', userId: userId, }, ticketId: ticket.id, msg });
} }
else { else {
@ -128,8 +135,8 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
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" });
@ -140,7 +147,7 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
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> => {
@ -151,7 +158,7 @@ export const count = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json(ticketCount); return res.status(200).json(ticketCount);
}; };
export const update = async (req: Request, res: Response): Promise<Response> => { export const update = async (req: Request, res: Response): Promise<Response> => {
@ -176,10 +183,6 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
}); });
///////////////////////////////
//
if (scheduleData.farewellMessage) { if (scheduleData.farewellMessage) {
const whatsapp = await ShowWhatsAppService(ticket.whatsappId); const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
@ -218,13 +221,23 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
} }
else { else {
const ticketData: TicketData = req.body; let ticketData: TicketData = req.body;
//ticketData: { status: 'open', userId: 4 } , ticketId const defaultWhatsapp: any = await GetDefaultWhatsApp(ticketData.userId);
const _ticket: any = await Ticket.findByPk(ticketId)
if (defaultWhatsapp && ticketData.status != 'open') {
await CheckContactOpenTickets(_ticket.dataValues.contactId, defaultWhatsapp.dataValues.id)
}
ticketData.whatsappId = defaultWhatsapp.dataValues.id
const { ticket } = await UpdateTicketService({ const { ticket } = await UpdateTicketService({
ticketData, ticketData,
ticketId ticketId,
}); });
if (ticketData.userId) { if (ticketData.userId) {

View File

@ -5,27 +5,22 @@ import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber
const CheckContactOpenTickets = async (contactId: number | string, whatsappId: number | string): Promise<void> => { const CheckContactOpenTickets = async (contactId: number | string, whatsappId: number | string): Promise<void> => {
let whats = await ListWhatsAppsNumber(whatsappId)
// let whats = await ListWhatsAppsNumber(whatsappId)
// console.log('----> whats: ', whats)
const ticket = await Ticket.findOne({ const ticket = await Ticket.findOne({
// where: { contactId, whatsappId, status: { [Op.or]: ["open", "pending"] } }
where: { where: {
[Op.and]: [ [Op.and]: [
{ contactId: contactId }, { contactId: contactId },
{ whatsappId: whatsappId }, { whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) }, },
{ status: { [Op.or]: ["open", "pending"] } }, { status: { [Op.or]: ["open", "pending"] } },
] ]
} }
}); });
console.log('>>>>>>>>>>>>>> ticket: ', (JSON.parse(JSON.stringify(ticket))))
if (ticket) { if (ticket) {
throw new AppError("ERR_OTHER_OPEN_TICKET"); throw new AppError("ERR_OTHER_OPEN_TICKET");
} }
}; };

View File

@ -42,20 +42,13 @@ const CreateTicketService = async ({
console.log('Create contact service........') console.log('Create contact service........')
const defaultWhatsapp = await GetDefaultWhatsApp(userId); const defaultWhatsapp = await GetDefaultWhatsApp(userId);
// console.log('defaultWhatsapp: ',defaultWhatsapp) const user = await User.findByPk(userId, { raw: true, })
// console.log('JSON.parse(JSON.stringify(defaultWhatsapp)): ',JSON.parse(JSON.stringify(defaultWhatsapp)))
const matchingQueue = await whatsappQueueMatchingUserQueue(userId, defaultWhatsapp, user?.profile);
const queueId = matchingQueue ? matchingQueue.queueId : undefined
const user = await User.findByPk(userId, { raw: true, })
console.log('user.profile: ', user?.profile)
const matchingQueue = await whatsappQueueMatchingUserQueue(userId, defaultWhatsapp, user?.profile);
console.log('matchingQueue: ', matchingQueue)
const queueId = matchingQueue ? matchingQueue.queueId : undefined
console.log('contactId, defaultWhatsapp.id: ',contactId, defaultWhatsapp.id)
await CheckContactOpenTickets(contactId, defaultWhatsapp.id); await CheckContactOpenTickets(contactId, defaultWhatsapp.id);

View File

@ -6,6 +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 (
@ -15,14 +16,17 @@ const FindOrCreateTicketService = async (
groupContact?: Contact groupContact?: Contact
): Promise<Ticket> => { ): Promise<Ticket> => {
try {
let whats = await ListWhatsAppsNumber(whatsappId)
try {
let ticket = await Ticket.findOne({ let ticket = await Ticket.findOne({
where: { where: {
status: { status: {
[Op.or]: ["open", "pending", "queueChoice"] [Op.or]: ["open", "pending", "queueChoice"]
}, },
contactId: groupContact ? groupContact.id : contact.id, contactId: groupContact ? groupContact.id : contact.id,
whatsappId: whatsappId whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) },
} }
}); });

View File

@ -9,6 +9,7 @@ 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";
import { number } from "yup";
var flatten = require('flat') var flatten = require('flat')
@ -17,12 +18,13 @@ interface TicketData {
status?: string; status?: string;
userId?: number; userId?: number;
queueId?: number; queueId?: number;
statusChatEnd?: string; statusChatEnd?: string;
whatsappId?: string | number;
} }
interface Request { interface Request {
ticketData: TicketData; ticketData: TicketData;
ticketId: string | number; ticketId: string | number;
msg?: string msg?: string
} }
@ -34,16 +36,15 @@ interface Response {
const UpdateTicketService = async ({ const UpdateTicketService = async ({
ticketData, ticketData,
ticketId, ticketId,
msg='' msg = ''
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
try { try {
const { status, userId, queueId, statusChatEnd } = ticketData; const { status, userId, queueId, statusChatEnd, whatsappId } = ticketData;
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
// await SetTicketMessagesAsRead(ticket);
const oldStatus = ticket.status; const oldStatus = ticket.status;
const oldUserId = ticket.user?.id; const oldUserId = ticket.user?.id;
@ -56,10 +57,11 @@ const UpdateTicketService = async ({
status, status,
queueId, queueId,
userId, userId,
statusChatEnd statusChatEnd,
whatsappId
}); });
await ticket.reload(); await ticket.reload();
if (msg.length > 0) { if (msg.length > 0) {
sendWhatsAppMessageSocket(ticket, msg) sendWhatsAppMessageSocket(ticket, msg)

View File

@ -7,27 +7,34 @@ 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 = [] let queueByUsersInfo: any = []
if (userId) { if (userId && profile) {
// CONSULTANDO FILAS PELO ID DO USUARIO // CONSULTANDO FILAS PELO ID DO 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.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 });
} }
return queueByUsersInfo; return queueByUsersInfo;

View File

@ -68,14 +68,20 @@ const SendWhatsAppMessage = async ({
console.log('ticket.whatsappIdticket.whatsappIdticket.whatsappIdticket: ', ticket.whatsappId) console.log('ticket.whatsappIdticket.whatsappIdticket.whatsappIdticket: ', ticket.whatsappId)
if (!ticket.whatsappId) {
const defaultWhatsapp: any = await GetDefaultWhatsApp(ticket.userId);
await ticket.update({ whatsappId: +defaultWhatsapp.id });
}
if (!listWhatsapp) { if (!listWhatsapp) {
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED') listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
} }
if (listWhatsapp.whatsapp && listWhatsapp.whatsapp.status != 'CONNECTED' && listWhatsapp.whatsapps.length > 0) { if (listWhatsapp.whatsapp && listWhatsapp.whatsapp.status != 'CONNECTED' && listWhatsapp.whatsapps.length > 0) {
// console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkk: ', listWhatsapp.whatsapps[0].id)
await ticket.update({ whatsappId: + listWhatsapp.whatsapps[0].id }); await ticket.update({ whatsappId: + listWhatsapp.whatsapps[0].id });
let _ticket = await Ticket.findByPk(listWhatsapp.whatsapps[0].id) let _ticket = await Ticket.findByPk(listWhatsapp.whatsapps[0].id)

View File

@ -504,7 +504,7 @@ const handleMessage = async (
const chat = wbot.chat const chat = wbot.chat
// if(chat.isGroup){ // if(chat.isGroup){
// console.log('This message is from a Group and will be ignored!') // console.log('This message is from a Group and will be ignored!')
// return // return
// } // }
@ -521,11 +521,9 @@ const handleMessage = async (
// } // }
// groupContact = await verifyContact(msgGroupContact); // groupContact = await verifyContact(msgGroupContact);
// } // }
const whatsapp = await ShowWhatsAppService(wbot.id!);
const whatsapp = await ShowWhatsAppService(wbot.id!);
// const whatsapp = await ShowWhatsAppService(46); // const whatsapp = await ShowWhatsAppService(46);
@ -894,9 +892,10 @@ const handleMessage = async (
// } // }
// //
} catch (err) { } catch (err: any) {
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`); logger.error(`Error handling whatsapp message: Err: ${err}`);
console.log('xxxxxxxxxxxxxxxxxx error: ', err)
} }
}; };