Finalização da correção do lembrete para usar cache

pull/21/head
adriano 2022-12-18 13:56:45 -03:00
parent bc4712362d
commit ad9cbafdf2
5 changed files with 128 additions and 126 deletions

View File

@ -94,7 +94,7 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
}); });
await stopWhoIsOnlineMonitor() // await stopWhoIsOnlineMonitor()
await startWhoIsOnlineMonitor() await startWhoIsOnlineMonitor()
return res.status(200).json(user); return res.status(200).json(user);

View File

@ -109,9 +109,7 @@ async function searchScheduleCache(date: string, hour: number | string, minute:
if (redis.status !== 'connect') return null if (redis.status !== 'connect') return null
date = escapeCharCache(date).trim() 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})`) const response: any = await redis.call('FT.SEARCH', 'idx_schedule', `(@date_escaped:${date}) (@hour:${hour}) (@minute:${minute})`)
redis.quit() redis.quit()

View File

@ -41,18 +41,19 @@ const monitor = async () => {
try { 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) if (schedulingNotifies && schedulingNotifies.length > 0) {
if (schedulingNotifies && schedulingNotifies.length > 0) {
console.log('ENTROU NA DATA schedulingNotifies: ', schedulingNotifies)
for (let i = 0; i < schedulingNotifies.length; i++) { 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); SetTicketMessagesAsRead(ticket);
@ -62,23 +63,11 @@ const monitor = async () => {
await deleteScheduleByTicketIdCache(schedulingNotifies[i].ticketId) 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 module.exports = SchedulingNotifySendMessage
// export const startSchedulingMonitor = async (mileseconds: number) => {
// timeInterval = mileseconds
// scheduler_monitor = setInterval(monitor, mileseconds)
// }
// export const stopSchedulingMonitor = async () => {
// clearInterval(scheduler_monitor)
// }

View File

@ -17,7 +17,7 @@ import { date } from "faker";
import sumOnlineTimeNow from '../helpers/SumOlineTimeNow' import sumOnlineTimeNow from '../helpers/SumOlineTimeNow'
import UserOnlineTime from "../models/UserOnlineTime"; import UserOnlineTime from "../models/UserOnlineTime";
let _fifo: any
let whoIsOnline_monitor: any; let whoIsOnline_monitor: any;
// const listUserId:any[] = [{'id':8, status: 'offline'},{'id':3, status: 'offline'},{'id':5, status: 'offline'}] // 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 lstOnline: any = []
let deleted: boolean = false; let deleted: boolean = false;
const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true) => { const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true) => {
@ -66,147 +66,179 @@ const monitor = async () => {
const usersSocket = require('./../libs/socket'); const usersSocket = require('./../libs/socket');
if (usersSocket.ob) { if (usersSocket.ob) {
if (count > 1) { if (count > 1) {
count = 0 count = 0
} }
if (count == 0) { if (count == 0) {
uuid = usersSocket.ob.uuid uuid = usersSocket.ob.uuid
} }
if (count == 1) { if (count == 1) {
if (uuid) { if (uuid) {
if (uuid == usersSocket.ob.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.listOnline = []
usersSocket.ob.listOnlineAux = [] usersSocket.ob.listOnlineAux = []
usersSocket.ob.uuid = undefined usersSocket.ob.uuid = undefined
} }
} }
} else { } else {
usersSocket.ob.listOnline.forEach(async (el: any) => { usersSocket.ob.listOnline.forEach(async (el: any) => {
const indexAux = lstOnline.findIndex((e: any) => e.id == el.id) 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' }) const userOnline = await createOrUpdateOnlineUserService({ userId: el.id, status: 'online' })
if (userOnline) { if (userOnline) {
el.onlineTime = userOnline.onlineTime el.onlineTime = userOnline.onlineTime
el.updatedAt = userOnline.updatedAt, el.updatedAt = userOnline.updatedAt,
console.log(' * CREATED OR UPDATED USER TO ONLINE: ', userOnline.userId) console.log(' * CREATED OR UPDATED USER TO ONLINE: ', userOnline.userId)
lstOnline.push({ 'id': el.id, 'status': 'online' }) lstOnline.push({ 'id': el.id, 'status': 'online' })
} }
} }
if (el.status == 'waiting...') { if (el.status == 'waiting...') {
emitterOnline(el, el.status, false) emitterOnline(el, el.status, false)
} }
else { else {
emitterOnline(el, el.status) emitterOnline(el, el.status)
} }
}); });
let difference = lstOnline.filter((x: any) => !usersSocket.ob.listOnline.map((e: any) => e.id).includes(x.id)); let difference = lstOnline.filter((x: any) => !usersSocket.ob.listOnline.map((e: any) => e.id).includes(x.id));
difference.forEach(async (e: any) => { difference.forEach(async (e: any) => {
const index = lstOnline.findIndex((x: any) => x.id == e.id) const index = lstOnline.findIndex((x: any) => x.id == e.id)
if (index != -1) { if (index != -1) {
lstOnline.splice(index, 1) lstOnline.splice(index, 1)
const userOnline = await createOrUpdateOnlineUserService({ userId: e.id, status: 'offline' }) const userOnline = await createOrUpdateOnlineUserService({ userId: e.id, status: 'offline' })
} }
}) })
} }
count++ count++
} }
if (countTest > 5) { if (countTest > 5) {
countTest = 0 countTest = 0
} }
if (countTest == 0) { if (countTest == 0) {
try { try {
console.log(' Carregando usuarios no listUserId...') console.log(' Carregando usuarios no listUserId...')
listUserId = await ListUserParamiterService({ profile: 'user' }) listUserId = await ListUserParamiterService({ profile: 'user' })
} catch (error) { } catch (error) {
console.log('There was an erro on ListUserParamiterService: ', error) console.log('There was an erro on ListUserParamiterService: ', error)
return return
} }
} }
countTest = 1 countTest = 1
listUserId.forEach((u) => { listUserId.forEach((u) => {
const io = getIO(); const io = getIO();
io.emit("isOnline", { action: "online", userId: u.id }); io.emit("isOnline", { action: "online", userId: u.id });
}); });
} catch (error) { } catch (error) {
console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ',error) console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ', error)
stopWhoIsOnlineMonitor()
startWhoIsOnlineMonitor() 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 = [] listUserId = []
count = 0 count = 0
countTest = 0 countTest = 0
uuid = 0 uuid = 0
if (mileseconds) { clearInterval(_fifo);
timeInterval = mileseconds _fifo = setInterval(WhoIsOnlineMonitor, 3000);
}
whoIsOnline_monitor = setInterval(monitor, timeInterval)
// if (mileseconds) {
// timeInterval = mileseconds
// }
} }
export const stopWhoIsOnlineMonitor = async () => { const stopWhoIsOnlineMonitor = async () => {
clearInterval(whoIsOnline_monitor) clearInterval(_fifo);
// _fifo = setInterval(WhoIsOnlineMonitor, 3000);
} }
export { WhoIsOnlineMonitor, startWhoIsOnlineMonitor, stopWhoIsOnlineMonitor }

View File

@ -3,16 +3,14 @@ import app from "./app";
import { initIO } from "./libs/socket"; import { initIO } from "./libs/socket";
import { logger } from "./utils/logger"; import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
import "./helpers/SchedulingNotifySendMessage"
import "./helpers/SchedulingNotifySendMessage" import "./helpers/WhoIsOnlineMonitor"
import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor"
import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache' import { loadTicketsCache, flushCache, cacheSize } from './helpers/TicketCache'
import { loadContactsCache } from './helpers/ContactsCache' import { loadContactsCache } from './helpers/ContactsCache'
import { loadWhatsappCache } from './helpers/WhatsCache' import { loadWhatsappCache } from './helpers/WhatsCache'
import { delRestoreControllFile } from "./helpers/RestoreControll"; import { delRestoreControllFile } from "./helpers/RestoreControll";
import { createSessionDir } from "./helpers/CreateSessionDir"; import { createSessionDir } from "./helpers/CreateSessionDir";
import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache"; import { loadSchedulesCache, } from "./helpers/SchedulingNotifyCache";
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}`);
@ -22,26 +20,25 @@ initIO(server);
StartAllWhatsAppsSessions(); StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
(async()=>{ (async () => {
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 loadWhatsappCache()
await loadSchedulesCache()
} }
await loadWhatsappCache()
await loadSchedulesCache()
})() })()
createSessionDir() createSessionDir()
delRestoreControllFile() delRestoreControllFile()
startWhoIsOnlineMonitor(3000)