Consulta por id, dataInicio, dataFim funcional porem com problema na renderização da tabela. Este commit será para alteração na versão da tabela materia-table para tentar corrigir o congelamento da página

pull/1/head
adriano 2022-01-25 11:24:05 -03:00
parent bd29afd402
commit dd06ac45c9
8 changed files with 299 additions and 83 deletions

View File

@ -5,7 +5,13 @@ import AppError from "../errors/AppError";
import ShowTicketReport from "../services/TicketServices/ShowTicketReport"; import ShowTicketReport from "../services/TicketServices/ShowTicketReport";
export const reportUser = async (req: Request, res: Response): Promise<Response> => { type IndexQuery = {
userId: string;
startDate: string;
endDate: string;
};
/*export const reportUser = async (req: Request, res: Response): Promise<Response> => {
const { userId } = req.params; const { userId } = req.params;
@ -15,6 +21,22 @@ export const reportUser = async (req: Request, res: Response): Promise<Response>
return res.status(200).json(test); return res.status(200).json(test);
};*/
export const reportUserByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => {
const { userId, startDate, endDate } = req.query as IndexQuery
console.log('******* Estrou no report')
console.log('******* userId: ', userId)
console.log('******* startDate: ', startDate)
console.log('******* endDate: ', endDate)
const data_query = await ShowTicketReport(userId, startDate, endDate);
return res.status(200).json(data_query);
}; };
/*export const reportAll = async (req: Request, res: Response): Promise<Response> => { /*export const reportAll = async (req: Request, res: Response): Promise<Response> => {

View File

@ -7,7 +7,9 @@ import * as ReportController from "../controllers/ReportController";
const reportRoutes = express.Router(); const reportRoutes = express.Router();
reportRoutes.get("/reports/:userId", /*isAuth,*/ ReportController.reportUser); //reportRoutes.get("/reports/:userId", /*isAuth,*/ ReportController.reportUser);
reportRoutes.get("/reports", /*isAuth,*/ ReportController.reportUserByDateStartDateEnd);
//reportRoutes.get("/reports", /*isAuth,*/ ReportController.reportAll); //reportRoutes.get("/reports", /*isAuth,*/ ReportController.reportAll);

View File

@ -7,7 +7,62 @@ import Queue from "../../models/Queue";
import Message from "../../models/Message"; import Message from "../../models/Message";
import { userInfo } from "os"; import { userInfo } from "os";
//Report by user import { Op } from "sequelize";
import { Sequelize } from "sequelize";
import moment from 'moment';
import { startOfDay, endOfDay, parseISO, getDate} from "date-fns";
//Report by user, startDate, endDate
const ShowTicketReport = async (id: string | number, startDate: string, endDate: string): Promise<Ticket[]> => {
const ticket = await Ticket.findAll({
where: {
userid: id,
//createdAt: {
// [Op.between]: [+new Date('2022-01-24').toISOString(), +new Date().toISOString()]
//},
createdAt: {
[Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999'
}
},
attributes: ['id', 'status', 'createdAt', 'updatedAt'],
include: [
{
model: Message,
required:true,
separate: true,
attributes: ['body', 'read', 'mediaType','fromMe', 'mediaUrl','createdAt'],
order: [
['createdAt', 'ASC']
]
},
{
model: Contact,
attributes: ['name', 'number']
},
{
model: User,
attributes: ['name', 'email']
},
{
model: Queue,
attributes: ['name']
},
],
});
/*//Report by user
const ShowTicketReport = async (id: string | number): Promise<Ticket[]> => { const ShowTicketReport = async (id: string | number): Promise<Ticket[]> => {
const ticket = await Ticket.findAll({ const ticket = await Ticket.findAll({
@ -38,45 +93,8 @@ const ShowTicketReport = async (id: string | number): Promise<Ticket[]> => {
], ],
});
/*const ticket = await Message.findAll({
//raw: true,
where:{''},
attributes: ['body', 'createdAt', 'ticketId'],
include: [
{
model: Ticket,
attributes: ['contactid', 'userid', 'queueid', 'status'],
include:[
{
model: Contact,
attributes: ['name', 'number']
},
{
model: User,
attributes: ['name', 'email']
},
{
model: Queue,
attributes: ['name']
}
],
},
],
order:
['ticketId', 'createdAt']
}); */ }); */
if (!ticket) { if (!ticket) {
throw new AppError("ERR_NO_TICKET_FOUND", 404); throw new AppError("ERR_NO_TICKET_FOUND", 404);
} }

View File

@ -13,10 +13,16 @@ import {
} from '@material-ui/pickers'; } from '@material-ui/pickers';
function formatDateDatePicker(data){
return String(new Date(data).getFullYear())+'-'+
String(new Date(data).getMonth() + 1).padStart(2,'0')+'-'+
String(new Date(data).getDate()).padStart(2,'0')
}
function ResponsiveDatePickers(props) { function ResponsiveDatePickers(props) {
const [selectedDate, handleDateChange] = useState(new Date()); const [selectedDate, handleDateChange] = useState(new Date());
props.func(selectedDate); props.func(formatDateDatePicker(selectedDate));
return ( return (

View File

@ -1,6 +1,12 @@
import { gridDateTimeFormatter } from "@mui/x-data-grid"; import { gridDateTimeFormatter } from "@mui/x-data-grid";
export const data = [ export const data = [
{ {
"id": 210, "id": 210,
"status": "closed", "status": "closed",
@ -109,5 +115,92 @@ export const data = [
"createdAt": "2022-01-18T20:26:04.360Z" "createdAt": "2022-01-18T20:26:04.360Z"
} }
] ]
},
{
"id":229,
"status":"closed",
"createdAt":"2022-01-24T13:20:01.000Z",
"updatedAt":"2022-01-24T13:21:02.000Z",
"contact":{
"name":"Meu Numero Oi",
"number":"5517988325936"
},
"user":{
"name":"Administrador",
"email":"admin@whaticket.com"
},
"queue":{
"name":"Cancelamento ou Sugestões"
},
"messages":[
{
"mediaUrl":null,
"body":"Bom dia",
"read":true,
"mediaType":"chat",
"fromMe":false,
"createdAt":"2022-01-24T13:20:01.562Z"
},
{
"mediaUrl":null,
"body":"HIT COMMUNICATIONS 🇧🇷\n\nBem vindo ao novo canal digital de atendimento ao cliente. Escolha uma opção do MENU abaixo 👇 e digite o número:\n*1* - Atendimento a Fornecedores\n*2* - Cancelamento ou Sugestões\n*3* - Cobrança\n*4* - Comercial\n*5* - Contas a Pagar\n*6* - Suporte Técnico\n",
"read":true,
"mediaType":"chat",
"fromMe":true,
"createdAt":"2022-01-24T13:20:04.674Z"
},
{
"mediaUrl":null,
"body":"2",
"read":true,
"mediaType":"chat",
"fromMe":false,
"createdAt":"2022-01-24T13:20:08.617Z"
},
{
"mediaUrl":null,
"body":"Olá, sou do Cancelamento ou Sugestões, vou te atender em alguns instantes!",
"read":true,
"mediaType":"chat",
"fromMe":true,
"createdAt":"2022-01-24T13:20:09.216Z"
},
{
"mediaUrl":null,
"body":"Ok obrigado",
"read":true,
"mediaType":"chat",
"fromMe":false,
"createdAt":"2022-01-24T13:20:13.902Z"
},
{
"mediaUrl":null,
"body":"*Administrador:*\nOlá bom dia como posso ajudar",
"read":true,
"mediaType":"chat",
"fromMe":true,
"createdAt":"2022-01-24T13:20:34.561Z"
},
{
"mediaUrl":null,
"body":"Estou com problemas técnicos",
"read":true,
"mediaType":"chat",
"fromMe":false,
"createdAt":"2022-01-24T13:20:54.191Z"
},
{
"mediaUrl":null,
"body":"*Administrador:*\nok",
"read":true,
"mediaType":"chat",
"fromMe":true,
"createdAt":"2022-01-24T13:20:57.847Z"
}
],
"tableData":{
"id":0
}
} }
] ]

View File

@ -5,20 +5,12 @@ import Modal from '../Modal'
import { render } from '@testing-library/react'; import { render } from '@testing-library/react';
import React from 'react'; import React from 'react';
import { fontSize } from '@mui/system';
import { FastField } from 'formik';
let child_columns = [
{ title: 'Atendente', field: 'user.name' }
];
const MTable = (props) => { const MTable = (props) => {
const [selectedRow, setSelectedRow] = useState(null); const [selectedRow, setSelectedRow] = useState(null);
console.log('rederizou....................') console.log('rederizou....................: ',props.data)
useEffect(() => { useEffect(() => {
@ -66,4 +58,5 @@ const MTable = (props) => {
}; };
export default React.memo(MTable);
export default React.memo(MTable)

View File

@ -7,6 +7,8 @@ import TextField from '@mui/material/TextField';
const SelectTextFields = (props) => { const SelectTextFields = (props) => {
const [currency, setCurrency] = React.useState('0'); const [currency, setCurrency] = React.useState('0');
props.currencies.push({ value: '0', label: ''})
props.func(currency); props.func(currency);
const handleChange = (event) => { const handleChange = (event) => {

View File

@ -14,7 +14,41 @@ import PropTypes from 'prop-types';
import Box from '@mui/material/Box'; import Box from '@mui/material/Box';
const reducerQ = (state, action) =>{
if(action.type === 'LOAD_QUERY'){
console.log('----------------action.payload: ', action.payload)
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 === "RESET") {
return [];
}
}
const reducer = (state, action) => { const reducer = (state, action) => {
if (action.type === "LOAD_USERS") { if (action.type === "LOAD_USERS") {
const users = action.payload; const users = action.payload;
const newUsers = []; const newUsers = [];
@ -38,6 +72,7 @@ const reducer = (state, action) => {
function Item(props) { function Item(props) {
const { sx, ...other } = props; const { sx, ...other } = props;
return ( return (
@ -72,8 +107,6 @@ Item.propTypes = {
let columnsData = [ let columnsData = [
{ title: 'Atendente', field: 'user.name' }, { title: 'Atendente', field: 'user.name' },
{ title: 'Contato', field: 'contact.number' }, { title: 'Contato', field: 'contact.number' },
@ -97,7 +130,7 @@ let columnsData = [
]; ];
const currencies = [ /*const currencies = [
{ {
value: '1', value: '1',
label: 'Adriano', label: 'Adriano',
@ -119,7 +152,7 @@ let columnsData = [
label: '', label: '',
}, },
]; ];*/
@ -132,25 +165,33 @@ const Report = () => {
const [pageNumber, setPageNumber] = useState(1); const [pageNumber, setPageNumber] = useState(1);
const [users, dispatch] = useReducer(reducer, []); const [users, dispatch] = useReducer(reducer, []);
const [tot, setTot] = useState(0)
const [columns, setColums] = useState(columnsData)
const [datePicker1, setDatePicker1] = useState(new Date()) const [columns, setColums] = useState([])
const [datePicker2, setDatePicker2] = useState(new Date())
const [startDate, setDatePicker1] = useState(new Date())
const [endDate, setDatePicker2] = useState(new Date())
const [userId, setUser] = useState(null) const [userId, setUser] = useState(null)
const [query, dispatchQ] = useReducer(reducerQ, [])
useEffect(() => { useEffect(() => {
dispatch({ type: "RESET" }); dispatch({ type: "RESET" });
dispatchQ({ type: "RESET" })
setPageNumber(1); setPageNumber(1);
}, [searchParam]); }, [searchParam]);
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
const delayDebounceFn = setTimeout(() => { const delayDebounceFn = setTimeout(() => {
const fetchUsers = async () => { const fetchUsers = async () => {
try { try {
const { data } = await api.get("/users/", { const { data } = await api.get("/users/", {
params: { searchParam, pageNumber }, params: { searchParam, pageNumber },
}); });
dispatch({ type: "LOAD_USERS", payload: data.users }); dispatch({ type: "LOAD_USERS", payload: data.users });
setHasMore(data.hasMore); setHasMore(data.hasMore);
setLoading(false); setLoading(false);
@ -158,40 +199,75 @@ const Report = () => {
console.log(err); console.log(err);
} }
}; };
fetchUsers(); fetchUsers();
}, 500); }, 500);
return () => clearTimeout(delayDebounceFn); return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber]); }, [searchParam, pageNumber]);
function handleTot (){ useEffect(() => {
setTot(tot+1)
setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchQueries = async () => {
try {
const dataQuery = await api.get("/reports/", {params: {userId, startDate, endDate },});
console.log('fffffffffffffffffffff query: ', dataQuery.data)
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchQueries();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [userId, startDate, endDate]);
// Get from child 1
const datePicker1Value = (data) => {
console.log('DATE1: ',(data));
setDatePicker1(data)
}
// Get from child 2
const datePicker2Value = (data) => {
console.log('DATE2: ',(data));
setDatePicker2(data)
}
// Get from child 3
const textFieldSelectUser = (data) => {
console.log('textField: ',data);
setUser(data)
}
function handleQuery (){
console.log('startDate: ', startDate)
console.log('endDate: ', endDate)
console.log('userid: ', userId)
console.log('Datepicker valeu: ',DatePicker1.data)
/* if(tot == 3){ /* if(tot == 3){
setColums(columns1) setColums(columns1)
} */ } */
} }
// Get from child 1 console.log('XXXXXXXXX: ', query)
const datePicker1Value = (data) => {
console.log(data);
setDatePicker1(data)
}
// Get from child 2
const datePicker2Value = (data) => {
console.log(data);
setDatePicker2(data)
}
// Get from child 3
const textFieldSelectUser = (data) => {
console.log(data);
setUser(data)
}
return ( return (
@ -200,12 +276,16 @@ const textFieldSelectUser = (data) => {
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)' }}>
<Item><SelectField func={textFieldSelectUser} currencies={currencies}/></Item> <Item><SelectField func={textFieldSelectUser} currencies={users.map((obj)=>{
return {'value': obj.id, 'label': obj.name}
})}/></Item>
<Item><DatePicker1 func={datePicker1Value} title={'Data inicio'}/></Item> <Item><DatePicker1 func={datePicker1Value} title={'Data inicio'}/></Item>
<Item><DatePicker2 func={datePicker2Value} title={'Data fim'}/></Item> <Item><DatePicker2 func={datePicker2Value} title={'Data fim'}/></Item>
<Item sx={{ gridColumn: '4 / 5' }}> <Item sx={{ gridColumn: '4 / 5' }}>
<Button size="small" variant="contained" onClick={()=>{handleTot()}}>GO</Button> <Button size="small" variant="contained" onClick={()=>{handleQuery()}}>GO</Button>
</Item> </Item>
</Box> </Box>
@ -214,7 +294,7 @@ const textFieldSelectUser = (data) => {
display: 'grid', display: 'grid',
}}> }}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}> <Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
<MTable data={data} columns={columns}/> <MTable data={query} columns={columnsData}/>
</Item> </Item>
</Box> </Box>