projeto-hit/frontend/src/pages/Dashboard/index.js

581 lines
14 KiB
JavaScript
Raw Normal View History

import React, { useContext, useReducer, useEffect, useState } from "react"
import Paper from "@material-ui/core/Paper"
import Container from "@material-ui/core/Container"
import Grid from "@material-ui/core/Grid"
import { makeStyles } from "@material-ui/core/styles"
import Typography from "@material-ui/core/Typography";
// import useTickets from "../../hooks/useTickets"
import { AuthContext } from "../../context/Auth/AuthContext";
import { i18n } from "../../translate/i18n";
import Chart from "./Chart"
import openSocket from "socket.io-client";
import api from "../../services/api";
import { Can } from "../../components/Can";
import { Button } from "@material-ui/core";
const useStyles = makeStyles(theme => ({
container: {
paddingTop: theme.spacing(4),
paddingBottom: theme.spacing(4),
},
fixedHeightPaper: {
padding: theme.spacing(2),
display: "flex",
overflow: "auto",
flexDirection: "column",
height: 240,
},
customFixedHeightPaper: {
padding: theme.spacing(2),
display: "flex",
overflow: "auto",
flexDirection: "column",
height: 120,
},
customFixedHeightPaperLg: {
padding: theme.spacing(2),
display: "flex",
overflow: "auto",
flexDirection: "column",
height: "100%",
},
}))
const reducer = (state, action) => {
if (action.type === "DELETE_USER_STATUS") {
const userId = action.payload;
const userIndex = state.findIndex((u) => `${u.id}` === `${userId}`);
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) {
state[queryIndex] = query
}
else {
newQueries.push(query)
}
})
return [...state, ...newQueries]
}
if (action.type === "UPDATE_STATUS_ONLINE") {
let onlineUser = action.payload
let index = -1
let onlySumOpenClosed = false
if (onlineUser.sumOpen || onlineUser.sumClosed) {
index = state.findIndex((e) => ((onlineUser.sumOpen && e.id === onlineUser.sumOpen.userId) || (onlineUser.sumClosed && e.id === onlineUser.sumClosed.userId)))
onlySumOpenClosed = true
}
else {
index = state.findIndex((e) => `${e.id}` === `${onlineUser.userId}`)
}
if (index !== -1) {
if (!onlySumOpenClosed) {
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
}
}
if(onlineUser.openClosedInQueue){
state[index].openClosedInQueue = onlineUser.openClosedInQueue
}
if(onlineUser.openClosedOutQueue){
state[index].openClosedOutQueue = onlineUser.openClosedOutQueue
}
// if(onlineUser.closedTicketByUserIn){
// state[index].closedTicketByUserIn = onlineUser.closedTicketByUserIn
// }
// if(onlineUser.closedTicketByUserOut){
// state[index].closedTicketByUserOut = onlineUser.closedTicketByUserOut
// }
// if(onlineUser.openTicketByUserIn){
// state[index].openTicketByUserIn = onlineUser.openTicketByUserIn
// }
// if(onlineUser.openTicketByUserOut){
// state[index].openTicketByUserOut = onlineUser.openTicketByUserOut
// }
}
return [...state]
}
if (action.type === "RESET") {
return [];
}
}
const Dashboard = () => {
const classes = useStyles()
const [usersOnlineInfo, dispatch] = useReducer(reducer, [])
const [open, setOpen] = useState(0)
const [closed, setClosed] = useState(0)
const [pending, setPending] = useState(0)
const { user } = useContext(AuthContext);
// var userQueueIds = [];
// if (user.queues && user.queues.length > 0) {
// userQueueIds = user.queues.map(q => q.id);
// }
// const GetTickets = (status, showAll, withUnreadMessages, unlimited) => {
// const { tickets } = useTickets({
// status: status,
// showAll: showAll,
// withUnreadMessages: withUnreadMessages,
// queueIds: JSON.stringify(userQueueIds),
// unlimited: unlimited
// });
// return tickets.length;
// }
useEffect(() => {
dispatch({ type: "RESET" });
}, []);
const handleLogouOnlineUser = async (userId) => {
try {
await api.get(`/users/logout/${userId}`);
//toast.success(("Desloged!"));
//handleDeleteRows(scheduleId)
} catch (err) {
// toastError(err);
}
};
useEffect(() => {
//setLoading(true);
const delayDebounceFn = setTimeout(() => {
// setLoading(true);
const fetchQueries = async () => {
try {
let date = new Date().toLocaleDateString('pt-BR').split('/')
let dateToday = `${date[2]}-${date[1]}-${date[0]}`
const dataQuery = await api.get("/reports/user/services", { params: { userId: null, startDate: dateToday, endDate: dateToday }, });
dispatch({ type: "RESET" })
dispatch({ type: "LOAD_QUERY", payload: dataQuery.data });
console.log('xxx REPORT 2 dataQuery : ', dataQuery.data)
//console.log()
} catch (err) {
console.log(err);
}
};
fetchQueries();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, []);
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
// socket.on("ticket", (data) => {
// console.log('OK')
// });
socket.on("onlineStatus", (data) => {
if (data.action === "logout" || (data.action === "update")) {
// console.log('>>>>>>> data.userOnlineTime: ', data.userOnlineTime)
dispatch({ type: "UPDATE_STATUS_ONLINE", payload: data.userOnlineTime });
}
else if (data.action === "delete") {
dispatch({ type: "DELETE_USER_STATUS", payload: data.userOnlineTime });
}
});
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();
};
}, []);
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
let date = new Date().toLocaleDateString('pt-BR').split('/')
let dateToday = `${date[2]}-${date[1]}-${date[0]}`
const _open = await api.get("/tickets/count", { params: { status: 'open', date: dateToday } });
const _closed = await api.get("/tickets/count", { params: { status: 'closed', date: dateToday } });
const _pending = await api.get("/tickets/count", { params: { status: 'pending', date: dateToday } });
setOpen(_open.data.count)
setClosed(_closed.data.count)
setPending(_pending.data.count)
} catch (err) {
console.log(err);
}
};
fetchQueries();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [usersOnlineInfo]);
return (
<Can
role={user.profile}
perform="dashboard-view:show"
yes={() => (
<div>
<Container maxWidth="lg" className={classes.container}>
<Grid container spacing={3}>
<Grid item xs={4}>
<Paper className={classes.customFixedHeightPaper} style={{ overflow: "hidden" }}>
<Typography component="h3" variant="h6" color="primary" paragraph>
{i18n.t("dashboard.messages.inAttendance.title")}
</Typography>
<Grid item>
<Typography component="h1" variant="h4">
{/* {GetTickets("open", "true", "false", "true")} */}
{open}
</Typography>
</Grid>
</Paper>
</Grid>
<Grid item xs={4}>
<Paper className={classes.customFixedHeightPaper} style={{ overflow: "hidden" }}>
<Typography component="h3" variant="h6" color="primary" paragraph>
{i18n.t("dashboard.messages.waiting.title")}
</Typography>
<Grid item>
<Typography component="h1" variant="h4">
{/* {GetTickets("pending", "true", "false", "true")} */}
{pending}
</Typography>
</Grid>
</Paper>
</Grid>
<Grid item xs={4}>
<Paper className={classes.customFixedHeightPaper} style={{ overflow: "hidden" }}>
<Typography component="h3" variant="h6" color="primary" paragraph>
{i18n.t("dashboard.messages.closed.title")}
</Typography>
<Grid item>
<Typography component="h1" variant="h4">
{/* {GetTickets("closed", "true", "false", "true")} */}
{closed}
</Typography>
</Grid>
</Paper>
</Grid>
<Grid item sm={6}>
<Paper style={{ padding: "15px", }}>
<Typography component="h3" color="primary" paragraph>
{'Total online'}
</Typography>
<Grid item>
<Typography component="h1" paragraph>
{usersOnlineInfo &&
usersOnlineInfo.filter((user) => user.statusOnline && user.statusOnline.status === 'online').length
}
</Typography>
</Grid>
</Paper>
</Grid>
<Grid item sm={6}>
<Paper style={{ padding: "15px", }}>
<Typography component="h3" color="primary" paragraph>
{'Total offline'}
</Typography>
<Grid item>
<Typography component="h1" paragraph>
{usersOnlineInfo &&
usersOnlineInfo.filter((user) => !user.statusOnline || user.statusOnline.status === 'offline').length
}
</Typography>
</Grid>
</Paper>
</Grid>
<Grid item xs={12}>
<Paper className={classes.fixedHeightPaper}>
<Chart />
</Paper>
</Grid>
2022-07-28 21:21:14 +00:00
{usersOnlineInfo &&
usersOnlineInfo.map((userInfo, index) => (
// <MenuItem key={index} value={option.value}> {option.label} </MenuItem>
<>
{userInfo.statusOnline &&
<Grid item sm={3} key={index} style={{ margin: "25px" }}>
<Paper style={{ height: "480px", width: "300px", padding: "5px", overflow: "hidden" }}>
<Typography component="h3" color="primary">
{userInfo.name}
</Typography>
<Grid item>
<Typography component="h1">
{userInfo.statusOnline &&
userInfo.statusOnline.status
}
</Typography>
<Typography component="h1">
Em atendimento: {userInfo.sumOpen && userInfo.sumOpen.count}
</Typography>
<Typography component="h1">
Finalizado: {userInfo.sumClosed && userInfo.sumClosed.count}
</Typography>
<Typography component="h1">
Tempo online: {userInfo.sumOnlineTime && userInfo.sumOnlineTime.sum}
</Typography>
<div style={{ border: 'dotted', margin: '3px', padding: '2px' }}>
<div>Em atendimento(open/closed) por fila, conversas iniciadas pelos clientes:</div>
{userInfo.openClosedInQueue &&
userInfo.openClosedInQueue.map((info, index) => (
<>
<Typography component="h1" key={index}>
{info.name}: OPEN {info.countOpen} | CLOSED {info.countClosed}
</Typography>
</>
))
}
</div>
<div style={{ border: 'dotted', margin: '3px', padding: '2px' }}>
<div>Em atendimento(open/closed) sem fila, conversas iniciadas por atendentes:</div>
{userInfo.openClosedOutQueue &&
<Typography component="h1" key={index}>
SEM FILA: OPEN {userInfo.openClosedOutQueue.countOpen} | CLOSED {userInfo.openClosedOutQueue.countClosed}
</Typography>
}
</div>
{userInfo.statusOnline && userInfo.statusOnline.status === "online" &&
userInfo.statusOnline &&
<Typography component="h1">
<Button style={{ display: "block" }}
variant="contained"
color="primary"
onClick={(e) => {
// handleCSVMessages()
handleLogouOnlineUser(userInfo.id)
}}
>
{"Deslogar"}
</Button>
</Typography>
}
</Grid>
</Paper>
</Grid>
}
</>
))
}
</Grid>
</Container >
</div >
)}
/>
/**/
)
}
export default Dashboard