finalização da implementação para que um mesmo contato fale com whatsapps distintos da interface omnihit

pull/21/head
adriano 2023-07-28 09:25:13 -03:00
parent 4ee65ad300
commit 1e0b8b9d29
10 changed files with 532 additions and 421 deletions

View File

@ -5,6 +5,7 @@ import AppError from "../errors/AppError";
import UpdateSettingService from "../services/SettingServices/UpdateSettingService"; import UpdateSettingService from "../services/SettingServices/UpdateSettingService";
import ListSettingsService from "../services/SettingServices/ListSettingsService"; import ListSettingsService from "../services/SettingServices/ListSettingsService";
import loadSettings from "../helpers/LoadSettings";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
// if (req.user.profile !== "master") { // if (req.user.profile !== "master") {
@ -31,6 +32,8 @@ export const update = async (
value value
}); });
loadSettings();
const io = getIO(); const io = getIO();
io.emit("settings", { io.emit("settings", {
action: "update", action: "update",

View File

@ -63,6 +63,7 @@ import endPointQuery from "../helpers/old_EndPointQuery";
import Contact from "../models/Contact"; import Contact from "../models/Contact";
import BotIsOnQueue from "../helpers/BotIsOnQueue"; import BotIsOnQueue from "../helpers/BotIsOnQueue";
import { setMessageAsRead } from "../helpers/SetMessageAsRead"; import { setMessageAsRead } from "../helpers/SetMessageAsRead";
import { getSettingValue } from "../helpers/WhaticketSettings";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { const {
@ -242,13 +243,7 @@ export const update = async (
let ticketData: TicketData = req.body; let ticketData: TicketData = req.body;
// console.log('ticketData: ', ticketData) if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
// console.log('ticketData.transfer', ticketData.transfer)
// return res.send()
if (1 == 1 + 1) {
} else {
if (ticketData.transfer) { if (ticketData.transfer) {
const defaultWhatsapp: any = await GetDefaultWhatsApp( const defaultWhatsapp: any = await GetDefaultWhatsApp(
ticketData.userId ticketData.userId

View File

@ -0,0 +1,22 @@
import { QueryInterface } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.bulkInsert(
"Settings",
[
{
key: "oneContactChatWithManyWhats",
value: "enabled",
createdAt: new Date(),
updatedAt: new Date()
}
],
{}
);
},
down: (queryInterface: QueryInterface) => {
return queryInterface.bulkDelete("Settings", {});
}
};

View File

@ -2,6 +2,7 @@ import { Op } from "sequelize";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"; import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
import { getSettingValue } from "./WhaticketSettings";
const CheckContactOpenTickets = async ( const CheckContactOpenTickets = async (
contactId: number, contactId: number,
@ -9,11 +10,7 @@ const CheckContactOpenTickets = async (
): Promise<void> => { ): Promise<void> => {
let ticket; let ticket;
if (1 == 1 + 1) { if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
ticket = await Ticket.findOne({
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
});
} else {
let whats = await ListWhatsAppsNumber(whatsappId); let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({ ticket = await Ticket.findOne({
@ -25,6 +22,10 @@ const CheckContactOpenTickets = async (
] ]
} }
}); });
} else {
ticket = await Ticket.findOne({
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
});
} }
if (ticket) { if (ticket) {

View File

@ -0,0 +1,27 @@
import Setting from "../models/Setting";
import fs from "fs";
import dir from "path";
import os from "os";
async function loadSettings() {
const setting = await Setting.findAll({});
if (setting) {
let sett = setting.map((s: any) => {
return { key: s.key, value: s.value };
});
try {
const keyFilename = dir.join(os.tmpdir(), `whaticket_settings.json`);
const jsonSettings = JSON.stringify(sett, null, 2);
fs.writeFileSync(keyFilename, jsonSettings);
console.log(`Settings saved to ${keyFilename}`);
} catch (err) {
console.error("Error saving Settings to file:", err);
}
}
}
export default loadSettings;

View File

@ -0,0 +1,18 @@
import fs from "fs";
import dir from "path";
import os from "os";
export function getSettingValue(key: any) {
let value: any = {};
try {
const keyFilename = dir.join(os.tmpdir(), `whaticket_settings.json`);
const jsonData = fs.readFileSync(keyFilename, "utf8");
const settings = JSON.parse(jsonData);
value = settings.find((s: any) => s.key === key);
} catch (err) {
console.error("Error reading or parsing data from file:", err);
}
return value;
}

View File

@ -11,15 +11,20 @@ import { loadContactsCache } from "./helpers/ContactsCache";
import { loadSchedulesCache } from "./helpers/SchedulingNotifyCache"; import { loadSchedulesCache } from "./helpers/SchedulingNotifyCache";
import { delRestoreControllFile } from "./helpers/RestoreControll"; import { delRestoreControllFile } from "./helpers/RestoreControll";
import "./helpers/SchedulingNotifySendMessage" import "./helpers/SchedulingNotifySendMessage";
import axios from "axios"; import axios from "axios";
import os from 'os'; import os from "os";
import Setting from "./models/Setting";
import fs from "fs";
import dir from "path";
import { getSettingValue } from "./helpers/WhaticketSettings";
import loadSettings from "./helpers/LoadSettings";
const server = app.listen(process.env.PORT, () => { const server = app.listen(process.env.PORT, () => {
logger.info(`Server started on port: ${process.env.PORT}`); logger.info(`Server started on port: ${process.env.PORT}`);
}); });
// if (global.gc) { // if (global.gc) {
// console.log(">> Starting Garbage Collector..."); // console.log(">> Starting Garbage Collector...");
// global.gc(); // global.gc();
@ -33,96 +38,83 @@ initIO(server);
gracefulShutdown(server); gracefulShutdown(server);
(async () => { (async () => {
console.log("os.tmpdir(): ", os.tmpdir());
console.log('os.tmpdir(): ', os.tmpdir()) loadSettings();
let whatsapps: any = await Whatsapp.findAll({ attributes: ['id', 'url'] }) let whatsapps: any = await Whatsapp.findAll({ attributes: ["id", "url"] });
// console.log('whatsapps: ', whatsapps) // console.log('whatsapps: ', whatsapps)
if (whatsapps && whatsapps.length > 0) { if (whatsapps && whatsapps.length > 0) {
for (let i = 0; i < whatsapps.length; i++) { for (let i = 0; i < whatsapps.length; i++) {
try { try {
console.log(
`API URL: ${whatsapps[i].dataValues.url}/api/connection/status`
);
console.log(`API URL: ${whatsapps[i].dataValues.url}/api/connection/status`) const response = await axios.get(
`${whatsapps[i].dataValues.url}/api/connection/status`,
{}
);
const response = await axios.get(`${whatsapps[i].dataValues.url}/api/connection/status`, {}); console.log(`-------> Response: ${response.data.data}`);
console.log(`-------> Response: ${response.data.data}`)
if (!response) { if (!response) {
throw new Error('Response null'); throw new Error("Response null");
} }
if (response.data.data && response.data.data == 'CONNECTED') { if (response.data.data && response.data.data == "CONNECTED") {
await whatsapps[i].update({ status: 'CONNECTED' }); await whatsapps[i].update({ status: "CONNECTED" });
} }
} catch (error: any) { } catch (error: any) {
await whatsapps[i].update({ status: "OPENING" });
await whatsapps[i].update({ status: 'OPENING' }); console.log(
`There was an error on try acess the api sessions ${whatsapps[i].dataValues.url}`
console.log(`There was an error on try acess the api sessions ${whatsapps[i].dataValues.url}`) );
} }
await new Promise(f => setTimeout(f, 100)); await new Promise(f => setTimeout(f, 100));
} }
} }
if (process.env.CACHE) { if (process.env.CACHE) {
const cacheLength = await cacheSize();
const cacheLength = await cacheSize() console.log("cacheSize: ", cacheLength);
console.log('cacheSize: ', cacheLength)
if (cacheLength == 0) { if (cacheLength == 0) {
console.log('Loading from cache...') console.log("Loading from cache...");
await flushCache() await flushCache();
await loadContactsCache() await loadContactsCache();
await loadTicketsCache() await loadTicketsCache();
} }
await loadSchedulesCache() await loadSchedulesCache();
// await loadWhatsappCache() // await loadWhatsappCache()
} }
delRestoreControllFile() delRestoreControllFile();
})() })();
setTimeout(async () => { setTimeout(async () => {
const io = getIO(); const io = getIO();
console.log('Triggered socket!') console.log("Triggered socket!");
let users = await User.findAll({ raw: true, attributes: ["id"], }) let users = await User.findAll({ raw: true, attributes: ["id"] });
if (users && users.length > 0) { if (users && users.length > 0) {
for (let i = 0; i < users.length; i++) { for (let i = 0; i < users.length; i++) {
io.emit("reload_page", { io.emit("reload_page", {
action: "update", action: "update",
userId: users[i].id userId: users[i].id
}); });
console.log('USER ID: ', users[i].id) console.log("USER ID: ", users[i].id);
await new Promise(f => setTimeout(f, 100)); await new Promise(f => setTimeout(f, 100));
} }
} }
}, 5000);
}, 5000)

View File

@ -7,6 +7,7 @@ import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import ShowTicketService from "./ShowTicketService"; import ShowTicketService from "./ShowTicketService";
import AppError from "../../errors/AppError"; import AppError from "../../errors/AppError";
import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber"; import ListWhatsAppsNumber from "../WhatsappService/ListWhatsAppsNumber";
import { getSettingValue } from "../../helpers/WhaticketSettings";
const FindOrCreateTicketService = async ( const FindOrCreateTicketService = async (
contact: Contact, contact: Contact,
@ -17,16 +18,7 @@ const FindOrCreateTicketService = async (
try { try {
let ticket; let ticket;
if (1 == 1 + 1) { if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id
}
});
} else {
let whats = await ListWhatsAppsNumber(whatsappId); let whats = await ListWhatsAppsNumber(whatsappId);
ticket = await Ticket.findOne({ ticket = await Ticket.findOne({
@ -38,6 +30,15 @@ const FindOrCreateTicketService = async (
whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) } whatsappId: { [Op.in]: whats.whatsapps.map((w: any) => w.id) }
} }
}); });
} else {
ticket = await Ticket.findOne({
where: {
status: {
[Op.or]: ["open", "pending", "queueChoice"]
},
contactId: groupContact ? groupContact.id : contact.id
}
});
} }
const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId); const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId);

File diff suppressed because it is too large Load Diff

View File

@ -198,6 +198,34 @@ const Settings = () => {
</Paper> </Paper>
</Container> </Container>
</div> </div>
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Paper className={classes.paper}>
<Typography variant="body1">
Contato conversar com whatsapps distintos no omnihit
</Typography>
<Select
margin="dense"
variant="outlined"
native
id="oneContactChatWithManyWhats-setting"
name="oneContactChatWithManyWhats"
value={
settings &&
settings.length > 0 &&
getSettingValue('oneContactChatWithManyWhats')
}
className={classes.settingOption}
onChange={handleChangeSetting}
>
<option value="enabled">Ativado</option>
<option value="disabled">Desativado</option>
</Select>
</Paper>
</Container>
</div>
</div> </div>
)} )}
/> />