Correção do useEffect

pull/1/head
adriano 2022-03-14 10:21:50 -03:00
parent e8eb00e96c
commit 0f3a0cdc0e
1 changed files with 229 additions and 259 deletions

View File

@ -123,7 +123,7 @@ const Modal = (props) => {
const [schedulesContact, dispatch] = useReducer(reducer, []); const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(null); const [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState( ); const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
@ -160,10 +160,124 @@ 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')}`
} }
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
const datePickerValue = (data) => {
console.log('datePickerValue: ',(data));
setDatePicker(data)
}
// Get from child 3
const timerPickerValue = (data) => {
console.log('timerPickerValue: ',(data));
setTimerPicker(data)
}
const dateCurrentFormated = () => {
let date = new Date()
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth()+1).toString().padStart(2, '0');
let year = date.getFullYear();
return `${year}-${month}-${day}`
}
const handleChatEnd = (event, reason) => {
if (reason && reason === "backdropClick")
return;
if (scheduleId === '1'){
}
else if(textArea1 && textArea1.trim().length<10){
alert('Mensagem muito curta!\nMínimo 10 caracteres.')
return
}
else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 7)){
alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 07:00 e 20:00')
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
}
props.func({
'scheduleId': scheduleId,
'schedulingDate': `${startDate} ${currencyHourBefore}:00`,
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)),
'message': textArea1
});
setOpen(false);
};
const descriptionElementRef = useRef(null);
useEffect(() => {
if (open) {
const { current: descriptionElement } = descriptionElementRef;
if (descriptionElement !== null) {
descriptionElement.focus();
}
}
}, [open]);
// Get from child 1
const textFieldSelect = (data) => {
console.log('textFieldSelect: ',data);
setScheduling(data)
}
const handleChangeHourBefore = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value);
setCurrency(event.target.value);
};
useEffect(()=>{
const hoursBeforeAvalible = (timer) =>{ const hoursBeforeAvalible = (timer) =>{
let hours = [] let hours = []
let hour = 1 let hour = 1
if(startDate === dateCurrentFormated()){ if(startDate === dateCurrentFormated()){
@ -220,146 +334,6 @@ const Modal = (props) => {
} }
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
const datePickerValue = (data) => {
console.log('datePickerValue: ',(data));
setDatePicker(data)
}
// Get from child 3
const timerPickerValue = (data) => {
console.log('timerPickerValue: ',(data));
setTimerPicker(data)
}
const dateCurrentFormated = () => {
let date = new Date()
let day = date.getDate().toString().padStart(2, '0');
let month = (date.getMonth()+1).toString().padStart(2, '0');
let year = date.getFullYear();
return `${year}-${month}-${day}`
}
const handleChatEnd = (event, reason) => {
if (reason && reason === "backdropClick")
return;
if (scheduleId === '1'){
}
else if(textArea1 && textArea1.trim().length<10){
alert('Mensagem muito curta!\nMínimo 10 caracteres.')
return
}
else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 7)){
alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 07:00 e 20:00')
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()){
// if(
// (new Date(subHours(timerPicker, 1)).getHours() <= new Date().getHours() &&
// new Date(subHours(timerPicker, 1)).getMinutes() <= new Date().getMinutes()) ||
// (new Date(subHours(timerPicker, 1)).getHours() == new Date().getHours() &&
// new Date(subHours(timerPicker, 1)).getMinutes() <= new Date().getMinutes())
// )
// {
// alert('Para agendamentos do dia, é necessário que o horário do lembrete seja no mínimo uma hora adiantado!')
// return
// }
// }
props.func({
'scheduleId': scheduleId,
// '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} ${currencyHourBefore}:00`,
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)),
'message': textArea1
});
setOpen(false);
};
const descriptionElementRef = useRef(null);
useEffect(() => {
if (open) {
const { current: descriptionElement } = descriptionElementRef;
if (descriptionElement !== null) {
descriptionElement.focus();
}
}
}, [open]);
// Get from child 1
const textFieldSelect = (data) => {
console.log('textFieldSelect: ',data);
setScheduling(data)
}
const handleChangeHourBefore = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value);
setCurrency(event.target.value);
};
// Get from child 4
// const textArea1Value = (data) => {
// console.log('textArea1Value: ',(data));
// setTextArea1(data)
// }
useEffect(()=>{
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time) setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
},[timerPicker, startDate]) },[timerPicker, startDate])
@ -382,7 +356,7 @@ useEffect(()=>{
setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1))) setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
} }
},[currencyHourBefore, startDate]) },[currencyHourBefore, startDate, timerPicker])
const handleChange = (event) => { const handleChange = (event) => {
@ -395,184 +369,180 @@ const handleChange = (event) => {
return ( return (
<Dialog
open={open}
onClose={handleCancel}
// fullWidth={true}
// maxWidth={true}
disableEscapeKeyDown
scroll={scroll}
aria-labelledby="scroll-dialog-title"
<Dialog aria-describedby="scroll-dialog-description"
open={open}
onClose={handleCancel}
// fullWidth={true}
// maxWidth={true}
disableEscapeKeyDown
scroll={scroll}
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
<DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'body'}>
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
> >
</DialogContentText> <DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'body'}>
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
</DialogContentText>
<Box <Box
sx={{ sx={{
width: 500, width: 500,
height: '100%', height: '100%',
// backgroundColor: 'primary.dark', // backgroundColor: 'primary.dark',
// '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],}, // '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],},
}}> }}>
<Box sx={{ <Box sx={{
display: 'grid', display: 'grid',
}}> }}>
<Item> <Item>
<span>Selecione uma opção para encerrar o Atendimento</span> <span>Selecione uma opção para encerrar o Atendimento</span>
<SelectField func={textFieldSelect} <SelectField func={textFieldSelect}
emptyField={false} emptyField={false}
header={'Opções de encerramento do atendimento'} header={'Opções de encerramento do atendimento'}
currencies={data.map((obj)=>{ currencies={data.map((obj)=>{
return {'value': obj.id, 'label': obj.name} return {'value': obj.id, 'label': obj.name}
})}/> })}/>
</Item>
</Box>
{scheduleId==='2' &&
<Item>
<span>Lembrete de retorno</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate = {true} title={'Data do agendamento'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora do agendamento'}/></Item>
</Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}>
{currencyHourBefore &&
<Item>
<TextFieldSelectHourBefore
id="outlined-select-currency"
select
label="Enviar mensagem para cliente"
value={currencyHourBefore}
size="small"
onChange={handleChangeHourBefore}
>
{currenciesTimeBefore.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextFieldSelectHourBefore>
</Item>
}
<Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem para lembrar cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</Item> </Item>
}
</Box> {schedulesContact.length>0 &&
{scheduleId==='2' &&
<Item>
<span>Lembrete de retorno</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate = {true} title={'Data do agendamento'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora do agendamento'}/></Item>
</Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}>
{currencyHourBefore &&
<Item>
<TextFieldSelectHourBefore
id="outlined-select-currency"
select
label="Enviar mensagem para cliente"
value={currencyHourBefore}
size="small"
onChange={handleChangeHourBefore}
>
{currenciesTimeBefore.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextFieldSelectHourBefore>
</Item>
}
<Item> <Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem para lembrar cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</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">
{schedulesContact.length>0 && <TableHead>
<TableRow>
<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"> <TableCell align="center">
Data
<IconButton </TableCell>
size="small" <TableCell align="center">
onClick={() => { Hora
setSelectedSchedule(scheduleData); </TableCell>
setConfirmModalOpen(true); <TableCell align="center">
Deletar
}}
>
<DeleteOutline />
</IconButton>
</TableCell> </TableCell>
</TableRow> </TableRow>
))} </TableHead>
</>
</TableBody> <TableBody>
</Table> <>
</Paper> {schedulesContact.map((scheduleData, index) => (
</Item>} <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>
<DialogActions> <DialogActions>
<div style={{marginRight:'50px'}}> <div style={{marginRight:'50px'}}>
<Button onClick={handleCancel}>Cancelar</Button> <Button onClick={handleCancel}>Cancelar</Button>
</div> </div>
<Button onClick={handleChatEnd}>Ok</Button> <Button onClick={handleChatEnd}>Ok</Button>
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} }