Criação do Delete e Update completo do recurso Lembrete

pull/1/head
adriano 2022-03-24 19:16:31 -03:00
parent 9e8c9be17d
commit 74c3be6690
12 changed files with 381 additions and 162 deletions

View File

@ -3,7 +3,7 @@ import AppError from "../errors/AppError";
import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
// const test = await ListSchedulingNotifyContactService('5517988310949','2022-03-18','2022-03-19');
// const test = await ListSchedulingNotifyContactService('','2022-03-18','2022-03-19');
@ -11,12 +11,17 @@ import ListSchedulingNotifyContactService from "../services/SchedulingNotifySer
// console.log('$$$$$$$$$$$$$$$$$$$$$$$$$$ test:\n', test)
type IndexQuery = {
contactNumber: string;
startDate: string;
endDate: string;
};
export const reportScheduleNotifyByDateStartDateEnd = async (req: Request, res: Response): Promise<Response> => {
@ -30,6 +35,29 @@ export const reportScheduleNotifyByDateStartDateEnd = async (req: Request, res:
};
export const createOrUpdateScheduleNotify = async (req: Request, res: Response): Promise<Response> => {
const scheduleData = req.body;
console.log(' +++++++++++ scheduleData: ', scheduleData)
const schedulingNotifyCreate = await CreateSchedulingNotifyService(
{
schedulingNotifyId: scheduleData.schedulingNotifyId,
ticketId: scheduleData.ticketId,
statusChatEndId: scheduleData.statusChatEndId,
schedulingDate: scheduleData.schedulingDate,
schedulingTime: scheduleData.schedulingTime,
message: scheduleData.message
}
)
console.group(':::::::::::::::::: DATA schedulingNotifyCreate:\n',schedulingNotifyCreate)
return res.status(200).json(schedulingNotifyCreate);
};
export const remove = async ( req: Request, res: Response ): Promise<Response> => {
console.log('EEEEEEEEEEEEEEEEEEEEEEEEEEE')

View File

@ -0,0 +1,12 @@
import { Request, Response } from "express";
import AppError from "../errors/AppError";
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
export const show = async (req: Request, res: Response): Promise<Response> => {
const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" });
return res.status(200).json(statusChatEnd);
};

View File

@ -7,6 +7,8 @@ const schedulingNotifiyRoutes = Router();
schedulingNotifiyRoutes.delete("/schedule/:scheduleId", isAuth, SchedulingNotifyController.remove);
schedulingNotifiyRoutes.post("/schedule", isAuth, SchedulingNotifyController.createOrUpdateScheduleNotify);
schedulingNotifiyRoutes.get("/schedules", isAuth, SchedulingNotifyController.reportScheduleNotifyByDateStartDateEnd);
export default schedulingNotifiyRoutes;

View File

@ -12,6 +12,7 @@ import queueRoutes from "./queueRoutes";
import quickAnswerRoutes from "./quickAnswerRoutes";
import reportRoutes from "./reportRoutes";
import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes";
import statusChatEndRoutes from "./statusChatEndRoutes";
const routes = Router();
@ -27,8 +28,8 @@ routes.use(whatsappSessionRoutes);
routes.use(queueRoutes);
routes.use(quickAnswerRoutes);
routes.use(schedulingNotifiyRoutes)
routes.use(schedulingNotifiyRoutes);
routes.use(reportRoutes);
routes.use(statusChatEndRoutes);
export default routes;

View File

@ -0,0 +1,10 @@
import { Router } from "express";
import isAuth from "../middleware/isAuth";
import * as StatusChatEnd from "../controllers/StatusChatEndController";
const statusChatEndRoutes = Router();
statusChatEndRoutes.get("/statusChatEnd", isAuth, StatusChatEnd.show);
export default statusChatEndRoutes;

View File

@ -3,27 +3,88 @@ import SchedulingNotify from "../../models/SchedulingNotify";
interface Request {
schedulingNotifyId?: string,
ticketId: string,
statusChatEndId: string,
schedulingDate: string,
schedulingTime: string,
message: string
}
const CreateSchedulingNotifyService = async ({ ticketId, statusChatEndId, schedulingDate, schedulingTime, message }: Request): Promise<SchedulingNotify> => {
}
const schedulingNotify = await SchedulingNotify.create(
{
ticketId,
statusChatEndId,
schedulingDate,
schedulingTime,
message
const CreateSchedulingNotifyService = async ({
schedulingNotifyId = '',
ticketId,
statusChatEndId,
schedulingDate,
schedulingTime,
message
}: Request): Promise<SchedulingNotify> => {
let schedulingNotify = null;
if(schedulingNotifyId){
console.log('000000000000000000000000000 ATUALIZOU!')
})
schedulingNotify = await SchedulingNotify.findOne({ where: { id: schedulingNotifyId } });
if(schedulingNotify){
try{
await schedulingNotify.update({ statusChatEndId, schedulingDate, schedulingTime, message});
}catch(err){
throw new AppError("ERR_NO_SCHEDULING_NOTIFY_FOUND", 404);
}
//await scheduleNotify.reload({attributes: ["id", "name"]});
}
}
if(!schedulingNotify){
console.log('111111111111111111111111111 criou!')
schedulingNotify = await SchedulingNotify.create(
{
ticketId,
statusChatEndId,
schedulingDate,
schedulingTime,
message
})
}
return schedulingNotify
}
// const CreateSchedulingNotifyService = async ({ ticketId, statusChatEndId, schedulingDate, schedulingTime, message }: Request): Promise<SchedulingNotify> => {
// const schedulingNotify = await SchedulingNotify.create(
// {
// ticketId,
// statusChatEndId,
// schedulingDate,
// schedulingTime,
// message
// })
// return schedulingNotify
// }
export default CreateSchedulingNotifyService

View File

@ -318,6 +318,7 @@ const handleChange = (event) => {
<SelectField func={textFieldSelect}
emptyField={false}
textBoxFieldSelected={'1'}
header={'Opções de encerramento do atendimento'}
currencies={props.statusChatEnd.map((obj)=>{
return {'value': obj.id, 'label': obj.name}
@ -360,7 +361,7 @@ const handleChange = (event) => {
</Item>
}
{schedulesContact.length>0 &&
{/* {schedulesContact.length>0 &&
@ -423,7 +424,7 @@ const handleChange = (event) => {
</TableBody>
</Table>
</Paper>
</Item>}
</Item>} */}
</Box>

View File

@ -21,12 +21,21 @@ function formatDateDatePicker(data){
String(new Date(data).getDate()).padStart(2,'0')
}
function formatDate(strDate){
const date = strDate.split(' ')[0].split('/')
const time = strDate.split(' ')[1]
return `${date[2]}-${date[1]}-${date[0]} ${time}`
}
function ResponsiveDatePickers(props) {
const [selectedDate, handleDateChange] = useState(null);
// props.func(formatDateDatePicker(selectedDate));
console.log('schedulingDate schedulingDate schedulingDate: ', formatDate(props.schedulingDate))
useEffect(()=>{
const [selectedDate, handleDateChange] = useState(new Date(formatDate(props.schedulingDate)));
useEffect(()=>{
if( !selectedDate ){
props.func('');

View File

@ -0,0 +1,93 @@
// import React, { useState } from "react";
// import { DateTimePicker, KeyboardDateTimePicker } from "@material-ui/pickers";
// function InlineDateTimePickerDemo(props) {
// const [selectedDate, handleDateChange] = useState(new Date("2018-01-01T00:00:00.000Z"));
// return (
// <>
// <DateTimePicker
// variant="inline"
// label="Basic example"
// value={selectedDate}
// onChange={handleDateChange}
// />
// <KeyboardDateTimePicker
// variant="inline"
// ampm={false}
// label="With keyboard"
// value={selectedDate}
// onChange={handleDateChange}
// onError={console.log}
// disablePast
// format="yyyy/MM/dd HH:mm"
// />
// </>
// );
// }
// export default InlineDateTimePickerDemo;
import React, { Fragment, useState, useEffect } from "react";
// import TextField from '@mui/material/TextField';
import DateFnsUtils from '@date-io/date-fns';
import {
TimePicker,
MuiPickersUtilsProvider,
} from '@material-ui/pickers';
import ptBrLocale from "date-fns/locale/pt-BR";
function formatDate(strDate){
const date = strDate.split(' ')[0].split('/')
const time = strDate.split(' ')[1]
return `${date[2]}-${date[1]}-${date[0]} ${time}`
}
const ResponsiveTimePickers = (props) => {
const [value, setValue] = useState(new Date(new Date(formatDate(props.schedulingDate))));
// props.func(value);
useEffect(()=>{
props.func(value);
}, [value, props])
return (
<Fragment>
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={ptBrLocale}>
<TimePicker
variant="outline"
label={props.title}
value={value}
ampm={false}
onChange={(newValue) => {
setValue(newValue);
}}
// Ativar se necessario
// renderInput={(params) => <TextField {...params} />}
/>
</MuiPickersUtilsProvider>
</Fragment>
);
}
export default ResponsiveTimePickers

View File

@ -11,7 +11,7 @@ import Box from '@mui/material/Box';
import SelectField from "../Report/SelectField";
import DatePicker from './DatePicker2'
import TimerPickerSelect from '../ChatEnd/TimerPickerSelect'
import TimerPickerSelect from './TimerPickerSelect2'
import TextareaAutosize from '@mui/material/TextareaAutosize';
// import { subHours } from "date-fns";
@ -112,9 +112,9 @@ const Modal = (props) => {
const [open, setOpen] = useState(true);
const [scroll, /*setScroll*/] = useState('body');
const [statusChatEndId, setStatusChatEnd] = useState(null)
const [startDate, setDatePicker] = useState(props.schedulingTime ? new Date(props.schedulingTime) : new Date())
const [startDate, setDatePicker] = useState(props.rowData.schedulingTime ? new Date(props.rowData.schedulingTime) : new Date())
const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState()
const [textArea1, setTextArea1] = useState(props.rowData.message)
const [schedulesContact, dispatch] = useReducer(reducer, []);
@ -135,7 +135,7 @@ const Modal = (props) => {
(async () => {
try {
const { data } = await api.get("/tickets/" + props.ticketId);
const { data } = await api.get("/tickets/" + props.rowData.ticketId);
dispatch({ type: "LOAD_SCHEDULES", payload: data.schedulesContact });
@ -233,15 +233,30 @@ const timerPickerValue = (data) => {
}
dataSendServer = {
'schedulingNotifyId': props.rowData.id,
'statusChatEndId': statusChatEndId,
'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)),
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)),
'message': textArea1
}
const formatDateTimeBrazil = (dateTime) => {
let date = dateTime.split(' ')[0]
let time = dateTime.split(' ')[1]
date = date.split('-')
return `${date[2]}/${date[1]}/${date[0]} ${time}`
}
props.rowData['schedulingDate'] = formatDateTimeBrazil(`${dataSendServer['schedulingDate']}:00`)
props.rowData['schedulingTime'] = formatDateTimeBrazil(`${dataSendServer['schedulingTime']}:00`)
props.rowData['message'] = textArea1
}
props.func(dataSendServer)
props.func(dataSendServer, props.rowData)
setOpen(false);
};
@ -317,6 +332,7 @@ const handleChange = (event) => {
<SelectField func={textFieldSelect}
emptyField={false}
textBoxFieldSelected={props.textBoxFieldSelected}
header={'Opções de encerramento do atendimento'}
currencies={props.statusChatEnd.map((obj)=>{
return {'value': obj.id, 'label': obj.name}
@ -337,12 +353,17 @@ const handleChange = (event) => {
<Item><DatePicker
func={datePickerValue}
minDate={true}
startEmpty={false}
minDate={false}
schedulingDate={props.rowData.schedulingDate}
title={'Data do lembrete'}/>
</Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora do lembrete'}/></Item>
<Item>
<TimerPickerSelect
func={timerPickerValue}
schedulingDate={props.rowData.schedulingDate}
title={'Hora do lembrete'}/>
</Item>
</Box>
@ -365,72 +386,7 @@ const handleChange = (event) => {
}
{schedulesContact.length>0 && !props.update &&
<Item>
<ConfirmationModal
title={selectedSchedule && `Deletar lembrete do dia ${selectedSchedule.schedulingTime.split(' ')[0]} ${selectedSchedule.schedulingTime.split(' ')[1]} ?`}
open={confirmModalOpen}
onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
>
<span>Deseja realmente deletar esse Lembrete? </span>
</ConfirmationModal>
<span>Lembretes</span>
<Paper variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
Data
</TableCell>
<TableCell align="center">
Hora
</TableCell>
<TableCell align="center">
Mensagem
</TableCell>
<TableCell align="center">
Deletar
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<>
{schedulesContact.map((scheduleData, index) => (
<TableRow key={scheduleData.id}>
<TableCell align="center">{scheduleData.schedulingDate.split(' ')[0]}</TableCell>
<TableCell align="center">{scheduleData.schedulingTime.split(' ')[1]}</TableCell>
<TableCell align="center">{scheduleData.message}</TableCell>
<TableCell align="center">
<IconButton
size="small"
onClick={() => {
setSelectedSchedule(scheduleData);
setConfirmModalOpen(true);
}}
>
<DeleteOutline />
</IconButton>
</TableCell>
</TableRow>
))}
</>
</TableBody>
</Table>
</Paper>
</Item>}
</Box>
</DialogContent>

View File

@ -7,9 +7,15 @@ import TextField from '@mui/material/TextField';
const SelectTextFields = (props) => {
const [currency, setCurrency] = useState(props.emptyField ? '0' : '1');
// const [currency, setCurrency] = useState(props.emptyField ? '0' : '1');
if(props.emptyField){
console.log(':::::::::::::::::::::: props.textBoxFieldSelected: ', props.textBoxFieldSelected)
const [currency, setCurrency] = useState(props.textBoxFieldSelected ? props.textBoxFieldSelected: '0');
// const [currency, setCurrency] = useState(props.textBoxFieldSelected);
if(!props.textBoxFieldSelected){
props.currencies.push({ 'value': 0, 'label': ''})
}

View File

@ -90,28 +90,28 @@ const reducerQ = (state, action) =>{
const reducer = (state, action) => {
// const reducer = (state, action) => {
if (action.type === "LOAD_SCHEDULES") {
const users = action.payload;
const newUsers = [];
// if (action.type === "LOAD_STATUS_CHAT_END") {
// const users = action.payload;
// const newUsers = [];
users.forEach((user) => {
const userIndex = state.findIndex((u) => u.id === user.id);
if (userIndex !== -1) {
state[userIndex] = user;
} else {
newUsers.push(user);
}
});
// users.forEach((user) => {
// const userIndex = state.findIndex((u) => u.id === user.id);
// if (userIndex !== -1) {
// state[userIndex] = user;
// } else {
// newUsers.push(user);
// }
// });
return [...state, ...newUsers];
}
// return [...state, ...newUsers];
// }
if (action.type === "RESET") {
return [];
}
};
// if (action.type === "RESET") {
// return [];
// }
// };
@ -150,17 +150,17 @@ Item.propTypes = {
let columnsData = [
// let columnsData = [
{ title: 'Foto', field: 'ticket.contact.profilePicUrl', render: rowData => <img src={rowData['ticket.contact.profilePicUrl']} style={{width: 40, borderRadius: '50%'}}/> },
// { 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' },
// { title: 'Nome', field: 'ticket.contact.name' },
// { title: 'Contato', field: 'ticket.contact.number' },
// { title: 'schedulingTime', field: 'schedulingTime' },
// { title: 'schedulingDate', field: 'schedulingDate' },
// { title: 'message', field: 'message' },
];
// ];
@ -171,10 +171,10 @@ const SchedulesReminder = () => {
//--------
const [searchParam] = useState("");
//const [loading, setLoading] = useState(false);
const [loading, setLoading] = useState(null);
//const [hasMore, setHasMore] = useState(false);
const [pageNumber, setPageNumber] = useState(1);
const [users, dispatch] = useReducer(reducer, []);
// const [users, dispatch] = useReducer(reducer, []);
//const [columns, setColums] = useState([])
const [startDate, setDatePicker1] = useState(new Date())
const [endDate, setDatePicker2] = useState(new Date())
@ -192,45 +192,47 @@ const SchedulesReminder = () => {
useEffect(() => {
dispatch({ type: "RESET" });
// dispatch({ type: "RESET" });
dispatchQ({ type: "RESET" })
setPageNumber(1);
}, [searchParam]);
//natalia
useEffect(() => {
//setLoading(true);
// setLoading(true);
const delayDebounceFn = setTimeout(() => {
const fetchUsers = async () => {
const fetchStatusChatEnd = async () => {
try {
const { data } = await api.get("/users/", {
const statusChatEndLoad = await api.get("/statusChatEnd", {
params: { searchParam, pageNumber },
});
dispatch({ type: "LOAD_SCHEDULES", payload: data.users });
// dispatch({ type: "LOAD_STATUS_CHAT_END", payload: statusChatEndLoad.data });
console.log(':::::::::::::: statusChatEndLoad: ', statusChatEndLoad.data)
setStatusEndChat(statusChatEndLoad.data)
//setHasMore(data.hasMore);
//setLoading(false);
// setLoading(false);
} catch (err) {
console.log(err);
}
};
fetchUsers();
fetchStatusChatEnd();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [searchParam, pageNumber]);
useEffect(() => {
setData(query)
}, [query])
useEffect(() => {
//setLoading(true);
setLoading(true);
const delayDebounceFn = setTimeout(() => {
@ -241,10 +243,7 @@ const SchedulesReminder = () => {
dispatchQ({ type: "RESET" })
dispatchQ({ type: "LOAD_QUERY", payload: dataQuery.data });
// setStatusEndChat(dataQuery.data.statusEndChat)
//setLoading(false);
setLoading(false);
} catch (err) {
console.log(err);
@ -257,6 +256,17 @@ const SchedulesReminder = () => {
return () => clearTimeout(delayDebounceFn);
}, [contactNumber, startDate, endDate]);
useEffect(() => {
if(!loading){
console.log('carregando table...')
setData(query)
}
}, [loading])
// Get from child 1
@ -291,6 +301,7 @@ const handleClear = () => {
const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false);
console.log('cancelou NULL 1')
setSelectedSchedule(null);
};
@ -315,22 +326,45 @@ const handleDeleteSchedule = async (scheduleId) => {
} catch (err) {
toastError(err);
}
console.log('cancelou NULL 2')
setSelectedSchedule(null);
};
const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
try {
await api.post("/schedule", scheduleData);
toast.success(("Lembrete atualizado com sucesso!"));
//////////////////
const dataUpdate = [...dataRows];
const index = rowsDataNew.tableData['id'];
dataUpdate[index] = rowsDataNew;
setData([...dataUpdate]);
/////////////////
} catch (err) {
toastError(err);
}
//console.log('cancelou NULL 3')
setSelectedSchedule(null);
};
const chatEndVal = (data) => {
const chatEndVal = (data, rowsDataNew) => {
if(data){
console.log('DATA SCHECULE: ', data)
console.log(':::::::::::::::::::: ChatEnd2: ',(data));
console.log(':::::::::::::::::::: Rows data fro child: ',(rowsDataNew));
// data = {...data, 'ticketId': ticket.id}
handleUpdateSchedule(data, rowsDataNew)
// console.log('ChatEnd: ',(data));
// handleUpdateTicketStatus(null, "closed", user?.id, data)
}
}
@ -341,12 +375,9 @@ const handleModal = (rowData) => {
render(<Modal
modal_header={'Editar Lembrete/Agendamentos'}
func={chatEndVal}
statusChatEnd={statusEndChat}
ticketId={rowData.ticketId}
update={true}
schedulingDate={rowData.schedulingDate}
schedulingTime={rowData.schedulingTime}
message={rowData.message}
statusChatEnd={statusEndChat}
textBoxFieldSelected={'2'}
rowData={rowData}
/>)
};
@ -403,13 +434,8 @@ const handleModal = (rowData) => {
display: 'grid',
}}>
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
{/* <MTable data={query}
columns={columnsData}
removeClickRow={true}
hasChild={true}
table_title={'Lembretes/Agendamentos'}/> */}
<Item sx={{ gridColumn: '1', gridRow: 'span 1' }}>
<ConfirmationModal
title={selectedSchedule && `Deletar lembrete do dia ${selectedSchedule.schedulingTime.split(' ')[0]} ${selectedSchedule.schedulingTime.split(' ')[1]} ?`}
@ -422,7 +448,19 @@ const handleModal = (rowData) => {
<MaterialTable
title="Lembretes/Agendamentos"
columns={columnsData}
columns={
[
{ 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' },
]
}
data={dataRows}
// icons={tableIcons}
@ -431,9 +469,11 @@ const handleModal = (rowData) => {
icon: Edit,
tooltip: 'Editar',
onClick: (event, rowData) => {
console.log("You saved ",rowData)
handleModal(rowData)
console.log("You want edit data ",rowData)
setSelectedSchedule(rowData);
handleModal(rowData)
}
},
{
icon: Delete,