Compare commits

..

No commits in common. "bc7fb4424cb7c72a1280518e6b01365fb21076ad" and "aa2ee9641289431c7016bb7120f4c51345dd397a" have entirely different histories.

3 changed files with 210 additions and 209 deletions

View File

@ -4,72 +4,50 @@ import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
import * as Sentry from "@sentry/node"; import * as Sentry from "@sentry/node";
import Whatsapp from "../models/Whatsapp"; import Whatsapp from "../models/Whatsapp";
import omnihitDashboardSession from "../helpers/OmnhitDashboardSession";
// type IndexQuery = { // type IndexQuery = {
// centro_custo: string; // centro_custo: string;
// }; // };
export const wbotMonitorRemote = async ( export const wbotMonitorRemote = async (req: Request, res: Response): Promise<Response> => {
req: Request,
res: Response
): Promise<Response> => {
const { action, whatsappId, reason } = req.body;
console.log( const { action, whatsappId, reason } = req.body
"action: ",
action,
" | whatsappId: ",
whatsappId,
" | reason: ",
reason
);
console.log("-----------> ACTION: ", req.body["action"]); console.log('action: ', action, ' | whatsappId: ', whatsappId, ' | reason: ', reason)
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }); console.log('-----------> ACTION: ', req.body['action'])
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true })
if (whatsapp) { if (whatsapp) {
if (action === "disconnected") { if (action === 'disconnected') {
logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`); logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`);
} }
let data: any = {};
data.whatsapp = { ...whatsapp, DB: process.env.DB_NAME };
data.action = "update";
await omnihitDashboardSession(data);
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
action: "update", action: "update",
session: whatsapp 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<Response> => {
const { whatsappId } = req.body;
console.log(
"-----------> QRCODE MONITOR whatsappId: ",
req.body["whatsappId"]
);
const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true });
export const wbotMonitorQrcodeRemote = async (req: Request, res: Response): Promise<Response> => {
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) // 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) { if (whatsapp) {
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
@ -78,22 +56,16 @@ export const wbotMonitorQrcodeRemote = async (
}); });
} }
return res.status(200).json({ message: "Ok" }); return res.status(200).json({ "message": "Ok" });
}; };
export const wbotMonitorQrcodeNumberRead = async (
req: Request,
res: Response
): Promise<Response> => {
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!`; export const wbotMonitorQrcodeNumberRead = async (req: Request, res: Response): Promise<Response> => {
let data: any = {};
data.msg = msg; const { number } = req.body
data.action = "error";
await omnihitDashboardSession(data); console.log('-----------> number read: ', number)
const io = getIO(); const io = getIO();
io.emit("whatsappSession", { io.emit("whatsappSession", {
@ -101,5 +73,9 @@ export const wbotMonitorQrcodeNumberRead = async (
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!` 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" }); return res.status(200).json({ "message": "Ok" });
}; };

View File

@ -1,24 +0,0 @@
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;

View File

@ -13,84 +13,85 @@ import SchedulingNotify from "../models/SchedulingNotify";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import User from "../models/User"; import User from "../models/User";
import { Sequelize, Op } from "sequelize"; import { Sequelize, Op } from "sequelize";
import omnihitDashboardSession from "./OmnhitDashboardSession";
const fastFolderSize = require("fast-folder-size");
const { promisify } = require("util"); const fastFolderSize = require('fast-folder-size')
const fs = require("fs"); const { promisify } = require('util')
const fs = require('fs')
const { exec } = require("child_process"); const { exec } = require("child_process");
let _fifo: any; let _fifo: any
let scheduler_monitor: any; let scheduler_monitor: any;
let timeInterval = 5; let timeInterval = 5
const monitor = async () => { const monitor = async () => {
let date = new Date();
let day = date.getDate().toString().padStart(2, "0"); let date = new Date()
let month = (date.getMonth() + 1).toString().padStart(2, "0");
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let year = date.getFullYear(); let year = date.getFullYear();
let hour = date.getHours(); let hour = date.getHours()
let minute = date.getMinutes(); let minute = date.getMinutes()
let fullDate = `${year}-${month}-${day}`; let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, "0")}:${minute let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`
.toString()
.padStart(2, "0")}:00`;
//console.log(dateParm); //console.log(dateParm);
try { try {
const { schedulingNotifies, count, hasMore } =
await ListSchedulingNotifyService({ const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
searchParam: dateParm,
pageNumber: "1"
});
if (schedulingNotifies && schedulingNotifies.length > 0) { if (schedulingNotifies && schedulingNotifies.length > 0) {
for (let i = 0; i < schedulingNotifies.length; i++) { for (let i = 0; i < schedulingNotifies.length; i++) {
const ticket: any = await ShowTicketService(
+schedulingNotifies[i].ticketId const ticket: any = await ShowTicketService(+schedulingNotifies[i].ticketId);
);
let _ticket = await Ticket.findOne({ let _ticket = await Ticket.findOne({
where: { where: {
contactId: ticket.contactId, contactId: ticket.contactId,
status: { [Op.in]: ["open", "pending"] } status: { [Op.in]: ['open', 'pending'] }
} }
}); })
await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId); await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId)
await DeleteSchedulingNotifyService(schedulingNotifies[i].id); await DeleteSchedulingNotifyService(schedulingNotifies[i].id)
if (_ticket) continue; if (_ticket) continue
if (ticket.dataValues.status == "closed") { if (ticket.dataValues.status == 'closed') {
await ticket.update({ status: "open" }); await ticket.update({ status: 'open' })
} }
const userId: number = ticket.getDataValue("userId"); const userId: number = ticket.getDataValue('userId');
let userN = ""; let userN = '';
if(userId){ if(userId){
const useer = await User.findByPk(userId); const useer = await User.findByPk(userId);
if(useer){ if(useer){
const userName: string = useer.getDataValue("name"); const userName: string = useer.getDataValue('name');
userN = `*${userName}:* \n`; userN = `*${userName}:* \n`;
} }
} }
await new Promise(f => setTimeout(f, 3000)); await new Promise(f => setTimeout(f, 3000));
await SendWhatsAppMessage({ await SendWhatsAppMessage({
body: userN + schedulingNotifies[i].message, body: userN+schedulingNotifies[i].message, ticket
ticket
}); });
}
} }
}
exec("df -h /", (error: any, stdout: any, stderr: any) => { exec("df -h /", (error: any, stdout: any, stderr: any) => {
if (error) { if (error) {
console.log(`exec error: ${error.message}`); console.log(`exec error: ${error.message}`);
return; return;
@ -100,8 +101,8 @@ const monitor = async () => {
return; return;
} }
stdout = stdout.split(/\r?\n/); stdout = stdout.split(/\r?\n/)
stdout = stdout[1].trim().split(/\s+/); stdout = stdout[1].trim().split(/\s+/)
// DISK SPACE MONITORING // DISK SPACE MONITORING
const io = getIO(); const io = getIO();
@ -115,36 +116,84 @@ const monitor = async () => {
} }
}); });
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);
}); });
// WHATS SESSION SIZE MONITORING
// const whatsapps = await ListWhatsAppsService();
// whatsapps.forEach(async whats => {
// 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) { } catch (error) {
console.log(">>> SchedulingNotifiySendMessage.ts error: ", error); console.log('>>> SchedulingNotifiySendMessage.ts error: ', error)
} }
}; };
const SchedulingNotifySendMessage = async () => { const SchedulingNotifySendMessage = async () => {
try { try {
clearInterval(_fifo); clearInterval(_fifo);
await monitor(); await monitor()
} catch (error) { } catch (error) {
console.log("error on SchedulingNotifySendMessage: ", error); console.log('error on SchedulingNotifySendMessage: ', error)
} finally { }
finally {
_fifo = setInterval(SchedulingNotifySendMessage, 5000); _fifo = setInterval(SchedulingNotifySendMessage, 5000);
} }
}; }
_fifo = setInterval(SchedulingNotifySendMessage, 5000); _fifo = setInterval(SchedulingNotifySendMessage, 5000);
module.exports = SchedulingNotifySendMessage;
module.exports = SchedulingNotifySendMessage