Merge branch 'testeA'

pull/1/head
adriano 2022-03-14 10:22:05 -03:00
commit d696b0b261
15 changed files with 472 additions and 129 deletions

View File

@ -37,7 +37,7 @@
"sequelize-cli": "^5.5.1", "sequelize-cli": "^5.5.1",
"sequelize-typescript": "^1.1.0", "sequelize-typescript": "^1.1.0",
"socket.io": "^3.0.5", "socket.io": "^3.0.5",
"whatsapp-web.js": "^1.15.5", "whatsapp-web.js": "^1.15.6",
"yup": "^0.32.8" "yup": "^0.32.8"
}, },
"devDependencies": { "devDependencies": {

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

@ -10,6 +10,7 @@ import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService"; import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
@ -94,9 +95,16 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
const { schedules, count, hasMore } = await ListScheduleService({ searchParam: "", pageNumber: "1" }); const { schedules, count, hasMore } = await ListScheduleService({ searchParam: "", pageNumber: "1" });
//////////////////
const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number);
/////////////////
// console.log('############### schedulesContact: ', schedulesContact)
// console.log('############### contact.contact.number: ',contact.contact.number)
// return res.status(200).json(contact); // return res.status(200).json(contact);
return res.status(200).json({contact, schedules}); return res.status(200).json({contact, schedules, schedulesContact});
}; };
@ -134,12 +142,13 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
// agendamento // agendamento
const scheduleData = JSON.parse(schedulingNotifyData) const scheduleData = JSON.parse(schedulingNotifyData)
if( scheduleData.scheduleId != '1'){ if( scheduleData.scheduleId === '2'){
const schedulingNotifyCreate = await CreateSchedulingNotifyService( const schedulingNotifyCreate = await CreateSchedulingNotifyService(
{ {
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

@ -78,8 +78,8 @@ class Ticket extends Model<Ticket> {
@HasMany(() => Message) @HasMany(() => Message)
messages: Message[]; messages: Message[];
@HasOne(() => SchedulingNotify) @HasMany(() => SchedulingNotify)
schedulingNotify: SchedulingNotify schedulingNotify: SchedulingNotify[];
} }
export default Ticket; export default Ticket;

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

@ -0,0 +1,44 @@
import Ticket from "../../models/Ticket";
import Contact from "../../models/Contact";
import SchedulingNotify from "../../models/SchedulingNotify";
import { Op, where, Sequelize } from "sequelize";
import AppError from "../../errors/AppError";
const ListSchedulingNotifyContactService = async (contactNumber: string): Promise<SchedulingNotify[]> => {
const ticket = await SchedulingNotify.findAll({
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: [
{
model: Ticket,
required:true,
attributes: [],
include: [
{
model: Contact,
where:{
number: contactNumber,
},
attributes: ['name', 'number']
},
]
},
],
});
if (!ticket) {
throw new AppError("ERR_NO_TICKET_FOUND", 404);
}
return ticket;
};
export default ListSchedulingNotifyContactService;

View File

@ -1,27 +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 MenuItem from '@mui/material/MenuItem';
import DatePicker from '../../Report/DatePicker' import DatePicker from '../../Report/DatePicker'
import TimerPickerSelect from '../TimerPickerSelect' import TimerPickerSelect from '../TimerPickerSelect'
import TextareaAutosize from '@mui/material/TextareaAutosize'; 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 [];
}
};
import { addHours } from "date-fns";
const Item = (props) => { const Item = (props) => {
@ -57,8 +103,12 @@ Item.propTypes = {
}; };
const Modal = (props) => { const Modal = (props) => {
// 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');
@ -70,6 +120,11 @@ const Modal = (props) => {
const [data] = useState(props.schedules) const [data] = useState(props.schedules)
const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
@ -80,6 +135,23 @@ 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}?`
} }
@ -89,16 +161,38 @@ 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 // Get from child 2
const datePickerValue = (data) => { const datePickerValue = (data) => {
console.log('datePickerValue: ',(data)); console.log('datePickerValue: ',(data));
setDatePicker(data) setDatePicker(data)
} }
// Get from child 3 // Get from child 3
const timerPickerValue = (data) => { const timerPickerValue = (data) => {
console.log('timerPickerValue: ',(data)); console.log('timerPickerValue: ',(data));
setTimerPicker(data) setTimerPicker(data)
} }
const dateCurrentFormated = () => { const dateCurrentFormated = () => {
@ -114,38 +208,38 @@ const dateCurrentFormated = () => {
const handleChatEnd = (event, reason) => { const handleChatEnd = (event, reason) => {
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
return; return;
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
} }
else if((new Date(timerPicker).getHours() > 16 && new Date(timerPicker).getMinutes() > 0) || else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 7)){ (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 17: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(startDate === dateCurrentFormated()){ 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!')
if(((new Date(timerPicker).getHours() === new Date().getHours()) &&
(new Date(timerPicker).getMinutes() <= new Date().getMinutes())) ||
(new Date(timerPicker).getHours() < new Date().getHours())
){
alert('Para agendamentos do dia, é necessário que o horário do lembrete seja maior que o horário atual!')
return return
}
} }
props.func({ props.func({
'scheduleId': scheduleId, 'scheduleId': scheduleId,
'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 'message': textArea1
}); });
setOpen(false); setOpen(false);
}; };
@ -168,28 +262,101 @@ const textFieldSelect = (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(()=>{ useEffect(()=>{
if (parseInt(timerPicker.getHours()) > 12 && parseInt(timerPicker.getHours()) < 18){ const hoursBeforeAvalible = (timer) =>{
setTextArea1('Boa tarde, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
} let hours = []
else if(parseInt(timerPicker.getHours()) < 12){ let hour = 1
setTextArea1('Bom dia, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
} if(startDate === dateCurrentFormated()){
else if(parseInt(timerPicker.getHours()) > 18){
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)))
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)
}
setTextArea1('Boa noite, '+greetMessageSchedule( formatedTimeHour(addHours(new Date(timerPicker), 1))))
} }
},[timerPicker]) 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)))
}
},[currencyHourBefore, startDate, timerPicker])
const handleChange = (event) => { const handleChange = (event) => {
@ -198,9 +365,10 @@ const handleChange = (event) => {
}; };
return (
return (
<Dialog <Dialog
open={open} open={open}
onClose={handleCancel} onClose={handleCancel}
@ -239,11 +407,13 @@ const handleChange = (event) => {
<Item> <Item>
<span>Selecione uma opção para encerrar o Atendimento</span> <span>Selecione uma opção para encerrar o Atendimento</span>
<Item> <SelectField func={textFieldSelect}
<SelectField func={textFieldSelect} emptyField={false} header={'Opções de encerramento do atendimento'} currencies={data.map((obj)=>{ emptyField={false}
header={'Opções de encerramento do atendimento'}
currencies={data.map((obj)=>{
return {'value': obj.id, 'label': obj.name} return {'value': obj.id, 'label': obj.name}
})}/> })}/>
</Item>
</Item> </Item>
@ -257,16 +427,35 @@ const handleChange = (event) => {
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate = {true} title={'Data do retorno'}/></Item> <Item><DatePicker func={datePickerValue} minDate = {true} title={'Data do agendamento'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora do lembrete'}/></Item> <Item><TimerPickerSelect func={timerPickerValue} title={'Hora do agendamento'}/></Item>
</Box> </Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}> <Box sx={{display: 'flex', flexDirection: 'column' }}>
{/* <Item><TextArea1 func={textArea1Value} greetRemember={greetRemember} hint={'Mensagem para cliente'}/></Item> */} {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 <TextareaAutosize
aria-label="minimum height" aria-label="minimum height"
@ -282,6 +471,67 @@ const handleChange = (event) => {
</Item> </Item>
} }
{schedulesContact.length>0 &&
<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>
@ -294,7 +544,6 @@ const handleChange = (event) => {
</DialogActions> </DialogActions>
</Dialog> </Dialog>
); );
} }

View File

@ -9,6 +9,9 @@ import {
MuiPickersUtilsProvider, MuiPickersUtilsProvider,
} from '@material-ui/pickers'; } from '@material-ui/pickers';
import ptBrLocale from "date-fns/locale/pt-BR"; import ptBrLocale from "date-fns/locale/pt-BR";

View File

@ -66,6 +66,7 @@ const TicketActionButtons = ({ ticket, schedule }) => {
modal_header={'Finalização de Atendimento'} modal_header={'Finalização de Atendimento'}
func={chatEndVal} func={chatEndVal}
schedules={schedule} schedules={schedule}
ticketId={ticket.id}
/>) />)
}; };