Correção no online/offiline para não sobrecarregar o servidor com emitters e evitar o memery leak(vazamento de memória)

pull/21/head
adriano 2022-12-27 11:25:50 -03:00
parent c5e9c8307f
commit 1602b71524
6 changed files with 203 additions and 95 deletions

View File

@ -27,6 +27,7 @@ import ShowQueuesByUser from "../services/UserServices/ShowQueuesByUser";
// import { filter } from "bluebird";
import { getIO } from "../libs/socket";
import { Json } from "sequelize/types/lib/utils";
type IndexQuery = {
userId: string;
@ -87,6 +88,10 @@ export const reportUserService = async (req: Request, res: Response): Promise<Re
let openCloseOnQueue = openByUserOnQueue.concat(closedByUserOnQueue)
let openCloseOutQueue = openByUserOutQueue.concat(closedUserOutQueue)
// console.log('onlineUsers: ',JSON.parse(JSON.stringify(onlineUsers)))
// console.log('sumUserOlineTime: ', JSON.parse(JSON.stringify(sumUserOlineTime)))
for (let i = 0; i < queuesByUser.length; i++) {
queuesByUser[i].countOpen = 0
@ -113,6 +118,8 @@ export const reportUserService = async (req: Request, res: Response): Promise<Re
if (index != -1) {
user.sumOnlineTime = sumUserOlineTime[index];
// console.log('user.sumOlineTime: 'user.sumOnlineTime)
}
index = closedByUser.findIndex((e: any) => e.userId == user.id)
@ -169,7 +176,7 @@ export const reportUserService = async (req: Request, res: Response): Promise<Re
})
return res.status(200).json(usersProfile);
return res.status(200).json({usersProfile: usersProfile});
};

View File

@ -23,7 +23,7 @@ let whoIsOnline_monitor: any;
// const listUserId:any[] = [{'id':8, status: 'offline'},{'id':3, status: 'offline'},{'id':5, status: 'offline'}]
let listUserId: any[] = []
let count = 0
let countTest = 0
// let countTest = 0
let uuid: any = 0
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let timeInterval = 5
@ -51,6 +51,10 @@ const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true
}
}
console.log('ENTROU NO EMMITER ONLINE: ', user.id)
// console.log('-------------> onlineTime: ', onlineTime)
const io = getIO();
io.emit("onlineStatus", {
action: "update",
@ -113,12 +117,14 @@ const monitor = async () => {
}
// console.log('el: ', el)
if (el.status == 'waiting...') {
emitterOnline(el, el.status, false)
}
else {
emitterOnline(el, el.status)
}
// else {
// emitterOnline(el, el.status)
// }
@ -147,39 +153,15 @@ const monitor = async () => {
}
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) => {
const io = getIO();
io.emit("isOnline", { action: "online", userId: u.id });
});
}
} catch (error) {
console.log('>>> There was an error no WhoIsOnlineMonitor.ts: ', error)
listUserId = []
count = 0
countTest = 0
// countTest = 0
uuid = 0
}
@ -211,7 +193,7 @@ const startWhoIsOnlineMonitor = async (mileseconds?: number) => {
listUserId = []
count = 0
countTest = 0
// countTest = 0
uuid = 0
clearInterval(_fifo);

View File

@ -47,6 +47,8 @@ export const initIO = (httpServer: Server): SocketIO => {
socket.on("online", (userId: any) => {
// console.log('userId: ', userId)
obj.uuid = uuidv4()

View File

@ -40,6 +40,29 @@ const useStyles = makeStyles(theme => ({
},
}));
let _fifo
// const onlineEmitter = async (socket, user) => {
// try {
// clearInterval(_fifo);
// socket.emit("online", user.id)
// } catch (error) {
// console.log('error on onlineEmitter: ', error)
// }
// finally {
// _fifo = setInterval(onlineEmitter, 3000);
// }
// }
// _fifo = setInterval(onlineEmitter, 3000);
const NotificationsPopOver = () => {
const classes = useStyles();
@ -57,20 +80,20 @@ const NotificationsPopOver = () => {
const [play] = useSound(alertSound);
const soundAlertRef = useRef();
const historyRef = useRef(history);
const historyRef = useRef(history);
const { handleLogout } = useContext(AuthContext);
const { handleLogout } = useContext(AuthContext);
// const [lastRef] = useState(+history.location.pathname.split("/")[2])
useEffect(() => {
soundAlertRef.current = play;
if (!("Notification" in window)) {
} else {
Notification.requestPermission();
}
@ -82,53 +105,70 @@ const NotificationsPopOver = () => {
useEffect(() => {
ticketIdRef.current = ticketIdUrl;
ticketIdRef.current = ticketIdUrl;
}, [ticketIdUrl]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("onlineStatus", (data) => {
if(data.action === "logout"){
socket.on("onlineStatus", (data) => {
if(`${user.id}` === data.userOnlineTime['userId']){
if (data.action === "logout") {
socket.emit("online", {logoutUserId: user.id})
if (`${user.id}` === data.userOnlineTime['userId']) {
socket.emit("online", { logoutUserId: user.id })
handleLogout();
}
}
}
}
});
// socket.on("isOnline", (data) => {
// if (data.action === "online") {
// if (data.userId === user.id) {
// socket.emit("online", user.id)
// }
// }
// });
if(user.profile === 'user'){
if(_fifo){
clearInterval(_fifo);
}
socket.on("isOnline", (data) => {
if(data.action === "online"){
if(data.userId === user.id){
_fifo = setInterval(()=>{
console.log('user.id: ', user.id)
socket.emit("online", user.id)
}
}, 3000);
}
}
});
return () => {
socket.disconnect();
socket.disconnect();
};
}, [user.id, handleLogout]);
}, [user.id, handleLogout]);
@ -136,13 +176,13 @@ const NotificationsPopOver = () => {
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("connect", () => socket.emit("joinNotification"));
socket.on("connect", () => socket.emit("joinNotification"));
socket.on("ticket", data => {
if (data.action === "updateUnread" || data.action === "delete") {
setNotifications(prevState => {
const ticketIndex = prevState.findIndex(t => t.id === data.ticketId);
@ -169,7 +209,7 @@ const NotificationsPopOver = () => {
socket.on("appMessage", data => {
if (
data.action === "create" &&
@ -177,12 +217,12 @@ const NotificationsPopOver = () => {
(data.ticket.userId === user?.id || !data.ticket.userId)
) {
setNotifications(prevState => {
// prevState.forEach((e)=>{
//
@ -190,23 +230,23 @@ const NotificationsPopOver = () => {
const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id);
if (ticketIndex !== -1) {
prevState[ticketIndex] = data.ticket;
return [...prevState];
}
return [data.ticket, ...prevState];
});
});
const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup || !data.ticket.userId;
if (shouldNotNotificate) return;
if (shouldNotNotificate) return;
handleNotifications(data);
}
@ -219,7 +259,7 @@ const NotificationsPopOver = () => {
const handleNotifications = data => {
const { message, contact, ticket } = data;
const options = {
body: `${message.body} - ${format(new Date(), "HH:mm")}`,
icon: contact.profilePicUrl,
@ -293,13 +333,13 @@ const NotificationsPopOver = () => {
onClose={handleClickAway}
>
<List dense className={classes.tabContainer}>
{notifications.length === 0 ? (
<ListItem>
{notifications.length === 0 ? (
<ListItem>
<ListItemText>{i18n.t("notifications.noTickets")}</ListItemText>
</ListItem>
) : (
) : (
notifications.map(ticket => (
notifications.map(ticket => (
<NotificationTicket key={ticket.id}>
<TicketListItem ticket={ticket} />
</NotificationTicket>

View File

@ -1,5 +1,7 @@
import React, { useContext, useReducer, useEffect, useState } from "react";
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
import Paper from "@material-ui/core/Paper";
import Container from "@material-ui/core/Container";
import Grid from "@material-ui/core/Grid";
@ -104,6 +106,36 @@ const useStyles = makeStyles((theme) => ({
},
}));
var _fifo
const sumOnlineTimeNow = (oldOnlineTimeSum) => {
let onlineTime = new Date()
onlineTime.setUTCHours(new Date(oldOnlineTimeSum.onlineTime).getHours())
onlineTime.setUTCMinutes(new Date(oldOnlineTimeSum.onlineTime).getMinutes())
onlineTime.setUTCSeconds(new Date(oldOnlineTimeSum.onlineTime).getSeconds())
let newtTime = intervalToDuration({ start: new Date(oldOnlineTimeSum.updatedAt), end: new Date() })
if (newtTime.hours && +newtTime.hours > 0) {
onlineTime = addHours(onlineTime, newtTime.hours)
}
if (newtTime.minutes && +newtTime.minutes > 0) {
onlineTime = addMinutes(onlineTime, newtTime.minutes)
}
if (newtTime.seconds && +newtTime.seconds > 0) {
onlineTime = addSeconds(onlineTime, newtTime.seconds)
}
const isoDate = new Date(onlineTime);
const newOnlinetime = isoDate.toJSON().slice(0, 19).replace('T', ' ');
return newOnlinetime
}
const reducer = (state, action) => {
if (action.type === "DELETE_USER_STATUS") {
const userId = action.payload;
@ -138,6 +170,8 @@ const reducer = (state, action) => {
let onlineUser = action.payload;
let index = -1;
// console.log('UPDATE_STATUS_ONLINE: ', onlineUser)
let onlySumOpenClosed = false;
if (onlineUser.sumOpen || onlineUser.sumClosed) {
@ -157,18 +191,27 @@ const reducer = (state, action) => {
if (!("statusOnline" in state[index])) {
state[index].statusOnline = onlineUser;
} else if ("statusOnline" in state[index]) {
state[index].statusOnline["status"] = onlineUser.status;
}
}
if ("onlineTime" in onlineUser) {
if ("sumOnlineTime" in state[index]) {
state[index].sumOnlineTime["sum"] = onlineUser.onlineTime.split(" ")[1];
} else if (!("sumOnlineTime" in state[index])) {
// console.log(' ffffffffffffffffffffffffffff ')
state[index].sumOnlineTime.sum = onlineUser.onlineTime.split(" ")[1]
} else if (!("sumOnlineTime" in state[index])) {
state[index].sumOnlineTime = {
userId: onlineUser.userId,
sum: onlineUser.onlineTime.split(" ")[1],
};
}
}
@ -235,13 +278,16 @@ const Dashboard = () => {
let date = new Date().toLocaleDateString("pt-BR").split("/");
let dateToday = `${date[2]}-${date[1]}-${date[0]}`;
const dataQuery = await api.get("/reports/user/services", {
const { data } = await api.get("/reports/user/services", {
params: { userId: null, startDate: dateToday, endDate: dateToday },
});
// console.log('data.data: ', data.usersProfile)
dispatch({ type: "RESET" });
dispatch({ type: "LOAD_QUERY", payload: dataQuery.data });
dispatch({ type: "LOAD_QUERY", payload: data.usersProfile });
} catch (err) {
}
};
@ -250,6 +296,37 @@ const Dashboard = () => {
return () => clearTimeout(delayDebounceFn);
}, []);
useEffect(() => {
if (!usersOnlineInfo || usersOnlineInfo.length == 0) return
if (_fifo) {
clearInterval(_fifo);
}
_fifo = setInterval(() => {
usersOnlineInfo.map((e) => {
if (e.statusOnline && e.statusOnline.status === 'online') {
let onlineTimeCurrent = sumOnlineTimeNow({onlineTime: e.statusOnline.onlineTime, updatedAt: e.statusOnline.updatedAt})
dispatch({ type: "UPDATE_STATUS_ONLINE", payload: { userId: e.id, status: e.statusOnline.status, onlineTime: onlineTimeCurrent } });
}
})
}, 3000);
}, [usersOnlineInfo])
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
@ -280,7 +357,7 @@ const Dashboard = () => {
}, []);
useEffect(() => {
if (ticketStatusChange === "") return
if (ticketStatusChange === "") return
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
@ -372,10 +449,10 @@ const Dashboard = () => {
style={{ overflow: "hidden" }}
variant="outlined"
>
<Typography component="h3" variant="h6" color="primary" style={{marginBottom:"0"}} paragraph>
<Typography component="h3" variant="h6" color="primary" style={{ marginBottom: "0" }} paragraph>
Em Atendimento
</Typography>
<Typography paragraph style={{fontSize: "12px", margin:"0px"}}>Hoje/Todo Periodo</Typography>
<Typography paragraph style={{ fontSize: "12px", margin: "0px" }}>Hoje/Todo Periodo</Typography>
<Grid item>
<Typography component="h1" variant="h4">

View File

@ -728,7 +728,7 @@ const Report = () => {
{ title: 'Tempo online', field: 'sumOnlineTime.sum' },
{ title: `${i18n.t("reports.dateStart")}`, field: 'startDate' },
{ title: `${i18n.t("reports.dateStart")}`, field: 'endDate' },
{ title: `${i18n.t("reports.dateEnd")}`, field: 'endDate' },
{ title: 'Em atendimento', field: 'sumOpen.count' },
{ title: 'Finalizado', field: 'sumClosed.count' },