modulo canpanha em desenvolvimento
parent
417f947263
commit
4ee65ad300
|
@ -8,24 +8,22 @@ import ShowTicketService from "../services/TicketServices/ShowTicketService";
|
|||
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
|
||||
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
|
||||
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 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 format from 'date-fns/format';
|
||||
import format from "date-fns/format";
|
||||
|
||||
import ListTicketsServiceCache from "../services/TicketServices/ListTicketServiceCache";
|
||||
|
||||
import { searchTicketCache, loadTicketsCache, } from '../helpers/TicketCache'
|
||||
import { searchTicketCache, loadTicketsCache } from "../helpers/TicketCache";
|
||||
import { Op } from "sequelize";
|
||||
|
||||
|
||||
|
||||
type IndexQuery = {
|
||||
searchParam: string;
|
||||
pageNumber: string;
|
||||
|
@ -35,7 +33,7 @@ type IndexQuery = {
|
|||
withUnreadMessages: string;
|
||||
queueIds: string;
|
||||
unlimited?: string;
|
||||
searchParamContent?: string
|
||||
searchParamContent?: string;
|
||||
};
|
||||
|
||||
interface TicketData {
|
||||
|
@ -43,13 +41,12 @@ interface TicketData {
|
|||
status: string;
|
||||
queueId: number;
|
||||
userId: number;
|
||||
whatsappId?: string | number
|
||||
msg?: string,
|
||||
transfer?: boolean | undefined,
|
||||
fromMe?: boolean
|
||||
whatsappId?: string | number;
|
||||
msg?: string;
|
||||
transfer?: boolean | undefined;
|
||||
fromMe?: boolean;
|
||||
}
|
||||
|
||||
|
||||
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
|
||||
import Ticket from "../models/Ticket";
|
||||
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
|
||||
|
@ -60,7 +57,6 @@ import ShowUserService from "../services/UserServices/ShowUserService";
|
|||
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 { getWbot } from "../libs/wbot";
|
||||
import endPointQuery from "../helpers/old_EndPointQuery";
|
||||
|
@ -69,7 +65,6 @@ import BotIsOnQueue from "../helpers/BotIsOnQueue";
|
|||
import { setMessageAsRead } from "../helpers/SetMessageAsRead";
|
||||
|
||||
export const index = async (req: Request, res: Response): Promise<Response> => {
|
||||
|
||||
const {
|
||||
pageNumber,
|
||||
status,
|
||||
|
@ -82,7 +77,6 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
|
|||
searchParamContent
|
||||
} = req.query as IndexQuery;
|
||||
|
||||
|
||||
const userId = req.user.id;
|
||||
|
||||
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> => {
|
||||
const { contactId, status, userId, msg, queueId }: TicketData = req.body;
|
||||
|
||||
const botInfo = await BotIsOnQueue('botqueue')
|
||||
// const botInfo = await BotIsOnQueue("botqueue");
|
||||
|
||||
let ticket = await Ticket.findOne({
|
||||
where: {
|
||||
[Op.or]: [
|
||||
{ contactId, status: 'queueChoice' },
|
||||
{ contactId, status: 'open', userId: botInfo.userIdBot }
|
||||
{ contactId, status: "queueChoice" }
|
||||
// { contactId, status: "open", userId: botInfo.userIdBot }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
if (ticket) {
|
||||
await UpdateTicketService({ ticketData: { status: 'open', userId: userId, queueId }, ticketId: ticket.id });
|
||||
|
||||
}
|
||||
else {
|
||||
await UpdateTicketService({
|
||||
ticketData: { status: "open", userId: userId, queueId },
|
||||
ticketId: ticket.id
|
||||
});
|
||||
} else {
|
||||
ticket = await CreateTicketService({ contactId, status, userId, queueId });
|
||||
}
|
||||
|
||||
|
@ -134,8 +129,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
|
|||
action: "update",
|
||||
ticket
|
||||
});
|
||||
//
|
||||
|
||||
//
|
||||
|
||||
// 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);
|
||||
};
|
||||
|
||||
|
||||
export const show = async (req: Request, res: Response): Promise<Response> => {
|
||||
const { ticketId } = req.params;
|
||||
|
||||
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 });
|
||||
};
|
||||
|
||||
export const count = async (req: Request, res: Response): Promise<Response> => {
|
||||
|
||||
// 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);
|
||||
|
||||
return res.status(200).json(ticketCount);
|
||||
};
|
||||
|
||||
|
||||
export const update = async (req: Request, res: Response): Promise<Response> => {
|
||||
|
||||
console.log('ENTROU NO UPDATE TICKET CONTROLLER')
|
||||
export const update = async (
|
||||
req: Request,
|
||||
res: Response
|
||||
): Promise<Response> => {
|
||||
console.log("ENTROU NO UPDATE TICKET CONTROLLER");
|
||||
|
||||
const { ticketId } = req.params;
|
||||
|
||||
const userOldInfo = await Ticket.findByPk(ticketId)
|
||||
const userOldInfo = await Ticket.findByPk(ticketId);
|
||||
|
||||
let ticket2 = {}
|
||||
|
||||
if (req.body['status'] === "closed") {
|
||||
let ticket2 = {};
|
||||
|
||||
if (req.body["status"] === "closed") {
|
||||
const { status, userId, schedulingNotifyData } = req.body;
|
||||
|
||||
// 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({
|
||||
ticketData: { 'status': status, 'userId': userId, 'statusChatEnd': statusChatEndName.name },
|
||||
ticketData: {
|
||||
status: status,
|
||||
userId: userId,
|
||||
statusChatEnd: statusChatEndName.name
|
||||
},
|
||||
ticketId
|
||||
});
|
||||
|
||||
|
||||
if (scheduleData.farewellMessage) {
|
||||
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
|
||||
|
||||
|
@ -210,37 +211,33 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
// lembrete // agendamento
|
||||
if (scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3') {
|
||||
|
||||
|
||||
if (isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)) {
|
||||
console.log('*** É AGENDAMENTO!')
|
||||
}
|
||||
else {
|
||||
console.log('*** É LEMBRETE!')
|
||||
if (
|
||||
scheduleData.statusChatEndId === "2" ||
|
||||
scheduleData.statusChatEndId === "3"
|
||||
) {
|
||||
if (
|
||||
isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)
|
||||
) {
|
||||
console.log("*** É AGENDAMENTO!");
|
||||
} else {
|
||||
console.log("*** É LEMBRETE!");
|
||||
}
|
||||
|
||||
const schedulingNotifyCreate = await CreateSchedulingNotifyService(
|
||||
{
|
||||
ticketId: scheduleData.ticketId,
|
||||
statusChatEndId: scheduleData.statusChatEndId,
|
||||
schedulingDate: scheduleData.schedulingDate,
|
||||
schedulingTime: scheduleData.schedulingTime,
|
||||
message: scheduleData.message
|
||||
}
|
||||
)
|
||||
const schedulingNotifyCreate = await CreateSchedulingNotifyService({
|
||||
ticketId: scheduleData.ticketId,
|
||||
statusChatEndId: scheduleData.statusChatEndId,
|
||||
schedulingDate: scheduleData.schedulingDate,
|
||||
schedulingTime: scheduleData.schedulingTime,
|
||||
message: scheduleData.message
|
||||
});
|
||||
}
|
||||
|
||||
ticket2 = ticket
|
||||
|
||||
}
|
||||
else {
|
||||
|
||||
ticket2 = ticket;
|
||||
} else {
|
||||
// Para aparecer pendente para todos usuarios que estao na fila
|
||||
if (req.body.transfer) {
|
||||
req.body.userId = null
|
||||
req.body.userId = null;
|
||||
}
|
||||
|
||||
let ticketData: TicketData = req.body;
|
||||
|
@ -250,75 +247,75 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
|
|||
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
ticketData.whatsappId = defaultWhatsapp.dataValues.id;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
"--------> ticketData.status: ",
|
||||
ticketData.status,
|
||||
" | ticketData.fromMe: ",
|
||||
ticketData.fromMe
|
||||
);
|
||||
|
||||
const { ticket } = await UpdateTicketService({
|
||||
ticketData,
|
||||
ticketId,
|
||||
ticketId
|
||||
});
|
||||
|
||||
|
||||
if (ticketData.status == 'open' && !ticketData.fromMe) {
|
||||
|
||||
if (ticketData.status == "open" && !ticketData.fromMe) {
|
||||
await setMessageAsRead(ticket);
|
||||
|
||||
}
|
||||
|
||||
console.log('ticket.unreadMessages: ', ticket.unreadMessages)
|
||||
console.log("ticket.unreadMessages: ", ticket.unreadMessages);
|
||||
|
||||
if (ticketData.userId) {
|
||||
|
||||
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
|
||||
TicketEmiterSumOpenClosedByUser(ticketData.userId.toString(), dateToday.fullDate, dateToday.fullDate)
|
||||
|
||||
const dateToday = splitDateTime(
|
||||
new Date(format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: ptBR }))
|
||||
);
|
||||
TicketEmiterSumOpenClosedByUser(
|
||||
ticketData.userId.toString(),
|
||||
dateToday.fullDate,
|
||||
dateToday.fullDate
|
||||
);
|
||||
}
|
||||
|
||||
ticket2 = ticket
|
||||
|
||||
ticket2 = ticket;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
if (userOldInfo) {
|
||||
|
||||
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 }))
|
||||
);
|
||||
|
||||
if (userOldInfo.userId) {
|
||||
|
||||
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate)
|
||||
|
||||
TicketEmiterSumOpenClosedByUser(
|
||||
userOldInfo.userId.toString(),
|
||||
dateToday.fullDate,
|
||||
dateToday.fullDate
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
return res.status(200).json(ticket2);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// export const update = async (
|
||||
// req: Request,
|
||||
// res: Response
|
||||
|
@ -341,7 +338,6 @@ export const update = async (req: Request, res: Response): Promise<Response> =>
|
|||
// }
|
||||
// }
|
||||
|
||||
|
||||
// return res.status(200).json(ticket);
|
||||
// };
|
||||
|
||||
|
@ -354,13 +350,10 @@ export const remove = async (
|
|||
const ticket = await DeleteTicketService(ticketId);
|
||||
|
||||
const io = getIO();
|
||||
io.to(ticket.status)
|
||||
.to(ticketId)
|
||||
.to("notification")
|
||||
.emit("ticket", {
|
||||
action: "delete",
|
||||
ticketId: +ticketId
|
||||
});
|
||||
io.to(ticket.status).to(ticketId).to("notification").emit("ticket", {
|
||||
action: "delete",
|
||||
ticketId: +ticketId
|
||||
});
|
||||
|
||||
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` });
|
||||
// }
|
||||
|
||||
|
|
|
@ -1,11 +1,31 @@
|
|||
import { Op } from "sequelize";
|
||||
import AppError from "../errors/AppError";
|
||||
import Ticket from "../models/Ticket";
|
||||
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
|
||||
|
||||
const CheckContactOpenTickets = async (contactId: number): Promise<void> => {
|
||||
const ticket = await Ticket.findOne({
|
||||
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
|
||||
});
|
||||
const CheckContactOpenTickets = async (
|
||||
contactId: number,
|
||||
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) {
|
||||
throw new AppError("ERR_OTHER_OPEN_TICKET");
|
||||
|
|
|
@ -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;
|
|
@ -4,42 +4,50 @@ import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
|
|||
import Ticket from "../../models/Ticket";
|
||||
import ShowContactService from "../ContactServices/ShowContactService";
|
||||
|
||||
|
||||
import { getIO } from "../../libs/socket";
|
||||
import ShowUserServiceReport from "../UserServices/ShowUserServiceReport";
|
||||
|
||||
import format from 'date-fns/format';
|
||||
import ptBR from 'date-fns/locale/pt-BR';
|
||||
import format from "date-fns/format";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
import { splitDateTime } from "../../helpers/SplitDateTime";
|
||||
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";
|
||||
|
||||
import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
|
||||
let flatten = require('flat')
|
||||
|
||||
|
||||
import { createOrUpdateTicketCache } from "../../helpers/TicketCache";
|
||||
import User from "../../models/User";
|
||||
import whatsappQueueMatchingUserQueue from "../../helpers/whatsappQueueMatchingUserQueue";
|
||||
let flatten = require("flat");
|
||||
|
||||
interface Request {
|
||||
contactId: number;
|
||||
status: string;
|
||||
userId: number;
|
||||
userId: number;
|
||||
queueId?: number | undefined;
|
||||
}
|
||||
|
||||
const CreateTicketService = async ({
|
||||
contactId,
|
||||
status,
|
||||
userId,
|
||||
userId,
|
||||
queueId = undefined
|
||||
}: Request): Promise<Ticket> => {
|
||||
|
||||
|
||||
console.log('========> queueId: ', queueId)
|
||||
console.log("========> queueId: ", queueId);
|
||||
|
||||
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);
|
||||
|
||||
|
@ -59,27 +67,32 @@ const CreateTicketService = async ({
|
|||
|
||||
// console.log('CONTACT ticket.id: ', ticket.id)
|
||||
|
||||
|
||||
// TEST DEL
|
||||
// TEST DEL
|
||||
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
|
||||
delete ticket_obj['contact']['extraInfo']
|
||||
delete ticket_obj["contact"]["extraInfo"];
|
||||
|
||||
ticket_obj = flatten(ticket_obj)
|
||||
|
||||
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
|
||||
ticket_obj = flatten(ticket_obj);
|
||||
|
||||
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
|
||||
} catch (error) {
|
||||
console.log('There was an error on UpdateTicketService.ts on createTicketCache 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(), dateToday.fullDate, dateToday.fullDate)
|
||||
TicketEmiterSumOpenClosedByUser(
|
||||
userId.toString(),
|
||||
dateToday.fullDate,
|
||||
dateToday.fullDate
|
||||
);
|
||||
|
||||
const io = getIO();
|
||||
io.emit("ticketStatus", {
|
||||
|
@ -87,14 +100,11 @@ const CreateTicketService = async ({
|
|||
ticketStatus: { ticketId: ticket.id, status: ticket.status }
|
||||
});
|
||||
|
||||
|
||||
return ticket;
|
||||
|
||||
} 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);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
export default CreateTicketService;
|
||||
|
|
|
@ -6,7 +6,7 @@ import Ticket from "../../models/Ticket";
|
|||
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
|
||||
import ShowTicketService from "./ShowTicketService";
|
||||
import AppError from "../../errors/AppError";
|
||||
|
||||
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
|
||||
|
||||
const FindOrCreateTicketService = async (
|
||||
contact: Contact,
|
||||
|
@ -14,26 +14,37 @@ const FindOrCreateTicketService = async (
|
|||
unreadMessages: number,
|
||||
groupContact?: Contact
|
||||
): Promise<Ticket> => {
|
||||
|
||||
try {
|
||||
let ticket;
|
||||
|
||||
let ticket = await Ticket.findOne({
|
||||
where: {
|
||||
status: {
|
||||
[Op.or]: ["open", "pending", "queueChoice"]
|
||||
},
|
||||
contactId: groupContact ? groupContact.id : contact.id
|
||||
}
|
||||
});
|
||||
if (1 == 1 + 1) {
|
||||
ticket = await Ticket.findOne({
|
||||
where: {
|
||||
status: {
|
||||
[Op.or]: ["open", "pending", "queueChoice"]
|
||||
},
|
||||
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);
|
||||
|
||||
|
||||
//Habilitar esse caso queira usar o bot
|
||||
// const botInfo = await BotIsOnQueue('botqueue')
|
||||
const botInfo = { isOnQueue: false }
|
||||
|
||||
|
||||
// const botInfo = await BotIsOnQueue('botqueue')
|
||||
const botInfo = { isOnQueue: false };
|
||||
|
||||
if (ticket) {
|
||||
await ticket.update({ unreadMessages });
|
||||
|
@ -47,10 +58,7 @@ const FindOrCreateTicketService = async (
|
|||
order: [["updatedAt", "DESC"]]
|
||||
});
|
||||
|
||||
|
||||
|
||||
if (ticket) {
|
||||
|
||||
await ticket.update({
|
||||
status: "pending",
|
||||
userId: null,
|
||||
|
@ -60,7 +68,6 @@ const FindOrCreateTicketService = async (
|
|||
}
|
||||
|
||||
if (!ticket && !groupContact) {
|
||||
|
||||
ticket = await Ticket.findOne({
|
||||
where: {
|
||||
updatedAt: {
|
||||
|
@ -78,7 +85,6 @@ const FindOrCreateTicketService = async (
|
|||
});
|
||||
|
||||
if (ticket) {
|
||||
|
||||
await ticket.update({
|
||||
status: "pending",
|
||||
userId: null,
|
||||
|
@ -88,11 +94,10 @@ const FindOrCreateTicketService = async (
|
|||
}
|
||||
|
||||
if (!ticket) {
|
||||
|
||||
let status = "pending"
|
||||
let status = "pending";
|
||||
|
||||
if (queues.length > 1 && !botInfo.isOnQueue) {
|
||||
status = "queueChoice"
|
||||
status = "queueChoice";
|
||||
}
|
||||
|
||||
ticket = await Ticket.create({
|
||||
|
@ -114,9 +119,8 @@ const FindOrCreateTicketService = async (
|
|||
ticket = await ShowTicketService(ticket.id);
|
||||
|
||||
return ticket;
|
||||
|
||||
} 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);
|
||||
}
|
||||
};
|
||||
|
|
|
@ -6,25 +6,24 @@ import SendWhatsAppMessage from "../WbotServices/SendWhatsAppMessage";
|
|||
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
|
||||
import ShowTicketService from "./ShowTicketService";
|
||||
|
||||
import { createOrUpdateTicketCache } from '../../helpers/TicketCache'
|
||||
import { createOrUpdateTicketCache } from "../../helpers/TicketCache";
|
||||
import AppError from "../../errors/AppError";
|
||||
import sendWhatsAppMessageSocket from "../../helpers/SendWhatsappMessageSocket";
|
||||
var flatten = require('flat')
|
||||
|
||||
|
||||
var flatten = require("flat");
|
||||
|
||||
interface TicketData {
|
||||
status?: string;
|
||||
userId?: number;
|
||||
queueId?: number;
|
||||
statusChatEnd?: string;
|
||||
statusChatEnd?: string;
|
||||
unreadMessages?: number;
|
||||
whatsappId?: string | number;
|
||||
}
|
||||
|
||||
interface Request {
|
||||
ticketData: TicketData;
|
||||
ticketId: string | number;
|
||||
msg?: string
|
||||
ticketId: string | number;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
|
@ -35,13 +34,18 @@ interface Response {
|
|||
|
||||
const UpdateTicketService = async ({
|
||||
ticketData,
|
||||
ticketId,
|
||||
msg=''
|
||||
ticketId,
|
||||
msg = ""
|
||||
}: Request): Promise<Response> => {
|
||||
|
||||
try {
|
||||
|
||||
const { status, userId, queueId, statusChatEnd, unreadMessages } = ticketData;
|
||||
const {
|
||||
status,
|
||||
userId,
|
||||
queueId,
|
||||
statusChatEnd,
|
||||
unreadMessages,
|
||||
whatsappId
|
||||
} = ticketData;
|
||||
|
||||
const ticket = await ShowTicketService(ticketId);
|
||||
// await SetTicketMessagesAsRead(ticket);
|
||||
|
@ -50,7 +54,7 @@ const UpdateTicketService = async ({
|
|||
const oldUserId = ticket.user?.id;
|
||||
|
||||
if (oldStatus === "closed") {
|
||||
await CheckContactOpenTickets(ticket.contact.id);
|
||||
await CheckContactOpenTickets(ticket.contact.id, ticket.whatsappId);
|
||||
}
|
||||
|
||||
await ticket.update({
|
||||
|
@ -58,36 +62,35 @@ const UpdateTicketService = async ({
|
|||
queueId,
|
||||
userId,
|
||||
unreadMessages,
|
||||
statusChatEnd
|
||||
statusChatEnd,
|
||||
whatsappId
|
||||
});
|
||||
|
||||
await ticket.reload();
|
||||
|
||||
if (msg.length > 0) {
|
||||
|
||||
if (msg.length > 0) {
|
||||
setTimeout(async () => {
|
||||
|
||||
sendWhatsAppMessageSocket(ticket, msg)
|
||||
|
||||
}, 2000)
|
||||
sendWhatsAppMessageSocket(ticket, msg);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// TEST DEL
|
||||
// TEST DEL
|
||||
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
|
||||
delete ticket_obj['contact']['extraInfo']
|
||||
delete ticket_obj['user']
|
||||
delete ticket_obj["contact"]["extraInfo"];
|
||||
delete ticket_obj["user"];
|
||||
|
||||
ticket_obj = flatten(ticket_obj)
|
||||
|
||||
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj)
|
||||
ticket_obj = flatten(ticket_obj);
|
||||
|
||||
await createOrUpdateTicketCache(`ticket:${ticket.id}`, ticket_obj);
|
||||
} catch (error) {
|
||||
console.log('There was an error on UpdateTicketService.ts on createTicketCache: ', error)
|
||||
console.log(
|
||||
"There was an error on UpdateTicketService.ts on createTicketCache: ",
|
||||
error
|
||||
);
|
||||
}
|
||||
//
|
||||
|
||||
|
@ -100,7 +103,6 @@ const UpdateTicketService = async ({
|
|||
});
|
||||
}
|
||||
|
||||
|
||||
io.to(ticket.status)
|
||||
.to("notification")
|
||||
.to(ticketId.toString())
|
||||
|
@ -109,20 +111,16 @@ const UpdateTicketService = async ({
|
|||
ticket
|
||||
});
|
||||
|
||||
|
||||
io.emit("ticketStatus", {
|
||||
action: "update",
|
||||
ticketStatus: { ticketId: ticket.id, status: ticket.status }
|
||||
});
|
||||
|
||||
|
||||
return { ticket, oldStatus, oldUserId };
|
||||
|
||||
} 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);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
export default UpdateTicketService;
|
||||
export default UpdateTicketService;
|
||||
|
|
|
@ -1,40 +1,62 @@
|
|||
|
||||
import { Sequelize, } from "sequelize";
|
||||
import { Sequelize } from "sequelize";
|
||||
|
||||
const dbConfig = require("../../config/database");
|
||||
const sequelize = new Sequelize(dbConfig);
|
||||
|
||||
const { QueryTypes } = require('sequelize');
|
||||
const { QueryTypes } = require("sequelize");
|
||||
|
||||
interface Request {
|
||||
profile: string;
|
||||
userId?: string | number;
|
||||
profile?: string;
|
||||
userId?: string | number;
|
||||
}
|
||||
|
||||
const QueuesByUser = async ({ profile, userId }: Request): Promise<any[]> => {
|
||||
let queueByUsersInfo: any = [];
|
||||
|
||||
let queueByUsersInfo = []
|
||||
|
||||
if (userId) {
|
||||
// CONSULTANDO FILAS PELO ID DO USUARIO
|
||||
queueByUsersInfo = await sequelize.query(`select UserQueues.userId, UserQueues.queueId, Users.name,
|
||||
if (userId && profile) {
|
||||
// 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,
|
||||
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 if (profile) {
|
||||
// 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 });
|
||||
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;
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -1,30 +1,32 @@
|
|||
|
||||
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({
|
||||
// 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 };
|
||||
let whatsapps: any = [];
|
||||
|
||||
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;
|
||||
|
|
Loading…
Reference in New Issue