diff --git a/backend/src/controllers/WbotMonitorController.ts b/backend/src/controllers/WbotMonitorController.ts index 7db701a..7d10765 100644 --- a/backend/src/controllers/WbotMonitorController.ts +++ b/backend/src/controllers/WbotMonitorController.ts @@ -4,78 +4,102 @@ import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService import { logger } from "../utils/logger"; import * as Sentry from "@sentry/node"; import Whatsapp from "../models/Whatsapp"; - +import omnihitDashboardSession from "../helpers/OmnhitDashboardSession"; // type IndexQuery = { -// centro_custo: string; -// }; +// centro_custo: string; +// }; -export const wbotMonitorRemote = async (req: Request, res: Response): Promise => { +export const wbotMonitorRemote = async ( + req: Request, + res: Response +): Promise => { + const { action, whatsappId, reason } = req.body; - const { action, whatsappId, reason } = req.body + console.log( + "action: ", + action, + " | whatsappId: ", + whatsappId, + " | reason: ", + reason + ); - console.log('action: ', action, ' | whatsappId: ', whatsappId, ' | reason: ', reason) + console.log("-----------> ACTION: ", req.body["action"]); - console.log('-----------> ACTION: ', req.body['action']) - - const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }) - - if (whatsapp) { - if (action === 'disconnected') { - logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`); - } - - const io = getIO(); - io.emit("whatsappSession", { - action: "update", - session: whatsapp - }); + const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }); + if (whatsapp) { + if (action === "disconnected") { + logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`); } - return res.status(200).json({ "message": "Ok" }); -}; + let data: any = {}; + data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME }; + data.action = "update"; + await omnihitDashboardSession(data); - - - -export const wbotMonitorQrcodeRemote = async (req: Request, res: Response): Promise => { - - const { whatsappId } = req.body - - console.log('-----------> QRCODE MONITOR whatsappId: ', req.body['whatsappId']) - - const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }) - // let whatsapp = await ShowWhatsAppService(whatsappId) - - if (whatsapp) { - const io = getIO(); - io.emit("whatsappSession", { - action: "update", - session: whatsapp - }); - } - - return res.status(200).json({ "message": "Ok" }); -}; - - - -export const wbotMonitorQrcodeNumberRead = async (req: Request, res: Response): Promise => { - - const { number } = req.body - - console.log('-----------> number read: ', number) - const io = getIO(); io.emit("whatsappSession", { - action: "error", - msg: `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!` + action: "update", + session: whatsapp }); + } - return res.status(200).json({ "message": "Ok" }); + return res.status(200).json({ message: "Ok" }); }; +export const wbotMonitorQrcodeRemote = async ( + req: Request, + res: Response +): Promise => { + const { whatsappId } = req.body; + console.log( + "-----------> QRCODE MONITOR whatsappId: ", + req.body["whatsappId"] + ); - \ No newline at end of file + const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }); + // let whatsapp = await ShowWhatsAppService(whatsappId) + + if (whatsapp) { + let data: any = {}; + data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME }; + data.action = "update"; + await omnihitDashboardSession(data); + } + + if (whatsapp) { + const io = getIO(); + io.emit("whatsappSession", { + action: "update", + session: whatsapp + }); + } + + return res.status(200).json({ message: "Ok" }); +}; + +export const wbotMonitorQrcodeNumberRead = async ( + req: Request, + res: Response +): Promise => { + const { number } = req.body; + + console.log("-----------> number read: ", number); + + const msg = `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!`; + let data: any = {}; + data.msg = msg; + data.action = "error"; + await omnihitDashboardSession(data); + + const io = getIO(); + io.emit("whatsappSession", { + action: "error", + msg: `Numero lido: ${number} \nEssa sessão de whatsapp foi desconectada porque o numero que esta descrito no nome dessa sessão não corresponde ao numero lido!` + }); + + return res.status(200).json({ message: "Ok" }); +}; diff --git a/backend/src/helpers/OmnhitDashboardSession.ts b/backend/src/helpers/OmnhitDashboardSession.ts new file mode 100644 index 0000000..075501a --- /dev/null +++ b/backend/src/helpers/OmnhitDashboardSession.ts @@ -0,0 +1,24 @@ +import axios from "axios"; + +async function omnihitDashboardSession(data: any) { + + // console.log('DATA: ', data) + + try { + await axios.post( + `${process.env.URL_DASHBOARD_SESSIONS}/api/v1/omnihit/monitor`, + data, + { + headers: { + Authorization: `Bearer ${process.env.TOKEN_DASHBOARD_SESSIONS}` + } + } + ); + } catch (error) { + console.log( + `Post request error to ${process.env.URL_DASHBOARD_SESSIONS}/api/v1/omnihit/monitor` + ); + } +} + +export default omnihitDashboardSession; diff --git a/backend/src/helpers/SchedulingNotifySendMessage.ts b/backend/src/helpers/SchedulingNotifySendMessage.ts index 3ba8e8c..01f1c0b 100644 --- a/backend/src/helpers/SchedulingNotifySendMessage.ts +++ b/backend/src/helpers/SchedulingNotifySendMessage.ts @@ -13,187 +13,138 @@ import SchedulingNotify from "../models/SchedulingNotify"; import Ticket from "../models/Ticket"; import User from "../models/User"; import { Sequelize, Op } from "sequelize"; +import omnihitDashboardSession from "./OmnhitDashboardSession"; - -const fastFolderSize = require('fast-folder-size') -const { promisify } = require('util') -const fs = require('fs') +const fastFolderSize = require("fast-folder-size"); +const { promisify } = require("util"); +const fs = require("fs"); const { exec } = require("child_process"); -let _fifo: any +let _fifo: any; let scheduler_monitor: any; -let timeInterval = 5 +let timeInterval = 5; const monitor = async () => { + let date = new Date(); - let date = new Date() + let day = date.getDate().toString().padStart(2, "0"); + let month = (date.getMonth() + 1).toString().padStart(2, "0"); + let year = date.getFullYear(); - let day = date.getDate().toString().padStart(2, '0'); - let month = (date.getMonth() + 1).toString().padStart(2, '0'); - let year = date.getFullYear(); + let hour = date.getHours(); + let minute = date.getMinutes(); - let hour = date.getHours() - let minute = date.getMinutes() + let fullDate = `${year}-${month}-${day}`; + let dateParm = `${fullDate} ${hour.toString().padStart(2, "0")}:${minute + .toString() + .padStart(2, "0")}:00`; - let fullDate = `${year}-${month}-${day}`; - let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00` + //console.log(dateParm); - //console.log(dateParm); + try { + const { schedulingNotifies, count, hasMore } = + await ListSchedulingNotifyService({ + searchParam: dateParm, + pageNumber: "1" + }); - try { - - const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); - - if (schedulingNotifies && schedulingNotifies.length > 0) { - - for (let i = 0; i < schedulingNotifies.length; i++) { - - const ticket: any = await ShowTicketService(+schedulingNotifies[i].ticketId); - - let _ticket = await Ticket.findOne({ - where: { - contactId: ticket.contactId, - status: { [Op.in]: ['open', 'pending'] } - } - }) - - await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId) - - await DeleteSchedulingNotifyService(schedulingNotifies[i].id) - - if (_ticket) continue - - if (ticket.dataValues.status == 'closed') { - await ticket.update({ status: 'open' }) - } - const userId: number = ticket.getDataValue('userId'); - let userN = ''; - if(userId){ - const useer = await User.findByPk(userId); - if(useer){ - const userName: string = useer.getDataValue('name'); - userN = `*${userName}:* \n`; - } - } - - await new Promise(f => setTimeout(f, 3000)); - await SendWhatsAppMessage({ - body: userN+schedulingNotifies[i].message, ticket - }); - - - - } - - } - - - exec("df -h /", (error: any, stdout: any, stderr: any) => { - - if (error) { - console.log(`exec error: ${error.message}`); - return; - } - if (stderr) { - console.log(`exec stderr: ${stderr}`); - return; - } - - stdout = stdout.split(/\r?\n/) - stdout = stdout[1].trim().split(/\s+/) - - // DISK SPACE MONITORING - const io = getIO(); - io.emit("diskSpaceMonit", { - action: "update", - diskSpace: { - size: stdout[1], - used: stdout[2], - available: stdout[3], - use: stdout[4] - } - }); + if (schedulingNotifies && schedulingNotifies.length > 0) { + for (let i = 0; i < schedulingNotifies.length; i++) { + const ticket: any = await ShowTicketService( + +schedulingNotifies[i].ticketId + ); + let _ticket = await Ticket.findOne({ + where: { + contactId: ticket.contactId, + status: { [Op.in]: ["open", "pending"] } + } }); + await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId); + await DeleteSchedulingNotifyService(schedulingNotifies[i].id); - // WHATS SESSION SIZE MONITORING - // const whatsapps = await ListWhatsAppsService(); + if (_ticket) continue; - // whatsapps.forEach(async whats => { + if (ticket.dataValues.status == "closed") { + await ticket.update({ status: "open" }); + } + const userId: number = ticket.getDataValue("userId"); + let userN = ""; + if (userId) { + const useer = await User.findByPk(userId); + if (useer) { + const userName: string = useer.getDataValue("name"); + userN = `*${userName}:* \n`; + } + } - - - // const sourcePath = path.join(__dirname, `../../.wwebjs_auth/`, `session-bd_${whats.id}`) - - // if (fs.existsSync(sourcePath)) { - - // try { - - // const fastFolderSizeAsync = promisify(fastFolderSize) - - // let size = await fastFolderSizeAsync(sourcePath) - - // size = convertBytes(size) - - - // // SESSION MONITORING - // const io = getIO(); - // io.emit("whatsappSessionMonit", { - // action: "update", - // whatsappSessionSize: { - // id: whats.id, - // sessionSize: size - // } - // }); - // } - // catch (err) { - // console.log('An error occurred while get info from the directory: ', err); - // } - - // } - // else { - - // // console.log('Directory not found to get size info: ', sourcePath) - - // } - - // }); - - - - } catch (error) { - console.log('>>> SchedulingNotifiySendMessage.ts error: ', error) + await new Promise(f => setTimeout(f, 3000)); + await SendWhatsAppMessage({ + body: userN + schedulingNotifies[i].message, + ticket + }); + } } + exec("df -h /", (error: any, stdout: any, stderr: any) => { + if (error) { + console.log(`exec error: ${error.message}`); + return; + } + if (stderr) { + console.log(`exec stderr: ${stderr}`); + return; + } + + stdout = stdout.split(/\r?\n/); + stdout = stdout[1].trim().split(/\s+/); + + // DISK SPACE MONITORING + const io = getIO(); + io.emit("diskSpaceMonit", { + action: "update", + diskSpace: { + size: stdout[1], + used: stdout[2], + available: stdout[3], + use: stdout[4] + } + }); + + let data: any = {}; + + data.diskSpace = { + DB: process.env.DB_NAME, + size: stdout[1], + used: stdout[2], + available: stdout[3], + use: stdout[4] + }; + data.action = "update"; + omnihitDashboardSession(data); + }); + + } catch (error) { + console.log(">>> SchedulingNotifiySendMessage.ts error: ", error); + } }; - const SchedulingNotifySendMessage = async () => { + try { + clearInterval(_fifo); - try { - clearInterval(_fifo); - - await monitor() - - } catch (error) { - console.log('error on SchedulingNotifySendMessage: ', error) - } - finally { - _fifo = setInterval(SchedulingNotifySendMessage, 5000); - } -} + await monitor(); + } catch (error) { + console.log("error on SchedulingNotifySendMessage: ", error); + } finally { + _fifo = setInterval(SchedulingNotifySendMessage, 5000); + } +}; _fifo = setInterval(SchedulingNotifySendMessage, 5000); - -module.exports = SchedulingNotifySendMessage - - - - - - +module.exports = SchedulingNotifySendMessage;