From 3980814c5e2792b463d8ea39feba58b445ba75ff Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 15 Dec 2022 19:20:33 -0300 Subject: [PATCH 1/4] =?UTF-8?q?Adi=C3=A7=C3=A3o=20de=20tradu=C3=A7=C3=A3o?= =?UTF-8?q?=20para=20novos=20recursos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/DashboardUser/TableUser.jsx | 15 +++--- .../src/components/Report/MTable/index.js | 4 +- frontend/src/components/Report/Modal/index.js | 8 ++-- frontend/src/layout/MainListItems.js | 2 +- frontend/src/pages/Report/index.js | 33 +++++++------ frontend/src/pages/SchedulesReminder/index.js | 31 +++++++----- frontend/src/translate/languages/en.js | 47 ++++++++++++++++++- frontend/src/translate/languages/es.js | 45 ++++++++++++++++++ frontend/src/translate/languages/pt.js | 46 ++++++++++++++++++ 9 files changed, 193 insertions(+), 38 deletions(-) diff --git a/frontend/src/components/DashboardUser/TableUser.jsx b/frontend/src/components/DashboardUser/TableUser.jsx index f91788e..e744d46 100644 --- a/frontend/src/components/DashboardUser/TableUser.jsx +++ b/frontend/src/components/DashboardUser/TableUser.jsx @@ -26,6 +26,8 @@ import ErrorIcon from "@material-ui/icons/Error"; import RemoveCircleIcon from "@material-ui/icons/RemoveCircle"; import PowerSettingsNewIcon from "@material-ui/icons/PowerSettingsNew"; +import { i18n } from "../../translate/i18n"; + const TableUser = ({ classes, usersOnlineInfo, logout }) => { const [search, setSearch] = React.useState(""); const [filterStatus, setFilterStatus] = React.useState(null); @@ -48,7 +50,8 @@ const TableUser = ({ classes, usersOnlineInfo, logout }) => { color="primary" style={{ marginBottom: "16px" }} > - Lista de Usuários + + {i18n.t("dashboard.table_users.title")} @@ -84,11 +87,11 @@ const TableUser = ({ classes, usersOnlineInfo, logout }) => { - Nome - Em Atendimento/Finalizado(s) - abertos Por Fila - Fechados Por Fila - Tempo Online + {i18n.t("dashboard.table_users.column0")} + {i18n.t("dashboard.table_users.column1")} + {i18n.t("dashboard.table_users.column2")} + {i18n.t("dashboard.table_users.column3")} + {i18n.t("dashboard.table_users.column4")} Ações diff --git a/frontend/src/components/Report/MTable/index.js b/frontend/src/components/Report/MTable/index.js index 198add1..76a140a 100644 --- a/frontend/src/components/Report/MTable/index.js +++ b/frontend/src/components/Report/MTable/index.js @@ -10,6 +10,8 @@ import chat from '@material-ui/icons/Chat'; import React from 'react'; +import { i18n } from '../../../translate/i18n'; + const MTable = (props) => { const tableRef = React.useRef(); @@ -79,7 +81,7 @@ const MTable = (props) => { if (props.hasChild) { render() } diff --git a/frontend/src/components/Report/Modal/index.js b/frontend/src/components/Report/Modal/index.js index bb7fadb..f4d7f96 100644 --- a/frontend/src/components/Report/Modal/index.js +++ b/frontend/src/components/Report/Modal/index.js @@ -10,23 +10,25 @@ import DialogTitle from '@mui/material/DialogTitle'; //import DataGridTable from '../Table'; import MTable from "../MTable"; +import { i18n } from '../../../translate/i18n'; + import ExportCSV from '../ExportCSV' //import { margin } from '@mui/system'; let columns = [ { - title: 'Atendente/Cliente', + title: `${i18n.t("reports.listColumns.column2_1")}`, field: 'fromMe', }, { - title: 'Mensagem', + title: `${i18n.t("reports.listColumns.column0_8")}`, field: 'body', //cellStyle: {whiteSpace: 'nowrap'}, }, - { title: 'Criado', field: 'createdAt' } + { title: `${i18n.t("reports.listColumns.column1_7")}`, field: 'createdAt' } /*cellStyle: { backgroundColor: '#039be5', diff --git a/frontend/src/layout/MainListItems.js b/frontend/src/layout/MainListItems.js index 0dfe6b9..1455c45 100644 --- a/frontend/src/layout/MainListItems.js +++ b/frontend/src/layout/MainListItems.js @@ -88,7 +88,7 @@ const MainListItems = (props) => { primary={i18n.t("mainDrawer.listItems.contacts")} icon={} /> - } /> + } /> { @@ -630,12 +633,12 @@ const Report = () => { - { + { return { 'value': obj.id, 'label': obj.name } })} /> - - + + @@ -672,7 +675,7 @@ const Report = () => { handleScroll={handleScroll} - table_title={'Atendimento por atendentes'} /> + table_title={i18n.t("reports.listTitles.title1_1")} /> @@ -689,7 +692,7 @@ const Report = () => { }} - title="Usuários online/offline" + title={i18n.t("reports.listTitles.title3_1")} columns={ [ @@ -724,8 +727,8 @@ const Report = () => { }, { title: 'Tempo online', field: 'sumOnlineTime.sum' }, - { title: 'Data inicio', field: 'startDate' }, - { title: 'Data fim', field: 'endDate' }, + { title: `${i18n.t("reports.dateStart")}`, field: 'startDate' }, + { title: `${i18n.t("reports.dateStart")}`, field: 'endDate' }, { title: 'Em atendimento', field: 'sumOpen.count' }, { title: 'Finalizado', field: 'sumClosed.count' }, diff --git a/frontend/src/pages/SchedulesReminder/index.js b/frontend/src/pages/SchedulesReminder/index.js index 1a7ee3c..c26d8dd 100644 --- a/frontend/src/pages/SchedulesReminder/index.js +++ b/frontend/src/pages/SchedulesReminder/index.js @@ -37,7 +37,7 @@ import { toast } from "react-toastify"; import toastError from "../../errors/toastError"; import ConfirmationModal from "../../components/ConfirmationModal"; - +import { i18n } from "../../translate/i18n"; const reducerQ = (state, action) => { @@ -465,8 +465,8 @@ const SchedulesReminder = () => { - - + + {/* */} @@ -501,17 +501,26 @@ const SchedulesReminder = () => { imagem de perfil do whatsapp }, - { title: 'Nome', field: 'ticket.contact.name' }, - { title: 'Contato', field: 'ticket.contact.number' }, - { title: 'Lemb/Agen', field: 'scheduleReminder' }, - { title: 'Envio', field: 'schedulingTime' }, - { title: 'Data', field: 'schedulingDate' }, - { title: 'Mensagem', field: 'message', width: "80%" }, + { title: `${i18n.t("reports.listColumns.column0_2")}`, field: 'ticket.contact.profilePicUrl', render: rowData => imagem de perfil do whatsapp }, + { title: `${i18n.t("reports.listColumns.column0_3")}`, field: 'ticket.contact.name' }, + { title: `${i18n.t("reports.listColumns.column0_4")}`, field: 'ticket.contact.number' }, + { title: `${i18n.t("reports.listColumns.column0_5")}`, field: 'scheduleReminder' }, + { title: `${i18n.t("reports.listColumns.column0_6")}`, field: 'schedulingTime' }, + { title: `${i18n.t("reports.listColumns.column0_7")}`, field: 'schedulingDate' }, + { title: `${i18n.t("reports.listColumns.column0_8")}`, field: 'message', width: "80%" }, ] } diff --git a/frontend/src/translate/languages/en.js b/frontend/src/translate/languages/en.js index 6484c5c..2ec83fa 100644 --- a/frontend/src/translate/languages/en.js +++ b/frontend/src/translate/languages/en.js @@ -49,6 +49,16 @@ const messages = { closed: { title: "Closed" } + }, + + table_users:{ + title: 'User List', + column0: 'Name', + column1: 'In Service/Finished', + column2: 'Open by Queue', + column3: 'Closed by Queue', + column4: 'Online time', + column4: 'Actions', } }, connections: { @@ -283,7 +293,8 @@ const messages = { queues: "Queues", administration: "Administration", users: "Users", - settings: "Settings", + settings: "Settings", + schedules: "Schedules" }, appBar: { user: { @@ -291,6 +302,40 @@ const messages = { logout: "Logout", }, }, + }, + reports: { + listTitles: { + title0_1: "Reminders/Schedulings", + title1_1: "Calls by attendants", + title2_1: "Whatsapp chat", + title3_1: "Users online/offline" + }, + listColumns:{ + column0_1: 'Actions', + column0_2: 'Pic', + column0_3: 'Name', + column0_4: 'Contact', + column0_5: 'Remin/Sched', + column0_6: 'Send', + column0_7: 'Date', + column0_8: 'Message', + + column1_1: 'Store', + column1_2: 'Attendant', + column1_5: 'Subject', + column1_6: 'Status', + column1_7: 'Created', + column1_8: 'Updated', + column1_9: 'Closing status', + + column2_1: 'Attendant/Client', + }, + search: 'Number/Name...', + dateStart: 'Start date', + dateEnd: 'End date', + user: 'User' + + }, notifications: { noTickets: "No notifications.", diff --git a/frontend/src/translate/languages/es.js b/frontend/src/translate/languages/es.js index 2e27e49..caad541 100644 --- a/frontend/src/translate/languages/es.js +++ b/frontend/src/translate/languages/es.js @@ -50,6 +50,17 @@ const messages = { closed: { title: "Finalizado" } + }, + + table_users:{ + + title: 'Lista de usuarios', + column0: 'Nombre', + column1: 'En servicio/Terminado(S)', + column2: 'Abrir por cola', + column3: 'Cerrado por cola', + column4: 'Tiempo Online', + column4: 'Actions', } }, connections: { @@ -288,6 +299,7 @@ const messages = { administration: "Administración", users: "Usuarios", settings: "Configuración", + schedules: "Recordatorio" }, appBar: { user: { @@ -296,6 +308,39 @@ const messages = { }, }, }, + reports: { + listTitles: { + title0_1: "Recordatorios/Programación", + title1_1: "Llamadas de asistentes", + title2_1: "Chat de whatsapp", + title3_1: "Usuarios online/offline" + }, + listColumns:{ + column0_1: 'Acción', + column0_2: 'Pic', + column0_3: 'Nombre', + column0_4: 'Contacto', + column0_5: 'Record/Progr', + column0_6: 'Envío', + column0_7: 'Fecha', + column0_8: 'Mensaje', + + column1_1: 'Almacenar', + column1_2: 'Secretario', + column1_5: 'Tema', + column1_6: 'Status', + column1_7: 'Creado', + column1_8: 'Actualizado', + column1_9: 'Estado de cierre', + + column2_1: 'Secretario/Cliente', + }, + search: 'Número/Nombre...', + dateStart: 'Fecha de inicio', + dateEnd: 'Fecha final', + user: 'Usuario' + + }, notifications: { noTickets: "Sin notificaciones.", }, diff --git a/frontend/src/translate/languages/pt.js b/frontend/src/translate/languages/pt.js index a92ab11..c6e6934 100644 --- a/frontend/src/translate/languages/pt.js +++ b/frontend/src/translate/languages/pt.js @@ -49,6 +49,16 @@ const messages = { closed: { title: "Finalizado" } + }, + + table_users:{ + title: 'Lista De Usuários', + column0: 'Nome', + column1: 'Em Atendimento/Finalizado(S)', + column2: 'Abertos Por Fila', + column3: 'Fechados Por Fila', + column4: 'Tempo Online', + column4: 'Ações', } }, connections: { @@ -288,6 +298,7 @@ const messages = { administration: "Administração", users: "Usuários", settings: "Configurações", + schedules: "Lembretes" }, appBar: { user: { @@ -295,6 +306,41 @@ const messages = { logout: "Sair", }, }, + }, + reports: { + listTitles: { + title0_1: "Lembretes/Agendamentos", + title1_1: "Atendimento por atendentes", + title2_1: "Chat do atendimento pelo Whatsapp", + title3_1: "Usuários online/offline" + }, + listColumns:{ + column0_1: 'Ações', + column0_2: 'Foto', + column0_3: 'Nome', + column0_4: 'Contato', + column0_5: 'Lemb/Agen', + column0_6: 'Envio', + column0_7: 'Data', + column0_8: 'Mensagem', + + column1_1: 'Unidade', + column1_2: 'Atendente', + column1_5: 'Assunto', + column1_6: 'Status', + column1_7: 'Criado', + column1_8: 'Atualizado', + column1_9: 'Status de encerramento', + + column2_1: 'Atendente/Cliente', + + }, + search: 'Numer/Nome...', + dateStart: 'Data início', + dateEnd: 'Data fim', + user: 'Usuário' + + }, notifications: { noTickets: "Nenhuma notificação.", From bc4712362def38078d58d24fe7911f1f034cf1c3 Mon Sep 17 00:00:00 2001 From: adriano Date: Sun, 18 Dec 2022 11:45:41 -0300 Subject: [PATCH 2/4] =?UTF-8?q?Cria=C3=A7=C3=A3o=20parcial=20de=20cache=20?= =?UTF-8?q?para=20consultar=20lembretes=20para=20envio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/SchedulingNotifyController.ts | 57 +++-- backend/src/helpers/SchedulingNotifyCache.ts | 221 ++++++++++++++++++ .../helpers/SchedulingNotifySendMessage.ts | 94 ++++++-- backend/src/server.ts | 8 +- .../CreateSchedulingNotifyService.ts | 6 +- .../ListSchedulingNotifyService.ts | 131 ++++++----- .../components/DashboardUser/TableUser.jsx | 2 +- frontend/src/translate/languages/en.js | 2 +- frontend/src/translate/languages/es.js | 2 +- frontend/src/translate/languages/pt.js | 2 +- 10 files changed, 404 insertions(+), 121 deletions(-) create mode 100644 backend/src/helpers/SchedulingNotifyCache.ts diff --git a/backend/src/controllers/SchedulingNotifyController.ts b/backend/src/controllers/SchedulingNotifyController.ts index 6ca142b..11cb315 100644 --- a/backend/src/controllers/SchedulingNotifyController.ts +++ b/backend/src/controllers/SchedulingNotifyController.ts @@ -1,18 +1,11 @@ import { Request, Response } from "express"; import AppError from "../errors/AppError"; -import { getIO } from "../libs/socket"; -import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService"; -import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService"; -import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService"; - -// const test = await ListSchedulingNotifyContactService('5517988310949','2022-03-18','2022-03-19'); -// const test = await ListSchedulingNotifyContactService('','2022-03-18','2022-03-19'); -// const test = await ListSchedulingNotifyContactService('5517988310949'); -// - - - - +import { getIO } from "../libs/socket"; +import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService"; +import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService"; +import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService"; +import ShowSchedulingNotifyService from "../services/SchedulingNotifyServices/ShowSchedulingNotifyService"; +import { deleteScheduleByTicketIdCache } from "../helpers/SchedulingNotifyCache"; type IndexQuery = { @@ -21,13 +14,13 @@ type IndexQuery = { endDate: string; }; - -export const reportScheduleNotifyByDateStartDateEnd = async (req: Request, res: Response): Promise => { - - const { contactNumber, startDate, endDate } = req.query as IndexQuery - const data_query = await ListSchedulingNotifyContactService(contactNumber, startDate, endDate); +export const reportScheduleNotifyByDateStartDateEnd = async (req: Request, res: Response): Promise => { + + const { contactNumber, startDate, endDate } = req.query as IndexQuery + + const data_query = await ListSchedulingNotifyContactService(contactNumber, startDate, endDate); // console.group('DATA QUERY SCHEDULE:\n',data_query) @@ -36,23 +29,23 @@ export const reportScheduleNotifyByDateStartDateEnd = async (req: Request, res: }; -export const createOrUpdateScheduleNotify = async (req: Request, res: Response): Promise => { - - const scheduleData = req.body; +export const createOrUpdateScheduleNotify = async (req: Request, res: Response): Promise => { + + const scheduleData = req.body; + - const schedulingNotifyCreate = await CreateSchedulingNotifyService( { schedulingNotifyId: scheduleData.schedulingNotifyId, ticketId: scheduleData.ticketId, - statusChatEndId: scheduleData.statusChatEndId, - schedulingDate: scheduleData.schedulingDate, + statusChatEndId: scheduleData.statusChatEndId, + schedulingDate: scheduleData.schedulingDate, schedulingTime: scheduleData.schedulingTime, - message: scheduleData.message + message: scheduleData.message } - ) - + ) + // console.group(':::::::::::::::::: DATA schedulingNotifyCreate:\n',schedulingNotifyCreate) // const io = getIO(); // io.emit("schedulingNotify", {action: "update", schedulingNotifyCreate }); @@ -61,13 +54,17 @@ export const createOrUpdateScheduleNotify = async (req: Request, res: Response): }; -export const remove = async ( req: Request, res: Response ): Promise => { +export const remove = async (req: Request, res: Response): Promise => { + - const { scheduleId } = req.params; - await DeleteSchedulingNotifyService(scheduleId); + let schedule: any = await ShowSchedulingNotifyService(scheduleId) + + await deleteScheduleByTicketIdCache(schedule.ticketId) + + await DeleteSchedulingNotifyService(scheduleId); return res.status(200).send(); }; diff --git a/backend/src/helpers/SchedulingNotifyCache.ts b/backend/src/helpers/SchedulingNotifyCache.ts new file mode 100644 index 0000000..b95ef36 --- /dev/null +++ b/backend/src/helpers/SchedulingNotifyCache.ts @@ -0,0 +1,221 @@ + +import Redis from 'ioredis' +import { type } from 'os' +const unflatten = require('flat').unflatten +var flatten = require('flat') +import ListContactsServiceCache from "../services/ContactServices/ListContactsServiceCache" +import { redisConn } from './TicketCache' + +import SchedulingNotify from '../models/SchedulingNotify' + +import { format } from "date-fns"; +import ptBR from 'date-fns/locale/pt-BR'; + +import { escapeCharCache } from './ContactsCache' + + +const deleteScheduleByTicketIdCache = async (ticketId: string | number) => { + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return + + const schedule_cache: any = await redis.hgetall(`schedule:${ticketId}`) + + try { + if (schedule_cache && Object.keys(schedule_cache).length > 0) { + + await redis.del(`schedule:${ticketId}`) + + console.log(`Schedule cache ticketId ${schedule_cache.ticketId} deleted!`) + } + else { + console.log('SCHEDULE CACHE NOT FOUND!') + } + } catch (error) { + console.log(`There was an error on deleteScheduleByTicketIdCache: ${error}`) + } + + redis.quit() +} + + + + + +const updateScheduleCacheByTicketId = async (scheduleNotify: any) => { + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return + + const pipeline = redis.pipeline() + + let entries = Object.entries(scheduleNotify) + + entries.forEach((e: any) => { + pipeline.hset(`schedule:${scheduleNotify.ticketId}`, e[0], e[1]) + }) + + await pipeline.exec(() => { console.log("schedule Key/value inserted/updated") }); + + redis.quit() + +} + + + + +const createSchedulingNotifyCache = async (scheduleNotify: any) => { + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return + + let date_time: any = format(new Date(scheduleNotify.schedulingTime), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }).split(' ') + + delete scheduleNotify.schedulingTime + delete scheduleNotify.updatedAt + delete scheduleNotify.createdAt + delete scheduleNotify.schedulingDate + + console.log('created date_time: ', date_time) + + scheduleNotify.date = date_time[0] + scheduleNotify.date_escaped = escapeCharCache(date_time[0]) + scheduleNotify.hour = date_time[1].split(':')[0] + scheduleNotify.minute = date_time[1].split(':')[1] + + await redis.hmset(`schedule:${scheduleNotify.ticketId}`, scheduleNotify); + + console.log(`${scheduleNotify.length} SCHEDULE NOTIFY INSERTED IN CACHE!`) + + redis.quit() + +} + + +async function searchScheduleCache(date: string, hour: number | string, minute: number | string) { + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return null + + date = escapeCharCache(date).trim() + + console.log('kkkkkkkkkkk date: ', date) + + const response: any = await redis.call('FT.SEARCH', 'idx_schedule', `(@date_escaped:${date}) (@hour:${hour}) (@minute:${minute})`) + redis.quit() + + + if (response.length === 1) { + return [] + } + + const results: any = [] + + for (let n = 2; n < response.length; n += 2) { + const result: any = {} + const fieldNamesAndValues = response[n] + + for (let m = 0; m < fieldNamesAndValues.length; m += 2) { + const k = fieldNamesAndValues[m] + const v = fieldNamesAndValues[m + 1] + result[k] = v + } + + results.push(result) + } + + return results +} + +const loadSchedulesCache = async () => { + + await createScheduleIndexCache('idx_schedule') + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return + + let schedules: any = await SchedulingNotify.findAll({ raw: true, attributes: ["id", "statusChatEndId", "ticketId", "schedulingTime", "message"] }); + + // console.log('SCHEDULE NOTIFY CACHE2: ', schedules) + + + const pipeline = redis.pipeline() + + for (let i = 0; i < schedules.length; i++) { + + let date_time: any = format(new Date(schedules[i].schedulingTime), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }).split(' ') + + delete schedules[i].schedulingTime + + console.log('date_time: ', date_time) + + schedules[i].date = date_time[0] + schedules[i].date_escaped = escapeCharCache(date_time[0]) + + schedules[i].hour = date_time[1].split(':')[0] + schedules[i].minute = date_time[1].split(':')[1] + + pipeline.hmset(`schedule:${schedules[i].ticketId}`, schedules[i]); + } + + await pipeline.exec(() => { console.log(`${schedules.length} SCHEDULES NOTIFY INSERTED IN CACHE!`) }); + + redis.quit() + + + // let test = await searchScheduleCache('2022-12-16', '18', '30') + + // console.log('--------------> TEST: ', test) + +} + +const createScheduleIndexCache = async (hashIndex: string) => { + + const redis: any = await redisConn(); + + if (!redis) return + + if (redis.status !== 'connect') return + + try { + + const lst_index_redis: any = await redis.call('FT._LIST') + + if (lst_index_redis.includes(hashIndex)) { + console.log('entrou...') + await redis.call('FT.DROPINDEX', hashIndex) + } + + const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'schedule:', 'SCHEMA', 'id', 'TEXT', 'SORTABLE', 'date_escaped', 'TEXT', 'SORTABLE', 'hour', 'TEXT', 'SORTABLE', 'minute', 'TEXT', 'SORTABLE') + + console.log('Schedule index created: ', response) + + } catch (error) { + console.log('There was an error on createScheduleIndexCache: ', error) + } + + redis.quit() +} + +export { + loadSchedulesCache, + searchScheduleCache, + updateScheduleCacheByTicketId, + createSchedulingNotifyCache, + deleteScheduleByTicketIdCache +} \ No newline at end of file diff --git a/backend/src/helpers/SchedulingNotifySendMessage.ts b/backend/src/helpers/SchedulingNotifySendMessage.ts index 44c8b54..ea64dae 100644 --- a/backend/src/helpers/SchedulingNotifySendMessage.ts +++ b/backend/src/helpers/SchedulingNotifySendMessage.ts @@ -8,6 +8,8 @@ import { getIO } from "../libs/socket"; import ListWhatsAppsService from "../services/WhatsappService/ListWhatsAppsService"; import path from "path"; import { convertBytes } from "./ConvertBytes"; +import { deleteScheduleByTicketIdCache } from "./SchedulingNotifyCache"; +import SchedulingNotify from "../models/SchedulingNotify"; const fastFolderSize = require('fast-folder-size') const { promisify } = require('util') @@ -15,6 +17,8 @@ const fs = require('fs') const { exec } = require("child_process"); +let _fifo: any + let scheduler_monitor: any; let timeInterval = 5 @@ -36,23 +40,46 @@ const monitor = async () => { try { - // const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); + const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); - // // console.log('schedulingNotifies: ',schedulingNotifies) + // console.log('schedulingNotifies: ',schedulingNotifies) - // if (schedulingNotifies && schedulingNotifies.length > 0) { + if (schedulingNotifies && schedulingNotifies.length > 0) { - // const ticket = await ShowTicketService(schedulingNotifies[0].ticketId); + console.log('ENTROU NA DATA schedulingNotifies: ', schedulingNotifies) - // SetTicketMessagesAsRead(ticket); - // await SendWhatsAppMessage({ - // body: schedulingNotifies[0].message, ticket - // }); + for (let i = 0; i < schedulingNotifies.length; i++) { - // DeleteSchedulingNotifyService(schedulingNotifies[0].id) - // } + const ticket = await ShowTicketService(schedulingNotifies[i].ticketId); + + SetTicketMessagesAsRead(ticket); + + await SendWhatsAppMessage({ + body: schedulingNotifies[i].message, ticket + }); + + await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId) + + await DeleteSchedulingNotifyService(schedulingNotifies[i].id) + + + } + + // const ticket = await ShowTicketService(schedulingNotifies[0].ticketId); + + // SetTicketMessagesAsRead(ticket); + + // await SendWhatsAppMessage({ + // body: schedulingNotifies[0].message, ticket + // }); + + // await deleteScheduleByTicketIdCache(schedulingNotifies[0].ticketId) + + // await DeleteSchedulingNotifyService(schedulingNotifies[0].id) + + } exec("df -h /", (error: any, stdout: any, stderr: any) => { @@ -66,9 +93,9 @@ const monitor = async () => { return; } - stdout = stdout.split(/\r?\n/) - stdout = stdout[1].trim().split(/\s+/) - + stdout = stdout.split(/\r?\n/) + stdout = stdout[1].trim().split(/\s+/) + // DISK SPACE MONITORING const io = getIO(); io.emit("diskSpaceMonit", { @@ -90,20 +117,20 @@ const monitor = async () => { 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(); @@ -132,27 +159,46 @@ const monitor = async () => { } catch (error) { console.log('>>> SchedulingNotifiySendMessage.ts error: ', error) - stopSchedulingMonitor() - startSchedulingMonitor(timeInterval) } }; -export const startSchedulingMonitor = async (mileseconds: number) => { +const SchedulingNotifySendMessage = async () => { - timeInterval = mileseconds + try { + clearInterval(_fifo); - scheduler_monitor = setInterval(monitor, mileseconds) + await monitor() + } catch (error) { + console.log('error on SchedulingNotifySendMessage: ', error) + } + finally { + _fifo = setInterval(SchedulingNotifySendMessage, 5000); + } } +_fifo = setInterval(SchedulingNotifySendMessage, 5000); -export const stopSchedulingMonitor = async () => { - clearInterval(scheduler_monitor) +module.exports = SchedulingNotifySendMessage -} + +// export const startSchedulingMonitor = async (mileseconds: number) => { + +// timeInterval = mileseconds + +// scheduler_monitor = setInterval(monitor, mileseconds) + +// } + + +// export const stopSchedulingMonitor = async () => { + +// clearInterval(scheduler_monitor) + +// } diff --git a/backend/src/server.ts b/backend/src/server.ts index 4602c3d..86b2cb4 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -4,14 +4,15 @@ import { initIO } from "./libs/socket"; import { logger } from "./utils/logger"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; -import { startSchedulingMonitor } from "./helpers/SchedulingNotifySendMessage" -import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor" +import "./helpers/SchedulingNotifySendMessage" +import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor" import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache' import { loadContactsCache } from './helpers/ContactsCache' import { loadWhatsappCache } from './helpers/WhatsCache' import { delRestoreControllFile } from "./helpers/RestoreControll"; import { createSessionDir } from "./helpers/CreateSessionDir"; +import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache"; const server = app.listen(process.env.PORT, () => { logger.info(`Server started on port: ${process.env.PORT}`); @@ -33,6 +34,7 @@ gracefulShutdown(server); await loadContactsCache() await loadTicketsCache() await loadWhatsappCache() + await loadSchedulesCache() } @@ -40,6 +42,6 @@ gracefulShutdown(server); createSessionDir() delRestoreControllFile() -startSchedulingMonitor(5000) + startWhoIsOnlineMonitor(3000) diff --git a/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts b/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts index 1315d5b..6c9d0e8 100644 --- a/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts +++ b/backend/src/services/SchedulingNotifyServices/CreateSchedulingNotifyService.ts @@ -1,4 +1,5 @@ import AppError from "../../errors/AppError"; +import { createSchedulingNotifyCache } from "../../helpers/SchedulingNotifyCache"; import SchedulingNotify from "../../models/SchedulingNotify"; @@ -55,10 +56,11 @@ const CreateSchedulingNotifyService = async ({ schedulingTime, message - }) - + }) } + await createSchedulingNotifyCache(JSON.parse(JSON.stringify(schedulingNotify))) + return schedulingNotify } diff --git a/backend/src/services/SchedulingNotifyServices/ListSchedulingNotifyService.ts b/backend/src/services/SchedulingNotifyServices/ListSchedulingNotifyService.ts index 1c42641..c88fd3f 100644 --- a/backend/src/services/SchedulingNotifyServices/ListSchedulingNotifyService.ts +++ b/backend/src/services/SchedulingNotifyServices/ListSchedulingNotifyService.ts @@ -1,68 +1,83 @@ import { Op, Sequelize } from "sequelize"; +import { searchScheduleCache } from "../../helpers/SchedulingNotifyCache"; import SchedulingNotify from "../../models/SchedulingNotify"; interface Request { - searchParam?: string; - pageNumber?: string; - } - - interface Response { - schedulingNotifies: SchedulingNotify[]; - count: number; - hasMore: boolean; - } - - const ListSchedulingNotifyService = async ({ - searchParam = "", - pageNumber = "1" - }: Request): Promise => { - // const whereCondition = { - // message: Sequelize.where( - - // Sequelize.fn("date", Sequelize.col("schedulingDate")), `${searchParam.toLowerCase().trim()}`, - - // ), - - // }; + searchParam?: string; + pageNumber?: string; +} - let date = searchParam.split(' ')[0] - let hour = searchParam.split(' ')[1].split(':')[0] - let minute = searchParam.split(' ')[1].split(':')[1] - - const whereCondition = { - [Op.and]: [ - { - "$schedulingTime$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingTime")), `${date.trim()}`) - }, - { - "$schedulingTime$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingTime")), `${hour.trim()}`) - }, - { - "$schedulingTime$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingTime")), `${minute.trim()}`) - } - ] - }; +interface Response { + schedulingNotifies: SchedulingNotify[]; + count: number; + hasMore: boolean; +} +const ListSchedulingNotifyService = async ({ + searchParam = "", + pageNumber = "1" +}: Request): Promise => { + // const whereCondition = { + // message: Sequelize.where( + + // Sequelize.fn("date", Sequelize.col("schedulingDate")), `${searchParam.toLowerCase().trim()}`, + + // ), + + // }; + + let date = searchParam.split(' ')[0] + let hour = searchParam.split(' ')[1].split(':')[0] + let minute = searchParam.split(' ')[1].split(':')[1] + + let fromCache = null + + fromCache = await searchScheduleCache(date, hour, minute) + + if (fromCache) { - const limit = 1; - const offset = limit * (+pageNumber - 1); - - const { count, rows: schedulingNotifies } = await SchedulingNotify.findAndCountAll({ - raw: true, - where: whereCondition, - limit, - offset, - order: [["id", "ASC"]] - }); - - const hasMore = count > offset + schedulingNotifies.length; - return { - schedulingNotifies, - count, - hasMore + schedulingNotifies: fromCache, + count: 0, + hasMore: false, }; + + } + + + const whereCondition = { + [Op.and]: [ + { + "$schedulingTime$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingTime")), `${date.trim()}`) + }, + { + "$schedulingTime$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingTime")), `${hour.trim()}`) + }, + { + "$schedulingTime$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingTime")), `${minute.trim()}`) + } + ] }; - - export default ListSchedulingNotifyService; - \ No newline at end of file + + + const limit = 1; + const offset = limit * (+pageNumber - 1); + + const { count, rows: schedulingNotifies } = await SchedulingNotify.findAndCountAll({ + raw: true, + where: whereCondition, + limit, + offset, + order: [["id", "ASC"]] + }); + + const hasMore = count > offset + schedulingNotifies.length; + + return { + schedulingNotifies, + count, + hasMore + }; +}; + +export default ListSchedulingNotifyService; diff --git a/frontend/src/components/DashboardUser/TableUser.jsx b/frontend/src/components/DashboardUser/TableUser.jsx index e744d46..66fc804 100644 --- a/frontend/src/components/DashboardUser/TableUser.jsx +++ b/frontend/src/components/DashboardUser/TableUser.jsx @@ -92,7 +92,7 @@ const TableUser = ({ classes, usersOnlineInfo, logout }) => { {i18n.t("dashboard.table_users.column2")} {i18n.t("dashboard.table_users.column3")} {i18n.t("dashboard.table_users.column4")} - Ações + {i18n.t("dashboard.table_users.column5")} diff --git a/frontend/src/translate/languages/en.js b/frontend/src/translate/languages/en.js index 2ec83fa..7410d89 100644 --- a/frontend/src/translate/languages/en.js +++ b/frontend/src/translate/languages/en.js @@ -58,7 +58,7 @@ const messages = { column2: 'Open by Queue', column3: 'Closed by Queue', column4: 'Online time', - column4: 'Actions', + column5: 'Actions', } }, connections: { diff --git a/frontend/src/translate/languages/es.js b/frontend/src/translate/languages/es.js index caad541..6e047b2 100644 --- a/frontend/src/translate/languages/es.js +++ b/frontend/src/translate/languages/es.js @@ -60,7 +60,7 @@ const messages = { column2: 'Abrir por cola', column3: 'Cerrado por cola', column4: 'Tiempo Online', - column4: 'Actions', + column5: 'Actions', } }, connections: { diff --git a/frontend/src/translate/languages/pt.js b/frontend/src/translate/languages/pt.js index c6e6934..ca12b50 100644 --- a/frontend/src/translate/languages/pt.js +++ b/frontend/src/translate/languages/pt.js @@ -58,7 +58,7 @@ const messages = { column2: 'Abertos Por Fila', column3: 'Fechados Por Fila', column4: 'Tempo Online', - column4: 'Ações', + column5: 'Ações', } }, connections: { From ad9cbafdf2a6786a6b5c75a55b6f5418e004501c Mon Sep 17 00:00:00 2001 From: adriano Date: Sun, 18 Dec 2022 13:56:45 -0300 Subject: [PATCH 3/4] =?UTF-8?q?Finaliza=C3=A7=C3=A3o=20da=20corre=C3=A7?= =?UTF-8?q?=C3=A3o=20do=20lembrete=20para=20usar=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/controllers/UserController.ts | 2 +- backend/src/helpers/SchedulingNotifyCache.ts | 4 +- .../helpers/SchedulingNotifySendMessage.ts | 51 ++---- backend/src/helpers/WhoIsOnlineMonitor.ts | 172 +++++++++++------- backend/src/server.ts | 25 ++- 5 files changed, 128 insertions(+), 126 deletions(-) diff --git a/backend/src/controllers/UserController.ts b/backend/src/controllers/UserController.ts index 89327f2..c41b912 100644 --- a/backend/src/controllers/UserController.ts +++ b/backend/src/controllers/UserController.ts @@ -94,7 +94,7 @@ export const store = async (req: Request, res: Response): Promise => { }); - await stopWhoIsOnlineMonitor() + // await stopWhoIsOnlineMonitor() await startWhoIsOnlineMonitor() return res.status(200).json(user); diff --git a/backend/src/helpers/SchedulingNotifyCache.ts b/backend/src/helpers/SchedulingNotifyCache.ts index b95ef36..0921724 100644 --- a/backend/src/helpers/SchedulingNotifyCache.ts +++ b/backend/src/helpers/SchedulingNotifyCache.ts @@ -109,9 +109,7 @@ async function searchScheduleCache(date: string, hour: number | string, minute: if (redis.status !== 'connect') return null - date = escapeCharCache(date).trim() - - console.log('kkkkkkkkkkk date: ', date) + date = escapeCharCache(date).trim() const response: any = await redis.call('FT.SEARCH', 'idx_schedule', `(@date_escaped:${date}) (@hour:${hour}) (@minute:${minute})`) redis.quit() diff --git a/backend/src/helpers/SchedulingNotifySendMessage.ts b/backend/src/helpers/SchedulingNotifySendMessage.ts index ea64dae..d46584d 100644 --- a/backend/src/helpers/SchedulingNotifySendMessage.ts +++ b/backend/src/helpers/SchedulingNotifySendMessage.ts @@ -41,18 +41,19 @@ const monitor = async () => { try { const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); - - // console.log('schedulingNotifies: ',schedulingNotifies) - - if (schedulingNotifies && schedulingNotifies.length > 0) { - - console.log('ENTROU NA DATA schedulingNotifies: ', schedulingNotifies) - + + if (schedulingNotifies && schedulingNotifies.length > 0) { for (let i = 0; i < schedulingNotifies.length; i++) { - const ticket = await ShowTicketService(schedulingNotifies[i].ticketId); + const ticket = await ShowTicketService(+schedulingNotifies[i].ticketId); + + await new Promise(f => setTimeout(f, 3000)); + + if(!ticket.queue){ + await ticket.update({status: 'open'}) + } SetTicketMessagesAsRead(ticket); @@ -62,23 +63,11 @@ const monitor = async () => { await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId) - await DeleteSchedulingNotifyService(schedulingNotifies[i].id) + await DeleteSchedulingNotifyService(schedulingNotifies[i].id) - } - - // const ticket = await ShowTicketService(schedulingNotifies[0].ticketId); - - // SetTicketMessagesAsRead(ticket); - - // await SendWhatsAppMessage({ - // body: schedulingNotifies[0].message, ticket - // }); - - // await deleteScheduleByTicketIdCache(schedulingNotifies[0].ticketId) - - // await DeleteSchedulingNotifyService(schedulingNotifies[0].id) - + } + } @@ -184,21 +173,7 @@ _fifo = setInterval(SchedulingNotifySendMessage, 5000); module.exports = SchedulingNotifySendMessage - -// export const startSchedulingMonitor = async (mileseconds: number) => { - -// timeInterval = mileseconds - -// scheduler_monitor = setInterval(monitor, mileseconds) - -// } - - -// export const stopSchedulingMonitor = async () => { - -// clearInterval(scheduler_monitor) - -// } + diff --git a/backend/src/helpers/WhoIsOnlineMonitor.ts b/backend/src/helpers/WhoIsOnlineMonitor.ts index 406c0e6..01d466c 100644 --- a/backend/src/helpers/WhoIsOnlineMonitor.ts +++ b/backend/src/helpers/WhoIsOnlineMonitor.ts @@ -17,7 +17,7 @@ import { date } from "faker"; import sumOnlineTimeNow from '../helpers/SumOlineTimeNow' import UserOnlineTime from "../models/UserOnlineTime"; - +let _fifo: any let whoIsOnline_monitor: any; // const listUserId:any[] = [{'id':8, status: 'offline'},{'id':3, status: 'offline'},{'id':5, status: 'offline'}] @@ -30,7 +30,7 @@ let timeInterval = 5 let lstOnline: any = [] let deleted: boolean = false; - + const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true) => { @@ -66,147 +66,179 @@ const monitor = async () => { const usersSocket = require('./../libs/socket'); if (usersSocket.ob) { - + if (count > 1) { count = 0 } - + if (count == 0) { uuid = usersSocket.ob.uuid } - + if (count == 1) { if (uuid) { if (uuid == usersSocket.ob.uuid) { - - console.log('ALL USERS CLIENTS OFFLINE 1...........') - + + console.log('ALL USERS CLIENTS OFFLINE 1...........') + usersSocket.ob.listOnline = [] usersSocket.ob.listOnlineAux = [] usersSocket.ob.uuid = undefined - + } - + } - - } else { - - usersSocket.ob.listOnline.forEach(async (el: any) => { - - + + } else { + + usersSocket.ob.listOnline.forEach(async (el: any) => { + + const indexAux = lstOnline.findIndex((e: any) => e.id == el.id) - - - if (indexAux == -1) { - + + + if (indexAux == -1) { + const userOnline = await createOrUpdateOnlineUserService({ userId: el.id, status: 'online' }) - + if (userOnline) { - + el.onlineTime = userOnline.onlineTime el.updatedAt = userOnline.updatedAt, - + console.log(' * CREATED OR UPDATED USER TO ONLINE: ', userOnline.userId) - + lstOnline.push({ 'id': el.id, 'status': 'online' }) } - + } - + if (el.status == 'waiting...') { emitterOnline(el, el.status, false) } else { emitterOnline(el, el.status) } - - - + + + }); - - - + + + let difference = lstOnline.filter((x: any) => !usersSocket.ob.listOnline.map((e: any) => e.id).includes(x.id)); - + difference.forEach(async (e: any) => { - + const index = lstOnline.findIndex((x: any) => x.id == e.id) - + if (index != -1) { - - lstOnline.splice(index, 1) - + + lstOnline.splice(index, 1) + const userOnline = await createOrUpdateOnlineUserService({ userId: e.id, status: 'offline' }) - - + + } - + }) - - - } - - count++ + + + } + + count++ } - - + + if (countTest > 5) { countTest = 0 } - + if (countTest == 0) { try { console.log(' Carregando usuarios no listUserId...') listUserId = await ListUserParamiterService({ profile: 'user' }) - + } catch (error) { console.log('There was an erro on ListUserParamiterService: ', error) return } - + } - + countTest = 1 - - listUserId.forEach((u) => { - + + listUserId.forEach((u) => { + const io = getIO(); io.emit("isOnline", { action: "online", userId: u.id }); }); - + } catch (error) { - console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ',error) - stopWhoIsOnlineMonitor() - startWhoIsOnlineMonitor() - } - + console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ', error) + + listUserId = [] + count = 0 + countTest = 0 + uuid = 0 + } + }; -export const startWhoIsOnlineMonitor = async (mileseconds?: number) => { + +const WhoIsOnlineMonitor = async () => { + + try { + clearInterval(_fifo); + + await monitor() + + } catch (error) { + console.log('error on WhoIsOnlineMonitor: ', error) + } + finally { + _fifo = setInterval(WhoIsOnlineMonitor, 3000); + } +} + +_fifo = setInterval(WhoIsOnlineMonitor, 3000); + + + +const startWhoIsOnlineMonitor = async (mileseconds?: number) => { listUserId = [] count = 0 countTest = 0 uuid = 0 - if (mileseconds) { - timeInterval = mileseconds - } - - - whoIsOnline_monitor = setInterval(monitor, timeInterval) + clearInterval(_fifo); + _fifo = setInterval(WhoIsOnlineMonitor, 3000); + // if (mileseconds) { + // timeInterval = mileseconds + // } } -export const stopWhoIsOnlineMonitor = async () => { +const stopWhoIsOnlineMonitor = async () => { - clearInterval(whoIsOnline_monitor) + clearInterval(_fifo); + // _fifo = setInterval(WhoIsOnlineMonitor, 3000); } +export { WhoIsOnlineMonitor, startWhoIsOnlineMonitor, stopWhoIsOnlineMonitor } + + + + + + + + diff --git a/backend/src/server.ts b/backend/src/server.ts index 86b2cb4..67ef9c4 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -3,16 +3,14 @@ import app from "./app"; import { initIO } from "./libs/socket"; import { logger } from "./utils/logger"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; - -import "./helpers/SchedulingNotifySendMessage" - -import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor" +import "./helpers/SchedulingNotifySendMessage" +import "./helpers/WhoIsOnlineMonitor" import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache' import { loadContactsCache } from './helpers/ContactsCache' import { loadWhatsappCache } from './helpers/WhatsCache' import { delRestoreControllFile } from "./helpers/RestoreControll"; import { createSessionDir } from "./helpers/CreateSessionDir"; -import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache"; +import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache"; const server = app.listen(process.env.PORT, () => { logger.info(`Server started on port: ${process.env.PORT}`); @@ -22,26 +20,25 @@ initIO(server); StartAllWhatsAppsSessions(); gracefulShutdown(server); -(async()=>{ +(async () => { const cacheLength = await cacheSize() console.log('cacheSize: ', cacheLength) - if(cacheLength == 0){ + if (cacheLength == 0) { console.log('Loading from cache...') - await flushCache() + await flushCache() await loadContactsCache() await loadTicketsCache() - await loadWhatsappCache() - await loadSchedulesCache() } - - + + await loadWhatsappCache() + await loadSchedulesCache() + })() + createSessionDir() delRestoreControllFile() - -startWhoIsOnlineMonitor(3000) From 397c18d80f4176447f2de35fd571d0c08397e014 Mon Sep 17 00:00:00 2001 From: adriano Date: Mon, 19 Dec 2022 12:05:35 -0300 Subject: [PATCH 4/4] =?UTF-8?q?Altera=C3=A7=C3=A3o=20para=20usar=20diretor?= =?UTF-8?q?io=20de=20m=C3=ADdias=20fora=20do=20diretorio=20do=20projeto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/src/config/upload.ts | 6 ++- .../WbotServices/wbotMessageListener.ts | 53 ++++--------------- 2 files changed, 15 insertions(+), 44 deletions(-) diff --git a/backend/src/config/upload.ts b/backend/src/config/upload.ts index 24fb8f8..e7d682d 100644 --- a/backend/src/config/upload.ts +++ b/backend/src/config/upload.ts @@ -1,7 +1,11 @@ import path from "path"; import multer from "multer"; -const publicFolder = path.resolve(__dirname, "..", "..", "public"); +// const publicFolder = path.resolve(__dirname, "..", "..", "public"); +const publicFolder = path.resolve(__dirname, "..", "..","..","..", "public"); + +console.log('publicFolder: ',publicFolder) + export default { directory: publicFolder, diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index f504bae..c2132f2 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -118,8 +118,14 @@ const verifyMediaMessage = async ( } try { + // await writeFileAsync( + // join(__dirname, "..", "..", "..", "public", media.filename), + // media.data, + // "base64" + // ); + await writeFileAsync( - join(__dirname, "..", "..", "..", "public", media.filename), + join(__dirname, "..", "..", "..", "..", "..", "public", media.filename), media.data, "base64" ); @@ -365,19 +371,11 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st const _clear_lst = () => { - console.log('WHATSAPP MESSAGE ID MULTI SESSION: ', lst.length) - - if (lst.length <= 200 ) return - - console.log('BEFORE lst SLICE: ', lst) - - console.log('lst whatsapp message id sliced! | lst.length: ', lst.length) + if (lst.length <= 200 ) return const chunk: any = Math.floor((lst.length / 2)) - lst = lst.slice(chunk, chunk + lst.length); - - console.log('AFTER lst SLICE: ', lst) + lst = lst.slice(chunk, chunk + lst.length); } @@ -426,38 +424,7 @@ const handleMessage = async ( // console.log('LIST OF ID MESSAGE lst: ', lst) - console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) - - // const contact_message = await getLastId(`contact_message:5517988310949`) - - // if (contact_message && contact_message.id == msg.id.id) { - // console.log('IGNORED MESSAGE SAME ID FROM CLIENT: ', contact_message.id) - // return - // } - - // await insertMessageContactCache(`contact_message:5517988310949`, - // { - // from: msg.from.split("@")[0], - // to: msg.to.split("@")[0], - // id: msg.id.id - // }) - - // console.log('PASSOU............................................... contact_message.id: ',contact_message.id) - - - // if (testLastId == msg.id.id) { - // console.log('IGNORED MESSAGE SAME ID!') - // return - // } - // testLastId = msg.id.id - - // console.log('PASSOU............................................... msg.id.id: ',msg.id.id) - - - - - - + console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id) if (!isValidMsg(msg)) {