commit antes da limpeza das variaveis nao utilizada

pull/1/head
adriano 2022-05-15 23:48:06 -03:00
parent 61e322ea6a
commit d74e3a7a97
21 changed files with 1916 additions and 840 deletions

View File

@ -10,13 +10,15 @@ import User from "../models/User";
import Queue from "../models/Queue"; import Queue from "../models/Queue";
import UserOnlineTime from "../models/UserOnlineTime"; import UserOnlineTime from "../models/UserOnlineTime";
import { Op, Sequelize } from "sequelize"; import { Op, Sequelize,literal } from "sequelize";
import format from 'date-fns/format'; import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime"; import { splitDateTime } from "../helpers/SplitDateTime";
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService"; import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService"; import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
type IndexQuery = { type IndexQuery = {
userId: string; userId: string;
@ -27,13 +29,13 @@ type IndexQuery = {
export const reportUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => { export const reportUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => {
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);
} }
const { userId, startDate, endDate } = req.query as IndexQuery const { userId, startDate, endDate } = req.query as IndexQuery
const data_query = await ShowTicketReport(userId, startDate, endDate); const data_query = await ShowTicketReport(userId, startDate, endDate);
return res.status(200).json(data_query); return res.status(200).json(data_query);
@ -41,6 +43,85 @@ export const reportUserByDateStartDateEnd = async (req: Request, res: Response):
}; };
export const reportUserService= async (req: Request, res: Response): Promise<Response> => {
if (req.user.profile !== "master" && req.user.profile !== "admin") {
throw new AppError("ERR_NO_PERMISSION", 403);
}
const { userId, startDate, endDate } = req.query as IndexQuery
//test del
console.log('startDate: ', startDate)
console.log('endDate: ', endDate)
console.log('userId: ', userId)
let usersProfile = await ListUserParamiterService({profile: 'user'})
const sumUserOlineTime = await ShowUserServiceReport({startDate, endDate, userId});
const closedByUser = await ShowUserServiceReport({startDate, endDate, ticketStatus: 'closed', userId});
const openByUser = await ShowUserServiceReport({startDate, endDate, ticketStatus: 'open', userId});
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate })
console.log('sumUserOlineTime: ',sumUserOlineTime )
console.log('closedByUser: ',closedByUser )
console.log('openByUser: ',openByUser )
console.log('usersProfile: ', usersProfile)
console.log('')
usersProfile.map((user:any) => {
let index = sumUserOlineTime.findIndex((e:any) => e.userId == user.id)
if (index != -1) {
user.sumOnlineTime = sumUserOlineTime[index];
}
index = closedByUser.findIndex((e:any) => e.userId == user.id)
if (index != -1) {
user.sumClosed = closedByUser[index];
}
index = openByUser.findIndex((e:any) => e.userId == user.id)
if (index != -1) {
user.sumOpen = openByUser[index]
}
index = onlineUsers.findIndex((e:any) => e.userId == user.id)
if (index != -1) {
user.statusOnline = onlineUsers[index]
}
if(startDate.length>0 && startDate.split('-').length == 3){
let date = startDate.split('-')
user.startDate = `${date[2]}/${date[1]}/${date[0]}`
}
if(endDate.length>0 && endDate.split('-').length == 3){
let date = endDate.split('-')
user.endDate = `${date[2]}/${date[1]}/${date[0]}`
}
})
console.log('')
console.log('usersProfile2: ',usersProfile)
//
// const data_query = await ShowTicketReport(userId, startDate, endDate);
return res.status(200).json(usersProfile);
};
export const reportMessagesUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => { export const reportMessagesUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => {

View File

@ -14,6 +14,10 @@ import ListSchedulingNotifyContactService from "../services/SchedulingNotifySer
import {isScheduling} from "../helpers/CheckSchedulingReminderNotify" import {isScheduling} from "../helpers/CheckSchedulingReminderNotify"
import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
type IndexQuery = { type IndexQuery = {
@ -37,6 +41,8 @@ interface TicketData {
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService"; import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
import TicketEmiterSumOpenClosedByUser from "../helpers/OnlineReporEmiterInfoByUser";
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { const {
@ -140,6 +146,8 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
const { ticketId } = req.params; const { ticketId } = req.params;
const userOldInfo = await Ticket.findByPk(ticketId)
let ticket2 = {} let ticket2 = {}
if(req.body['status'] === "closed"){ if(req.body['status'] === "closed"){
@ -152,6 +160,8 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
}); });
/////////////////////////////// ///////////////////////////////
const whatsapp = await ShowWhatsAppService(ticket.whatsappId); const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
@ -208,6 +218,19 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
} }
// test del
if(userOldInfo){
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate)
}
//
return res.status(200).json(ticket2); return res.status(200).json(ticket2);
}; };

View File

@ -10,25 +10,33 @@ import UpdateUserService from "../services/UserServices/UpdateUserService";
import ShowUserService from "../services/UserServices/ShowUserService"; import ShowUserService from "../services/UserServices/ShowUserService";
import DeleteUserService from "../services/UserServices/DeleteUserService"; import DeleteUserService from "../services/UserServices/DeleteUserService";
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService"
import User from "../models/User";
import { startWhoIsOnlineMonitor, stopWhoIsOnlineMonitor } from "../helpers/WhoIsOnlineMonitor"
import UserOnlineTIme from '../models/UserOnlineTime'
type IndexQuery = { type IndexQuery = {
searchParam: string; searchParam: string;
pageNumber: string; pageNumber: string;
profile?: string;
}; };
export const index = async (req: Request, res: Response): Promise<Response> => { export const index = async (req: Request, res: Response): Promise<Response> => {
const { searchParam, pageNumber } = req.query as IndexQuery; const { searchParam, pageNumber, profile } = req.query as IndexQuery;
const { users, count, hasMore } = await ListUsersService({ const { users, count, hasMore } = await ListUsersService({
searchParam, searchParam,
pageNumber pageNumber,
profile
}); });
if(req.user.profile!=='master'){ if (req.user.profile !== 'master') {
let auxUsers: Array<object> = []; let auxUsers: Array<object> = [];
for (var user of users) { for (var user of users) {
if(user.profile!=='master'){ if (user.profile !== 'master') {
auxUsers.push(user) auxUsers.push(user)
} }
} }
@ -37,8 +45,31 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
} }
return res.json({ users, count, hasMore }); return res.json({ users, count, hasMore });
// const { users, count, hasMore } = await ListUsersService({
// searchParam,
// pageNumber
// });
// if(req.user.profile!=='master'){
// let auxUsers: Array<object> = [];
// for (var user of users) {
// if(user.profile!=='master'){
// auxUsers.push(user)
// }
// }
// return res.json({ users: auxUsers, count, hasMore });
// }
// return res.json({ users, count, hasMore });
}; };
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { email, password, name, profile, queueIds } = req.body; const { email, password, name, profile, queueIds } = req.body;
@ -62,6 +93,10 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
user user
}); });
await stopWhoIsOnlineMonitor()
await startWhoIsOnlineMonitor()
return res.status(200).json(user); return res.status(200).json(user);
}; };
@ -73,6 +108,35 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json(user); return res.status(200).json(user);
}; };
export const logoutUser = async (req: Request, res: Response): Promise<Response> => {
const { userId } = req.params;
//const user = await ShowUserService(userId);
console.log('userId: ', userId)
//test del
await stopWhoIsOnlineMonitor()
let onlineTime = {
userId: userId,
status: 'logout...'
}
const io = getIO();
io.emit("onlineStatus", {
action: "logout",
userOnlineTime: onlineTime
});
await startWhoIsOnlineMonitor()
//
return res.status(200).json({});
};
export const update = async ( export const update = async (
req: Request, req: Request,
res: Response res: Response
@ -105,13 +169,27 @@ export const remove = async (
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
await DeleteUserService(userId); await DeleteUserService(userId);
const io = getIO(); const io = getIO();
io.emit("user", { io.emit("user", {
action: "delete", action: "delete",
userId userId
}); });
//test del
await stopWhoIsOnlineMonitor()
io.emit("onlineStatus", {
action: "delete",
userOnlineTime: userId
});
await startWhoIsOnlineMonitor()
//
return res.status(200).json({ message: "User deleted" }); return res.status(200).json({ message: "User deleted" });
}; };

View File

@ -0,0 +1,26 @@
import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
import ShowUserServiceReport from '../services/UserServices/ShowUserServiceReport';
import { getIO } from "../libs/socket";
const TicketEmiterSumOpenClosedByUser = async (userId: string, startDate: string, endDate: string) => {
const openByUser: any[] = await ShowUserServiceReport({ startDate: startDate, endDate:endDate, ticketStatus: 'open', userId: userId.toString() });
const closedByUser: any[] = await ShowUserServiceReport({ startDate: endDate, endDate:endDate, ticketStatus: 'closed', userId: userId.toString() });
//openByUser : [ { id: 13, status: 'online' } ]
const io = getIO();
io.emit("onlineStatus", {
action: "update",
userOnlineTime: {
sumOpen: openByUser.length > 0 ? openByUser[0] : { userId: userId, count: '' },
sumClosed: closedByUser.length > 0 ? closedByUser[0] : { userId: userId, count: '' },
}
});
};
export default TicketEmiterSumOpenClosedByUser

View File

@ -25,6 +25,7 @@ const monitor = async () => {
//console.log(dateParm); //console.log(dateParm);
try {
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" }); const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
@ -42,6 +43,9 @@ const monitor = async () => {
} }
} catch (error) {
console.log('>>> SchedulingNotifiySendMessage.ts error: ', error)
}
}; };

View File

@ -0,0 +1,32 @@
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
const sumOnlineTimeNow = (oldOnlineTimeSum:any) => {
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', ' ');
console.log('sum new online time: ', newOnlinetime)
return newOnlinetime
}
export default sumOnlineTimeNow

View File

@ -11,6 +11,13 @@ import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from 'date-fns/locale/pt-BR';
import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService"; import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
import { check } from "prettier"; import { check } from "prettier";
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
import { date } from "faker";
import sumOnlineTimeNow from '../helpers/SumOlineTimeNow'
import UserOnlineTime from "../models/UserOnlineTime";
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'}]
@ -19,20 +26,48 @@ let count = 0
let countTest = 0 let countTest = 0
let uuid: any = 0 let uuid: any = 0
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
let checked: boolean = false let timeInterval = 5
let count2 = 0 let lstOnline: any = []
let deleted: boolean = false;
const setOfflineAllUsers = async () => { const setOfflineAllUsers = async () => {
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' }) // const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' })
console.log(' onlineUsers: ', onlineUsers) // console.log('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX onlineUsers: ', onlineUsers)
if (onlineUsers.length > 0) { // if (onlineUsers.length > 0) {
onlineUsers.forEach(async user => { // onlineUsers.forEach(async user => {
await createOrUpdateOnlineUserService({ userId: user.userId, status: 'offline' }) // await createOrUpdateOnlineUserService({ userId: user.userId, status: 'offline' })
}); // });
// }
}
const emitterOnline = (user: any, status: string, showOnlineTime: boolean = true) => {
if (!user.id) return
let newOnlinetime = sumOnlineTimeNow(user)
let onlineTime: any = {
userId: user.id,
status: status,
onlineTime: newOnlinetime,
} }
if (!showOnlineTime) {
onlineTime = {
userId: user.id,
status: status
}
}
const io = getIO();
io.emit("onlineStatus", {
action: "update",
userOnlineTime: onlineTime
});
} }
@ -40,46 +75,13 @@ const monitor = async () => {
const test = require('./../libs/socket'); const test = require('./../libs/socket');
console.log(' TEST OBJ', test.ob) if (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();
io.emit("isOnline", { action: "online", userId: u.id });
});
if(test.ob){
if (count > 1) { if (count > 1) {
count = 0 count = 0
} }
if (count == 0) { if (count == 0) {
// uuid = test.uuid
uuid = test.ob.uuid uuid = test.ob.uuid
} }
@ -89,55 +91,136 @@ const monitor = async () => {
console.log('ALL USERS CLIENTS OFFLINE 1...........') console.log('ALL USERS CLIENTS OFFLINE 1...........')
await setOfflineAllUsers() //await setOfflineAllUsers()
test.ob.listOnline = [] test.ob.listOnline = []
test.ob.listOnline2 = [] test.ob.listOnlineAux = []
test.ob.uuid = undefined test.ob.uuid = undefined
checked = true
}
}
} else {
console.log(' * TEST OBJ', test.ob)
test.ob.listOnline.forEach(async (el: any) => {
const indexAux = lstOnline.findIndex((e: any) => e.id == el.id)
if (indexAux == -1) {
console.log(' entrou indexAux: ', indexAux)
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 { else {
console.log('*usersOnline: ', test.ob.listOnline) emitterOnline(el, el.status)
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)
});
console.log('----------- 1 lstOnline: ', lstOnline)
let difference = lstOnline.filter((x: any) => !test.ob.listOnline.map((e: any) => e.id).includes(x.id));
console.log(' * diference: ', difference)
difference.forEach(async (e: any) => {
const index = lstOnline.findIndex((x: any) => x.id == e.id)
if (index != -1) {
lstOnline.splice(index, 1)
console.log('----------- 2 lstOnline: ', lstOnline)
const userOnline = await createOrUpdateOnlineUserService({ userId: e.id, status: 'offline' })
if (userOnline) {
console.log(' * UPDATED USER TO OFFLINE: ', userOnline.userId)
}
}
})
}
count++ count++
} }
else {
console.log('ALL USERS CLIENTS OFFLINE 3...........')
if(!checked && count2>10){
await setOfflineAllUsers() if (countTest > 5) {
checked = true countTest = 0
} }
if(count2 < 12){ if (countTest == 0) {
count2++ try {
console.log(' Carregando usuárion no listUserId...')
listUserId = await ListUserParamiterService({ profile: 'user' })
} catch (error) {
console.log('There was an erro on ListUserParamiterService: ', error)
return
} }
console.log('>>>>>>>>>>>>>>>>>>> count2: ', count2)
} }
countTest = 1
listUserId.forEach((u) => {
// console.log(' *** listUserId: ', listUserId)
const io = getIO();
io.emit("isOnline", { action: "online", userId: u.id });
});
console.log('***************** TIME INTERVAL: ', timeInterval)
}; };
export const startWhoIsOnlinegMonitor = async (mileseconds: number) => { export const startWhoIsOnlineMonitor = async (mileseconds?: number) => {
whoIsOnline_monitor = setInterval(monitor, mileseconds) listUserId = []
count = 0
countTest = 0
uuid = 0
if (mileseconds) {
timeInterval = mileseconds
}
whoIsOnline_monitor = setInterval(monitor, timeInterval)
} }

View File

@ -5,7 +5,7 @@ import { logger } from "../utils/logger";
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import ListUserParamiterService from "../services/UserServices/ListUserParamiterService"; import ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
let io: SocketIO; let io: SocketIO;
@ -18,12 +18,17 @@ import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOffli
let count: number = 0 let count: number = 0
let listOnline: any[] = [] let listOnline: any[] = []
let listOnline2: any[] = [] let listOnlineAux: any[] = []
let countOnline: number = 0 let countOnline: number = 0
//let obj = { DESCENT_STEPS: 5000, ALPHA: 0.0005} let obj: any = { listOnline: [], uuid: null, listOnlineAux: [] }
let lstOnline: any[] = []
let lstOnlineAux: any[] = []
let lstTry: any[] = []
let obj:any = { listOnline: [], listOnline2: [], uuid: null}
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
@ -31,6 +36,9 @@ let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss',
// //
export const initIO = (httpServer: Server): SocketIO => { export const initIO = (httpServer: Server): SocketIO => {
io = new SocketIO(httpServer, { io = new SocketIO(httpServer, {
cors: { cors: {
@ -43,69 +51,135 @@ export const initIO = (httpServer: Server): SocketIO => {
logger.info("Client Connected"); logger.info("Client Connected");
socket.on("online", async (userId: string) => { socket.on("online", (userId: any) => {
console.log(' ----------------------------- listOnlie: ', obj.listOnline)
const indexUser = obj.listOnline.findIndex((e:any) => e.id == userId)
if (indexUser == -1) {
obj.listOnline.push({ 'id': userId })
const onlineUser = await createOrUpdateOnlineUserService({ userId: userId, status: 'online' })
const onlineUsers = await ListUserOnlineOffline({ date: dateTime.fullDate, status: 'online' })
countOnline = onlineUsers.length
console.log(' PUSHED NEW ID: ', userId)
}
const index = obj.listOnline2.findIndex((e:any) => e.id == userId)
if (index == -1) {
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
}
obj.uuid = uuidv4() obj.uuid = uuidv4()
if (userId.logoutUserId) {
let index = lstOnline.findIndex((x: any) => x.id == userId.logoutUserId)
if (index != -1) {
lstOnline.splice(index, 1)
}
index = lstOnlineAux.findIndex((x: any) => x.id == userId.logoutUserId)
if (index != -1) {
lstOnlineAux.splice(index, 1)
}
return
}
if (lstOnline.length == 0) {
const index = listOnlineAux.findIndex((e: any) => e.id == userId)
if (index == -1) {
listOnlineAux.push({ 'id': userId })
}
else {
console.log(' -------------- PULO FORA')
return
}
lstOnline.push({ 'id': userId, 'status': 'online', 'try': 0 })
lstOnlineAux.push({ 'id': userId })
console.log(' 1 PUSHED NEW USER ID 1: ', userId)
obj.listOnline = lstOnline
}
else {
const indexAux = lstOnlineAux.findIndex((e: any) => e.id == userId)
if (indexAux == -1) {
lstOnlineAux.push({ 'id': userId })
}
const index = lstOnline.findIndex((e: any) => e.id == userId)
if (index == -1) {
lstOnline.push({ 'id': userId, 'status': 'online', 'try': 0 })
console.log(' 2 PUSHED NEW USER ID: ', userId)
obj.listOnline = lstOnline
}
else {
if (countOnline > (lstOnline.length - 1)) {
lstOnline.forEach((x: any) => {
if (lstOnlineAux.map((e: any) => e.id).includes(x.id)) {
x.try = 0
x.status = 'online'
}
})
var difference = lstOnline.filter((x: any) => !lstOnlineAux.map((e: any) => e.id).includes(x.id));
//console.log('>>>>>>>>>>> difference: ', difference)
if (difference.length > 0) {
difference.forEach((e) => {
e.try += 1
if (e.try > 1) {
e.status = 'waiting...'
}
if (e.try > 3) {
const index = lstOnline.findIndex((x: any) => x.id == e.id)
if (index != -1) {
lstOnline.splice(index, 1)
}
}
})
console.log(' difference2: ', difference)
}
obj.listOnline = lstOnline
obj.listOnlineAux = lstOnlineAux
// console.log(' >>>>>> lstOnline: ', lstOnline)
// console.log('')
// console.log(' >>>>>> lstOnlineAux: ', lstOnlineAux)
lstOnlineAux = []
listOnlineAux = []
countOnline = -1
}
countOnline++
}
}
exports.ob = obj exports.ob = obj
count++
}); });

View File

@ -9,6 +9,8 @@ const reportRoutes = express.Router();
reportRoutes.get("/reports", isAuth, ReportController.reportUserByDateStartDateEnd); reportRoutes.get("/reports", isAuth, ReportController.reportUserByDateStartDateEnd);
reportRoutes.get("/reports/user/services", isAuth, ReportController.reportUserService);
reportRoutes.get("/reports/messages", isAuth, ReportController.reportMessagesUserByDateStartDateEnd); reportRoutes.get("/reports/messages", isAuth, ReportController.reportMessagesUserByDateStartDateEnd);
export default reportRoutes; export default reportRoutes;

View File

@ -6,7 +6,6 @@ import * as UserController from "../controllers/UserController";
const userRoutes = Router(); const userRoutes = Router();
userRoutes.get("/users", isAuth, UserController.index); userRoutes.get("/users", isAuth, UserController.index);
userRoutes.post("/users", isAuth, UserController.store); userRoutes.post("/users", isAuth, UserController.store);
@ -15,6 +14,8 @@ userRoutes.put("/users/:userId", isAuth, UserController.update);
userRoutes.get("/users/:userId", isAuth, UserController.show); userRoutes.get("/users/:userId", isAuth, UserController.show);
userRoutes.get("/users/logout/:userId", isAuth, UserController.logoutUser);
userRoutes.delete("/users/:userId", isAuth, UserController.remove); userRoutes.delete("/users/:userId", isAuth, UserController.remove);
export default userRoutes; export default userRoutes;

View File

@ -5,7 +5,7 @@ import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions"; import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
import { startSchedulingMonitor } from "./helpers/SchedulingNotifySendMessage" import { startSchedulingMonitor } from "./helpers/SchedulingNotifySendMessage"
import { startWhoIsOnlinegMonitor } from "./helpers/WhoIsOnlineMonitor" import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor"
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}`);
@ -16,4 +16,4 @@ StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);
startSchedulingMonitor(5000) startSchedulingMonitor(5000)
startWhoIsOnlinegMonitor(5000) startWhoIsOnlineMonitor(2000)

View File

@ -4,6 +4,15 @@ import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import ShowContactService from "../ContactServices/ShowContactService"; import ShowContactService from "../ContactServices/ShowContactService";
import { getIO } from "../../libs/socket";
import ShowUserServiceReport from "../UserServices/ShowUserServiceReport";
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../../helpers/SplitDateTime";
import TicketEmiterSumOpenClosedByUser from "../../helpers/OnlineReporEmiterInfoByUser";
interface Request { interface Request {
contactId: number; contactId: number;
status: string; status: string;
@ -34,6 +43,21 @@ const CreateTicketService = async ({
throw new AppError("ERR_CREATING_TICKET"); throw new AppError("ERR_CREATING_TICKET");
} }
//test del
// 2022-05-11T05:20:33.000Z,
// const dateToday = ticket.createdAt.toISOString().split('T')[0]
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
//openByUser : [ { id: 13, status: 'online' } ]
TicketEmiterSumOpenClosedByUser(userId.toString(), dateToday.fullDate, dateToday.fullDate)
//
return ticket; return ticket;
}; };

View File

@ -6,23 +6,48 @@ import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-
import format from 'date-fns/format'; import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from 'date-fns/locale/pt-BR';
import { stat } from "fs"; import { stat } from "fs";
import { getIO } from "../../libs/socket";
import User from '../../models/User'
interface Request { interface Request {
userId: string | number, userId: string | number,
status: string, status: string,
} }
const formatDateTimeString = (date: Date) => {
let newDate = new Date()
newDate.setUTCHours(date.getHours())
newDate.setUTCMinutes(date.getMinutes())
newDate.setUTCSeconds(date.getSeconds())
const newD = new Date(newDate);
const newDateString = newD.toJSON().slice(0, 19).replace('T', ' ');
return newDateString
}
const CreateOrUpdateUserOnlineTime = async ({ const CreateOrUpdateUserOnlineTime = async ({
userId, userId,
status, status,
}: Request): Promise<UserOnlineTime> => { }: Request): Promise<UserOnlineTime> => {
let userOnlineTime = null;
// let dateTime = splitDateTime(new Date(new Date() + 'UTC'))
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }) ))
const io = getIO();
let userOnlineTime:any = null;
const user = await User.findOne({ where: { id: userId } });
if (!user) {
console.log(' yyyyyyyyyyyyyyyyyyyyyyyyyy não tem mais esse usuario id: ', userId)
return userOnlineTime
}
let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
userOnlineTime = await UserOnlineTime.findOne({ userOnlineTime = await UserOnlineTime.findOne({
where: { where: {
@ -37,14 +62,17 @@ const CreateOrUpdateUserOnlineTime = async ({
} }
}); });
if(userOnlineTime){ if (userOnlineTime) {
try{ try {
let oldStatus = userOnlineTime.status let oldStatus = userOnlineTime.status
if(oldStatus=='online' && status === 'offline'){
console.log('>>>>>>>>> oldStatus: ', oldStatus, ' | new status', 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)
console.log('hours: ', newtTime.hours, ' | minutes: ', newtTime.minutes, ' | seconds: ', newtTime.seconds) console.log('hours: ', newtTime.hours, ' | minutes: ', newtTime.minutes, ' | seconds: ', newtTime.seconds)
@ -55,21 +83,21 @@ const CreateOrUpdateUserOnlineTime = async ({
onlineTime.setUTCMinutes(userOnlineTime.onlineTime.getMinutes()) onlineTime.setUTCMinutes(userOnlineTime.onlineTime.getMinutes())
onlineTime.setUTCSeconds(userOnlineTime.onlineTime.getSeconds()) onlineTime.setUTCSeconds(userOnlineTime.onlineTime.getSeconds())
console.log('userOnlineTime.onlineTime: ',userOnlineTime.onlineTime) console.log('userOnlineTime.onlineTime: ', userOnlineTime.onlineTime)
console.log('userOnlineTime.onlineTime.getHours(): ',userOnlineTime.onlineTime.getHours()) console.log('userOnlineTime.onlineTime.getHours(): ', userOnlineTime.onlineTime.getHours())
console.log('userOnlineTime.onlineTime.getMinutes(): ',userOnlineTime.onlineTime.getMinutes()) console.log('userOnlineTime.onlineTime.getMinutes(): ', userOnlineTime.onlineTime.getMinutes())
console.log('userOnlineTime.onlineTime.getSeconds(): ',userOnlineTime.onlineTime.getSeconds()) console.log('userOnlineTime.onlineTime.getSeconds(): ', userOnlineTime.onlineTime.getSeconds())
console.log('online time 3: ', onlineTime) console.log('online time 3: ', onlineTime)
if(newtTime.hours && +newtTime.hours > 0){ if (newtTime.hours && +newtTime.hours > 0) {
onlineTime = addHours(onlineTime, newtTime.hours) onlineTime = addHours(onlineTime, newtTime.hours)
} }
if(newtTime.minutes && +newtTime.minutes > 0){ if (newtTime.minutes && +newtTime.minutes > 0) {
onlineTime = addMinutes(onlineTime,newtTime.minutes) onlineTime = addMinutes(onlineTime, newtTime.minutes)
} }
if(newtTime.seconds && +newtTime.seconds > 0){ if (newtTime.seconds && +newtTime.seconds > 0) {
onlineTime = addSeconds(onlineTime, newtTime.seconds) onlineTime = addSeconds(onlineTime, newtTime.seconds)
} }
@ -81,22 +109,52 @@ const CreateOrUpdateUserOnlineTime = async ({
await userOnlineTime.update({ status, onlineTime: mySQLDateString }) await userOnlineTime.update({ status, onlineTime: mySQLDateString })
//test del
const updatedAtString = formatDateTimeString(userOnlineTime.updatedAt)
const createdAtString = formatDateTimeString(userOnlineTime.createdAt)
console.log('CreatedAt string: ', createdAtString)
console.log('UpdatedAt string: ', updatedAtString)
//
io.emit("onlineStatus", {
action: "update",
userOnlineTime: {
userId: userOnlineTime.userId,
status: userOnlineTime.status,
onlineTime: mySQLDateString,
createdAt: createdAtString,
updatedAt: updatedAtString
} }
else if(oldStatus=='offline' && status === 'online'){ });
}
else if (oldStatus == 'offline' && status === 'online') {
await userOnlineTime.update({ status }) await userOnlineTime.update({ status })
io.emit("onlineStatus", {
action: "update",
userOnlineTime: {
userId: userOnlineTime.userId,
status: userOnlineTime.status,
createdAt: formatDateTimeString(userOnlineTime.createdAt),
updatedAt: formatDateTimeString(userOnlineTime.updatedAt)
} }
else{ });
}
else {
console.log('NOT UPDATED THE USER: ', userOnlineTime.userId) console.log('NOT UPDATED THE USER: ', userOnlineTime.userId)
} }
}catch(err){ } catch (err) {
throw new AppError("ERR_NO_USER_ONLINE_FOUND", 404); throw new AppError("ERR_NO_USER_ONLINE_FOUND", 404);
} }
} }
if(!userOnlineTime){ if (!userOnlineTime) {
userOnlineTime = await UserOnlineTime.create( userOnlineTime = await UserOnlineTime.create(
{ {
@ -105,12 +163,24 @@ const CreateOrUpdateUserOnlineTime = async ({
onlineTime: `${dateTime.fullDate} 00:00:00` onlineTime: `${dateTime.fullDate} 00:00:00`
}) })
io.emit("onlineStatus", {
action: "update",
userOnlineTime: {
userId: userOnlineTime.userId,
status: userOnlineTime.status,
createdAt: formatDateTimeString(userOnlineTime.createdAt),
updatedAt: formatDateTimeString(userOnlineTime.updatedAt)
}
});
} }
return userOnlineTime return userOnlineTime
} }
export default CreateOrUpdateUserOnlineTime export default CreateOrUpdateUserOnlineTime

View File

@ -3,6 +3,7 @@ import AppError from "../../errors/AppError";
import Ticket from "../../models/Ticket"; import Ticket from "../../models/Ticket";
import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus"; import UpdateDeletedUserOpenTicketsStatus from "../../helpers/UpdateDeletedUserOpenTicketsStatus";
const DeleteUserService = async (id: string | number): Promise<void> => { const DeleteUserService = async (id: string | number): Promise<void> => {
const user = await User.findOne({ const user = await User.findOne({
where: { id } where: { id }
@ -20,7 +21,9 @@ const DeleteUserService = async (id: string | number): Promise<void> => {
UpdateDeletedUserOpenTicketsStatus(userOpenTickets); UpdateDeletedUserOpenTicketsStatus(userOpenTickets);
} }
await user.destroy(); await user.destroy();
}; };
export default DeleteUserService; export default DeleteUserService;

View File

@ -13,6 +13,7 @@ const ListUserOnlineOffline = async ({date, userId, status}: Request): Promise<U
let where_clause = {} let where_clause = {}
if(userId && status){ if(userId && status){
where_clause = { where_clause = {
[Op.and]: [ [Op.and]: [
@ -57,6 +58,12 @@ const ListUserOnlineOffline = async ({date, userId, status}: Request): Promise<U
const users = await UserOnlineTime.findAll({ const users = await UserOnlineTime.findAll({
where: where_clause, where: where_clause,
raw:true, raw:true,
attributes: ['id', 'userId', 'status',
[Sequelize.fn("DATE_FORMAT",Sequelize.col("UserOnlineTime.onlineTime"),"%Y-%m-%d %H:%i:%s"),"onlineTime"],
[Sequelize.fn("DATE_FORMAT",Sequelize.col("UserOnlineTime.createdAt"),"%Y-%m-%d %H:%i:%s"),"createdAt"],
[Sequelize.fn("DATE_FORMAT",Sequelize.col("UserOnlineTime.updatedAt"),"%Y-%m-%d %H:%i:%s"),"updatedAt"]],
order: [["id", "ASC"]], order: [["id", "ASC"]],
}) })

View File

@ -5,6 +5,7 @@ import User from "../../models/User";
interface Request { interface Request {
searchParam?: string; searchParam?: string;
pageNumber?: string | number; pageNumber?: string | number;
profile?: string;
} }
interface Response { interface Response {
@ -15,9 +16,19 @@ interface Response {
const ListUsersService = async ({ const ListUsersService = async ({
searchParam = "", searchParam = "",
pageNumber = "1" pageNumber = "1",
profile = ""
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const whereCondition = {
let whereCondition = {}
if (profile.length > 0) {
whereCondition = {
profile: profile
}
}
else {
whereCondition = {
[Op.or]: [ [Op.or]: [
{ {
"$User.name$": Sequelize.where( "$User.name$": Sequelize.where(
@ -29,7 +40,25 @@ const ListUsersService = async ({
{ email: { [Op.like]: `%${searchParam.toLowerCase()}%` } } { email: { [Op.like]: `%${searchParam.toLowerCase()}%` } }
] ]
}; };
const limit = 20; }
// const whereCondition = {
// [Op.or]: [
// {
// "$User.name$": Sequelize.where(
// Sequelize.fn("LOWER", Sequelize.col("User.name")),
// "LIKE",
// `%${searchParam.toLowerCase()}%`
// )
// },
// { email: { [Op.like]: `%${searchParam.toLowerCase()}%` } }
// ]
// };
// const limit = 20;
const limit = 100;
const offset = limit * (+pageNumber - 1); const offset = limit * (+pageNumber - 1);
const { count, rows: users } = await User.findAndCountAll({ const { count, rows: users } = await User.findAndCountAll({

View File

@ -12,63 +12,107 @@ import { Op, where } from "sequelize";
import { Sequelize } from "sequelize"; import { Sequelize } from "sequelize";
import moment from 'moment'; import moment from 'moment';
import { startOfDay, endOfDay, parseISO, getDate} from "date-fns"; import { startOfDay, endOfDay, parseISO, getDate } from "date-fns";
import { string } from "yup/lib/locale"; import { string } from "yup/lib/locale";
import Whatsapp from "../../models/Whatsapp"; import Whatsapp from "../../models/Whatsapp";
import UserOnlineTime from "../../models/UserOnlineTime";
interface Request {
startDate: string;
endDate: string;
userId?: string;
ticketStatus?: string;
}
//Report by user, startDate, endDate //Report by user, startDate, endDate
const ShowUserServiceReport = async (id: string | number, startDate: string, endDate: string): Promise<Ticket[]> => { const ShowUserServiceReport = async ({
startDate,
endDate,
userId="",
ticketStatus=""
}: Request): Promise<Object[]> => {
// Para contornar a gambiarra do ShowTicketReport
userId=='0' ? userId='' : userId = userId
let where_clause = {} let where_clause = {}
let objQuery: Object[] = []
if(id=='0'){
if (ticketStatus.length>0) {
if (userId.length>0) {
where_clause = { where_clause = {
userId: userId,
status: ticketStatus,
createdAt: { createdAt: {
[Op.gte]: startDate+' 00:00:00.000000', [Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999' [Op.lte]: endDate + ' 23:59:59.999999'
}, },
} }
} }
else{ else {
where_clause = { where_clause = {
userid: id, status: ticketStatus,
createdAt: { createdAt: {
[Op.gte]: startDate+' 00:00:00.000000', [Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999' [Op.lte]: endDate + ' 23:59:59.999999'
}, },
} }
} }
objQuery = await Ticket.findAll({
const ticket = await Ticket.findAll({ where: where_clause,
raw: true,
attributes: ['userId', [Sequelize.fn("COUNT", Sequelize.col("Ticket.status")), "count"]],
group: ['userId']
// where: where_clause , });
}
else {
// attributes: ['id', 'status', [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"], if (userId.length>0) {
// [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.updatedAt"),"%d/%m/%Y %H:%i:%s"),"updatedAt"]], where_clause = {
userId: userId,
createdAt: {
[Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate + ' 23:59:59.999999'
},
}
}
else {
where_clause = {
createdAt: {
[Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate + ' 23:59:59.999999'
},
}
}
// include: [ objQuery = await UserOnlineTime.findAll({
// {
// model: Message,
// required:true,
// separate: true,
// attributes: ['body', 'read', 'mediaType','fromMe', 'mediaUrl', [Sequelize.fn("DATE_FORMAT",Sequelize.col("createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"]], where: where_clause,
raw: true,
// order: [ // attributes: ['userId', [Sequelize.literal(`( SELECT SUM(time_to_sec(TIME(onlineTime)) ))`), 'sum']],
// ['createdAt', 'ASC'] attributes: ['userId', [Sequelize.literal(`( SELECT SEC_TO_TIME(SUM(time_to_sec(TIME(onlineTime)) )))`), 'sum']],
// ] group: ['userId']
// }
// ],
}); });
if (!ticket) {
throw new AppError("ERR_NO_TICKET_FOUND", 404);
} }
return ticket;
if (!objQuery) {
throw new AppError("ERR_NO_OBJ_QUERY_FOUND", 404);
}
return objQuery;
}; };
export default ShowUserServiceReport; export default ShowUserServiceReport;

View File

@ -59,6 +59,10 @@ const NotificationsPopOver = () => {
const historyRef = useRef(history); const historyRef = useRef(history);
const { handleLogout } = useContext(AuthContext);
useEffect(() => { useEffect(() => {
soundAlertRef.current = play; soundAlertRef.current = play;
@ -83,6 +87,23 @@ const NotificationsPopOver = () => {
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"){
console.log('___________data.userId: ', data.userOnlineTime['status'])
if(`${user.id}` === data.userOnlineTime['userId']){
socket.emit("online", {logoutUserId: user.id})
handleLogout();
}
}
});
socket.on("isOnline", (data) => { socket.on("isOnline", (data) => {
// console.log('___________data.userId: ', data.userId) // console.log('___________data.userId: ', data.userId)

View File

@ -0,0 +1,126 @@
import React, { useState, useEffect, useReducer, useContext, useRef } from "react";
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Switch from '@mui/material/Switch';
export default function MaxWidthDialog(props) {
const [open, setOpen] = useState(false);
const [fullWidth, setFullWidth] = useState(true);
const [currency, setCurrency] = useState(props.reportOption);
useEffect(()=>{
props.func(currency);
},[currency, props])
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const handleMaxWidthChange = (event) => {
setCurrency( event.target.value)
console.log('event.target.value: ', event.target.value)
};
const handleFullWidthChange = (event) => {
setFullWidth(event.target.checked);
};
return (
<React.Fragment>
<Button variant="outlined" onClick={handleClickOpen}>
MENU
</Button>
<Dialog
fullWidth={fullWidth}
maxWidth={'sm'}
open={open}
onClose={handleClose}
>
<DialogTitle>Relatórios</DialogTitle>
<DialogContent>
<DialogContentText>
Escolha uma opção de relatório abaixo
</DialogContentText>
<Box
noValidate
component="form"
sx={{
display: 'flex',
flexDirection: 'column',
m: 'auto',
width: 'fit-content',
}}
>
<FormControl sx={{ mt: 2, minWidth: 420 }}>
<InputLabel htmlFor="opcoes">opcoes</InputLabel>
<Select
autoFocus
value={currency}
onChange={handleMaxWidthChange}
label="opcoes"
inputProps={{
name: 'opcoes',
id: 'opcoes',
}}
>
{props.currencies.map((option, index) => (
<MenuItem key={index} value={option.value}> {option.label} </MenuItem>
))}
{/* <MenuItem value={false}>false</MenuItem>
<MenuItem value="1">xs</MenuItem>
<MenuItem value="2">sm</MenuItem>
<MenuItem value="3">md</MenuItem>
<MenuItem value="4">lg</MenuItem>
<MenuItem value="5">xl</MenuItem> */}
</Select>
</FormControl>
{/* <FormControlLabel
sx={{ mt: 1 }}
control={
<Switch checked={fullWidth} onChange={handleFullWidthChange} />
}
label="Full width"
/> */}
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Ok</Button>
</DialogActions>
</Dialog>
</React.Fragment>
);
}

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect, useReducer, useContext, useRef} from "react"; import React, { useState, useEffect, useReducer, useContext, useRef } from "react";
import MainContainer from "../../components/MainContainer"; import MainContainer from "../../components/MainContainer";
import api from "../../services/api"; import api from "../../services/api";
import SelectField from "../../components/Report/SelectField"; import SelectField from "../../components/Report/SelectField";
@ -13,13 +13,19 @@ import { Can } from "../../components/Can";
import { Button } from "@material-ui/core"; import { Button } from "@material-ui/core";
import ReportModal from "../../components/ReportModal";
// test del import MaterialTable from 'material-table';
import Delete from '@material-ui/icons/Delete';
// import ExportCSV from '../../components/Report/ExportCSV' import Edit from '@material-ui/icons/Edit';
import LogoutIcon from '@material-ui/icons/CancelOutlined';
import { CSVLink } from "react-csv"; import { CSVLink } from "react-csv";
import openSocket from "socket.io-client";
const report = [{ 'value': '1', 'label': 'Atendimento por atendentes' }, { 'value': '2', 'label': 'Usuários online/offline' }]
let columns = [ let columns = [
{ {
key: 'ticket.whatsapp.name', key: 'ticket.whatsapp.name',
@ -69,17 +75,42 @@ let columns = [
{ {
key: 'ticket.status', key: 'ticket.status',
label: 'Status', label: 'Status',
}, }]
]
// //
const reducerQ = (state, action) =>{
if(action.type === 'LOAD_QUERY'){
const reducerQ = (state, action) => {
if (action.type === "DELETE_USER_STATUS") {
const userId = action.payload;
console.log('Entrou no delete user status userId: ', userId)
const userIndex = state.findIndex((u) => `${u.id}` === `${userId}`);
console.log('>>>>>>>>>>>>>>>>>>>>> userIndex: ', userIndex)
if (userIndex !== -1) {
state.splice(userIndex, 1);
}
return [...state];
}
if (action.type === 'LOAD_QUERY') {
const queries = action.payload const queries = action.payload
@ -89,10 +120,10 @@ const reducerQ = (state, action) =>{
const queryIndex = state.findIndex((q) => q.id === query.id) const queryIndex = state.findIndex((q) => q.id === query.id)
if(queryIndex !== -1){ if (queryIndex !== -1) {
state[queryIndex] = query state[queryIndex] = query
} }
else{ else {
newQueries.push(query) newQueries.push(query)
} }
@ -101,6 +132,81 @@ const reducerQ = (state, action) =>{
return [...state, ...newQueries] return [...state, ...newQueries]
} }
if (action.type === "UPDATE_STATUS_ONLINE") {
let onlineUser = action.payload
let index = -1
console.log('sssssssssstate: ', state, ' | ONLINE USERS: onlineUser.userId ', onlineUser.userId)
if (onlineUser.sumOpen || onlineUser.sumClosed) {
index = state.findIndex((e) => ((onlineUser.sumOpen && e.id === onlineUser.sumOpen.userId) || (onlineUser.sumClosed && e.id === onlineUser.sumClosed.userId)))
}
else {
index = state.findIndex((e) => `${e.id}` === `${onlineUser.userId}`)
}
console.log(' *********************** index: ', index)
if (index !== -1) {
console.log('ENTROU NO INDEX')
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])) {
state[index].sumOnlineTime = { userId: onlineUser.userId, sum: (onlineUser.onlineTime).split(" ")[1] }
}
}
if (onlineUser.sumOpen) {
if ("sumOpen" in state[index]) {
console.log(' >>>>>>>>>>>>>>>>>> sumOpen 1 | state[index].sumOpen["count"]: ', state[index].sumOpen['count'], ' | onlineUser.sumOpen.count: ', onlineUser.sumOpen.count)
state[index].sumOpen['count'] = onlineUser.sumOpen.count
} else if (!("sumOpen" in state[index])) {
console.log(' >>>>>>>>>>>>>>>>>> sumOpen 1')
state[index].sumOpen = onlineUser.sumOpen
}
}
if (onlineUser.sumClosed) {
if ("sumClosed" in state[index]) {
console.log(' >>>>>>>>>>>>>>>>>> sumClosed 1 | state[index].sumClosed["count"]: ', state[index].sumClosed['count'], ' | onlineUser.sumClosed.count: ', onlineUser.sumClosed.count)
state[index].sumClosed['count'] = onlineUser.sumClosed.count
} else if (!("sumClosed" in state[index])) {
console.log(' >>>>>>>>>>>>>>>>>> sumOpen 1')
state[index].sumClosed = onlineUser.sumClosed
}
}
}
return [...state]
}
if (action.type === "RESET") { if (action.type === "RESET") {
return []; return [];
} }
@ -127,6 +233,16 @@ const reducer = (state, action) => {
return [...state, ...newUsers]; return [...state, ...newUsers];
} }
if (action.type === "DELETE_USER") {
const userId = action.payload;
const userIndex = state.findIndex((u) => u.id === userId);
if (userIndex !== -1) {
state.splice(userIndex, 1);
}
return [...state];
}
if (action.type === "RESET") { if (action.type === "RESET") {
return []; return [];
} }
@ -177,47 +293,10 @@ let columnsData = [
{ title: 'Assunto', field: 'queue.name' }, { title: 'Assunto', field: 'queue.name' },
{ title: 'Status', field: 'status' }, { title: 'Status', field: 'status' },
{ title: 'Criado', field: 'createdAt' }, { title: 'Criado', field: 'createdAt' },
{ title: 'Atualizado', field: 'updatedAt',
/*cellStyle: {
backgroundColor: '#039be5',
color: '#FFF'
},
headerStyle: {
backgroundColor: '#039be5',
fontSize: 12
}*/
},
];
/*const currencies = [
{ {
value: '1', title: 'Atualizado', field: 'updatedAt',
label: 'Adriano',
},
{
value: '2',
label: 'Aguinaldo',
},
{
value: '3',
label: 'Maria',
},
{
value: '4',
label: 'Suely',
},
{
value: '0',
label: '',
},
];*/
}];
const Report = () => { const Report = () => {
@ -241,12 +320,22 @@ const Report = () => {
const [dataCSV, setDataCSV] = useState([]) const [dataCSV, setDataCSV] = useState([])
const [isMount, setIsMount] = useState(true); const [isMount, setIsMount] = useState(true);
const [reportOption, setReport] = useState('1')
const [reporList,] = useState(report)
const [profile, setProfile] = useState('')
const [dataRows, setData] = useState([]);
const [selectedUserId, setSelectedUserId] = useState(null);
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }); dispatch({ type: "RESET" });
dispatchQ({ type: "RESET" }) dispatchQ({ type: "RESET" })
setPageNumber(1); setPageNumber(1);
}, [searchParam]); }, [searchParam, profile]);
useEffect(() => { useEffect(() => {
//setLoading(true); //setLoading(true);
@ -255,13 +344,18 @@ const Report = () => {
const fetchUsers = async () => { const fetchUsers = async () => {
try { try {
console.log('profile: ', profile)
const { data } = await api.get("/users/", { const { data } = await api.get("/users/", {
params: { searchParam, pageNumber }, params: { searchParam, pageNumber, profile },
}); });
dispatch({ type: "LOAD_USERS", payload: data.users }); dispatch({ type: "LOAD_USERS", payload: data.users });
//setHasMore(data.hasMore); //setHasMore(data.hasMore);
//setLoading(false); //setLoading(false);
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
@ -271,7 +365,7 @@ const Report = () => {
}, 500); }, 500);
return () => clearTimeout(delayDebounceFn); return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber]); }, [searchParam, pageNumber, reportOption, profile]);
@ -284,7 +378,9 @@ const Report = () => {
const fetchQueries = async () => { const fetchQueries = async () => {
try { try {
const dataQuery = await api.get("/reports/", {params: {userId, startDate, endDate },}); if (reportOption === '1') {
const dataQuery = await api.get("/reports/", { params: { userId, startDate, endDate }, });
dispatchQ({ type: "RESET" }) dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data }); dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
@ -294,6 +390,21 @@ const Report = () => {
console.log() console.log()
}
else if (reportOption === '2') {
const dataQuery = await api.get("/reports/user/services", { params: { userId, startDate, endDate }, });
dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
//setLoading(false);
console.log('REPORT 2 dataQuery : ', dataQuery.data)
console.log()
}
} catch (err) { } catch (err) {
console.log(err); console.log(err);
} }
@ -304,34 +415,61 @@ const Report = () => {
}, 500); }, 500);
return () => clearTimeout(delayDebounceFn); return () => clearTimeout(delayDebounceFn);
}, [userId, startDate, endDate]); }, [userId, startDate, endDate, reportOption]);
// Get from child 1 // Get from child 1
const datePicker1Value = (data) => { const datePicker1Value = (data) => {
setDatePicker1(data) setDatePicker1(data)
} }
// Get from child 2 // Get from child 2
const datePicker2Value = (data) => { const datePicker2Value = (data) => {
setDatePicker2(data) setDatePicker2(data)
} }
// Get from child 3 // Get from child 3
const textFieldSelectUser = (data) => { const textFieldSelectUser = (data) => {
setUser(data) setUser(data)
} }
// Get from report option
const reportValue = (data) => {
// test del setReport(data)
const handleCSVMessages = () =>{ console.log(' data: ', data)
}
useEffect(() => {
if (reportOption === '1') {
setProfile('')
}
else if (reportOption === '2') {
setProfile('user')
}
}, [reportOption])
// useEffect(() => {
// console.log('>>>>>>>>>>>>>>>>>> New query: ', query)
// }, [query])
// test del
const handleCSVMessages = () => {
// setLoading(true); // setLoading(true);
@ -339,19 +477,19 @@ const handleCSVMessages = () =>{
try { try {
const dataQuery = await api.get("/reports/messages", {params: {userId, startDate, endDate },}); const dataQuery = await api.get("/reports/messages", { params: { userId, startDate, endDate }, });
// console.log('dataQuery messages: ', dataQuery.data) // console.log('dataQuery messages: ', dataQuery.data)
if(dataQuery.data.length > 0){ if (dataQuery.data.length > 0) {
let dataCSVFormat = dataQuery.data ; let dataCSVFormat = dataQuery.data;
for(var i = 0; i<dataCSVFormat.length; i++){ for (var i = 0; i < dataCSVFormat.length; i++) {
if(dataCSVFormat[i].fromMe){ if (dataCSVFormat[i].fromMe) {
dataCSVFormat[i].fromMe = 'Atendente' dataCSVFormat[i].fromMe = 'Atendente'
} }
else{ else {
dataCSVFormat[i].fromMe = 'Cliente' dataCSVFormat[i].fromMe = 'Cliente'
} }
} }
@ -372,24 +510,116 @@ const handleCSVMessages = () =>{
fetchQueries(); fetchQueries();
} }
useEffect(() => { useEffect(() => {
if(isMount){ if (isMount) {
return; return;
} }
csvLink.current.link.click() csvLink.current.link.click()
}, [dataCSV, isMount, csvLink]); }, [dataCSV, isMount, csvLink]);
useEffect(() => {
if (reportOption === '2') {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("onlineStatus", (data) => {
// setLoading(true);
let date = new Date().toLocaleDateString('pt-BR').split('/')
let dateToday = `${date[2]}-${date[1]}-${date[0]}`
console.log('date: ', new Date(startDate).toLocaleDateString('pt-BR'))
console.log('date2: ', startDate)
if (data.action === "logout" || (data.action === "update" &&
((`${startDate}` === `${endDate}`) && (`${endDate}` === `${dateToday}`) && (`${startDate}` === `${dateToday}`)))) {
console.log('UPDATE FROM ONLINE/OFFLINE LOGED USERS: ', data.userOnlineTime, ' | data.action : ', data.action)
dispatchQ({ type: "UPDATE_STATUS_ONLINE", payload: data.userOnlineTime });
}
else if (data.action === "delete") {
dispatchQ({ type: "DELETE_USER_STATUS", payload: data.userOnlineTime });
}
// setLoading(false);
});
socket.on("user", (data) => {
if (data.action === "delete") {
console.log(' entrou no delete user: ', data)
dispatch({ type: "DELETE_USER", payload: +data.userId });
}
});
return () => {
socket.disconnect();
};
}
}, [reportOption, startDate, endDate]);
// const handleDeleteRows = (id) => {
// let _data = [...dataRows];
// _data.forEach(rd => {
// _data = _data.filter(t => t.id !== id);
// });
// setData(_data);
// };
useEffect(() => {
//if (!loading) {
// setData(query.map(({ scheduleReminder, ...others }) => (
// { ...others, 'scheduleReminder': `${others.statusChatEndId}` === '3' ? 'Agendamento' : 'Lembrete' }
// )))
// }
setData(query.map((column) => { return { ...column } }))
}, [query])
const handleLogouOnlineUser = async (userId) => {
try {
await api.get(`/users/logout/${userId}`);
//toast.success(("Desloged!"));
//handleDeleteRows(scheduleId)
} catch (err) {
// toastError(err);
}
setSelectedUserId(null);
};
return ( return (
<Can <Can
@ -400,16 +630,18 @@ useEffect(() => {
<MainContainer> <MainContainer>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}>
<Item><SelectField func={textFieldSelectUser} emptyField={true} header={'Usuário'} currencies={users.map((obj)=>{ <Item><SelectField func={textFieldSelectUser} emptyField={true} header={'Usuário'} currencies={users.map((obj) => {
return {'value': obj.id, 'label': obj.name} return { 'value': obj.id, 'label': obj.name }
})}/></Item> })} /></Item>
<Item><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={false} title={'Data inicio'}/></Item> <Item><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={false} title={'Data inicio'} /></Item>
<Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={false} title={'Data fim'}/></Item> <Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={false} title={'Data fim'} /></Item>
<Item sx={{ gridColumn: '4 / 5' }}> <Item sx={{ gridColumn: '4 / 5' }}>
<Button <ReportModal currencies={reporList} func={reportValue} reportOption={reportOption} />
{/* <Button
variant="contained" variant="contained"
color="primary" color="primary"
onClick={(e) => handleCSVMessages()} onClick={(e) => handleCSVMessages()}
@ -421,10 +653,10 @@ useEffect(() => {
<CSVLink <CSVLink
data={dataCSV} data={dataCSV}
headers={columns} headers={columns}
filename= {'Relatorio_detalhado_atendimento_atendentes.csv'} filename={'Relatorio_detalhado_atendimento_atendentes.csv'}
target={'_blank'} target={'_blank'}
ref={csvLink}/> ref={csvLink} />
</div> </div> */}
</Item> </Item>
@ -435,11 +667,140 @@ useEffect(() => {
}}> }}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}> <Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
{reportOption === '1' &&
<MTable data={query} <MTable data={query}
columns={columnsData} columns={columnsData}
hasChild={true} hasChild={true}
removeClickRow={false} removeClickRow={false}
table_title={'Relatório de atendimento por atendentes'}/> table_title={'Atendimento por atendentes'} />
}
{reportOption === '2' &&
<MaterialTable
localization={{
header: {
actions: 'Deslogar'
},
}}
title="Usuários online/offline"
columns={
[
// { title: 'Foto', field: 'ticket.contact.profilePicUrl', render: rowData => <img src={rowData['ticket.contact.profilePicUrl']} alt="imagem de perfil do whatsapp" style={{ width: 40, borderRadius: '50%' }} /> },
{ title: 'Nome', field: 'name' },
{
title: 'Status', field: 'statusOnline.status',
cellStyle: (e, rowData) => {
if (rowData['statusOnline'] && rowData['statusOnline'].status) {
if (rowData['statusOnline'].status === 'offline') {
return { color: "red" };
}
else if (rowData['statusOnline'].status === 'online') {
return { color: "green" };
}
else if (rowData['statusOnline'].status === 'logout...') {
return { color: "orange" };
}
else if (rowData['statusOnline'].status === 'waiting...') {
return { color: "orange" };
}
}
},
},
{ title: 'Tempo online', field: 'sumOnlineTime.sum' },
{ title: 'Data inicio', field: 'startDate' },
{ title: 'Data fim', field: 'endDate' },
{ title: 'Em atendimento', field: 'sumOpen.count' },
{ title: 'Finalizado', field: 'sumClosed.count' },
]
}
data={dataRows}
// icons={tableIcons}
actions={[
(rowData) => {
if (rowData.statusOnline &&
rowData.statusOnline['status'] &&
rowData.statusOnline['status'] === 'online') {
return {
icon: LogoutIcon,
tooltip: 'deslogar',
disable: false,
onClick: (event, rowData) => {
console.log(' ROW DATA INFO: ', rowData, ' | rowData: ', rowData.id)
handleLogouOnlineUser(rowData.id)
}
}
}
}
]}
options={
{
search: true,
selection: false,
paging: false,
padding: 'dense',
sorting: true,
//loadingType: 'linear',
searchFieldStyle: {
width: 300,
},
pageSize: 20,
headerStyle: {
position: "sticky",
top: "0"
},
maxBodyHeight: "400px",
rowStyle: {
fontSize: 14,
}
// cellStyle: (rowData) => {
// return {
// fontSize: 12,
// color: "#fff",
// };
// }
}}
/>
}
</Item> </Item>
</Box> </Box>

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect, useReducer} from "react"; import React, { useState, useEffect, useReducer } from "react";
import MainContainer from "../../components/MainContainer"; import MainContainer from "../../components/MainContainer";
import api from "../../services/api"; import api from "../../services/api";
@ -39,9 +39,9 @@ import ConfirmationModal from "../../components/ConfirmationModal";
const reducerQ = (state, action) =>{ const reducerQ = (state, action) => {
if(action.type === 'LOAD_QUERY'){ if (action.type === 'LOAD_QUERY') {
const queries = action.payload const queries = action.payload
@ -51,10 +51,10 @@ const reducerQ = (state, action) =>{
const queryIndex = state.findIndex((q) => q.id === query.id) const queryIndex = state.findIndex((q) => q.id === query.id)
if(queryIndex !== -1){ if (queryIndex !== -1) {
state[queryIndex] = query state[queryIndex] = query
} }
else{ else {
newQueries.push(query) newQueries.push(query)
} }
@ -172,19 +172,6 @@ Item.propTypes = {
// let columnsData = [
// { title: 'Foto', field: 'ticket.contact.profilePicUrl', render: rowData => <img src={rowData['ticket.contact.profilePicUrl']} style={{width: 40, borderRadius: '50%'}}/> },
// { title: 'Nome', field: 'ticket.contact.name' },
// { title: 'Contato', field: 'ticket.contact.number' },
// { title: 'schedulingTime', field: 'schedulingTime' },
// { title: 'schedulingDate', field: 'schedulingDate' },
// { title: 'message', field: 'message' },
// ];
const SchedulesReminder = () => { const SchedulesReminder = () => {
@ -302,7 +289,7 @@ const SchedulesReminder = () => {
const fetchQueries = async () => { const fetchQueries = async () => {
try { try {
const dataQuery = await api.get("/schedules/", {params: {contactNumber, startDate, endDate },}); const dataQuery = await api.get("/schedules/", { params: { contactNumber, startDate, endDate }, });
dispatchQ({ type: "RESET" }) dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data }); dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
@ -324,7 +311,7 @@ const SchedulesReminder = () => {
useEffect(() => { useEffect(() => {
if(!loading){ if (!loading) {
@ -336,52 +323,52 @@ const SchedulesReminder = () => {
}, [loading, query]) }, [loading, query])
// Get from child 1 // Get from child 1
const datePicker1Value = (data) => { const datePicker1Value = (data) => {
setDatePicker1(data) setDatePicker1(data)
} }
// Get from child 2 // Get from child 2
const datePicker2Value = (data) => { const datePicker2Value = (data) => {
setDatePicker2(data) setDatePicker2(data)
} }
const handleSearch = (event) => { const handleSearch = (event) => {
setContactNumber(event.target.value.toLowerCase()); setContactNumber(event.target.value.toLowerCase());
}; };
const handleClear = () => { const handleClear = () => {
setContactNumber('') setContactNumber('')
setReset(true) setReset(true)
} }
const handleCloseConfirmationModal = () => { const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false); setConfirmModalOpen(false);
setSelectedSchedule(null); setSelectedSchedule(null);
}; };
// const handleDeleteRows = (id) => { // const handleDeleteRows = (id) => {
// let _data = [...dataRows]; // let _data = [...dataRows];
// _data.forEach(rd => { // _data.forEach(rd => {
// _data = _data.filter(t => t.id !== id); // _data = _data.filter(t => t.id !== id);
// }); // });
// setData(_data); // setData(_data);
// }; // };
const handleDeleteSchedule = async (scheduleId) => { const handleDeleteSchedule = async (scheduleId) => {
try { try {
await api.delete(`/schedule/${scheduleId}`); await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete/Agendamento deletado com sucesso!")); toast.success(("Lembrete/Agendamento deletado com sucesso!"));
@ -391,11 +378,11 @@ const handleDeleteSchedule = async (scheduleId) => {
} }
setSelectedSchedule(null); setSelectedSchedule(null);
}; };
const handleUpdateSchedule = async (scheduleData, rowsDataNew) => { const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
try { try {
await api.post("/schedule", scheduleData); await api.post("/schedule", scheduleData);
@ -421,12 +408,12 @@ const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
} }
// //
setSelectedSchedule(null); setSelectedSchedule(null);
}; };
const chatEndVal = (data, rowsDataNew) => { const chatEndVal = (data, rowsDataNew) => {
if(data){ if (data) {
@ -437,10 +424,10 @@ const chatEndVal = (data, rowsDataNew) => {
} }
} }
const handleModal = (rowData) => { const handleModal = (rowData) => {
// NATY // NATY
@ -452,7 +439,7 @@ const handleModal = (rowData) => {
rowData={rowData} rowData={rowData}
/>) />)
}; };
return ( return (
@ -478,8 +465,8 @@ const handleModal = (rowData) => {
<Item><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={true} reset={resetChild} setReset={setReset} title={'Data inicio'}/></Item> <Item><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={true} reset={resetChild} setReset={setReset} title={'Data inicio'} /></Item>
<Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={true} reset={resetChild} setReset={setReset} title={'Data fim'}/></Item> <Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={true} reset={resetChild} setReset={setReset} title={'Data fim'} /></Item>
<Item sx={{ gridColumn: '4 / 5' }}> <Item sx={{ gridColumn: '4 / 5' }}>
{/* <Button size="small" variant="contained" onClick={()=>{handleQuery()}}>GO</Button>*/} {/* <Button size="small" variant="contained" onClick={()=>{handleQuery()}}>GO</Button>*/}
@ -505,7 +492,7 @@ const handleModal = (rowData) => {
<ConfirmationModal <ConfirmationModal
title={selectedSchedule && `Deletar ${''+selectedSchedule.statusChatEndId === '2' ? 'lembrete' : 'agendamento'} do dia ${selectedSchedule.schedulingDate.split(' ')[0]} ${selectedSchedule.schedulingDate.split(' ')[1]} ?`} title={selectedSchedule && `Deletar ${'' + selectedSchedule.statusChatEndId === '2' ? 'lembrete' : 'agendamento'} do dia ${selectedSchedule.schedulingDate.split(' ')[0]} ${selectedSchedule.schedulingDate.split(' ')[1]} ?`}
open={confirmModalOpen} open={confirmModalOpen}
onClose={handleCloseConfirmationModal} onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)} onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
@ -518,10 +505,10 @@ const handleModal = (rowData) => {
columns={ columns={
[ [
{ title: 'Foto', field: 'ticket.contact.profilePicUrl', render: rowData => <img src={rowData['ticket.contact.profilePicUrl']} alt="imagem de perfil do whatsapp" style={{width: 40, borderRadius: '50%'}}/> }, { title: 'Foto', field: 'ticket.contact.profilePicUrl', render: rowData => <img src={rowData['ticket.contact.profilePicUrl']} alt="imagem de perfil do whatsapp" style={{ width: 40, borderRadius: '50%' }} /> },
{ title: 'Nome', field: 'ticket.contact.name' }, { title: 'Nome', field: 'ticket.contact.name' },
{ title: 'Contato', field: 'ticket.contact.number' }, { title: 'Contato', field: 'ticket.contact.number' },
{ title: 'Lemb/Agen', field: 'scheduleReminder'}, { title: 'Lemb/Agen', field: 'scheduleReminder' },
{ title: 'Envio', field: 'schedulingTime' }, { title: 'Envio', field: 'schedulingTime' },
{ title: 'Data', field: 'schedulingDate' }, { title: 'Data', field: 'schedulingDate' },
{ title: 'Mensagem', field: 'message', width: "80%" }, { title: 'Mensagem', field: 'message', width: "80%" },