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 UserOnlineTime from "../models/UserOnlineTime";
import { Op, Sequelize } from "sequelize";
import { Op, Sequelize,literal } 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";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
type IndexQuery = {
userId: string;
@ -27,13 +29,13 @@ type IndexQuery = {
export const reportUserByDateStartDateEnd = 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
const data_query = await ShowTicketReport(userId, startDate, endDate);
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> => {

View File

@ -14,6 +14,10 @@ import ListSchedulingNotifyContactService from "../services/SchedulingNotifySer
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 = {
@ -37,6 +41,8 @@ interface TicketData {
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
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> => {
const {
@ -140,6 +146,8 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
const { ticketId } = req.params;
const userOldInfo = await Ticket.findByPk(ticketId)
let ticket2 = {}
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);
@ -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);
};

View File

@ -10,35 +10,66 @@ import UpdateUserService from "../services/UserServices/UpdateUserService";
import ShowUserService from "../services/UserServices/ShowUserService";
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 = {
searchParam: string;
pageNumber: string;
profile?: string;
};
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({
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) {
if(user.profile!=='master'){
if (user.profile !== 'master') {
auxUsers.push(user)
}
}
return res.json({ users: auxUsers, 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> => {
const { email, password, name, profile, queueIds } = req.body;
@ -62,6 +93,10 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
user
});
await stopWhoIsOnlineMonitor()
await startWhoIsOnlineMonitor()
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);
};
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 (
req: Request,
res: Response
@ -105,13 +169,27 @@ export const remove = async (
throw new AppError("ERR_NO_PERMISSION", 403);
}
await DeleteUserService(userId);
const io = getIO();
io.emit("user", {
action: "delete",
userId
});
//test del
await stopWhoIsOnlineMonitor()
io.emit("onlineStatus", {
action: "delete",
userOnlineTime: userId
});
await startWhoIsOnlineMonitor()
//
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,24 +25,28 @@ const monitor = async () => {
//console.log(dateParm);
try {
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
const { schedulingNotifies, count, hasMore } = await ListSchedulingNotifyService({ searchParam: dateParm, pageNumber: "1" });
if(schedulingNotifies.length){
if(schedulingNotifies.length){
const ticket = await ShowTicketService(schedulingNotifies[0].ticketId);
const ticket = await ShowTicketService(schedulingNotifies[0].ticketId);
SetTicketMessagesAsRead(ticket);
SetTicketMessagesAsRead(ticket);
await SendWhatsAppMessage({
body: schedulingNotifies[0].message, ticket
});
await SendWhatsAppMessage({
body: schedulingNotifies[0].message, ticket
});
DeleteSchedulingNotifyService(schedulingNotifies[0].id)
DeleteSchedulingNotifyService(schedulingNotifies[0].id)
}
} 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 ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOfflineService";
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;
// 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 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
let timeInterval = 5
let lstOnline: any = []
let deleted: boolean = false;
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) {
onlineUsers.forEach(async user => {
await createOrUpdateOnlineUserService({ userId: user.userId, status: 'offline' })
});
// if (onlineUsers.length > 0) {
// onlineUsers.forEach(async user => {
// 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');
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();
io.emit("isOnline", { action: "online", userId: u.id });
});
if(test.ob){
if (test.ob) {
if (count > 1) {
count = 0
}
if (count == 0) {
// uuid = test.uuid
uuid = test.ob.uuid
}
@ -89,55 +91,136 @@ const monitor = async () => {
console.log('ALL USERS CLIENTS OFFLINE 1...........')
await setOfflineAllUsers()
//await setOfflineAllUsers()
test.ob.listOnline = []
test.ob.listOnline2 = []
test.ob.listOnlineAux = []
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 {
console.log('*usersOnline: ', test.ob.listOnline)
checked = false
count2 = 0
}
}
else {
console.log('ALL USERS CLIENTS OFFLINE 2...........')
if(!checked){
await setOfflineAllUsers()
checked = true
emitterOnline(el, el.status)
}
}
});
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)
}
}
})
}
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)
if (countTest > 5) {
countTest = 0
}
if (countTest == 0) {
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
}
}
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 ListUserParamiterService from "../services/UserServices/ListUserParamiterService";
import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-fns";
let io: SocketIO;
@ -18,12 +18,17 @@ import ListUserOnlineOffline from "../services/UserServices/ListUsersOnlineOffli
let count: number = 0
let listOnline: any[] = []
let listOnline2: any[] = []
let listOnlineAux: any[] = []
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 })))
@ -31,6 +36,9 @@ let dateTime = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss',
//
export const initIO = (httpServer: Server): SocketIO => {
io = new SocketIO(httpServer, {
cors: {
@ -43,69 +51,135 @@ export const initIO = (httpServer: Server): SocketIO => {
logger.info("Client Connected");
socket.on("online", async (userId: string) => {
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
}
socket.on("online", (userId: any) => {
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
count++
});

View File

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

View File

@ -6,7 +6,6 @@ import * as UserController from "../controllers/UserController";
const userRoutes = Router();
userRoutes.get("/users", isAuth, UserController.index);
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/logout/:userId", isAuth, UserController.logoutUser);
userRoutes.delete("/users/:userId", isAuth, UserController.remove);
export default userRoutes;

View File

@ -5,7 +5,7 @@ import { logger } from "./utils/logger";
import { StartAllWhatsAppsSessions } from "./services/WbotServices/StartAllWhatsAppsSessions";
import { startSchedulingMonitor } from "./helpers/SchedulingNotifySendMessage"
import { startWhoIsOnlinegMonitor } from "./helpers/WhoIsOnlineMonitor"
import { startWhoIsOnlineMonitor } from "./helpers/WhoIsOnlineMonitor"
const server = app.listen(process.env.PORT, () => {
logger.info(`Server started on port: ${process.env.PORT}`);
@ -16,4 +16,4 @@ StartAllWhatsAppsSessions();
gracefulShutdown(server);
startSchedulingMonitor(5000)
startWhoIsOnlinegMonitor(5000)
startWhoIsOnlineMonitor(2000)

View File

@ -4,6 +4,15 @@ import GetDefaultWhatsApp from "../../helpers/GetDefaultWhatsApp";
import Ticket from "../../models/Ticket";
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 {
contactId: number;
status: string;
@ -34,6 +43,21 @@ const CreateTicketService = async ({
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;
};

View File

@ -6,45 +6,73 @@ import { addHours, addMinutes, addSeconds, intervalToDuration, add } from "date-
import format from 'date-fns/format';
import ptBR from 'date-fns/locale/pt-BR';
import { stat } from "fs";
import { getIO } from "../../libs/socket";
import User from '../../models/User'
interface Request {
userId: string | number,
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 ({
userId,
status,
}: 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({
where: {
[Op.and]: [
{
userId: userId
userId: userId
},
{
"$createdAt$": Sequelize.where(Sequelize.fn("date", Sequelize.col("createdAt")), `${dateTime.fullDate}`)
},
]
]
}
});
if(userOnlineTime){
try{
if (userOnlineTime) {
try {
let oldStatus = userOnlineTime.status
if(oldStatus=='online' && status === 'offline'){
//updatedAt
let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date()})
console.log('>>>>>>>>> oldStatus: ', oldStatus, ' | new status', status)
if (oldStatus == 'online' && status === 'offline') {
//updatedAt
let newtTime = intervalToDuration({ start: userOnlineTime.updatedAt, end: new Date() })
console.log('TESTANDO INTERVAL DURATION: ', newtTime)
console.log('hours: ', newtTime.hours, ' | minutes: ', newtTime.minutes, ' | seconds: ', newtTime.seconds)
@ -55,21 +83,21 @@ const CreateOrUpdateUserOnlineTime = async ({
onlineTime.setUTCMinutes(userOnlineTime.onlineTime.getMinutes())
onlineTime.setUTCSeconds(userOnlineTime.onlineTime.getSeconds())
console.log('userOnlineTime.onlineTime: ',userOnlineTime.onlineTime)
console.log('userOnlineTime.onlineTime.getHours(): ',userOnlineTime.onlineTime.getHours())
console.log('userOnlineTime.onlineTime.getMinutes(): ',userOnlineTime.onlineTime.getMinutes())
console.log('userOnlineTime.onlineTime.getSeconds(): ',userOnlineTime.onlineTime.getSeconds())
console.log('userOnlineTime.onlineTime: ', userOnlineTime.onlineTime)
console.log('userOnlineTime.onlineTime.getHours(): ', userOnlineTime.onlineTime.getHours())
console.log('userOnlineTime.onlineTime.getMinutes(): ', userOnlineTime.onlineTime.getMinutes())
console.log('userOnlineTime.onlineTime.getSeconds(): ', userOnlineTime.onlineTime.getSeconds())
console.log('online time 3: ', onlineTime)
if(newtTime.hours && +newtTime.hours > 0){
if (newtTime.hours && +newtTime.hours > 0) {
onlineTime = addHours(onlineTime, newtTime.hours)
}
if(newtTime.minutes && +newtTime.minutes > 0){
onlineTime = addMinutes(onlineTime,newtTime.minutes)
if (newtTime.minutes && +newtTime.minutes > 0) {
onlineTime = addMinutes(onlineTime, newtTime.minutes)
}
if(newtTime.seconds && +newtTime.seconds > 0){
if (newtTime.seconds && +newtTime.seconds > 0) {
onlineTime = addSeconds(onlineTime, newtTime.seconds)
}
@ -81,22 +109,52 @@ const CreateOrUpdateUserOnlineTime = async ({
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 })
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)
}
}catch(err){
} catch (err) {
throw new AppError("ERR_NO_USER_ONLINE_FOUND", 404);
}
}
if(!userOnlineTime){
if (!userOnlineTime) {
userOnlineTime = await UserOnlineTime.create(
{
@ -105,12 +163,24 @@ const CreateOrUpdateUserOnlineTime = async ({
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
}
}
export default CreateOrUpdateUserOnlineTime
export default CreateOrUpdateUserOnlineTime

View File

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

View File

@ -13,6 +13,7 @@ const ListUserOnlineOffline = async ({date, userId, status}: Request): Promise<U
let where_clause = {}
if(userId && status){
where_clause = {
[Op.and]: [
@ -57,6 +58,12 @@ const ListUserOnlineOffline = async ({date, userId, status}: Request): Promise<U
const users = await UserOnlineTime.findAll({
where: where_clause,
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"]],
})

View File

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

View File

@ -12,63 +12,107 @@ import { Op, where } from "sequelize";
import { Sequelize } from "sequelize";
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 Whatsapp from "../../models/Whatsapp";
import UserOnlineTime from "../../models/UserOnlineTime";
interface Request {
startDate: string;
endDate: string;
userId?: string;
ticketStatus?: string;
}
//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 objQuery: Object[] = []
if(id=='0'){
where_clause = {
createdAt: {
[Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999'
},
if (ticketStatus.length>0) {
if (userId.length>0) {
where_clause = {
userId: userId,
status: ticketStatus,
createdAt: {
[Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate + ' 23:59:59.999999'
},
}
}
}
else{
where_clause = {
userid: id,
createdAt: {
[Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999'
},
else {
where_clause = {
status: ticketStatus,
createdAt: {
[Op.gte]: startDate + ' 00:00:00.000000',
[Op.lte]: endDate + ' 23:59:59.999999'
},
}
}
objQuery = await Ticket.findAll({
where: where_clause,
raw: true,
attributes: ['userId', [Sequelize.fn("COUNT", Sequelize.col("Ticket.status")), "count"]],
group: ['userId']
});
}
else {
if (userId.length>0) {
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'
},
}
}
objQuery = await UserOnlineTime.findAll({
where: where_clause,
raw: true,
// attributes: ['userId', [Sequelize.literal(`( SELECT SUM(time_to_sec(TIME(onlineTime)) ))`), 'sum']],
attributes: ['userId', [Sequelize.literal(`( SELECT SEC_TO_TIME(SUM(time_to_sec(TIME(onlineTime)) )))`), 'sum']],
group: ['userId']
});
}
const ticket = await Ticket.findAll({
// where: where_clause ,
// attributes: ['id', 'status', [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"],
// [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.updatedAt"),"%d/%m/%Y %H:%i:%s"),"updatedAt"]],
// include: [
// {
// 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"]],
// order: [
// ['createdAt', 'ASC']
// ]
// }
// ],
});
if (!ticket) {
throw new AppError("ERR_NO_TICKET_FOUND", 404);
if (!objQuery) {
throw new AppError("ERR_NO_OBJ_QUERY_FOUND", 404);
}
return ticket;
return objQuery;
};
export default ShowUserServiceReport;

View File

@ -59,6 +59,10 @@ const NotificationsPopOver = () => {
const historyRef = useRef(history);
const { handleLogout } = useContext(AuthContext);
useEffect(() => {
soundAlertRef.current = play;
@ -83,6 +87,23 @@ const NotificationsPopOver = () => {
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) => {
// 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 api from "../../services/api";
import SelectField from "../../components/Report/SelectField";
@ -13,13 +13,19 @@ import { Can } from "../../components/Can";
import { Button } from "@material-ui/core";
// test del
// import ExportCSV from '../../components/Report/ExportCSV'
import ReportModal from "../../components/ReportModal";
import MaterialTable from 'material-table';
import Delete from '@material-ui/icons/Delete';
import Edit from '@material-ui/icons/Edit';
import LogoutIcon from '@material-ui/icons/CancelOutlined';
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 = [
{
key: 'ticket.whatsapp.name',
@ -69,30 +75,55 @@ let columns = [
{
key: 'ticket.status',
label: 'Status',
},
]
}]
//
const reducerQ = (state, action) =>{
if(action.type === 'LOAD_QUERY'){
const queries = action.payload
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 newQueries = []
queries.forEach((query) => {
const queryIndex = state.findIndex((q) => q.id === query.id)
if(queryIndex !== -1){
if (queryIndex !== -1) {
state[queryIndex] = query
}
else{
else {
newQueries.push(query)
}
@ -101,6 +132,81 @@ const reducerQ = (state, action) =>{
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") {
return [];
}
@ -127,6 +233,16 @@ const reducer = (state, action) => {
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") {
return [];
}
@ -170,54 +286,17 @@ Item.propTypes = {
let columnsData = [
{ title: 'Unidade', field: 'whatsapp.name' },
{ title: 'Atendente', field: 'user.name' },
{ title: 'Contato', field: 'contact.number' },
{ title: 'Nome', field: 'contact.name' },
{ title: 'Assunto', field: 'queue.name' },
{ title: 'Status', field: 'status' },
{ title: 'Criado', field: 'createdAt' },
{ title: 'Atualizado', field: 'updatedAt',
/*cellStyle: {
backgroundColor: '#039be5',
color: '#FFF'
},
headerStyle: {
backgroundColor: '#039be5',
fontSize: 12
}*/
},
];
/*const currencies = [
{
value: '1',
label: 'Adriano',
},
{
value: '2',
label: 'Aguinaldo',
},
{
value: '3',
label: 'Maria',
},
{
value: '4',
label: 'Suely',
},
{
value: '0',
label: '',
},
];*/
{ title: 'Unidade', field: 'whatsapp.name' },
{ title: 'Atendente', field: 'user.name' },
{ title: 'Contato', field: 'contact.number' },
{ title: 'Nome', field: 'contact.name' },
{ title: 'Assunto', field: 'queue.name' },
{ title: 'Status', field: 'status' },
{ title: 'Criado', field: 'createdAt' },
{
title: 'Atualizado', field: 'updatedAt',
}];
const Report = () => {
@ -241,12 +320,22 @@ const Report = () => {
const [dataCSV, setDataCSV] = useState([])
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(() => {
dispatch({ type: "RESET" });
dispatch({ type: "RESET" });
dispatchQ({ type: "RESET" })
setPageNumber(1);
}, [searchParam]);
}, [searchParam, profile]);
useEffect(() => {
//setLoading(true);
@ -255,13 +344,18 @@ const Report = () => {
const fetchUsers = async () => {
try {
console.log('profile: ', profile)
const { data } = await api.get("/users/", {
params: { searchParam, pageNumber },
params: { searchParam, pageNumber, profile },
});
dispatch({ type: "LOAD_USERS", payload: data.users });
//setHasMore(data.hasMore);
//setLoading(false);
} catch (err) {
console.log(err);
}
@ -271,28 +365,45 @@ const Report = () => {
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber]);
}, [searchParam, pageNumber, reportOption, profile]);
useEffect(() => {
//setLoading(true);
//setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
const dataQuery = await api.get("/reports/", {params: {userId, startDate, endDate },});
dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
if (reportOption === '1') {
//setLoading(false);
const dataQuery = await api.get("/reports/", { params: { userId, startDate, endDate }, });
dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
console.log('dataQuery: ', dataQuery.data)
//setLoading(false);
console.log()
console.log('dataQuery: ', dataQuery.data)
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) {
console.log(err);
@ -304,149 +415,399 @@ const Report = () => {
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [userId, startDate, endDate]);
}, [userId, startDate, endDate, reportOption]);
// Get from child 1
const datePicker1Value = (data) => {
// Get from child 1
const datePicker1Value = (data) => {
setDatePicker1(data)
}
// Get from child 2
const datePicker2Value = (data) => {
setDatePicker2(data)
}
// Get from child 3
const textFieldSelectUser = (data) => {
setUser(data)
}
// test del
const handleCSVMessages = () =>{
// setLoading(true);
const fetchQueries = async () => {
try {
const dataQuery = await api.get("/reports/messages", {params: {userId, startDate, endDate },});
// console.log('dataQuery messages: ', dataQuery.data)
if(dataQuery.data.length > 0){
let dataCSVFormat = dataQuery.data ;
for(var i = 0; i<dataCSVFormat.length; i++){
if(dataCSVFormat[i].fromMe){
dataCSVFormat[i].fromMe = 'Atendente'
}
else{
dataCSVFormat[i].fromMe = 'Cliente'
}
}
// console.log('dataCSVFormat: ', dataCSVFormat)
setDataCSV(dataCSVFormat)
setIsMount(false);
// setDataCSV(dataQuery.data)
}
// setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchQueries();
}
useEffect(() => {
if(isMount){
return;
}
csvLink.current.link.click()
// Get from child 2
const datePicker2Value = (data) => {
}, [dataCSV, isMount, csvLink]);
setDatePicker2(data)
}
// Get from child 3
const textFieldSelectUser = (data) => {
setUser(data)
}
// Get from report option
const reportValue = (data) => {
setReport(data)
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);
const fetchQueries = async () => {
try {
const dataQuery = await api.get("/reports/messages", { params: { userId, startDate, endDate }, });
// console.log('dataQuery messages: ', dataQuery.data)
if (dataQuery.data.length > 0) {
let dataCSVFormat = dataQuery.data;
for (var i = 0; i < dataCSVFormat.length; i++) {
if (dataCSVFormat[i].fromMe) {
dataCSVFormat[i].fromMe = 'Atendente'
}
else {
dataCSVFormat[i].fromMe = 'Cliente'
}
}
// console.log('dataCSVFormat: ', dataCSVFormat)
setDataCSV(dataCSVFormat)
setIsMount(false);
// setDataCSV(dataQuery.data)
}
// setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchQueries();
}
useEffect(() => {
if (isMount) {
return;
}
csvLink.current.link.click()
}, [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 (
<Can
role={userA.profile}
perform="ticket-report:show"
yes={() => (
role={userA.profile}
perform="ticket-report:show"
yes={() => (
<MainContainer>
<MainContainer>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}>
<Item><SelectField func={textFieldSelectUser} emptyField={true} header={'Usuário'} currencies={users.map((obj)=>{
return {'value': obj.id, 'label': obj.name}
})}/></Item>
<Item><SelectField func={textFieldSelectUser} emptyField={true} header={'Usuário'} currencies={users.map((obj) => {
return { 'value': obj.id, 'label': obj.name }
})} /></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><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={false} title={'Data inicio'} /></Item>
<Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={false} title={'Data fim'} /></Item>
<Item sx={{ gridColumn: '4 / 5' }}>
<Button
variant="contained"
color="primary"
onClick={(e) => handleCSVMessages()}
>
{"CSV ALL"}
</Button>
<ReportModal currencies={reporList} func={reportValue} reportOption={reportOption} />
{/* <Button
variant="contained"
color="primary"
onClick={(e) => handleCSVMessages()}
>
{"CSV ALL"}
</Button>
<div>
<CSVLink
data={dataCSV}
headers={columns}
filename= {'Relatorio_detalhado_atendimento_atendentes.csv'}
target={'_blank'}
ref={csvLink}/>
</div>
data={dataCSV}
headers={columns}
filename={'Relatorio_detalhado_atendimento_atendentes.csv'}
target={'_blank'}
ref={csvLink} />
</div> */}
</Item>
</Box>
<Box sx={{
display: 'grid',
}}>
<Box sx={{
display: 'grid',
}}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
{reportOption === '1' &&
<MTable data={query}
columns={columnsData}
hasChild={true}
removeClickRow={false}
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 sx={{ gridColumn: '1', gridRow: 'span 1' }}>
<MTable data={query}
columns={columnsData}
hasChild={true}
removeClickRow={false}
table_title={'Relatório de atendimento por atendentes'}/>
</Item>
</Box>
</MainContainer>
)}
/>
)}
/>
)
};

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 api from "../../services/api";
@ -39,22 +39,22 @@ 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
const newQueries = []
queries.forEach((query) => {
const queryIndex = state.findIndex((q) => q.id === query.id)
if(queryIndex !== -1){
if (queryIndex !== -1) {
state[queryIndex] = query
}
else{
else {
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 = () => {
@ -295,14 +282,14 @@ const SchedulesReminder = () => {
useEffect(() => {
setLoading(true);
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
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: "LOAD_QUERY", payload: dataQuery.data });
@ -324,267 +311,267 @@ const SchedulesReminder = () => {
useEffect(() => {
if(!loading){
if (!loading) {
setData(query.map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': `${others.statusChatEndId}` === '3' ? 'Agendamento' : 'Lembrete' }
)))
)))
}
}, [loading, query])
// Get from child 1
const datePicker1Value = (data) => {
// Get from child 1
const datePicker1Value = (data) => {
setDatePicker1(data)
}
// Get from child 2
const datePicker2Value = (data) => {
setDatePicker2(data)
}
const handleSearch = (event) => {
setContactNumber(event.target.value.toLowerCase());
};
const handleClear = () => {
setContactNumber('')
setReset(true)
}
const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false);
setSelectedSchedule(null);
};
// const handleDeleteRows = (id) => {
// let _data = [...dataRows];
// _data.forEach(rd => {
// _data = _data.filter(t => t.id !== id);
// });
// setData(_data);
// };
const handleDeleteSchedule = async (scheduleId) => {
try {
await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete/Agendamento deletado com sucesso!"));
//handleDeleteRows(scheduleId)
} catch (err) {
toastError(err);
}
setSelectedSchedule(null);
};
// Get from child 2
const datePicker2Value = (data) => {
setDatePicker2(data)
}
const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
try {
const handleSearch = (event) => {
setContactNumber(event.target.value.toLowerCase());
};
await api.post("/schedule", scheduleData);
toast.success(("Lembrete/Agendamento atualizado com sucesso!"));
//////////////////
const handleClear = () => {
const dataUpdate = [...dataRows];
const index = rowsDataNew.tableData['id'];
dataUpdate[index] = rowsDataNew;
setContactNumber('')
setData([...dataUpdate].map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': `${others.statusChatEndId}` === '3' ? 'Agendamento' : 'Lembrete' }
setReset(true)
}
const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false);
setSelectedSchedule(null);
};
// const handleDeleteRows = (id) => {
// let _data = [...dataRows];
// _data.forEach(rd => {
// _data = _data.filter(t => t.id !== id);
// });
// setData(_data);
// };
const handleDeleteSchedule = async (scheduleId) => {
try {
await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete/Agendamento deletado com sucesso!"));
//handleDeleteRows(scheduleId)
} catch (err) {
toastError(err);
}
setSelectedSchedule(null);
};
const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
try {
await api.post("/schedule", scheduleData);
toast.success(("Lembrete/Agendamento atualizado com sucesso!"));
//////////////////
const dataUpdate = [...dataRows];
const index = rowsDataNew.tableData['id'];
dataUpdate[index] = rowsDataNew;
setData([...dataUpdate].map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': `${others.statusChatEndId}` === '3' ? 'Agendamento' : 'Lembrete' }
)));
/////////////////
/////////////////
} catch (err) {
toastError(err);
}
//
setSelectedSchedule(null);
};
} catch (err) {
toastError(err);
}
//
setSelectedSchedule(null);
};
const chatEndVal = (data, rowsDataNew) => {
const chatEndVal = (data, rowsDataNew) => {
if(data){
if (data) {
handleUpdateSchedule(data, rowsDataNew)
handleUpdateSchedule(data, rowsDataNew)
}
}
}
const handleModal = (rowData) => {
const handleModal = (rowData) => {
// NATY
// NATY
render(<Modal
render(<Modal
modal_header={'Editar Lembrete/Agendamentos'}
func={chatEndVal}
statusChatEnd={statusEndChat}
// textBoxFieldSelected={'2'}
rowData={rowData}
/>)
/>)
};
};
return (
<MainContainer>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}>
<MainContainer>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}>
<Item>
<TextField
placeholder='Numero/Nome...'
type="search"
value={contactNumber}
onChange={handleSearch}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon style={{ color: "gray" }} />
</InputAdornment>
),
}}
/>
</Item>
<Item>
<TextField
placeholder='Numero/Nome...'
type="search"
value={contactNumber}
onChange={handleSearch}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<SearchIcon style={{ color: "gray" }} />
</InputAdornment>
),
}}
/>
</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><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 sx={{ gridColumn: '4 / 5' }}>
{/* <Button size="small" variant="contained" onClick={()=>{handleQuery()}}>GO</Button>*/}
<Item sx={{ gridColumn: '4 / 5' }}>
{/* <Button size="small" variant="contained" onClick={()=>{handleQuery()}}>GO</Button>*/}
<Button
variant="contained"
color="primary"
onClick={(e) => handleClear()}
>
{"CLEAR"}
</Button>
</Item>
<Button
variant="contained"
color="primary"
onClick={(e) => handleClear()}
>
{"CLEAR"}
</Button>
</Item>
</Box>
</Box>
<Box sx={{
display: 'grid',
}}>
<Box sx={{
display: 'grid',
}}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
<ConfirmationModal
title={selectedSchedule && `Deletar ${''+selectedSchedule.statusChatEndId === '2' ? 'lembrete' : 'agendamento'} do dia ${selectedSchedule.schedulingDate.split(' ')[0]} ${selectedSchedule.schedulingDate.split(' ')[1]} ?`}
open={confirmModalOpen}
onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
>
<span>Deseja realmente deletar esse lembrete/agendamento ? </span>
</ConfirmationModal>
<ConfirmationModal
title={selectedSchedule && `Deletar ${'' + selectedSchedule.statusChatEndId === '2' ? 'lembrete' : 'agendamento'} do dia ${selectedSchedule.schedulingDate.split(' ')[0]} ${selectedSchedule.schedulingDate.split(' ')[1]} ?`}
open={confirmModalOpen}
onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
>
<span>Deseja realmente deletar esse lembrete/agendamento ? </span>
</ConfirmationModal>
<MaterialTable
title="Lembretes/Agendamentos"
columns={
[
<MaterialTable
title="Lembretes/Agendamentos"
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: 'ticket.contact.name' },
{ title: 'Contato', field: 'ticket.contact.number' },
{ title: 'Lemb/Agen', field: 'scheduleReminder'},
{ title: 'Envio', field: 'schedulingTime' },
{ title: 'Data', field: 'schedulingDate' },
{ title: 'Mensagem', field: 'message', width: "80%" },
{ title: '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: 'Contato', field: 'ticket.contact.number' },
{ title: 'Lemb/Agen', field: 'scheduleReminder' },
{ title: 'Envio', field: 'schedulingTime' },
{ title: 'Data', field: 'schedulingDate' },
{ title: 'Mensagem', field: 'message', width: "80%" },
]
]
}
data={dataRows}
// icons={tableIcons}
actions={[
{
icon: Edit,
tooltip: 'Editar',
onClick: (event, rowData) => {
setSelectedSchedule(rowData);
handleModal(rowData)
}
data={dataRows}
// icons={tableIcons}
actions={[
{
icon: Edit,
tooltip: 'Editar',
onClick: (event, rowData) => {
},
{
icon: Delete,
tooltip: 'Deletar',
onClick: (event, rowData) => {
setSelectedSchedule(rowData);
handleModal(rowData)
}
setSelectedSchedule(rowData);
setConfirmModalOpen(true);
}
// onClick: handleDeleteRows
}
]}
},
{
icon: Delete,
tooltip: 'Deletar',
onClick: (event, rowData) => {
options={
{
search: true,
selection: false,
paging: false,
padding: 'dense',
sorting: true,
//loadingType: 'linear',
searchFieldStyle: {
width: 300,
},
setSelectedSchedule(rowData);
setConfirmModalOpen(true);
}
// onClick: handleDeleteRows
}
]}
pageSize: 20,
headerStyle: {
position: "sticky",
top: "0"
},
maxBodyHeight: "400px",
options={
{
search: true,
selection: false,
paging: false,
padding: 'dense',
sorting: true,
//loadingType: 'linear',
searchFieldStyle: {
width: 300,
},
rowStyle: {
fontSize: 12,
}
pageSize: 20,
headerStyle: {
position: "sticky",
top: "0"
},
maxBodyHeight: "400px",
rowStyle: {
fontSize: 12,
}
}}
/>
}}
/>
</Item>
</Item>
</Box>
</MainContainer>
</Box>
</MainContainer>
)