Finalização do relatorio carregado sob demanda

pull/18/head
adriano 2022-07-28 14:55:23 -03:00
parent 75fd79fc8d
commit ffcefe8f12
14 changed files with 588 additions and 329 deletions

View File

@ -24,6 +24,7 @@ type IndexQuery = {
userId: string;
startDate: string;
endDate: string;
pageNumber: string;
};
@ -33,13 +34,17 @@ export const reportUserByDateStartDateEnd = async (req: Request, res: Response):
throw new AppError("ERR_NO_PERMISSION", 403);
}
const { userId, startDate, endDate } = req.query as IndexQuery
const { userId, startDate, endDate, pageNumber } = req.query as IndexQuery
const data_query = await ShowTicketReport(userId, startDate, endDate);
console.log('PAGE NUMBER: ', pageNumber)
return res.status(200).json(data_query);
const { tickets, count, hasMore } = await ShowTicketReport({userId, startDate, endDate, pageNumber});
// return res.status(200).json(data_query);
return res.status(200).json({ tickets, count, hasMore });
};

View File

@ -6,7 +6,7 @@ module.exports = {
"StatusChatEnds",
[
{
name: "SEM RETORNO DO CLIENTE",
name: "FINALIZADO",
createdAt: new Date(),
updatedAt: new Date()
},

View File

@ -13,6 +13,8 @@ const fastFolderSize = require('fast-folder-size')
const { promisify } = require('util')
const fs = require('fs')
const { exec } = require("child_process");
let scheduler_monitor: any;
let timeInterval = 5
@ -53,6 +55,35 @@ const monitor = async () => {
}
exec("df -h /", (error: any, stdout: any, stderr: any) => {
if (error) {
console.log(`exec error: ${error.message}`);
return;
}
if (stderr) {
console.log(`exec stderr: ${stderr}`);
return;
}
stdout = stdout.split(/\r?\n/)
stdout = stdout[1].trim().split(/\s+/)
// DISK SPACE MONITORING
const io = getIO();
io.emit("diskSpaceMonit", {
action: "update",
diskSpace: {
size: stdout[1],
used: stdout[2],
available: stdout[3],
use: stdout[4]
}
});
});
// WHATS SESSION SIZE MONITORING
const whatsapps = await ListWhatsAppsService();

View File

@ -16,12 +16,31 @@ import { startOfDay, endOfDay, parseISO, getDate} from "date-fns";
import { string } from "yup/lib/locale";
import Whatsapp from "../../models/Whatsapp";
interface Request {
userId: string | number;
startDate: string;
endDate: string;
pageNumber?: string;
}
interface Response {
tickets: Ticket[];
count: number;
hasMore: boolean;
}
//Report by user, startDate, endDate
const ShowTicketReport = async (id: string | number, startDate: string, endDate: string): Promise<Ticket[]> => {
const ShowTicketReport = async ({
userId,
startDate,
endDate,
pageNumber = "1"
}: Request): Promise<Response> => {
let where_clause = {}
if(id=='0'){
if(userId=='0'){
where_clause = {
createdAt: {
[Op.gte]: startDate+' 00:00:00.000000',
@ -31,7 +50,7 @@ const ShowTicketReport = async (id: string | number, startDate: string, endDate:
}
else{
where_clause = {
userid: id,
userid: userId,
createdAt: {
[Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999'
@ -40,11 +59,14 @@ const ShowTicketReport = async (id: string | number, startDate: string, endDate:
}
const limit = 40;
const offset = limit * (+pageNumber - 1);
const ticket = await Ticket.findAll({
const {count, rows: tickets} = await Ticket.findAndCountAll({
where: where_clause ,
limit,
offset,
//attributes: ['id', 'status', 'createdAt', 'updatedAt'],
attributes: ['id', 'status', 'statusChatEnd', [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"],
@ -82,14 +104,20 @@ const ShowTicketReport = async (id: string | number, startDate: string, endDate:
},
],
order: [
['id', 'ASC']
]
});
const hasMore = count > offset + tickets.length;
if (!ticket) {
if (!tickets) {
throw new AppError("ERR_NO_TICKET_FOUND", 404);
}
return ticket;
return {tickets, count, hasMore};
};
export default ShowTicketReport;

View File

@ -825,6 +825,7 @@ const handleMsgAck = async (msg: WbotMessage, ack: MessageAck) => {
action: "update",
message: messageToUpdate
});
} catch (err) {
Sentry.captureException(err);
logger.error(`Error handling message ack. Err: ${err}`);

View File

@ -362,15 +362,17 @@ const MessagesList = ({ ticketId, isGroup }) => {
socket.on("connect", () => socket.emit("joinChatBox", ticketId));
socket.on("appMessage", (data) => {
if (data.action === "create") {
dispatch({ type: "ADD_MESSAGE", payload: data.message });
// console.log('* NOVA MENSAGEM CAP: ', data.message)
scrollToBottom();
}
if (data.action === "update") {
console.log('2 THIS IS THE DATA: ', data)
dispatch({ type: "UPDATE_MESSAGE", payload: data.message });
}
});

View File

@ -4,82 +4,154 @@ import MaterialTable from 'material-table';
import Modal from '../Modal'
import { render } from '@testing-library/react';
import chat from '@material-ui/icons/Chat';
// import Button from "@material-ui/core/Button";
import React from 'react';
const MTable = (props) => {
const [selectedRow, setSelectedRow] = useState(null);
const tableRef = React.useRef();
const openInNewTab = url => {
window.open(url, '_blank', 'noopener,noreferrer');
};
const [selectedRow, setSelectedRow] = useState(null);
//const dataLoad = props.data.map((dt) => { return { ...dt }});
const dataLoad = props.data.map(({ user, ...others }) => ({ ...others, 'user': user ? user : { name: 'Aguardando atendente', email: '' } }));
const columnsLoad = props.columns.map((column) => { return { ...column } });
useEffect(() => {
console.log(`You have clicked the button ${selectedRow} times`)
// console.log('TABLE REF: ', tableRef)
}, [selectedRow]);
useEffect(() => {
if (!tableRef.current) return
const element = tableRef.current.tableContainerDiv.current;
element.addEventListener('scroll', props.handleScroll);
return () => {
element.removeEventListener('scroll', props.handleScroll);
};
}, [props]);
return (
<MaterialTable
title={props.table_title}
columns={columnsLoad}
data={dataLoad}
<>
{/* <Button onClick={handleTest}>Toggle</Button> */}
maxWidth={true}
{/* <CircularProgress /> */}
onRowClick={(evt, selectedRow) => {
<MaterialTable
title={props.table_title}
columns={columnsLoad}
data={dataLoad}
maxWidth={true}
if(props.removeClickRow){
return
tableRef={tableRef}
localization={{ header: { actions: props.hasChild ? 'Ticket' : null },}}
onRowClick={(evt, selectedRow) => {
if (props.removeClickRow) {
return
}
console.log(selectedRow.tableData.id);
console.log(selectedRow);
console.log(selectedRow.messages);
setSelectedRow(selectedRow.tableData.id)
if (props.hasChild) {
render(<Modal data={selectedRow.messages}
hasChild={false}
modal_header={'Chat do atendimento pelo Whatsapp'}
user={selectedRow.user.name}
clientContactNumber={selectedRow.contact.number} />)
}
console.log('props.hasChild: ', props.hasChild)
//evt.stopPropagation()
}
}
console.log(selectedRow.tableData.id);
console.log(selectedRow);
console.log(selectedRow.messages);
setSelectedRow(selectedRow.tableData.id)
if (props.hasChild) {
render(<Modal data={selectedRow.messages}
hasChild={false}
modal_header={'Chat do atendimento pelo Whatsapp'}
user={selectedRow.user.name}
clientContactNumber={selectedRow.contact.number} />)
}
actions={[
(rowData) => {
console.log('props.hasChild: ', props.hasChild)
if(props.hasChild){
return {
icon: chat,
tooltip: `Ticket id ${rowData.id}`,
disable: false,
onClick: (event, rowData) => {
//evt.stopPropagation()
}
}
openInNewTab(`/tickets/${rowData.id}`)
options={{
search: true,
selection: false,
paging: false,
padding: 'dense',
sorting: true ? props.hasChild : false,
//loadingType: 'linear',
searchFieldStyle: {
width: 300,
},
}
}
}
}
]}
options={{
search: true,
selection: false,
paging: false,
padding: 'dense',
exportButton: props.hasChild ? true : null,
exportAllData: true,
sorting: true ? props.hasChild : false,
loadingType: 'circular',
searchFieldStyle: {
width: 300,
},
pageSize: 20,
headerStyle: {
position: "sticky",
top: "0"
},
maxBodyHeight: "400px",
// minBodyHeight: "85vh", //FIXME to calculate dynamic height, needed for correct scroll position identification
// maxBodyHeight: "85vh",
rowStyle: rowData => ({
fontSize: 12,
backgroundColor: selectedRow === rowData.tableData.id ? '#ec5114' : '#FFF'
})
}}
/>
</>
pageSize: 20,
headerStyle: {
position: "sticky",
top: "0"
},
maxBodyHeight: "400px",
rowStyle: rowData => ({
fontSize: 12,
backgroundColor: selectedRow === rowData.tableData.id ? '#ec5114' : '#FFF'
})
}}
/>
);
};

View File

@ -286,6 +286,7 @@ const TicketsList = (props) => {
};
const handleScroll = e => {
if (!hasMore || loading) return;
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;

View File

@ -39,6 +39,19 @@ const reducer = (state, action) => {
}
// if (action.type === "UPDATE_DISK_SPACE_MONIT") {
// const whatsApp = action.payload;
// const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id);
// if (whatsAppIndex !== -1) {
// state[whatsAppIndex].sessionSize = whatsApp.sessionSize;
// return [...state];
// } else {
// return [whatsApp, ...state];
// }
// }
if (action.type === "UPDATE_WHATSAPPS_SESSION_MONIT") {
const whatsApp = action.payload;
const whatsAppIndex = state.findIndex(s => s.id === whatsApp.id);
@ -108,10 +121,6 @@ const useWhatsApps = () => {
}
});
//test del
socket.on("whatsappSessionMonit", data => {
if (data.action === "update") {
@ -121,7 +130,7 @@ const useWhatsApps = () => {
}
});
//
return () => {
socket.disconnect();

View File

@ -1,7 +1,9 @@
import React, { useState, useCallback, useContext } from "react";
import React, { useState, useCallback, useEffect, useContext } from "react";
import { toast } from "react-toastify";
import { format, parseISO } from "date-fns";
import openSocket from "socket.io-client";
import { makeStyles } from "@material-ui/core/styles";
import { green } from "@material-ui/core/colors";
import {
@ -111,6 +113,8 @@ const Connections = () => {
const [selectedWhatsApp, setSelectedWhatsApp] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [diskSpaceInfo, setDiskSpaceInfo] = useState({});
@ -324,6 +328,23 @@ const Connections = () => {
);
};
useEffect(() => {
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
socket.on("diskSpaceMonit", data => {
if (data.action === "update") {
setDiskSpaceInfo(data.diskSpace)
}
});
return () => {
socket.disconnect();
};
}, []);
return (
<Can
@ -355,7 +376,10 @@ const Connections = () => {
/>
<MainHeader>
<Title>{i18n.t("connections.title")}</Title>
<MainHeaderButtonsWrapper>
<Can
role={user.profile}
@ -370,193 +394,236 @@ const Connections = () => {
)}
/>
</MainHeaderButtonsWrapper>
</MainHeader>
<Paper className={classes.mainPaper} variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<>
<TableCell align="center">
{i18n.t("connections.table.name")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.status")}
</TableCell>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
{i18n.t("connections.table.session")}
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Restore
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Session MB
</TableCell>
)}
/>
<TableCell align="center">
{i18n.t("connections.table.lastUpdate")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.default")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.actions")}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRowSkeleton />
) : (
<Can
role={user.profile}
perform="space-disk-info:show"
yes={() => (
<>
{whatsApps?.length > 0 &&
whatsApps.map(whatsApp => (
<TableRow key={whatsApp.id}>
<TableCell align="center">{whatsApp.name}</TableCell>
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
Size
</TableCell>
<TableCell align="center">
Used
</TableCell>
<TableCell align="center">
Available
</TableCell>
<TableCell align="center">
Use%
</TableCell>
</TableRow>
</TableHead>
<TableCell align="center">
{renderStatusToolTips(whatsApp)}
</TableCell>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
{renderActionButtons(whatsApp)}
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<Button
size="small"
variant="contained"
color="primary"
onClick={() => handleRestartWhatsAppSession(whatsApp.id)}
>
Restore
</Button>
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<CustomToolTip
title={'Informação da sessão em Megabytes'}
content={'Tamanho do diretorio da sessão atualizado a cada 5 segundos'}
>
<div>{whatsApp.sessionSize}</div>
</CustomToolTip>
</TableCell>
)}
/>
<TableCell align="center">
{format(parseISO(whatsApp.updatedAt), "dd/MM/yy HH:mm")}
</TableCell>
<TableCell align="center">
{whatsApp.isDefault && (
<div className={classes.customTableCell}>
<CheckCircle style={{ color: green[500] }} />
</div>
)}
</TableCell>
<TableCell align="center">
<Can
role={user.profile}
perform="show-icon-edit-whatsapp"
yes={() => (
<IconButton
size="small"
onClick={() => handleEditWhatsApp(whatsApp)}
>
<Edit />
</IconButton>
)}
/>
<Can
role={user.profile}
perform="btn-remove-whatsapp"
yes={() => (
<IconButton
size="small"
onClick={e => {
handleOpenConfirmationModal("delete", whatsApp.id);
}}
>
<DeleteOutline />
</IconButton>
)}
/>
</TableCell>
</TableRow>
))}
</>
<TableBody>
<TableRow>
<TableCell align="center">{diskSpaceInfo.size}</TableCell>
<TableCell align="center">{diskSpaceInfo.used}</TableCell>
<TableCell align="center">{diskSpaceInfo.available}</TableCell>
<TableCell align="center">{diskSpaceInfo.use}</TableCell>
</TableRow>
</TableBody>
</Table>
<br />
</>
)}
</TableBody>
</Table>
/>
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
{i18n.t("connections.table.name")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.status")}
</TableCell>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
{i18n.t("connections.table.session")}
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Restore
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
Session MB
</TableCell>
)}
/>
<TableCell align="center">
{i18n.t("connections.table.lastUpdate")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.default")}
</TableCell>
<TableCell align="center">
{i18n.t("connections.table.actions")}
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRowSkeleton />
) : (
<>
{whatsApps?.length > 0 &&
whatsApps.map(whatsApp => (
<TableRow key={whatsApp.id}>
<TableCell align="center">{whatsApp.name}</TableCell>
<TableCell align="center">
{renderStatusToolTips(whatsApp)}
</TableCell>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
{renderActionButtons(whatsApp)}
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<Button
size="small"
variant="contained"
color="primary"
onClick={() => handleRestartWhatsAppSession(whatsApp.id)}
>
Restore
</Button>
</TableCell>
)}
/>
<Can
role={user.profile}
perform="connection-button:show"
yes={() => (
<TableCell align="center">
<CustomToolTip
title={'Informação da sessão em Megabytes'}
content={'Tamanho do diretorio da sessão atualizado a cada 5 segundos'}
>
<div>{whatsApp.sessionSize}</div>
</CustomToolTip>
</TableCell>
)}
/>
<TableCell align="center">
{format(parseISO(whatsApp.updatedAt), "dd/MM/yy HH:mm")}
</TableCell>
<TableCell align="center">
{whatsApp.isDefault && (
<div className={classes.customTableCell}>
<CheckCircle style={{ color: green[500] }} />
</div>
)}
</TableCell>
<TableCell align="center">
<Can
role={user.profile}
perform="show-icon-edit-whatsapp"
yes={() => (
<IconButton
size="small"
onClick={() => handleEditWhatsApp(whatsApp)}
>
<Edit />
</IconButton>
)}
/>
<Can
role={user.profile}
perform="btn-remove-whatsapp"
yes={() => (
<IconButton
size="small"
onClick={e => {
handleOpenConfirmationModal("delete", whatsApp.id);
}}
>
<DeleteOutline />
</IconButton>
)}
/>
</TableCell>
</TableRow>
))}
</>
)}
</TableBody>
</Table>
</>
</Paper>
</MainContainer>
)}

View File

@ -36,17 +36,23 @@ import { AuthContext } from "../../context/Auth/AuthContext";
import { Can } from "../../components/Can";
const reducer = (state, action) => {
if (action.type === "LOAD_CONTACTS") {
const contacts = action.payload;
const newContacts = [];
contacts.forEach((contact) => {
const contactIndex = state.findIndex((c) => c.id === contact.id);
if (contactIndex !== -1) {
state[contactIndex] = contact;
} else {
newContacts.push(contact);
}
});
return [...state, ...newContacts];
@ -210,6 +216,9 @@ const Contacts = () => {
const handleScroll = (e) => {
if (!hasMore || loading) return;
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
// console.log('scrollTop: ', scrollTop, ' | scrollHeight: ', scrollHeight, ' | clientHeight: ', clientHeight)
if (scrollHeight - (scrollTop + 100) < clientHeight) {
loadMore();
}

View File

@ -18,8 +18,11 @@ import MaterialTable from 'material-table';
import LogoutIcon from '@material-ui/icons/CancelOutlined';
import { CSVLink } from "react-csv";
// import CircularProgress from '@mui/material/CircularProgress';
import openSocket from "socket.io-client";
@ -104,7 +107,7 @@ const reducerQ = (state, action) => {
const userIndex = state.findIndex((u) => `${u.id}` === `${userId}`);
// console.log('>>>>>>>>>>>>>>>>>>>>> userIndex: ', userIndex)
// console.log('>>>>>>>>>>>>>>>>>>>>> userIndex: ', userIndex)
if (userIndex !== -1) {
state.splice(userIndex, 1);
@ -117,7 +120,6 @@ const reducerQ = (state, action) => {
if (action.type === 'LOAD_QUERY') {
const queries = action.payload
const newQueries = []
@ -143,7 +145,7 @@ const reducerQ = (state, action) => {
let onlineUser = action.payload
let index = -1
// console.log('sssssssssstate: ', state, ' | ONLINE USERS: onlineUser.userId ', onlineUser.userId)
// 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)))
@ -152,13 +154,13 @@ const reducerQ = (state, action) => {
index = state.findIndex((e) => `${e.id}` === `${onlineUser.userId}`)
}
//console.log(' *********************** index: ', index)
//console.log(' *********************** index: ', index)
if (index !== -1) {
// console.log('ENTROU NO INDEX')
// console.log('ENTROU NO INDEX')
if (!("statusOnline" in state[index])) {
@ -183,10 +185,10 @@ const reducerQ = (state, action) => {
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)
// 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')
// console.log(' >>>>>>>>>>>>>>>>>> sumOpen 1')
state[index].sumOpen = onlineUser.sumOpen
}
@ -195,10 +197,10 @@ const reducerQ = (state, action) => {
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)
// 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')
// console.log(' >>>>>>>>>>>>>>>>>> sumOpen 1')
state[index].sumClosed = onlineUser.sumClosed
}
@ -301,19 +303,26 @@ let columnsData = [
{ title: 'Criado', field: 'createdAt' },
//{title: 'Atualizado', field: 'updatedAt'},
{title: 'Status de encerramento', field: 'statusChatEnd'}];
{ title: 'Status de encerramento', field: 'statusChatEnd' }];
const Report = () => {
const csvLink = useRef()
const { user: userA } = useContext(AuthContext);
//--------
const [searchParam] = useState("");
//const [loading, setLoading] = useState(false);
//const [hasMore, setHasMore] = useState(false);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(false);
const [pageNumberTickets, setTicketsPageNumber] = useState(1);
const [totalCountTickets, setTotalCountTickets] = useState(0);
const [pageNumber, setPageNumber] = useState(1);
const [users, dispatch] = useReducer(reducer, []);
//const [columns, setColums] = useState([])
@ -336,7 +345,7 @@ const Report = () => {
useEffect(() => {
dispatch({ type: "RESET" });
dispatchQ({ type: "RESET" })
setTicketsPageNumber(1)
setPageNumber(1);
}, [searchParam, profile]);
@ -380,20 +389,24 @@ const Report = () => {
const delayDebounceFn = setTimeout(() => {
setLoading(true);
const fetchQueries = async () => {
try {
if (reportOption === '1') {
const dataQuery = await api.get("/reports/", { params: { userId, startDate, endDate }, });
dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
const { data } = await api.get("/reports/", { params: { userId, startDate, endDate, pageNumber: pageNumberTickets }, });
//setLoading(false);
console.log('dataQuery: ', data)
console.log('pageNumberTickets: ', pageNumberTickets)
// console.log('dataQuery: ', dataQuery.data)
// dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: data.tickets });
setHasMore(data.hasMore);
setTotalCountTickets(data.count)
setLoading(false);
// console.log()
}
else if (reportOption === '2') {
@ -404,7 +417,7 @@ const Report = () => {
//setLoading(false);
// console.log('REPORT 2 dataQuery : ', dataQuery.data)
// console.log('REPORT 2 dataQuery : ', dataQuery.data)
//console.log()
@ -420,7 +433,7 @@ const Report = () => {
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [userId, startDate, endDate, reportOption]);
}, [userId, startDate, endDate, reportOption, pageNumberTickets, totalCountTickets]);
// Get from child 1
@ -449,7 +462,7 @@ const Report = () => {
setReport(data)
// console.log(' data: ', data)
// console.log(' data: ', data)
}
useEffect(() => {
@ -464,27 +477,15 @@ const Report = () => {
}, [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)
console.log('dataQuery messages: ', dataQuery.data)
if (dataQuery.data.length > 0) {
@ -499,15 +500,10 @@ const Report = () => {
}
}
// console.log('dataCSVFormat: ', dataCSVFormat)
setDataCSV(dataCSVFormat)
setIsMount(false);
// setDataCSV(dataQuery.data)
}
// setLoading(false);
} catch (err) {
console.log(err);
}
@ -548,8 +544,8 @@ const Report = () => {
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)
// console.log('date: ', new Date(startDate).toLocaleDateString('pt-BR'))
// console.log('date2: ', startDate)
if (data.action === "logout" || (data.action === "update" &&
@ -571,7 +567,7 @@ const Report = () => {
socket.on("user", (data) => {
if (data.action === "delete") {
// console.log(' entrou no delete user: ', data)
// console.log(' entrou no delete user: ', data)
dispatch({ type: "DELETE_USER", payload: +data.userId });
}
});
@ -581,9 +577,13 @@ const Report = () => {
};
}
else if (reportOption === "1") {
dispatchQ({ type: "RESET" })
setTicketsPageNumber(1)
}
}, [reportOption, startDate, endDate]);
}, [reportOption, startDate, endDate, userId]);
// const handleDeleteRows = (id) => {
@ -625,6 +625,30 @@ const Report = () => {
};
const loadMore = () => {
setTicketsPageNumber((prevState) => prevState + 1);
};
const handleScroll = (e) => {
if (!hasMore || loading) return;
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
// console.log('scrollTop: ', scrollTop,
// ' | scrollHeight: ', scrollHeight,
// ' | clientHeight: ', clientHeight,
// ' | scrollHeight - (scrollTop + 1): ', scrollHeight - (scrollTop + 1))
if (scrollHeight - (scrollTop + 1) < clientHeight) {
loadMore();
// e.currentTarget.scrollTo(0, 200);
}
};
return (
<Can
@ -639,7 +663,7 @@ const Report = () => {
return { 'value': obj.id, 'label': obj.name }
})} /></Item>
<Item><DatePicker1 func={datePicker1Value} minDate={true} 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 sx={{ display: 'grid', gridColumn: '4 / 5', }}>
@ -651,13 +675,15 @@ const Report = () => {
{reportOption === '1' &&
<div>
{/* <Button
<Button style={{display: "none"}}
variant="contained"
color="primary"
onClick={(e) => handleCSVMessages()}
onClick={(e) => {
handleCSVMessages()
}}
>
{"CSV ALL"}
</Button> */}
</Button>
<div>
<CSVLink
@ -674,10 +700,6 @@ const Report = () => {
</Item>
</Box>
<Box sx={{
@ -688,11 +710,22 @@ const Report = () => {
{reportOption === '1' &&
<MTable data={query}
columns={columnsData}
hasChild={true}
removeClickRow={false}
table_title={'Atendimento por atendentes'} />
// <div onScroll={handleScroll} style={{ height: 400, overflowY: "scroll" }}>
// </div>
<>
<MTable data={query}
columns={columnsData}
hasChild={true}
removeClickRow={false}
handleScroll={handleScroll}
table_title={'Atendimento por atendentes'} />
</>
}
{reportOption === '2' &&
@ -711,7 +744,7 @@ const Report = () => {
[
// { 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', cellStyle: {whiteSpace: 'nowrap'}, },
{ title: 'Nome', field: 'name', cellStyle: { whiteSpace: 'nowrap' }, },
{
title: 'Status', field: 'statusOnline.status',
@ -765,7 +798,7 @@ const Report = () => {
disable: false,
onClick: (event, rowData) => {
// console.log(' ROW DATA INFO: ', rowData, ' | rowData: ', rowData.id)
// console.log(' ROW DATA INFO: ', rowData, ' | rowData: ', rowData.id)
handleLogouOnlineUser(rowData.id)
}
}

View File

@ -29,6 +29,7 @@ const rules = {
"show-icon-add-queue",
"show-icon-edit-queue",
"show-icon-delete-queue",
"space-disk-info:show",
"drawer-admin-items:view",