From 0113f1a73c0e37556a7f1f50497a689a925e9f7e Mon Sep 17 00:00:00 2001 From: adriano Date: Sat, 19 Nov 2022 19:34:39 -0300 Subject: [PATCH] =?UTF-8?q?Implementa=C3=A7=C3=A3o=20de=20fecamento=20de?= =?UTF-8?q?=20tickets=20do=20Bot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/helpers/CloseBotTickets.ts | 46 +++++++++++++++++-- backend/src/server.ts | 4 ++ .../TicketServices/ListTicketTimeLife.ts | 46 +++++++++++++++++++ .../WbotServices/wbotMessageListener.ts | 22 +++++++-- 4 files changed, 112 insertions(+), 6 deletions(-) create mode 100644 backend/src/services/TicketServices/ListTicketTimeLife.ts diff --git a/backend/src/helpers/CloseBotTickets.ts b/backend/src/helpers/CloseBotTickets.ts index 6b5e853..43cbe81 100644 --- a/backend/src/helpers/CloseBotTickets.ts +++ b/backend/src/helpers/CloseBotTickets.ts @@ -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 fs = require('fs') +const fs = require('fs') + +let timer: any const CloseBotTickets = async () => { 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) { console.log('There was an error on try close the bot tickets: ', error) } } -export default CloseBotTickets; \ No newline at end of file +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; \ No newline at end of file diff --git a/backend/src/server.ts b/backend/src/server.ts index f4949f6..2f239f1 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -9,6 +9,8 @@ import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor" import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache' import { loadContactsCache } from './helpers/ContactsCache' + +import "./helpers/CloseBotTickets"; const server = app.listen(process.env.PORT, () => { logger.info(`Server started on port: ${process.env.PORT}`); @@ -18,6 +20,8 @@ initIO(server); StartAllWhatsAppsSessions(); gracefulShutdown(server); + + (async()=>{ const cacheLength = await cacheSize() diff --git a/backend/src/services/TicketServices/ListTicketTimeLife.ts b/backend/src/services/TicketServices/ListTicketTimeLife.ts new file mode 100644 index 0000000..f44a493 --- /dev/null +++ b/backend/src/services/TicketServices/ListTicketTimeLife.ts @@ -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 => { + + 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; + + + + diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index c355b96..0ddfc32 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -438,7 +438,7 @@ async function sendDelayedMessages(wbot: Session, ticket: Ticket, contact: Conta (endPointResponse.data.categoria == 'INFRAESTRUTURA' && endPointResponse.data.subcategoria == 'INTERNET' && 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') @@ -978,7 +978,7 @@ const handleMessage = async ( 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) break @@ -986,7 +986,7 @@ const handleMessage = async ( } 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) break @@ -1002,6 +1002,22 @@ const handleMessage = async ( 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') {