Criação do lembrete e agendamento completo

pull/1/head
adriano 2022-03-28 16:28:35 -03:00
parent 74c3be6690
commit 682bfc1116
9 changed files with 580 additions and 83 deletions

View File

@ -12,6 +12,7 @@ import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService"; import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService"; import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import {isScheduling} from "../helpers/CheckSchedulingReminderNotify"
@ -135,10 +136,23 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
} }
/////////////////////////////// ///////////////////////////////
// lembrete // lembrete
const scheduleData = JSON.parse(schedulingNotifyData) const scheduleData = JSON.parse(schedulingNotifyData)
// lembrete // agendamento
if( scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3'){
console.log('*** schedulingDate: ', scheduleData.schedulingDate)
console.log('*** schedulingTime: ', scheduleData.schedulingTime)
if(isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)){
console.log('*** É AGENDAMENTO!')
}
else{
console.log('*** É LEMBRETE!')
}
if( scheduleData.statusChatEndId === '2'){
const schedulingNotifyCreate = await CreateSchedulingNotifyService( const schedulingNotifyCreate = await CreateSchedulingNotifyService(
{ {
ticketId: scheduleData.ticketId, ticketId: scheduleData.ticketId,

View File

@ -0,0 +1,11 @@
export const isScheduling = (schedulingDate:string, schedulingTime:string) => {
if (schedulingDate === schedulingTime){
return false
}
return true
}

View File

@ -45,7 +45,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
where_clause = {} where_clause = {}
where_clause_notify = { where_clause_notify = {
schedulingTime: { schedulingDate: {
[Op.gte]: startDate+' 00:00:00.000000', [Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999' [Op.lte]: endDate +' 23:59:59.999999'
}, },
@ -57,7 +57,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
where_clause = {} where_clause = {}
where_clause_notify = { where_clause_notify = {
schedulingTime: { schedulingDate: {
[Op.gte]: startDate+' 00:00:00.000000', [Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: startDate +' 23:59:59.999999' [Op.lte]: startDate +' 23:59:59.999999'
}, },
@ -69,7 +69,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
where_clause = {} where_clause = {}
where_clause_notify = { where_clause_notify = {
schedulingTime: { schedulingDate: {
[Op.gte]: endDate+' 00:00:00.000000', [Op.gte]: endDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999' [Op.lte]: endDate +' 23:59:59.999999'
}, },
@ -81,7 +81,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
where_clause = nameNumber where_clause = nameNumber
where_clause_notify = { where_clause_notify = {
schedulingTime: { schedulingDate: {
[Op.gte]: startDate+' 00:00:00.000000', [Op.gte]: startDate+' 00:00:00.000000',
[Op.lte]: startDate +' 23:59:59.999999' [Op.lte]: startDate +' 23:59:59.999999'
}, },
@ -93,7 +93,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
where_clause = nameNumber where_clause = nameNumber
where_clause_notify = { where_clause_notify = {
schedulingTime: { schedulingDate: {
[Op.gte]: endDate+' 00:00:00.000000', [Op.gte]: endDate+' 00:00:00.000000',
[Op.lte]: endDate +' 23:59:59.999999' [Op.lte]: endDate +' 23:59:59.999999'
}, },
@ -112,7 +112,7 @@ const ListSchedulingNotifyContactService = async (contactNumber: string = '', st
raw: true, raw: true,
where: where_clause_notify, where: where_clause_notify,
attributes:['id', 'ticketId', [Sequelize.fn("DATE_FORMAT",Sequelize.col("schedulingDate"),"%d/%m/%Y %H:%i:%s"),"schedulingDate"], attributes:['id', 'ticketId','statusChatEndId', [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'], [Sequelize.fn("DATE_FORMAT",Sequelize.col("schedulingTime"),"%d/%m/%Y %H:%i:%s"),"schedulingTime"], 'message'],
include: [ include: [

View File

@ -32,13 +32,13 @@ interface Request {
const whereCondition = { const whereCondition = {
[Op.and]: [ [Op.and]: [
{ {
"$schedulingDate$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingDate")), `${date.trim()}`) "$schedulingTime$": Sequelize.where(Sequelize.fn("date", Sequelize.col("schedulingTime")), `${date.trim()}`)
}, },
{ {
"$schedulingDate$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingDate")), `${hour.trim()}`) "$schedulingTime$": Sequelize.where(Sequelize.fn("hour", Sequelize.col("schedulingTime")), `${hour.trim()}`)
}, },
{ {
"$schedulingDate$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingDate")), `${minute.trim()}`) "$schedulingTime$": Sequelize.where(Sequelize.fn("minute", Sequelize.col("schedulingTime")), `${minute.trim()}`)
} }
] ]
}; };

View File

@ -9,11 +9,13 @@ 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 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 { subHours, addDays, isEqual, subDays} from "date-fns";
import TextFieldSelectHourBefore from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
@ -109,17 +111,17 @@ const Modal = (props) => {
// const [clientSchedules, dispatch] = useReducer(reducer, []); // const [clientSchedules, dispatch] = useReducer(reducer, []);
const [selectedSchedule, setSelectedSchedule] = useState(null); const [selectedSchedule, setSelectedSchedule] = useState(null);
const [confirmModalOpen, setConfirmModalOpen] = useState(false); 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');
const [statusChatEndId, setStatusChatEnd] = useState(null) const [statusChatEndId, setStatusChatEnd] = useState(null)
const [startDate, setDatePicker] = useState(new Date()) const [startDate, setDatePicker] = useState(new Date())
const [timerPicker, setTimerPicker] = useState(new Date()) const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState() const [textArea1, setTextArea1] = useState()
const [schedulesContact, dispatch] = useReducer(reducer, []); const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
@ -130,7 +132,6 @@ const Modal = (props) => {
}; };
useEffect(() => { useEffect(() => {
(async () => { (async () => {
@ -170,7 +171,7 @@ const Modal = (props) => {
const handleDeleteSchedule = async (scheduleId) => { const handleDeleteSchedule = async (scheduleId) => {
try { try {
await api.delete(`/schedule/${scheduleId}`); await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete deletado com sucesso!")); toast.success(("Lembrete/Agendamento deletado com sucesso!"));
dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId }); dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId });
} catch (err) { } catch (err) {
toastError(err); toastError(err);
@ -194,7 +195,24 @@ const timerPickerValue = (data) => {
} }
const dateCurrentFormated = (dateF=null) => {
let date =null
if(dateF){
date = new Date(dateF)
}
else{
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) => { const handleChatEnd = (event, reason) => {
@ -203,12 +221,18 @@ const timerPickerValue = (data) => {
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
return; return;
if (statusChatEndId === '2'){ if (statusChatEndId === '2' || statusChatEndId === '3'){
console.log('Entrou! textArea1: ', textArea1) console.log('Entrou! textArea1: ', textArea1)
if( startDate.trim().length==0){
if(textArea1 && textArea1.trim().length<5){ alert('Selecione uma data atual ou futura!')
return
}
else if(textArea1 && textArea1.trim().length<5){
alert('Mensagem muito curta!') alert('Mensagem muito curta!')
return return
} }
@ -216,38 +240,162 @@ const timerPickerValue = (data) => {
alert('Defina uma mensagem para enviar para o cliente!') alert('Defina uma mensagem para enviar para o cliente!')
return return
} }
else if(formatedFullCurrentDate()===startDate){ else if(formatedFullCurrentDate()===startDate &&
((new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
if((new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() === new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) || (new Date(timerPicker).getHours() === new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() >= new Date().getMinutes()) || (new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() >= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() < new Date().getHours)){ (new Date(timerPicker).getHours() < new Date().getHours))){
alert('Horário menor ou igual horário atual!') alert('Horário menor ou igual horário atual!')
return return
} }
}
else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) || else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 6)){ (new Date(timerPicker).getHours() < 6)){
alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 06:00 e 20:00') alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 06:00 e 20:00')
return return
} }
let dateSendMessage = startDate
let timeBefore = formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))
if(statusChatEndId === '3'){
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
}
timeBefore = currencyHourBefore
let sendMessageDayBefore = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
if(sendMessageDayBefore.length > 0 && timeBefore === formatedTimeHour(timerPicker))
{
console.log('ENVIAR MENSAGEM UM DIA ANTES!')
console.log('MENSAGEM SERÁ ENVIA NO DIA: ', dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1))))
dateSendMessage = dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1)))
}
console.log('AGENDAMENTO ENVIO MENSAGEM1: ', `${dateSendMessage} ${timeBefore}:00` )
} else if (statusChatEndId === '2'){
console.log('AGENDAMENTO ENVIO MENSAGEM2: ', startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)) )
}
dataSendServer = { dataSendServer = {
'statusChatEndId': statusChatEndId, 'statusChatEndId': statusChatEndId,
'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}`))+':00',
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1 'message': textArea1
} }
} }
props.func(dataSendServer) props.func(dataSendServer)
setOpen(false); setOpen(false);
}; };
useEffect(()=>{
const hoursBeforeAvalible = (timer) =>{
let hours = []
let hour = 1
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', startDate )
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> dateCurrentFormated: ', dateCurrentFormated() )
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ',typeof(startDate) )
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ',(startDate) )
if(typeof(startDate)==='string' && startDate.trim().length>0 && startDate === dateCurrentFormated()){
console.log('HOJE++++')
while(subHours(timer, hour).getHours()>=6 &&
subHours(timer, hour).getHours()>=new Date().getHours() &&
subHours(timer, hour).getHours()<=20){
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()<=20){
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(new Date(startDate) > addDays(new Date(), 1) ){
hours.push({value: formatedTimeHour(timerPicker) , label: `24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO`})
console.log('#subDays: ', dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1))))
}
console.log('hourshourshourshourshourshourshourshourshourshourshourshours ', hours)
return {time: hours, hour:hour}
}
console.log('===================================== addDays: ', addDays(new Date(), 1))
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
},[timerPicker, startDate])
const descriptionElementRef = useRef(null); const descriptionElementRef = useRef(null);
useEffect(() => { useEffect(() => {
if (open) { if (open) {
@ -263,11 +411,10 @@ const timerPickerValue = (data) => {
const textFieldSelect = (data) => { const textFieldSelect = (data) => {
console.log('textFieldSelect: ',data); console.log('textFieldSelect: ',data);
setStatusChatEnd(data) setStatusChatEnd(data)
} }
const handleChange = (event) => { const handleChange = (event) => {
setTextArea1(event.target.value); setTextArea1(event.target.value);
@ -275,6 +422,19 @@ const handleChange = (event) => {
}; };
const handleChangeHourBefore = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value);
// var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
// console.log('textFihandleChangeHourBefore matchedTime: ',matchedTime);
setCurrency(event.target.value);
};
return ( return (
@ -361,6 +521,64 @@ const handleChange = (event) => {
</Item> </Item>
} }
{statusChatEndId==='3' &&
<Item>
<span>Agendamento</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data do lembrete'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora do lembrete'}/></Item>
</Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}>
<Item>
{currencyHourBefore && startDate && typeof(startDate)==='string' && startDate.trim().length > 0 && currenciesTimeBefore.length > 0 &&
<TextFieldSelectHourBefore
id="outlined-select-currency"
disabled={startDate.length>0 ? false : true}
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 de envio para cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</Item>
}
{/* {schedulesContact.length>0 && {/* {schedulesContact.length>0 &&

View File

@ -31,6 +31,7 @@ function formatDate(strDate){
function ResponsiveDatePickers(props) { function ResponsiveDatePickers(props) {
console.log('schedulingDate schedulingDate schedulingDate2: ', (props.schedulingDate))
console.log('schedulingDate schedulingDate schedulingDate: ', formatDate(props.schedulingDate)) console.log('schedulingDate schedulingDate schedulingDate: ', formatDate(props.schedulingDate))
const [selectedDate, handleDateChange] = useState(new Date(formatDate(props.schedulingDate))); const [selectedDate, handleDateChange] = useState(new Date(formatDate(props.schedulingDate)));

View File

@ -13,7 +13,12 @@ import SelectField from "../Report/SelectField";
import DatePicker from './DatePicker2' import DatePicker from './DatePicker2'
import TimerPickerSelect from './TimerPickerSelect2' import TimerPickerSelect from './TimerPickerSelect2'
import TextareaAutosize from '@mui/material/TextareaAutosize'; import TextareaAutosize from '@mui/material/TextareaAutosize';
// import { subHours } from "date-fns";
import { subHours, addDays, isEqual, subDays} from "date-fns";
import TextFieldSelectHourBefore from '@mui/material/TextField';
import MenuItem from '@mui/material/MenuItem';
@ -111,14 +116,19 @@ const Modal = (props) => {
const [open, setOpen] = useState(true); const [open, setOpen] = useState(true);
const [scroll, /*setScroll*/] = useState('body'); const [scroll, /*setScroll*/] = useState('body');
const [statusChatEndId, setStatusChatEnd] = useState(null) const [statusChatEndId, setStatusChatEnd] = useState(props.rowData.statusChatEndId)
const [startDate, setDatePicker] = useState(props.rowData.schedulingTime ? new Date(props.rowData.schedulingTime) : new Date()) const [startDate, setDatePicker] = useState(props.rowData.schedulingTime ? new Date(props.rowData.schedulingTime) : new Date())
const [timerPicker, setTimerPicker] = useState(new Date()) const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState(props.rowData.message) const [textArea1, setTextArea1] = useState(props.rowData.message)
const [schedulesContact, dispatch] = useReducer(reducer, []); const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(props.rowData.schedulingTime.split(' ')[1].slice(0,5));
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const [contador, setCount] = useState(0)
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
@ -169,7 +179,7 @@ const Modal = (props) => {
const handleDeleteSchedule = async (scheduleId) => { const handleDeleteSchedule = async (scheduleId) => {
try { try {
await api.delete(`/schedule/${scheduleId}`); await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete deletado com sucesso!")); toast.success(("Lembrete/Agendamento deletado com sucesso!"));
dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId }); dispatch({ type: "DELETE_SCHEDULE", payload: scheduleId });
} catch (err) { } catch (err) {
toastError(err); toastError(err);
@ -195,6 +205,27 @@ const timerPickerValue = (data) => {
const dateCurrentFormated = (dateF=null) => {
let date =null
if(dateF){
date = new Date(dateF)
}
else{
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) => { const handleChatEnd = (event, reason) => {
let dataSendServer = {'statusChatEndId': statusChatEndId} let dataSendServer = {'statusChatEndId': statusChatEndId}
@ -202,7 +233,7 @@ const timerPickerValue = (data) => {
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
return; return;
if (statusChatEndId === '2'){ if (statusChatEndId === '2'|| statusChatEndId === '3'){
console.log('Entrou! textArea1: ', textArea1) console.log('Entrou! textArea1: ', textArea1)
@ -215,32 +246,63 @@ const timerPickerValue = (data) => {
alert('Defina uma mensagem para enviar para o cliente!') alert('Defina uma mensagem para enviar para o cliente!')
return return
} }
else if(formatedFullCurrentDate()===startDate){ else if(formatedFullCurrentDate()===startDate &&
((new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
if((new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() === new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) || (new Date(timerPicker).getHours() === new Date().getHours() && new Date(timerPicker).getMinutes() <= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() >= new Date().getMinutes()) || (new Date(timerPicker).getHours() < new Date().getHours() && new Date(timerPicker).getMinutes() >= new Date().getMinutes()) ||
(new Date(timerPicker).getHours() < new Date().getHours)){ (new Date(timerPicker).getHours() < new Date().getHours))){
alert('Horário menor ou igual horário atual!') alert('Horário menor ou igual horário atual!')
return return
} }
}
else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) || else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 6)){ (new Date(timerPicker).getHours() < 6)){
alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 06:00 e 20:00') alert('Horário comercial inválido!\n Selecione um horário de lembrete válido entre às 06:00 e 20:00')
return return
} }
let dateSendMessage = startDate
let timeBefore = formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))
if(statusChatEndId === '3'){
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
}
timeBefore = currencyHourBefore
let sendMessageDayBefore = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
if(sendMessageDayBefore.length > 0 && timeBefore === formatedTimeHour(timerPicker))
{
console.log('ENVIAR MENSAGEM UM DIA ANTES!')
console.log('MENSAGEM SERÁ ENVIA NO DIA: ', dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1))))
dateSendMessage = dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1)))
}
console.log('AGENDAMENTO ENVIO MENSAGEM1: ', `${dateSendMessage} ${timeBefore}:00` )
} else if (statusChatEndId === '2'){
console.log('AGENDAMENTO ENVIO MENSAGEM2: ', startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}`)) )
}
dataSendServer = { dataSendServer = {
'schedulingNotifyId': props.rowData.id, 'schedulingNotifyId': props.rowData.id,
'statusChatEndId': statusChatEndId, 'statusChatEndId': statusChatEndId,
'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}`))+':00',
'schedulingTime': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)), 'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1 'message': textArea1
} }
const formatDateTimeBrazil = (dateTime) => { const formatDateTimeBrazil = (dateTime) => {
let date = dateTime.split(' ')[0] let date = dateTime.split(' ')[0]
let time = dateTime.split(' ')[1] let time = dateTime.split(' ')[1]
@ -249,11 +311,11 @@ const timerPickerValue = (data) => {
} }
props.rowData['schedulingDate'] = formatDateTimeBrazil(`${dataSendServer['schedulingDate']}:00`) props.rowData['statusChatEndId'] = statusChatEndId
props.rowData['schedulingTime'] = formatDateTimeBrazil(`${dataSendServer['schedulingTime']}:00`) props.rowData['schedulingDate'] = formatDateTimeBrazil(`${dataSendServer['schedulingDate']}`)
props.rowData['schedulingTime'] = formatDateTimeBrazil(`${dataSendServer['schedulingTime']}`)
props.rowData['message'] = textArea1 props.rowData['message'] = textArea1
} }
props.func(dataSendServer, props.rowData) props.func(dataSendServer, props.rowData)
@ -262,6 +324,92 @@ const timerPickerValue = (data) => {
}; };
useEffect(()=>{
setCount(contador+1)
const hoursBeforeAvalible = (timer) =>{
let hours = []
let hour = 1
if(typeof(startDate)==='string' && startDate.trim().length>0 && startDate === dateCurrentFormated()){
console.log('HOJE++++')
while(subHours(timer, hour).getHours()>=6 &&
subHours(timer, hour).getHours()>=new Date().getHours() &&
subHours(timer, hour).getHours()<=20){
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){
hours.pop()
if(contador>1)
setCurrency( hours[0].value)
}
else{
setCurrency(null)
}
}
else{
while(subHours(timer, hour).getHours()>=6 && subHours(timer, hour).getHours()<=20){
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){
if(contador>1)
setCurrency( hours[0].value)
}
else{
setCurrency(null)
}
}
if(new Date(startDate) > addDays(new Date(), 1) ){
hours.push({value: formatedTimeHour(timerPicker) , label: `24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO`})
console.log('#subDays: ', dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1))))
}
return {time: hours, hour:hour}
}
console.log('CONTADOR 1: ', contador)
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
},[timerPicker, startDate])
const descriptionElementRef = useRef(null); const descriptionElementRef = useRef(null);
useEffect(() => { useEffect(() => {
if (open) { if (open) {
@ -289,6 +437,15 @@ const handleChange = (event) => {
}; };
const handleChangeHourBefore = (event) => {
setCurrency(event.target.value);
console.log('CONTADOR 2: ', contador)
};
return ( return (
@ -332,7 +489,7 @@ const handleChange = (event) => {
<SelectField func={textFieldSelect} <SelectField func={textFieldSelect}
emptyField={false} emptyField={false}
textBoxFieldSelected={props.textBoxFieldSelected} textBoxFieldSelected={`${props.rowData.statusChatEndId}`}
header={'Opções de encerramento do atendimento'} header={'Opções de encerramento do atendimento'}
currencies={props.statusChatEnd.map((obj)=>{ currencies={props.statusChatEnd.map((obj)=>{
return {'value': obj.id, 'label': obj.name} return {'value': obj.id, 'label': obj.name}
@ -351,7 +508,8 @@ const handleChange = (event) => {
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker <Item>
<DatePicker
func={datePickerValue} func={datePickerValue}
minDate={false} minDate={false}
schedulingDate={props.rowData.schedulingDate} schedulingDate={props.rowData.schedulingDate}
@ -386,6 +544,76 @@ const handleChange = (event) => {
} }
{statusChatEndId==='3' &&
<Item>
<span>Agendamento</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item>
<DatePicker
func={datePickerValue}
minDate={false}
schedulingDate={props.rowData.schedulingDate}
title={'Data do lembrete'}/>
</Item>
<Item>
<TimerPickerSelect
func={timerPickerValue}
schedulingDate={props.rowData.schedulingDate}
title={'Hora do lembrete'}/>
</Item>
</Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}>
<Item>
{currencyHourBefore && startDate && typeof(startDate)==='string' && startDate.trim().length > 0 && currenciesTimeBefore.length > 0 &&
<TextFieldSelectHourBefore
id="outlined-select-currency"
disabled={startDate.length>0 ? false : true}
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 de envio para cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</Item>
}
</Box> </Box>

View File

@ -263,7 +263,18 @@ const SchedulesReminder = () => {
if(!loading){ if(!loading){
console.log('carregando table...') console.log('carregando table...')
setData(query)
const dataLoad = query.map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': others.statusChatEndId == '3' ? 'Agendamento' : 'Lembrete' }
));
console.log('NEW DATA: ', dataLoad)
setData(query.map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': others.statusChatEndId == '3' ? 'Agendamento' : 'Lembrete' }
)))
} }
}, [loading]) }, [loading])
@ -321,7 +332,7 @@ const handleDeleteRows = (id) => {
const handleDeleteSchedule = async (scheduleId) => { const handleDeleteSchedule = async (scheduleId) => {
try { try {
await api.delete(`/schedule/${scheduleId}`); await api.delete(`/schedule/${scheduleId}`);
toast.success(("Lembrete deletado com sucesso!")); toast.success(("Lembrete/Agendamento deletado com sucesso!"));
handleDeleteRows(scheduleId) handleDeleteRows(scheduleId)
} catch (err) { } catch (err) {
toastError(err); toastError(err);
@ -334,14 +345,21 @@ const handleDeleteSchedule = async (scheduleId) => {
const handleUpdateSchedule = async (scheduleData, rowsDataNew) => { const handleUpdateSchedule = async (scheduleData, rowsDataNew) => {
try { try {
await api.post("/schedule", scheduleData); await api.post("/schedule", scheduleData);
toast.success(("Lembrete atualizado com sucesso!")); toast.success(("Lembrete/Agendamento atualizado com sucesso!"));
////////////////// //////////////////
const dataUpdate = [...dataRows]; const dataUpdate = [...dataRows];
const index = rowsDataNew.tableData['id']; const index = rowsDataNew.tableData['id'];
dataUpdate[index] = rowsDataNew; dataUpdate[index] = rowsDataNew;
setData([...dataUpdate]);
setData([...dataUpdate].map(({ scheduleReminder, ...others }) => (
{ ...others, 'scheduleReminder': others.statusChatEndId == '3' ? 'Agendamento' : 'Lembrete' }
)));
///////////////// /////////////////
@ -372,11 +390,13 @@ const chatEndVal = (data, rowsDataNew) => {
const handleModal = (rowData) => { const handleModal = (rowData) => {
// NATY
render(<Modal render(<Modal
modal_header={'Editar Lembrete/Agendamentos'} modal_header={'Editar Lembrete/Agendamentos'}
func={chatEndVal} func={chatEndVal}
statusChatEnd={statusEndChat} statusChatEnd={statusEndChat}
textBoxFieldSelected={'2'} // textBoxFieldSelected={'2'}
rowData={rowData} rowData={rowData}
/>) />)
@ -438,12 +458,12 @@ const handleModal = (rowData) => {
<ConfirmationModal <ConfirmationModal
title={selectedSchedule && `Deletar lembrete do dia ${selectedSchedule.schedulingTime.split(' ')[0]} ${selectedSchedule.schedulingTime.split(' ')[1]} ?`} title={selectedSchedule && `Deletar ${selectedSchedule.statusChatEndId=='2' ? 'lembrete' : 'agendamento'} do dia ${selectedSchedule.schedulingDate.split(' ')[0]} ${selectedSchedule.schedulingDate.split(' ')[1]} ?`}
open={confirmModalOpen} open={confirmModalOpen}
onClose={handleCloseConfirmationModal} onClose={handleCloseConfirmationModal}
onConfirm={() => handleDeleteSchedule(selectedSchedule.id)} onConfirm={() => handleDeleteSchedule(selectedSchedule.id)}
> >
<span>Deseja realmente deletar esse Lembrete? </span> <span>Deseja realmente deletar esse lembrete/agendamento ? </span>
</ConfirmationModal> </ConfirmationModal>
<MaterialTable <MaterialTable
@ -452,12 +472,12 @@ const handleModal = (rowData) => {
[ [
{ 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: 'Nome', field: 'ticket.contact.name' },
{ title: 'Contato', field: 'ticket.contact.number' }, { title: 'Contato', field: 'ticket.contact.number' },
{ title: 'schedulingTime', field: 'schedulingTime' }, { title: 'Lemb/Agen', field: 'scheduleReminder'},
{ title: 'schedulingDate', field: 'schedulingDate' }, { title: 'Envio', field: 'schedulingTime' },
{ title: 'message', field: 'message' }, { title: 'Data', field: 'schedulingDate' },
{ title: 'Mensagem', field: 'message', width: "80%" },
] ]
} }
@ -487,7 +507,8 @@ const handleModal = (rowData) => {
} }
]} ]}
options={{ options={
{
search: true, search: true,
selection: false, selection: false,
paging: false, paging: false,
@ -498,6 +519,10 @@ const handleModal = (rowData) => {
width: 300, width: 300,
}, },
rowStyle: {
fontSize: 12,
}
}} }}
/> />