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

View File

@ -63,6 +63,7 @@ import endPointQuery from "../helpers/old_EndPointQuery";
import Contact from "../models/Contact";
import BotIsOnQueue from "../helpers/BotIsOnQueue";
import { setMessageAsRead } from "../helpers/SetMessageAsRead";
import { getSettingValue } from "../helpers/WhaticketSettings";
export const index = async (req: Request, res: Response): Promise<Response> => {
const {
@ -242,13 +243,7 @@ export const update = async (
let ticketData: TicketData = req.body;
// console.log('ticketData: ', ticketData)
// console.log('ticketData.transfer', ticketData.transfer)
// return res.send()
if (1 == 1 + 1) {
} else {
if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
if (ticketData.transfer) {
const defaultWhatsapp: any = await GetDefaultWhatsApp(
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 Ticket from "../models/Ticket";
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber";
import { getSettingValue } from "./WhaticketSettings";
const CheckContactOpenTickets = async (
contactId: number,
@ -9,11 +10,7 @@ const CheckContactOpenTickets = async (
): Promise<void> => {
let ticket;
if (1 == 1 + 1) {
ticket = await Ticket.findOne({
where: { contactId, status: { [Op.or]: ["open", "pending"] } }
});
} else {
if (getSettingValue("oneContactChatWithManyWhats")?.value == "enabled") {
let whats = await ListWhatsAppsNumber(whatsappId);
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) {

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 { delRestoreControllFile } from "./helpers/RestoreControll";
import "./helpers/SchedulingNotifySendMessage"
import "./helpers/SchedulingNotifySendMessage";
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, () => {
logger.info(`Server started on port: ${process.env.PORT}`);
});
// if (global.gc) {
// console.log(">> Starting Garbage Collector...");
// global.gc();
@ -33,96 +38,83 @@ initIO(server);
gracefulShutdown(server);
(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)
if (whatsapps && whatsapps.length > 0) {
for (let i = 0; i < whatsapps.length; i++) {
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) {
throw new Error('Response null');
throw new Error("Response null");
}
if (response.data.data && response.data.data == 'CONNECTED') {
await whatsapps[i].update({ status: 'CONNECTED' });
if (response.data.data && response.data.data == "CONNECTED") {
await whatsapps[i].update({ status: "CONNECTED" });
}
} 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));
}
}
if (process.env.CACHE) {
const cacheLength = await cacheSize();
const cacheLength = await cacheSize()
console.log('cacheSize: ', cacheLength)
console.log("cacheSize: ", cacheLength);
if (cacheLength == 0) {
console.log('Loading from cache...')
await flushCache()
await loadContactsCache()
await loadTicketsCache()
console.log("Loading from cache...");
await flushCache();
await loadContactsCache();
await loadTicketsCache();
}
await loadSchedulesCache()
await loadSchedulesCache();
// await loadWhatsappCache()
}
delRestoreControllFile()
})()
delRestoreControllFile();
})();
setTimeout(async () => {
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) {
for (let i = 0; i < users.length; i++) {
io.emit("reload_page", {
action: "update",
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));
}
}
}, 5000)
}, 5000);

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -198,6 +198,34 @@ const Settings = () => {
</Paper>
</Container>
</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>
)}
/>