Criação do agendamento com opção de excluira agendametnos anteriores

pull/1/head
adriano 2022-03-12 02:13:15 -03:00
parent 68a421c567
commit e8eb00e96c
11 changed files with 297 additions and 190 deletions

View File

@ -0,0 +1,15 @@
import { Request, Response } from "express";
import DeleteSchedulingNotifyService from "../services/SchedulingNotifyServices/DeleteSchedulingNotifyService";
export const remove = async ( req: Request, res: Response ): Promise<Response> => {
console.log('EEEEEEEEEEEEEEEEEEEEEEEEEEE')
const { scheduleId } = req.params;
await DeleteSchedulingNotifyService(scheduleId);
return res.status(200).send();
};

View File

@ -148,6 +148,7 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
ticketId: scheduleData.ticketId, ticketId: scheduleData.ticketId,
scheduleId: scheduleData.scheduleId, scheduleId: scheduleData.scheduleId,
schedulingDate: scheduleData.schedulingDate, schedulingDate: scheduleData.schedulingDate,
schedulingTime: scheduleData.schedulingTime,
message: scheduleData.message message: scheduleData.message
} }
) )

View File

@ -27,6 +27,10 @@ module.exports = {
type: DataTypes.DATE, type: DataTypes.DATE,
allowNull: false allowNull: false
}, },
schedulingTime: {
type: DataTypes.DATE,
allowNull: false
},
message: { message: {
type: DataTypes.STRING, type: DataTypes.STRING,
allowNull: false allowNull: false

View File

@ -38,6 +38,9 @@ import {
@Column @Column
schedulingDate: Date; schedulingDate: Date;
@Column
schedulingTime: Date;
@Column @Column
message: string message: string

View File

@ -0,0 +1,10 @@
import { Router } from "express";
import isAuth from "../middleware/isAuth";
import * as SchedulingNotifyController from "../controllers/SchedulingNotifyController";
const schedulingNotifiyRoutes = Router();
schedulingNotifiyRoutes.delete("/schedule/:scheduleId", isAuth, SchedulingNotifyController.remove);
export default schedulingNotifiyRoutes;

View File

@ -11,6 +11,7 @@ import whatsappSessionRoutes from "./whatsappSessionRoutes";
import queueRoutes from "./queueRoutes"; import queueRoutes from "./queueRoutes";
import quickAnswerRoutes from "./quickAnswerRoutes"; import quickAnswerRoutes from "./quickAnswerRoutes";
import reportRoutes from "./reportRoutes"; import reportRoutes from "./reportRoutes";
import schedulingNotifiyRoutes from "./SchedulingNotifyRoutes";
const routes = Router(); const routes = Router();
@ -26,6 +27,7 @@ routes.use(whatsappSessionRoutes);
routes.use(queueRoutes); routes.use(queueRoutes);
routes.use(quickAnswerRoutes); routes.use(quickAnswerRoutes);
routes.use(schedulingNotifiyRoutes)
routes.use(reportRoutes); routes.use(reportRoutes);

View File

@ -6,6 +6,7 @@ interface Request {
ticketId: string, ticketId: string,
scheduleId: string, scheduleId: string,
schedulingDate: string, schedulingDate: string,
schedulingTime: string,
message: string message: string
} }
@ -15,6 +16,7 @@ const CreateSchedulingNotifyService = async (
ticketId, ticketId,
scheduleId, scheduleId,
schedulingDate, schedulingDate,
schedulingTime,
message message
}: Request): Promise<SchedulingNotify> => { }: Request): Promise<SchedulingNotify> => {
@ -24,6 +26,7 @@ const CreateSchedulingNotifyService = async (
ticketId, ticketId,
scheduleId, scheduleId,
schedulingDate, schedulingDate,
schedulingTime,
message message
}) })

View File

@ -9,7 +9,8 @@ const ListSchedulingNotifyContactService = async (contactNumber: string): Promis
const ticket = await SchedulingNotify.findAll({ const ticket = await SchedulingNotify.findAll({
attributes:['id', [Sequelize.fn("DATE_FORMAT",Sequelize.col("schedulingDate"),"%d/%m/%Y %H:%i:%s"),"schedulingDate"], 'message'], attributes:['id', [Sequelize.fn("DATE_FORMAT",Sequelize.col("schedulingDate"),"%d/%m/%Y %H:%i:%s"),"schedulingDate"],
[Sequelize.fn("DATE_FORMAT",Sequelize.col("schedulingTime"),"%d/%m/%Y %H:%i:%s"),"schedulingTime"], 'message'],
include: [ include: [
{ {

View File

@ -1,59 +1,73 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef, useReducer } from 'react';
import Button from '@mui/material/Button'; import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog'; import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions'; import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent'; import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText'; import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle'; import DialogTitle from '@mui/material/DialogTitle';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import Box from '@mui/material/Box'; import Box from '@mui/material/Box';
import SelectField from "../../Report/SelectField"; import SelectField from "../../Report/SelectField";
import TextFieldSelectHourBefore from '@mui/material/TextField'; import TextFieldSelectHourBefore from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem'; import MenuItem from '@mui/material/MenuItem';
import DatePicker from '../../Report/DatePicker' import DatePicker from '../../Report/DatePicker'
import TimerPickerSelect from '../TimerPickerSelect' import TimerPickerSelect from '../TimerPickerSelect'
// import MainHeader from "../../components/MainHeader";
// import MainHeaderButtonsWrapper from "../../components/MainHeaderButtonsWrapper";
// import TableRowSkeleton from "../../components/TableRowSkeleton";
// import Title from "../../components/Title";
import TextareaAutosize from '@mui/material/TextareaAutosize'; import TextareaAutosize from '@mui/material/TextareaAutosize';
import { subHours } from "date-fns";
import { addHours, subHours, subMinutes } from "date-fns";
import { import {
IconButton, IconButton,
makeStyles,
Paper, Paper,
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
TableHead, TableHead,
TableRow, TableRow,
Typography,
} from "@material-ui/core"; } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({ import { DeleteOutline } from "@material-ui/icons";
mainPaper: { import { toast } from "react-toastify"; import api from "../../../services/api";
flex: 1, import toastError from "../../../errors/toastError";
padding: theme.spacing(1), import ConfirmationModal from "../../ConfirmationModal";
overflowY: "scroll",
...theme.scrollbarStyles,
}, const reducer = (state, action) => {
customTableCell: {
display: "flex",
alignItems: "center", if (action.type === "LOAD_SCHEDULES") {
justifyContent: "center", const schedulesContact = action.payload;
}, const newSchedules= [];
}));
schedulesContact.forEach((schedule) => {
const scheduleIndex = state.findIndex((s) => s.id === schedule.id);
if (scheduleIndex !== -1) {
state[scheduleIndex] = schedule;
} else {
newSchedules.push(schedule);
}
});
return [...state, ...newSchedules];
}
if (action.type === "DELETE_SCHEDULE") {
const scheduleId = action.payload;
const scheduleIndex = state.findIndex((q) => q.id === scheduleId);
if (scheduleIndex !== -1) {
state.splice(scheduleIndex, 1);
}
return [...state];
}
if (action.type === "RESET") {
return [];
}
};
const Item = (props) => { const Item = (props) => {
@ -92,7 +106,9 @@ Item.propTypes = {
const Modal = (props) => { const Modal = (props) => {
const classes = useStyles(); // const [clientSchedules, dispatch] = useReducer(reducer, []);
const [selectedSchedule, setSelectedSchedule] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
const [scroll, /*setScroll*/] = useState('body'); const [scroll, /*setScroll*/] = useState('body');
@ -104,11 +120,10 @@ const Modal = (props) => {
const [data] = useState(props.schedules) const [data] = useState(props.schedules)
const [schedulesContact] = useState(props.schedulesContact) const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(formatedTimeHour(subHours(timerPicker,1))); const [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState( ); const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState( );
const [test, setTest] = useState(null);
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
@ -120,6 +135,22 @@ const Modal = (props) => {
useEffect(() => {
(async () => {
try {
const { data } = await api.get("/tickets/" + props.ticketId);
dispatch({ type: "LOAD_SCHEDULES", payload: data.schedulesContact });
} catch (err) {
toastError(err);
}
})();
}, [props]);
function greetMessageSchedule(scheduleDate){ function greetMessageSchedule(scheduleDate){
return `podemos confirmar sua consulta agendada para hoje às ${scheduleDate}?` return `podemos confirmar sua consulta agendada para hoje às ${scheduleDate}?`
@ -129,36 +160,85 @@ const Modal = (props) => {
return `${timer.getHours().toString().padStart(2, '0')}:${timer.getMinutes().toString().padStart(2, '0')}` return `${timer.getHours().toString().padStart(2, '0')}:${timer.getMinutes().toString().padStart(2, '0')}`
} }
function hoursBeforeAvalible(timer){ const hoursBeforeAvalible = (timer) =>{
let hours = [] let hours = []
let hour = 1 let hour = 1
while(subHours(timer, hour).getHours()>=6 /*&& subHours(timer, hour).getHours()>=new Date().getHours()*/){ if(startDate === dateCurrentFormated()){
console.log('******** TIMER: ', formatedTimeHour(subHours(timer,hour))) console.log('HOJE++++')
hours.push( while(subHours(timer, hour).getHours()>=6 &&
{value: formatedTimeHour(subHours(timer,hour)), subHours(timer, hour).getHours()>=new Date().getHours() &&
label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO`}) subHours(timer, hour).getHours()<=19){
console.log('******** TIMER: ', formatedTimeHour(subHours(timer,hour)))
hours.push(
{value: formatedTimeHour(subHours(timer,hour)),
label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO`})
hour++;
}
if(hours.length>1){
console.log('entrou----------------------: ', hours.length)
hours.pop()
setCurrency(hours[0].value)
}
else{
setCurrency(null)
}
hour++;
} }
else{
while(subHours(timer, hour).getHours()>=6 && subHours(timer, hour).getHours()<=19){
console.log('******** another day TIMER: ', formatedTimeHour(subHours(timer,hour)))
hours.push(
{value: formatedTimeHour(subHours(timer,hour)),
label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO`})
hour++;
}
if(hours.length>0){
console.log('entrou----------------------: ', hours.length)
setCurrency(hours[0].value)
}
else{
setCurrency(null)
}
if(hours){
setCurrency(hours[0].value)
} }
return hours return {time: hours, hour:hour}
console.log('HOURS: ',hours)
} }
const handleCloseConfirmationModal = () => {
setConfirmModalOpen(false);
setSelectedSchedule(null);
};
const handleDeleteSchedule = async (scheduleId) => {
try {
await api.delete(`/schedule/${scheduleId}`);
toast.success(("Agendamento deletado com sucesso!"));
dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId });
} catch (err) {
toastError(err);
}
setSelectedSchedule(null);
};
// Get from child 2 // Get from child 2
const datePickerValue = (data) => { const datePickerValue = (data) => {
console.log('datePickerValue: ',(data)); console.log('datePickerValue: ',(data));
@ -190,7 +270,7 @@ const dateCurrentFormated = () => {
if (scheduleId === '1'){ if (scheduleId === '1'){
} }
else if(textArea1.trim().length<10){ else if(textArea1 && textArea1.trim().length<10){
alert('Mensagem muito curta!\nMínimo 10 caracteres.') alert('Mensagem muito curta!\nMínimo 10 caracteres.')
return return
} }
@ -199,6 +279,13 @@ const dateCurrentFormated = () => {
alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 07:00 e 20:00') alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 07:00 e 20:00')
return return
} }
else if(!currencyHourBefore){
alert('Para agendamentos do dia corrente, essa funcionalidade atende a agendeamentos com no mínimo 2 horas adiantado a partir da hora atual!')
return
}
// else if(startDate === dateCurrentFormated()){ // else if(startDate === dateCurrentFormated()){
// if( // if(
// (new Date(subHours(timerPicker, 1)).getHours() <= new Date().getHours() && // (new Date(subHours(timerPicker, 1)).getHours() <= new Date().getHours() &&
@ -225,6 +312,7 @@ const dateCurrentFormated = () => {
// 'schedulingDate': startDate+' '+formatedTimeHour(subHours(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:${timerPicker.getSeconds()}`), 1))+':00', // 'schedulingDate': startDate+' '+formatedTimeHour(subHours(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:${timerPicker.getSeconds()}`), 1))+':00',
// 'schedulingDate': `${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:${timerPicker.getSeconds()}`, // 'schedulingDate': `${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:${timerPicker.getSeconds()}`,
'schedulingDate': `${startDate} ${currencyHourBefore}:00`, 'schedulingDate': `${startDate} ${currencyHourBefore}:00`,
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)),
'message': textArea1 'message': textArea1
}); });
@ -256,6 +344,7 @@ const handleChangeHourBefore = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value); console.log('textFihandleChangeHourBefore: ',event.target.value);
setCurrency(event.target.value); setCurrency(event.target.value);
}; };
@ -271,24 +360,29 @@ const handleChangeHourBefore = (event) => {
useEffect(()=>{ useEffect(()=>{
if (parseInt(timerPicker.getHours()) > 11 && parseInt(timerPicker.getHours()) < 18){ setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
// setTextArea1('Boa tarde, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
},[timerPicker, startDate])
useEffect(()=>{
console.log('CURRENCY HOUR BEFORE: ', `${startDate} ${currencyHourBefore}:00`)
let auxDate = new Date(`${startDate} ${currencyHourBefore}:00`)
if (parseInt(auxDate.getHours()) > 11 && parseInt(auxDate.getHours()) < 18){
setTextArea1('Boa tarde, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1))) setTextArea1('Boa tarde, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
} }
else if(parseInt(timerPicker.getHours()) < 12){ else if(parseInt(auxDate.getHours()) < 12){
// setTextArea1('Bom dia, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
setTextArea1('Bom dia, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1))) setTextArea1('Bom dia, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
} }
else if(parseInt(timerPicker.getHours()) > 17){ else if(parseInt(auxDate.getHours()) > 17){
// setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1))) setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
} }
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker)) },[currencyHourBefore, startDate])
},[timerPicker])
const handleChange = (event) => { const handleChange = (event) => {
@ -302,6 +396,8 @@ const handleChange = (event) => {
return ( return (
<Dialog <Dialog
open={open} open={open}
onClose={handleCancel} onClose={handleCancel}
@ -369,22 +465,24 @@ const handleChange = (event) => {
<Box sx={{display: 'flex', flexDirection: 'column' }}> <Box sx={{display: 'flex', flexDirection: 'column' }}>
<Item> {currencyHourBefore &&
<TextFieldSelectHourBefore <Item>
id="outlined-select-currency" <TextFieldSelectHourBefore
select id="outlined-select-currency"
label="Enviar mensagem para cliente" select
value={currencyHourBefore} label="Enviar mensagem para cliente"
size="small" value={currencyHourBefore}
onChange={handleChangeHourBefore} size="small"
> onChange={handleChangeHourBefore}
{currenciesTimeBefore.map((option) => ( >
<MenuItem key={option.value} value={option.value}> {currenciesTimeBefore.map((option) => (
{option.label} <MenuItem key={option.value} value={option.value}>
</MenuItem> {option.label}
))} </MenuItem>
</TextFieldSelectHourBefore> ))}
</Item> </TextFieldSelectHourBefore>
</Item>
}
<Item> <Item>
@ -402,92 +500,66 @@ const handleChange = (event) => {
</Item> </Item>
} }
{/* <Item> {schedulesContact.length>0 &&
<MainHeader>
<Title>Titulo 1</Title>
<MainHeaderButtonsWrapper>
<Button
variant="contained"
color="primary"
// onClick={handleOpenQueueModal}
>
buttons add
</Button>
</MainHeaderButtonsWrapper>
</MainHeader>
<Paper variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
table name
</TableCell>
<TableCell align="center">
table color
</TableCell>
<TableCell align="center">
table greeting
</TableCell>
<TableCell align="center">
table actions
</TableCell>
</TableRow>
</TableHead>
<TableBody>
<>
{schedulesContact.map((queue) => (
<TableRow key={queue.id}>
<TableCell align="center">{queue.name}</TableCell>
<TableCell align="center">
<div className={classes.customTableCell}>
<span
style={{
backgroundColor: queue.color,
width: 60,
height: 20,
alignSelf: "center",
}}
/>
</div>
</TableCell>
<TableCell align="center">
<div className={classes.customTableCell}>
<Typography
style={{ width: 300, align: "center" }}
noWrap
variant="body2"
>
{queue.greetingMessage}
</Typography>
</div>
</TableCell>
<TableCell align="center">
<IconButton
size="small"
// onClick={() => handleEditQueue(queue)}
>
<Edit />
</IconButton>
<IconButton
size="small"
onClick={() => {
setSelectedQueue(queue);
setConfirmModalOpen(true);
}}
>
<DeleteOutline />
</IconButton>
</TableCell>
</TableRow>
))}
{loading && <TableRowSkeleton columns={4} />}
</>
</TableBody>
</Table>
</Paper>
</Item> */}
<Item>
<ConfirmationModal
title={selectedSchedule && `Deletar agendamento do dia ${selectedSchedule.schedulingTime.split(' ')[0]} ${selectedSchedule.schedulingTime.split(' ')[1]} ?`}
open={confirmModalOpen}
onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
>
<span>Deseja realmente deletar esse Agendamento? </span>
</ConfirmationModal>
<span>Agendamentos</span>
<Paper variant="outlined">
<Table size="small">
<TableHead>
<TableRow>
<TableCell align="center">
Data
</TableCell>
<TableCell align="center">
Hora
</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">
<IconButton
size="small"
onClick={() => {
setSelectedSchedule(scheduleData);
setConfirmModalOpen(true);
}}
>
<DeleteOutline />
</IconButton>
</TableCell>
</TableRow>
))}
</>
</TableBody>
</Table>
</Paper>
</Item>}
</Box> </Box>
</DialogContent> </DialogContent>

View File

@ -84,7 +84,6 @@ const Ticket = () => {
const [ticket, setTicket] = useState({}); const [ticket, setTicket] = useState({});
const [schedule, setSchedule] = useState({}) const [schedule, setSchedule] = useState({})
const [schedulesContact, setSchedulesContact] = useState({})
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
@ -99,13 +98,10 @@ const Ticket = () => {
// setContact(data.contact); // setContact(data.contact);
// setTicket(data); // setTicket(data);
console.log('SCHEDULE CONTACT: ',data.schedulesContact)
setContact(data.contact.contact); setContact(data.contact.contact);
setTicket(data.contact); setTicket(data.contact);
setSchedule(data.schedules) setSchedule(data.schedules)
setSchedulesContact(data.schedulesContact)
setLoading(false); setLoading(false);
} catch (err) { } catch (err) {
@ -176,7 +172,7 @@ const Ticket = () => {
/> />
</div> </div>
<div className={classes.ticketActionButtons}> <div className={classes.ticketActionButtons}>
<TicketActionButtons ticket={ticket} schedule={schedule} schedulesContact={schedulesContact}/> <TicketActionButtons ticket={ticket} schedule={schedule}/>
</div> </div>
</TicketHeader> </TicketHeader>
<ReplyMessageProvider> <ReplyMessageProvider>

View File

@ -27,7 +27,7 @@ const useStyles = makeStyles(theme => ({
}, },
})); }));
const TicketActionButtons = ({ ticket, schedule, schedulesContact }) => { const TicketActionButtons = ({ ticket, schedule }) => {
const classes = useStyles(); const classes = useStyles();
const history = useHistory(); const history = useHistory();
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
@ -65,7 +65,7 @@ const TicketActionButtons = ({ ticket, schedule, schedulesContact }) => {
modal_header={'Finalização de Atendimento'} modal_header={'Finalização de Atendimento'}
func={chatEndVal} func={chatEndVal}
schedules={schedule} schedules={schedule}
schedulesContact={schedulesContact} ticketId={ticket.id}
/>) />)
}; };