Implementação de fecamento de tickets do Bot

pull/20/head
adriano 2022-11-19 19:34:39 -03:00
parent f32cfdfe7f
commit 0113f1a73c
4 changed files with 112 additions and 6 deletions

View File

@ -1,14 +1,54 @@
import ListTicketTimeLife from "../services/TicketServices/ListTicketTimeLife";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import BotIsOnQueue from "./BotIsOnQueue";
const fsPromises = require("fs/promises"); const fsPromises = require("fs/promises");
const fs = require('fs') const fs = require('fs')
let timer: any
const CloseBotTickets = async () => { const CloseBotTickets = async () => {
try { try {
const botInfo = await BotIsOnQueue('botqueue')
if (!botInfo.userIdBot) return
let tickets: any = await ListTicketTimeLife({ timeseconds: 60, status: 'open', userId: botInfo.userIdBot })
console.log('tickets: ', tickets)
for (let i = 0; i < tickets.length; i++) {
await UpdateTicketService({
ticketData: { 'status': 'closed', 'userId': botInfo.userIdBot, 'statusChatEnd': 'FINALIZADO' },
ticketId: tickets[i].ticket_id
});
}
} catch (error) { } catch (error) {
console.log('There was an error on try close the bot tickets: ', error) console.log('There was an error on try close the bot tickets: ', error)
} }
} }
export default CloseBotTickets; const schedule = async () => {
try {
clearInterval(timer);
await CloseBotTickets()
} catch (error) {
console.log('error on schedule: ', error)
}
finally {
timer = setInterval(schedule, 60000);
}
}
timer = setInterval(schedule, 60000);
export default schedule;

View File

@ -10,6 +10,8 @@ import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor"
import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache' import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache'
import { loadContactsCache } from './helpers/ContactsCache' import { loadContactsCache } from './helpers/ContactsCache'
import "./helpers/CloseBotTickets";
const server = app.listen(process.env.PORT, () => { const server = app.listen(process.env.PORT, () => {
logger.info(`Server started on port: ${process.env.PORT}`); logger.info(`Server started on port: ${process.env.PORT}`);
}); });
@ -18,6 +20,8 @@ initIO(server);
StartAllWhatsAppsSessions(); StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
(async()=>{ (async()=>{
const cacheLength = await cacheSize() const cacheLength = await cacheSize()

View File

@ -0,0 +1,46 @@
import { Sequelize, } from "sequelize";
const dbConfig = require("../../config/database");
const sequelize = new Sequelize(dbConfig);
const { QueryTypes } = require('sequelize');
import { splitDateTime } from "../../helpers/SplitDateTime";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
interface Request {
timeseconds: string | number;
status: string;
userId?: string | number;
}
const ListTicketTimeLife = async ({timeseconds, status, userId }: Request): Promise<any[]> => {
let tickets = []
let currentDate = format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })
console.log('------------------> currentDate: ', currentDate)
if (userId) {
// CONSULTANDO FILAS PELO ID DO USUARIO
tickets = await sequelize.query(`select user.id as user_id, user.name as user_name, t.id as ticket_id from Tickets as t inner join Users as user on
t.userId = user.id and user.name = 'botqueue' and t.status='${status}' and (TIMESTAMPDIFF(SECOND, t.updatedAt, '${currentDate}')) >= ${timeseconds};`, { type: QueryTypes.SELECT });
} else {
// CONSULTANDO FILAS PELO USUARIO
tickets = await sequelize.query(`select id as ticket_id from Tickets where status='${status}' and
(TIMESTAMPDIFF(SECOND, updatedAt, '${currentDate}')) >= ${timeseconds};`, { type: QueryTypes.SELECT });
}
return tickets;
};
export default ListTicketTimeLife;

View File

@ -438,7 +438,7 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta
(endPointResponse.data.categoria == 'INFRAESTRUTURA' && endPointResponse.data.subcategoria == 'INTERNET' && (endPointResponse.data.categoria == 'INFRAESTRUTURA' && endPointResponse.data.subcategoria == 'INTERNET' &&
endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO') || endPointResponse.data.terceiro_nivel == 'PROBLEMA DE LENTIDÃO') ||
(endPointResponse.data.categoria == 'ELOS' && endPointResponse.data.subcategoria == 'VENDA') || (endPointResponse.data.categoria == 'ELOS' && endPointResponse.data.subcategoria == 'VENDAS') ||
(endPointResponse.data.categoria == 'ELOS' && endPointResponse.data.subcategoria == 'INDISPONIBILIDADE') (endPointResponse.data.categoria == 'ELOS' && endPointResponse.data.subcategoria == 'INDISPONIBILIDADE')
@ -978,7 +978,7 @@ const handleMessage = async (
if (test[i].body.includes('*categoria*: INFRAESTRUTURA')) { if (test[i].body.includes('*categoria*: INFRAESTRUTURA')) {
botSendMessage(ticket, contact, wbot, `Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!`) botSendMessage(ticket, contact, wbot, `Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!\n\nPara voltar ao atendimento *automatizado* e sair da fila de atendimento *humano* digite *0*`)
await transferTicket(0, wbot, ticket, contact) await transferTicket(0, wbot, ticket, contact)
break break
@ -986,7 +986,7 @@ const handleMessage = async (
} }
else if (test[i].body.includes('*categoria*: ELOS')) { else if (test[i].body.includes('*categoria*: ELOS')) {
botSendMessage(ticket, contact, wbot, `Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!`) botSendMessage(ticket, contact, wbot, `Estamos direcionando seu atendimento para o Suporte. Em breve você será atendido por um de nossos atendentes!\n\nPara voltar ao atendimento *automatizado* e sair da fila de atendimento *humano* digite *0*`)
await transferTicket(1, wbot, ticket, contact) await transferTicket(1, wbot, ticket, contact)
break break
@ -1002,6 +1002,22 @@ const handleMessage = async (
await sendDialogflowAwswer(wbot, ticket, msg, contact, chat); await sendDialogflowAwswer(wbot, ticket, msg, contact, chat);
} }
else if (botInfo.isOnQueue && !msg.fromMe && msg.body=='0'){
console.log('Entrou onde não devia..........')
let choosenQueue = await ShowQueueService(botInfo.botQueueId);
await UpdateTicketService({
ticketData: { status: 'open', userId: botInfo.userIdBot, queueId: choosenQueue.id },
ticketId: ticket.id
});
const _ticket = await ShowTicketService(ticket.id);
const chat = await msg.getChat();
await sendDialogflowAwswer(wbot, _ticket, msg, contact, chat);
return
}
// if (msg.body.trim() == 'broken') { // if (msg.body.trim() == 'broken') {