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,102 +4,78 @@ 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;
// };
export const wbotMonitorRemote = async (
req: Request,
res: Response
): Promise<Response> => {
const { action, whatsappId, reason } = req.body;
export const wbotMonitorRemote = async (req: Request, res: Response): Promise<Response> => {
console.log(
"action: ",
action,
" | whatsappId: ",
whatsappId,
" | reason: ",
reason
);
const { action, whatsappId, reason } = req.body
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 (action === 'disconnected') {
logger.info(`Disconnected session: ${whatsapp.name}, reason: ${reason}`);
}
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
if (whatsapp) {
if (action === "disconnected") {
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);
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 })
// 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<Response> => {
const { number } = req.body
console.log('-----------> number read: ', number)
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whatsapp
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" });
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 });
// 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<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!`;
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" });
};

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,138 +13,187 @@ 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 day = date.getDate().toString().padStart(2, "0");
let month = (date.getMonth() + 1).toString().padStart(2, "0");
let year = date.getFullYear();
let date = new Date()
let hour = date.getHours();
let minute = date.getMinutes();
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let year = date.getFullYear();
let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, "0")}:${minute
.toString()
.padStart(2, "0")}:00`;
let hour = date.getHours()
let minute = date.getMinutes()
//console.log(dateParm);
let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`
try {
const { schedulingNotifies, count, hasMore } =
await ListSchedulingNotifyService({
searchParam: dateParm,
pageNumber: "1"
});
//console.log(dateParm);
if (schedulingNotifies && schedulingNotifies.length > 0) {
for (let i = 0; i < schedulingNotifies.length; i++) {
const ticket: any = await ShowTicketService(
+schedulingNotifies[i].ticketId
);
try {
let _ticket = await Ticket.findOne({
where: {
contactId: ticket.contactId,
status: { [Op.in]: ["open", "pending"] }
}
});
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId);
if (schedulingNotifies && schedulingNotifies.length > 0) {
await DeleteSchedulingNotifyService(schedulingNotifies[i].id);
for (let i = 0; i < schedulingNotifies.length; i++) {
if (_ticket) continue;
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
});
}
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]
}
});
});
}
// 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) {
console.log('>>> SchedulingNotifiySendMessage.ts error: ', error)
}
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);
await monitor();
} catch (error) {
console.log("error on SchedulingNotifySendMessage: ", error);
} finally {
_fifo = setInterval(SchedulingNotifySendMessage, 5000);
}
};
try {
clearInterval(_fifo);
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