codificação completa para registro do online offline

pull/1/head
adriano 2022-05-06 19:49:45 -03:00
parent be3320e883
commit 61e322ea6a
12 changed files with 407 additions and 59 deletions

View File

@ -38,6 +38,7 @@
"sequelize-cli": "^5.5.1", "sequelize-cli": "^5.5.1",
"sequelize-typescript": "^1.1.0", "sequelize-typescript": "^1.1.0",
"socket.io": "^3.0.5", "socket.io": "^3.0.5",
"uuid": "^8.3.2",
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js", "whatsapp-web.js": "github:pedroslopez/whatsapp-web.js",
"yup": "^0.32.8" "yup": "^0.32.8"
}, },
@ -54,6 +55,7 @@
"@types/multer": "^1.4.4", "@types/multer": "^1.4.4",
"@types/node": "^14.11.8", "@types/node": "^14.11.8",
"@types/supertest": "^2.0.10", "@types/supertest": "^2.0.10",
"@types/uuid": "^8.3.4",
"@types/validator": "^13.1.0", "@types/validator": "^13.1.0",
"@types/yup": "^0.29.8", "@types/yup": "^0.29.8",
"@typescript-eslint/eslint-plugin": "^4.4.0", "@typescript-eslint/eslint-plugin": "^4.4.0",

View File

@ -6,6 +6,16 @@ import ShowTicketReport from "../services/TicketServices/ShowTicketReport";
import ShowMessageReport from "../services/MessageServices/ShowMessageReport"; import ShowMessageReport from "../services/MessageServices/ShowMessageReport";
import onlineUserService from "../services/UserServices/CreateOrUpdateOnlineUserService"; import onlineUserService from "../services/UserServices/CreateOrUpdateOnlineUserService";
import User from "../models/User";
import Queue from "../models/Queue";
import UserOnlineTime from "../models/UserOnlineTime";
import { Op, Sequelize } from "sequelize";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime";
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
type IndexQuery = { type IndexQuery = {
@ -18,9 +28,6 @@ type IndexQuery = {
export const reportUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => { export const reportUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => {
//const test = await onlineUserService({userId: 3, status: 'offline'})
if (req.user.profile !== "master" && req.user.profile !== "admin") { if (req.user.profile !== "master" && req.user.profile !== "admin") {
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }

View File

@ -23,7 +23,7 @@ const monitor = async () => {
let fullDate = `${year}-${month}-${day}`; let fullDate = `${year}-${month}-${day}`;
let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00` let dateParm = `${fullDate} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`
console.log(dateParm); //console.log(dateParm);
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });

View File

@ -1,29 +1,148 @@
import e from "express";
import { bool, number } from "yup";
import { getIO } from "../libs/socket"; import { getIO } from "../libs/socket";
// import usersOnline from '../libs/socket' import Queue from "../models/Queue";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
import createOrUpdateOnlineUserService from "../services/UserServices/CreateOrUpdateOnlineUserService";
import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
import { check } from "prettier";
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 uuid: any = 0
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let checked: boolean = false
let count2 = 0
const setOfflineAllUsers = async () => {
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' })
console.log(' onlineUsers: ', onlineUsers)
if (onlineUsers.length > 0) {
onlineUsers.forEach(async user => {
await createOrUpdateOnlineUserService({ userId: user.userId, status: 'offline' })
});
}
}
let whoIsOnline_monitor:any;
const monitor = async () => { const monitor = async () => {
const test = require('./../libs/socket');
console.log(' TEST OBJ', test.ob)
//test del
if(countTest > 5){
countTest = 0
}
if (countTest == 0) {
//console.log('NEW USERS QUERY EMITER!')
listUserId = await ListUserParamiterService({ profile: 'user' })
//console.log('----------- listUserId: ', listUserId)
}
countTest++
//
if(listUserId.length == 0){
return;
}
listUserId.forEach((u) => {
const io = getIO(); const io = getIO();
io.emit("isOnline"); io.emit("isOnline", { action: "online", userId: u.id });
});
//const test = require('./../libs/socket');
// console.log('*usersOnline: ', test.listOnlineUsers)
if(test.ob){
if (count > 1) {
count = 0
}
if (count == 0) {
// uuid = test.uuid
uuid = test.ob.uuid
}
if (count == 1) {
if (uuid) {
if (uuid == test.ob.uuid) {
console.log('ALL USERS CLIENTS OFFLINE 1...........')
await setOfflineAllUsers()
test.ob.listOnline = []
test.ob.listOnline2 = []
test.ob.uuid = undefined
checked = true
}
else {
console.log('*usersOnline: ', test.ob.listOnline)
checked = false
count2 = 0
}
}
else {
console.log('ALL USERS CLIENTS OFFLINE 2...........')
if(!checked){
await setOfflineAllUsers()
checked = true
}
}
}
console.log(' | count: ',count, ' | test.ob.listOnline: ', test.ob.listOnline)
count++
}
else {
console.log('ALL USERS CLIENTS OFFLINE 3...........')
if(!checked && count2>10){
await setOfflineAllUsers()
checked = true
}
if(count2 < 12){
count2++
}
console.log('>>>>>>>>>>>>>>>>>>> count2: ', count2)
}
}; };
export const startWhoIsOnlinegMonitor =async (mileseconds: number) => { export const startWhoIsOnlinegMonitor = async (mileseconds: number) => {
whoIsOnline_monitor = setInterval(monitor, mileseconds) whoIsOnline_monitor = setInterval(monitor, mileseconds)
} }
export const stopWhoIsOnlineMonitor =async ( ) => { export const stopWhoIsOnlineMonitor = async () => {
clearInterval(whoIsOnline_monitor) clearInterval(whoIsOnline_monitor)
@ -32,4 +151,3 @@ export const stopWhoIsOnlineMonitor =async ( ) => {

View File

@ -3,11 +3,31 @@ import { Server } from "http";
import AppError from "../errors/AppError"; import AppError from "../errors/AppError";
import { logger } from "../utils/logger"; import { logger } from "../utils/logger";
import { v4 as uuidv4 } from 'uuid';
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
let io: SocketIO; let io: SocketIO;
//test del //test del
let listOnlineUsers:any[]=[] import createOrUpdateOnlineUserService from "../services/UserServices/CreateOrUpdateOnlineUserService";
let count:number = 0 import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
let count: number = 0
let listOnline: any[] = []
let listOnline2: any[] = []
let countOnline: number = 0
//let obj = { DESCENT_STEPS: 5000, ALPHA: 0.0005}
let obj:any = { listOnline: [], listOnline2: [], uuid: null}
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
// //
@ -23,29 +43,67 @@ export const initIO = (httpServer: Server): SocketIO => {
logger.info("Client Connected"); logger.info("Client Connected");
socket.on("online", (userId: string) => { socket.on("online", async (userId: string) => {
logger.info(`CLIENT ID ${userId}` ); console.log(' ----------------------------- listOnlie: ', obj.listOnline)
const indexUser = obj.listOnline.findIndex((e:any) => e.id == userId)
const indexUser = listOnlineUsers.findIndex((e) => e.userId == userId) if (indexUser == -1) {
obj.listOnline.push({ 'id': userId })
if(indexUser == -1){ const onlineUser = await createOrUpdateOnlineUserService({ userId: userId, status: 'online' })
//listOnlineUsers.push({userId: userId, status: 'online'})
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' })
countOnline = onlineUsers.length
console.log(' PUSHED NEW ID: ', userId)
} }
count++
//console.log('count: ', count) const index = obj.listOnline2.findIndex((e:any) => e.id == userId)
if(count >= listOnlineUsers.length){ if (index == -1) {
//console.log('listOnlineUsers1: ', listOnlineUsers) obj.listOnline2.push({ 'id': userId })
}
if (count > (countOnline - 1)) {
var difference = obj.listOnline.filter((x:any) => !obj.listOnline2.map((e:any) => e.id).includes(x.id));
console.log('############> difference: ', difference)
if (difference.length > 0) {
difference.forEach(async (x:any) => {
let index = obj.listOnline.findIndex((e:any) => e.id == x.id)
if (index != -1) {
obj.listOnline.splice(index, 1)
const onlineUser = await createOrUpdateOnlineUserService({ userId: x.id, status: 'offline' })
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' })
countOnline = onlineUsers.length
}
})
}
obj.listOnline2 = []
count = 0 count = 0
} }
//console.log('listOnlineUsers1: ', listOnlineUsers)
obj.uuid = uuidv4()
exports.ob = obj
count++
@ -81,5 +139,6 @@ export const getIO = (): SocketIO => {
}; };
exports.listOnlineUsers = listOnlineUsers // exports.listOnlineUsers = listUserId
// exports.listUserId

View File

@ -16,4 +16,4 @@ StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
startSchedulingMonitor(5000) startSchedulingMonitor(5000)
startWhoIsOnlinegMonitor(3000) startWhoIsOnlinegMonitor(5000)

View File

@ -40,7 +40,9 @@ const CreateOrUpdateUserOnlineTime = async ({
if(userOnlineTime){ if(userOnlineTime){
try{ try{
if(status === 'offline'){ let oldStatus = userOnlineTime.status
if(oldStatus=='online' && status === 'offline'){
//updatedAt //updatedAt
let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date()}) let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date()})
console.log('TESTANDO INTERVAL DURATION: ', newtTime) console.log('TESTANDO INTERVAL DURATION: ', newtTime)
@ -80,9 +82,12 @@ const CreateOrUpdateUserOnlineTime = async ({
await userOnlineTime.update({ status, onlineTime: mySQLDateString }) await userOnlineTime.update({ status, onlineTime: mySQLDateString })
} }
else if(status === 'online'){ else if(oldStatus=='offline' && status === 'online'){
await userOnlineTime.update({ status }) await userOnlineTime.update({ status })
} }
else{
console.log('NOT UPDATED THE USER: ', userOnlineTime.userId)
}
}catch(err){ }catch(err){

View File

@ -0,0 +1,54 @@
import { Op, Sequelize } from "sequelize";
import User from "../../models/User";
interface Request {
userId?: string | number;
profile?: string;
}
const ListUser = async ({profile, userId}: Request): Promise<User[]> => {
let where_clause = {}
if(userId && profile){
where_clause = {
[Op.and]: [
{userId: userId},
{profile: profile}
]
}
}
else if(userId){
where_clause = {
[Op.and]: [
{userId: userId},
]
}
}
else if(profile){
where_clause = {
profile: profile
}
}
const users = await User.findAll({
where: where_clause,
raw:true,
attributes: ['id', 'name', 'email'],
order: [["id", "ASC"]],
})
return users;
};
export default ListUser;

View File

@ -0,0 +1,72 @@
import UserOnlineTime from "../../models/UserOnlineTime";
import { Op, Sequelize } from "sequelize";
interface Request {
userId?: string | number;
status?: string;
date: string;
}
const ListUserOnlineOffline = async ({date, userId, status}: Request): Promise<UserOnlineTime[]> => {
let where_clause = {}
if(userId && status){
where_clause = {
[Op.and]: [
{userId: userId},
{status: status},
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${date}`)
},
]
}
}
else if(userId){
where_clause = {
[Op.and]: [
{userId: userId},
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${date}`)
},
]
}
}
else if(status){
where_clause = {
[Op.and]: [
{status: status},
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${date}`)
},
]
}
}
else{
where_clause = {
[Op.and]: [
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${date}`)
},
]
}
}
const users = await UserOnlineTime.findAll({
where: where_clause,
raw:true,
order: [["id", "ASC"]],
})
return users;
};
export default ListUserOnlineOffline;

View File

@ -275,7 +275,7 @@ const verifyQueue = async (
} }
console.log('TICKET MESSAGE ON QUEUE CHOICE: ', ticket_message) //console.log('TICKET MESSAGE ON QUEUE CHOICE: ', ticket_message)
// //
} }

View File

@ -77,11 +77,41 @@ const NotificationsPopOver = () => {
ticketIdRef.current = ticketIdUrl; ticketIdRef.current = ticketIdUrl;
}, [ticketIdUrl]); }, [ticketIdUrl]);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("isOnline", (data) => {
// console.log('___________data.userId: ', data.userId)
if(data.action === "online"){
if(data.userId === user.id){
socket.emit("online", user.id)
}
}
});
return () => {
socket.disconnect();
};
}, []);
useEffect(() => { useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL); 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 => { socket.on("ticket", data => {
if (data.action === "updateUnread" || data.action === "delete") { if (data.action === "updateUnread" || data.action === "delete") {
setNotifications(prevState => { setNotifications(prevState => {
@ -114,9 +144,9 @@ const NotificationsPopOver = () => {
(data.ticket.userId === user?.id || !data.ticket.userId) (data.ticket.userId === user?.id || !data.ticket.userId)
) { ) {
console.log(`data.ticket.userId: ${data.ticket.userId }\n // console.log(`data.ticket.userId: ${data.ticket.userId }\n
data.ticket.status: ${data.ticket.status}\n // data.ticket.status: ${data.ticket.status}\n
data.ticket.userId: ${data.ticket.userId }`) // data.ticket.userId: ${data.ticket.userId }`)
setNotifications(prevState => { setNotifications(prevState => {
const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id); const ticketIndex = prevState.findIndex(t => t.id === data.ticket.id);

View File

@ -197,6 +197,7 @@ const reducer = (state, action) => {
} else { } else {
socket.emit("joinNotification"); socket.emit("joinNotification");
} }
}); });
socket.on("ticket", data => { socket.on("ticket", data => {