Finalização de implementação do controle do botão restore

pull/21/head
adriano 2022-12-11 04:47:32 -03:00
parent 408bb16e87
commit 330299726d
14 changed files with 311 additions and 100 deletions

View File

@ -8,6 +8,10 @@ import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppSer
import { restartWhatsSession } from "../helpers/RestartWhatsSession";
import path from 'path';
import { getIO } from "../libs/socket";
import { stat } from "fs";
let lstRestore: any = []
// import { WWebJsw } from "../../WWebJS/session-bd_40"
@ -36,16 +40,51 @@ const update = async (req: Request, res: Response): Promise<Response> => {
const restart = async (req: Request, res: Response): Promise<Response> => {
const { whatsappId } = req.params;
console.log('FROM REQUEST WHATSAPP ID: ', whatsappId)
const io = getIO();
if (Object.keys(req.body).length > 0) {
for (let i = 0; i < lstRestore.length; i++) {
io.emit("whatsappSession", {
action: "update",
session: { 'id': +lstRestore[i].id, 'disabled': true }
});
}
return res.status(200).json({});
}
const whatsapp = await ShowWhatsAppService(whatsappId);
restartWhatsSession(whatsapp, true)
//restartWhatsSession(whatsapp)
lstRestore.push({ 'id': +whatsappId, 'disabled': true })
io.emit("whatsappSession", {
action: "update",
session: { 'id': +whatsappId, 'disabled': true }
});
setTimeout(() => {
let whatsapp = lstRestore.shift();
whatsapp.disabled = false
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
}, 25000);
return res.status(200).json({ message: "Starting session." });
};

View File

@ -9,7 +9,7 @@ const sendMessageMultiSession = async (ticket: Ticket, body?: any, quotedMsgSeri
const listWhatsapp: any = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
if (listWhatsapp.length > 1) {
if (listWhatsapp.length > 0) {
for (let w = 0; w < listWhatsapp.length; w++) {

View File

@ -113,17 +113,19 @@ async function searchWhatsappCache(id: string, status: string) {
if (redis.status !== 'connect') return null
const number_cache: any = await redis.hgetall(`whatsapp:${id}`)
if(Object.entries(number_cache).length == 0){
return []
}
console.log('NUMBER_CACHED: ', number_cache)
// @x:foo @y:bar
// const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number}*)`, 'SORTBY', 'status', 'ASC')
const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC')
// const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@id:*${id}*))`)
const response: any = []
const number_cache: any = await redis.hgetall(`whatsapp:${14}`)
console.log('NUMBER CACHED: ', number_cache)
redis.quit()
@ -175,7 +177,7 @@ const insertOrUpeateWhatsCache = async (hash:any, whatsapp: any) => {
await redis.hmset(hash,JSON.parse(JSON.stringify(whatsapp)));
console.log(`${whatsapp.length} WHATSAPP INSERTED OR UPADTED IN CACHE!`)
console.log(`WHATSAPP ID ${whatsapp.id} INSERTED OR UPADTED IN CACHE!`)
}
@ -232,7 +234,7 @@ const createWhatsappIndexCache = async (hashIndex: string) => {
await redis.call('FT.DROPINDEX', hashIndex)
}
const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA','id', 'NUMERIC', 'SORTABLE', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT')
const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA','id', 'NUMERIC', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT', 'SORTABLE')
console.log('Whatsapp index created: ', response)

View File

@ -21,6 +21,8 @@ const sessions: Session[] = [];
let backupSession: any[] = []
import { insertOrUpeateWhatsCache } from "../helpers/WhatsCache";
import { json } from "sequelize/types";
import { restartWhatsSession } from "../helpers/RestartWhatsSession";
@ -138,7 +140,27 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
wbot.on("ready", async () => {
logger.info(`Session: ${sessionName} READY`);
console.log('>>>>>>>>>>>>>> ready wbot.ts MOBILE NUMBER: ', wbot.info["wid"]["user"])
// console.log('>>>>>>>>>>>>>> ready wbot.ts MOBILE NUMBER: ', wbot.info["wid"]["user"])
// console.log('::::::: WHATSAPP INFO: ', JSON.parse(JSON.stringify(whatsapp)))
if(whatsapp.name.includes(wbot.info["wid"]["user"])){
console.log('-----------------> THIS IS THE RIGHT NUMBER')
}
else{
console.log('-----------------> THIS IS THE WRONG NUMBER')
let read_number = wbot.info["wid"]["user"]
await wbot.logout()
io.emit("whatsappSession", {
action: "error",
msg: `Numero lido: ${read_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!`
});
// restartWhatsSession(whatsapp)
return
}
await whatsapp.update({

View File

@ -13,6 +13,7 @@ whatsappSessionRoutes.post(
WhatsAppSessionController.store
);
whatsappSessionRoutes.put(
"/whatsappsession/:whatsappId",
isAuth,

View File

@ -21,6 +21,7 @@ import { json } from "sequelize/types";
import sendMessageMultiSession from "../../helpers/TrySendMessageMultiSession";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
import { insertOrUpeateWhatsCache, searchWhatsappCache } from "../../helpers/WhatsCache";
import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
@ -48,40 +49,39 @@ const SendWhatsAppMessage = async ({
quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg);
}
//TEST DEL
let whats_number = await searchWhatsappCache(`${ticket.whatsappId}`)
console.log('---')
console.log('whats_number search: ', whats_number)
console.log('---')
let whatsapps: any
const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
//TEST DEL
// const defaultWhatsapp = await GetDefaultWhatsApp();
// console.log('DEFAULT WHATSAPP: ', JSON.parse(JSON.stringify(defaultWhatsapp)))
let listWhatsapp = null
listWhatsapp = await searchWhatsappCache(`${ticket.whatsappId}`, 'CONNECTED')
if(!listWhatsapp){
listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
}
// console.log('---')
// console.log('listWhatsapp search: ', listWhatsapp)
// console.log('---')
if (listWhatsapp.length > 1) {
console.log('entrou --------------------->')
const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
await ticket.update({ whatsappId: _whatsapp.id });
await ticket.update({ whatsappId: +_whatsapp.id });
}
else {
whatsapps = await Whatsapp.findOne({
where: { id: ticket.whatsappId },
attributes: ['status']
})
}
console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) {
if (listWhatsapp.length == 0) {
whatsapps = await wbotByUserQueue(ticket.userId)
@ -102,6 +102,57 @@ const SendWhatsAppMessage = async ({
}
//
// const listWhatsapp = await ListWhatsAppsNumber(ticket.whatsappId, 'CONNECTED')
// if (listWhatsapp.length > 1) {
// const _whatsapp = listWhatsapp[Math.floor(Math.random() * listWhatsapp.length)];
// await ticket.update({ whatsappId: _whatsapp.id });
// }
// else {
// whatsapps = await Whatsapp.findOne({
// where: { id: ticket.whatsappId },
// attributes: ['status']
// })
// }
// console.log('1 --------> ticket.whatsappId: ', ticket.whatsappId)
// if (listWhatsapp.length == 0 || (whatsapps && whatsapps.status != 'CONNECTED')) {
// whatsapps = await wbotByUserQueue(ticket.userId)
// if (whatsapps.length > 0) {
// if (whatsapps.length > 1) {
// await ticket.update({ whatsappId: whatsapps[+WhatsIndex(whatsapps)].id });
// }
// else {
// await ticket.update({ whatsappId: whatsapps[0].id });
// }
// }
// }
const wbot = await GetTicketWbot(ticket);
console.log('2 --------> send from whatsapp ticket.whatsappId: ', ticket.whatsappId)

View File

@ -365,9 +365,9 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st
const _clear_lst = () => {
console.log('LIST (lst.length) WHATSAPP MESSAGE ID MULTI SESSION: : ', lst.length)
console.log('WHATSAPP MESSAGE ID MULTI SESSION: ', lst.length)
if (lst.length < 800 ) return
if (lst.length < 200 ) return
console.log('BEFORE lst SLICE: ', lst)

View File

@ -6,6 +6,10 @@ import Whatsapp from "../../models/Whatsapp";
import ShowWhatsAppService from "./ShowWhatsAppService";
import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
import { insertOrUpeateWhatsCache } from "../../helpers/WhatsCache";
import { getWbot } from "../../libs/wbot";
import { restartWhatsSession } from "../../helpers/RestartWhatsSession";
interface WhatsappData {
name?: string;
@ -47,6 +51,8 @@ const UpdateWhatsAppService = async ({
queueIds = []
} = whatsappData;
try {
await schema.validate({ name, status, isDefault });
} catch (err) {
@ -70,6 +76,14 @@ const UpdateWhatsAppService = async ({
const whatsapp = await ShowWhatsAppService(whatsappId);
// console.log('############## whatsapp: ', JSON.parse(JSON.stringify(whatsapp)))
if(name && !name.includes(whatsapp.number) && whatsapp.status === 'CONNECTED'){
throw new AppError("ERR_WAPP_WRONG_SESSION_NAME");
}
await whatsapp.update({
name,
status,

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useContext } from "react";
import QRCode from "qrcode.react";
import openSocket from "socket.io-client";
import toastError from "../../errors/toastError";
@ -7,7 +7,12 @@ import { Dialog, DialogContent, Paper, Typography } from "@material-ui/core";
import { i18n } from "../../translate/i18n";
import api from "../../services/api";
import { AuthContext } from "../../context/Auth/AuthContext";
const QrcodeModal = ({ open, onClose, whatsAppId }) => {
const { user } = useContext(AuthContext);
const [qrCode, setQrCode] = useState("");
useEffect(() => {
@ -36,12 +41,24 @@ const QrcodeModal = ({ open, onClose, whatsAppId }) => {
if (data.action === "update" && data.session.qrcode === "") {
onClose();
}
if (data.action === "error") {
console.log('user.profile: ', user.profile)
if(user.profile === 'master'){
alert(data.msg)
}
}
});
return () => {
socket.disconnect();
};
}, [whatsAppId, onClose]);
}, [whatsAppId, onClose, user.profile]);
return (
<Dialog open={open} onClose={onClose} maxWidth="lg" scroll="paper">

View File

@ -2,6 +2,7 @@ import { useState, useEffect, useReducer } from "react";
import openSocket from "socket.io-client";
import toastError from "../../errors/toastError";
import api from "../../services/api";
const reducer = (state, action) => {
@ -28,16 +29,39 @@ const reducer = (state, action) => {
const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id);
if (whatsAppIndex !== -1) {
if ('disabled' in whatsApp) {
state[whatsAppIndex].disabled = whatsApp.disabled
}
else {
state[whatsAppIndex].status = whatsApp.status;
state[whatsAppIndex].updatedAt = whatsApp.updatedAt;
state[whatsAppIndex].qrcode = whatsApp.qrcode;
state[whatsAppIndex].retries = whatsApp.retries;
}
return [...state];
} else {
return [...state];
}
}
// if(action.type === "UPDATE_SESSION_RESTORE"){
// const whatsApp = action.payload;
// console.log('------> whatsApp: ', whatsApp)
// const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id);
// if (whatsAppIndex !== -1) {
// console.log('kkkkkkkkkkkkkkkkkkkkkkkkkk: ',whatsAppIndex)
// return [...state];
// }
// }
// if (action.type === "UPDATE_DISK_SPACE_MONIT") {
// const whatsApp = action.payload;
@ -84,6 +108,8 @@ const useWhatsApps = () => {
const [whatsApps, dispatch] = useReducer(reducer, []);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
const fetchSession = async () => {
@ -116,16 +142,15 @@ const useWhatsApps = () => {
socket.on("whatsappSession", data => {
if (data.action === "update") {
dispatch({ type: "UPDATE_SESSION", payload: data.session });
}
else if (data.action === "update_restore") {
dispatch({ type: "UPDATE_SESSION_RESTORE", payload: data.session });
}
});
socket.on("whatsappSessionMonit", data => {
if (data.action === "update") {
dispatch({ type: "UPDATE_WHATSAPPS_SESSION_MONIT", payload: data.whatsappSessionSize });
}
});

View File

@ -115,7 +115,7 @@ const Connections = () => {
const [diskSpaceInfo, setDiskSpaceInfo] = useState({});
const [disabled, setDisabled] = useState(true);
const confirmationModalInitialState = {
@ -140,7 +140,9 @@ const Connections = () => {
const handleRestartWhatsAppSession = async whatsAppId => {
try {
await api.post(`/restartwhatsappsession/${whatsAppId}`);
} catch (err) {
toastError(err);
}
@ -329,6 +331,32 @@ const Connections = () => {
};
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
await api.post(`/restartwhatsappsession/0`, { params: { status: 'status' }, });
setDisabled(false)
} catch (err) {
console.log(err);
}
};
fetchQueries();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, []);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
@ -533,9 +561,11 @@ const Connections = () => {
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<Button
disabled={whatsApp.disabled || disabled ? true : false}
size="small"
variant="contained"
color="primary"
@ -543,6 +573,7 @@ const Connections = () => {
>
Restore
</Button>
</TableCell>

View File

@ -453,6 +453,8 @@ const messages = {
"This color is already in use, pick another one.",
ERR_WAPP_GREETING_REQUIRED:
"Greeting message is required if there is more than one queue.",
ERR_WAPP_WRONG_SESSION_NAME:
"The number updated in the session name does not match the number read! To change the new number in the name disconnect the session!",
},
},
},

View File

@ -460,6 +460,9 @@ const messages = {
"Este color ya está en uso, elija otro.",
ERR_WAPP_GREETING_REQUIRED:
"El mensaje de saludo es obligatorio cuando hay más de una cola.",
ERR_WAPP_WRONG_SESSION_NAME:
"¡El número actualizado en el nombre de la sesión no coincide con el número leído! Para cambiar el nuevo número en el nombre desconecte la sesión!",
},
},
},

View File

@ -458,6 +458,10 @@ const messages = {
"Esta cor já está em uso, escolha outra.",
ERR_WAPP_GREETING_REQUIRED:
"A mensagem de saudação é obrigatório quando há mais de uma fila.",
ERR_WAPP_WRONG_SESSION_NAME:
"O numero atualizado no nome da sessão não corresponde ao numero lido! Para alterar o novo numero no nome desconecte a sessão!",
},
},
},