projeto-hit/frontend/src/components/ChatEnd/ModalChatEnd/index.js

550 lines
16 KiB
JavaScript
Raw Normal View History

import React, { useState, useEffect, useRef, useReducer } from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import PropTypes from 'prop-types';
import Box from '@mui/material/Box';
import SelectField from "../../Report/SelectField";
import TextFieldSelectHourBefore from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
import DatePicker from '../../Report/DatePicker'
import TimerPickerSelect from '../TimerPickerSelect'
import TextareaAutosize from '@mui/material/TextareaAutosize';
import { subHours } from "date-fns";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@material-ui/core";
import { DeleteOutline } from "@material-ui/icons";
import { toast } from "react-toastify"; import api from "../../../services/api";
import toastError from "../../../errors/toastError";
import ConfirmationModal from "../../ConfirmationModal";
const reducer = (state, action) => {
if (action.type === "LOAD_SCHEDULES") {
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 { sx, ...other } = props;
return (
<Box
sx={{
bgcolor: (theme) => (theme.palette.mode === 'dark' ? '#101010' : '#fff'),
color: (theme) => (theme.palette.mode === 'dark' ? 'grey.300' : 'grey.800'),
border: '1px solid',
borderColor: (theme) =>
theme.palette.mode === 'dark' ? 'grey.800' : 'grey.300',
p: 1,
m: 1,
borderRadius: 2,
fontSize: '0.875rem',
fontWeight: '700',
...sx,
}}
{...other}
/>
);
}
Item.propTypes = {
sx: PropTypes.oneOfType([
PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool]),
),
PropTypes.func,
PropTypes.object,
]),
};
const Modal = (props) => {
// const [clientSchedules, dispatch] = useReducer(reducer, []);
const [selectedSchedule, setSelectedSchedule] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false);
const [open, setOpen] = useState(true);
const [scroll, /*setScroll*/] = useState('body');
const [scheduleId, setScheduling] = useState(null)
const [startDate, setDatePicker] = useState(new Date())
const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState()
const [data] = useState(props.schedules)
const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(null);
2022-03-14 13:21:50 +00:00
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const handleCancel = (event, reason) => {
if (reason && reason === "backdropClick")
return;
setOpen(false);
};
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){
return `podemos confirmar sua consulta agendada para hoje às ${scheduleDate}?`
}
function formatedTimeHour(timer){
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)
2022-03-14 13:21:50 +00:00
}
// Get from child 3
const timerPickerValue = (data) => {
console.log('timerPickerValue: ',(data));
setTimerPicker(data)
2022-03-14 13:21:50 +00:00
}
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
2022-03-14 13:21:50 +00:00
}
props.func({
2022-03-14 13:21:50 +00:00
'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);
};
2022-03-14 13:21:50 +00:00
2022-03-14 13:21:50 +00:00
useEffect(()=>{
2022-03-14 13:21:50 +00:00
const hoursBeforeAvalible = (timer) =>{
2022-03-14 13:21:50 +00:00
let hours = []
let hour = 1
2022-03-14 13:21:50 +00:00
if(startDate === dateCurrentFormated()){
2022-03-14 13:21:50 +00:00
console.log('HOJE++++')
while(subHours(timer, hour).getHours()>=6 &&
subHours(timer, hour).getHours()>=new Date().getHours() &&
subHours(timer, hour).getHours()<=19){
console.log('******** TIMER: ', formatedTimeHour(subHours(timer,hour)))
2022-03-14 13:21:50 +00:00
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)
}
}
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)
}
}
return {time: hours, hour:hour}
}
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
},[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)))
}
else if(parseInt(auxDate.getHours()) < 12){
setTextArea1('Bom dia, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
}
else if(parseInt(auxDate.getHours()) > 17){
setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(new Date(timerPicker), 1)))
}
2022-03-14 13:21:50 +00:00
},[currencyHourBefore, startDate, timerPicker])
const handleChange = (event) => {
setTextArea1(event.target.value);
};
2022-03-14 13:21:50 +00:00
return (
2022-03-14 13:21:50 +00:00
<Dialog
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>
<Box
sx={{
width: 500,
height: '100%',
// backgroundColor: 'primary.dark',
// '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],},
}}>
<Box sx={{
display: 'grid',
}}>
<Item>
<span>Selecione uma opção para encerrar o Atendimento</span>
<SelectField func={textFieldSelect}
emptyField={false}
header={'Opções de encerramento do atendimento'}
currencies={data.map((obj)=>{
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)' }}>
2022-03-14 13:21:50 +00:00
<Item><DatePicker func={datePickerValue} minDate = {true} title={'Data do agendamento'}/></Item>
2022-03-14 13:21:50 +00:00
<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>
}
2022-03-14 13:21:50 +00:00
<Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem para lembrar cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
2022-03-14 13:21:50 +00:00
</Item>
}
2022-03-14 13:21:50 +00:00
{schedulesContact.length>0 &&
2022-03-14 13:21:50 +00:00
<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>
2022-03-14 13:21:50 +00:00
</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>
</DialogContent>
<DialogActions>
<div style={{marginRight:'50px'}}>
<Button onClick={handleCancel}>Cancelar</Button>
</div>
<Button onClick={handleChatEnd}>Ok</Button>
</DialogActions>
</Dialog>
);
}
export default Modal