Codificaçao do recurso opcional de finalização de atendimento e inclução do status de encerramento de atendimento

pull/1/head
adriano 2022-05-19 18:29:38 -03:00
parent 70245a9904
commit a3be6063c4
9 changed files with 519 additions and 454 deletions

View File

@ -8,11 +8,12 @@ import ShowTicketService from "../services/TicketServices/ShowTicketService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService"; import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage"; import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService"; import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import ShowStatusChatEndService from '../services/StatusChatEndService/ShowStatusChatEndService'
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" import { isScheduling } from "../helpers/CheckSchedulingReminderNotify"
import ptBR from 'date-fns/locale/pt-BR'; import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime"; import { splitDateTime } from "../helpers/SplitDateTime";
@ -39,7 +40,7 @@ interface TicketData {
} }
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService"; import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
import Ticket from "../models/Ticket"; import Ticket from "../models/Ticket";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport"; import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
import TicketEmiterSumOpenClosedByUser from "../helpers/OnlineReporEmiterInfoByUser"; import TicketEmiterSumOpenClosedByUser from "../helpers/OnlineReporEmiterInfoByUser";
@ -90,26 +91,26 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
// ) // )
// test del // test del
let ticket = await Ticket.findOne({where: { contactId, status: 'queueChoice' } }); let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } });
if(ticket){ if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open',userId: userId,}, ticketId: ticket.id}); await UpdateTicketService({ ticketData: { status: 'open', userId: userId, }, ticketId: ticket.id });
console.log('TICKET QUEUE CHOICE !!!!!!!') console.log('TICKET QUEUE CHOICE !!!!!!!')
} }
else{ else {
ticket = await CreateTicketService({ contactId, status, userId }); ticket = await CreateTicketService({ contactId, status, userId });
} }
const io = getIO(); const io = getIO();
io.to(ticket.status).emit("ticket", { io.to(ticket.status).emit("ticket", {
action: "update", action: "update",
ticket ticket
}); });
// //
// const ticket = await CreateTicketService({ contactId, status, userId }); // const ticket = await CreateTicketService({ contactId, status, userId });
// const io = getIO(); // const io = getIO();
// io.to(ticket.status).emit("ticket", { // io.to(ticket.status).emit("ticket", {
@ -133,7 +134,7 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
///////////////// /////////////////
return res.status(200).json({contact, statusChatEnd, schedulesContact}); return res.status(200).json({ contact, statusChatEnd, schedulesContact });
}; };
@ -142,50 +143,56 @@ export const show = async (req: Request, res: Response): Promise<Response> => {
export const update = async ( req: Request, res: Response ): Promise<Response> => { export const update = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const userOldInfo = await Ticket.findByPk(ticketId) const userOldInfo = await Ticket.findByPk(ticketId)
let ticket2 = {} let ticket2 = {}
if(req.body['status'] === "closed"){ if (req.body['status'] === "closed") {
const {status, userId, schedulingNotifyData} = req.body; const { status, userId, schedulingNotifyData } = req.body;
// lembrete
const scheduleData = JSON.parse(schedulingNotifyData)
const statusChatEndName = await ShowStatusChatEndService(scheduleData.statusChatEndId)
const { ticket } = await UpdateTicketService({ const { ticket } = await UpdateTicketService({
ticketData:{'status': status, 'userId': userId}, ticketData: { 'status': status, 'userId': userId, 'statusChatEnd': statusChatEndName.name },
ticketId ticketId
}); });
/////////////////////////////// ///////////////////////////////
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
const { farewellMessage } = whatsapp; console.log('------- scheduleData.farewellMessage: ', scheduleData.farewellMessage)
if (farewellMessage) { if (scheduleData.farewellMessage) {
await SendWhatsAppMessage({ body: farewellMessage, ticket }); const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
const { farewellMessage } = whatsapp;
if (farewellMessage) {
await SendWhatsAppMessage({ body: farewellMessage, ticket });
}
} }
/////////////////////////////// ///////////////////////////////
// lembrete // agendamento
// lembrete if (scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3') {
const scheduleData = JSON.parse(schedulingNotifyData)
// lembrete // agendamento
if( scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3'){
console.log('*** schedulingDate: ', scheduleData.schedulingDate) console.log('*** schedulingDate: ', scheduleData.schedulingDate)
console.log('*** schedulingTime: ', scheduleData.schedulingTime) console.log('*** schedulingTime: ', scheduleData.schedulingTime)
if(isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)){ if (isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)) {
console.log('*** É AGENDAMENTO!') console.log('*** É AGENDAMENTO!')
} }
else{ else {
console.log('*** É LEMBRETE!') console.log('*** É LEMBRETE!')
} }
@ -203,7 +210,7 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
ticket2 = ticket ticket2 = ticket
} }
else{ else {
const ticketData: TicketData = req.body; const ticketData: TicketData = req.body;
@ -221,18 +228,18 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
// test del // test del
if(userOldInfo){ if (userOldInfo) {
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR }))) const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
if(userOldInfo.userId){ if (userOldInfo.userId) {
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate) TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate)
} }
} }
// //
return res.status(200).json(ticket2); return res.status(200).json(ticket2);
}; };

View File

@ -0,0 +1,15 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Tickets", "statusChatEnd", {
type: DataTypes.STRING,
allowNull: true,
defaultValue: ''
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Tickets", "statusChatEnd");
}
};

View File

@ -10,7 +10,8 @@ import {
HasMany, HasMany,
HasOne, HasOne,
AutoIncrement, AutoIncrement,
Default Default,
DataType
} from "sequelize-typescript"; } from "sequelize-typescript";
import Contact from "./Contact"; import Contact from "./Contact";
@ -41,6 +42,9 @@ class Ticket extends Model<Ticket> {
@Column @Column
isGroup: boolean; isGroup: boolean;
@Column
statusChatEnd: string;
@CreatedAt @CreatedAt
createdAt: Date; createdAt: Date;

View File

@ -60,7 +60,7 @@ const ShowMessageReport = async (id: string | number, startDate: string, endDate
where: where_clause_user, where: where_clause_user,
required:true, required:true,
attributes: ['id', 'status'], attributes: ['id', 'status', 'statusChatEnd'],
include: [ include: [
{ {

View File

@ -0,0 +1,14 @@
import StatusChatEnd from "../../models/StatusChatEnd";
import AppError from "../../errors/AppError";
const ShowStatusChatEndService = async (id: string | number): Promise<StatusChatEnd> => {
const status = await StatusChatEnd.findByPk(id, { attributes: ['id', 'name'], });
if (!status) {
throw new AppError("ERR_NO_STATUS_FOUND", 404);
}
return status;
};
export default ShowStatusChatEndService;

View File

@ -47,7 +47,7 @@ const ShowTicketReport = async (id: string | number, startDate: string, endDate:
where: where_clause , where: where_clause ,
//attributes: ['id', 'status', 'createdAt', 'updatedAt'], //attributes: ['id', 'status', 'createdAt', 'updatedAt'],
attributes: ['id', 'status', [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"], attributes: ['id', 'status', 'statusChatEnd', [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.createdAt"),"%d/%m/%Y %H:%i:%s"),"createdAt"],
[Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.updatedAt"),"%d/%m/%Y %H:%i:%s"),"updatedAt"]], [Sequelize.fn("DATE_FORMAT",Sequelize.col("Ticket.updatedAt"),"%d/%m/%Y %H:%i:%s"),"updatedAt"]],
include: [ include: [

View File

@ -10,6 +10,7 @@ interface TicketData {
status?: string; status?: string;
userId?: number; userId?: number;
queueId?: number; queueId?: number;
statusChatEnd?: string
} }
interface Request { interface Request {
@ -27,7 +28,7 @@ const UpdateTicketService = async ({
ticketData, ticketData,
ticketId ticketId
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const { status, userId, queueId } = ticketData; const { status, userId, queueId, statusChatEnd } = ticketData;
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
await SetTicketMessagesAsRead(ticket); await SetTicketMessagesAsRead(ticket);
@ -42,7 +43,8 @@ const UpdateTicketService = async ({
await ticket.update({ await ticket.update({
status, status,
queueId, queueId,
userId userId,
statusChatEnd
}); });

View File

@ -13,13 +13,14 @@ 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, addDays, subDays} from "date-fns"; import { subHours, addDays, subDays } from "date-fns";
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 Checkbox from '@mui/material/Checkbox';
import FormControlLabel from "@mui/material/FormControlLabel";
import api from "../../../services/api";
import api from "../../../services/api";
import toastError from "../../../errors/toastError"; import toastError from "../../../errors/toastError";
@ -28,7 +29,7 @@ const reducer = (state, action) => {
if (action.type === "LOAD_SCHEDULES") { if (action.type === "LOAD_SCHEDULES") {
const schedulesContact = action.payload; const schedulesContact = action.payload;
const newSchedules= []; const newSchedules = [];
schedulesContact.forEach((schedule) => { schedulesContact.forEach((schedule) => {
const scheduleIndex = state.findIndex((s) => s.id === schedule.id); const scheduleIndex = state.findIndex((s) => s.id === schedule.id);
@ -103,16 +104,18 @@ const Modal = (props) => {
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 [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null); const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const [checked, setChecked] = useState(false);
const handleCancel = (event, reason) => { const handleCancel = (event, reason) => {
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
return; return;
setOpen(false); setOpen(false);
}; };
@ -134,14 +137,14 @@ const Modal = (props) => {
}, [props]); }, [props]);
function formatedTimeHour(timer){ function formatedTimeHour(timer) {
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 formatedFullCurrentDate(){ function formatedFullCurrentDate() {
let dateCurrent = new Date() let dateCurrent = new Date()
let day = dateCurrent.getDate().toString().padStart(2, '0'); let day = dateCurrent.getDate().toString().padStart(2, '0');
let month = (dateCurrent.getMonth()+1).toString().padStart(2, '0'); let month = (dateCurrent.getMonth() + 1).toString().padStart(2, '0');
let year = dateCurrent.getFullYear(); let year = dateCurrent.getFullYear();
return `${year}-${month}-${day}`; return `${year}-${month}-${day}`;
} }
@ -161,76 +164,76 @@ const Modal = (props) => {
// }; // };
// 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
const timerPickerValue = (data) => {
console.log('timerPickerValue: ',(data));
setTimerPicker(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'); // Get from child 3
let month = (date.getMonth()+1).toString().padStart(2, '0'); const timerPickerValue = (data) => {
let year = date.getFullYear(); console.log('timerPickerValue: ', (data));
setTimerPicker(data)
return `${year}-${month}-${day}`
} }
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, 'farewellMessage':checked }
if (reason && reason === "backdropClick") if (reason && reason === "backdropClick")
return; return;
if (statusChatEndId === '2' || statusChatEndId === '3'){ if (statusChatEndId === '2' || statusChatEndId === '3') {
console.log('Entrou! textArea1: ', textArea1) console.log('Entrou! textArea1: ', textArea1)
if( startDate.trim().length === 0){ if (startDate.trim().length === 0) {
alert('Selecione uma data atual ou futura!') alert('Selecione uma data atual ou futura!')
return return
} }
else if(textArea1 && textArea1.trim().length<5){ else if (textArea1 && textArea1.trim().length < 5) {
alert('Mensagem muito curta!') alert('Mensagem muito curta!')
return return
} }
else if(!textArea1){ else if (!textArea1) {
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()) || ((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
} }
@ -240,9 +243,9 @@ const timerPickerValue = (data) => {
let dateSendMessage = startDate let dateSendMessage = startDate
let timeBefore = formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)) let timeBefore = formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))
if(statusChatEndId === '3'){ if (statusChatEndId === '3') {
if(!currencyHourBefore){ 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!') alert('Para agendamentos do dia corrente, essa funcionalidade atende a agendeamentos com no mínimo 2 horas adiantado a partir da hora atual!')
return return
} }
@ -251,26 +254,25 @@ const timerPickerValue = (data) => {
let sendMessageDayBefore = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0); let sendMessageDayBefore = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
if(sendMessageDayBefore.length > 0 && timeBefore === formatedTimeHour(timerPicker)) if (sendMessageDayBefore.length > 0 && timeBefore === formatedTimeHour(timerPicker)) {
{
console.log('ENVIAR MENSAGEM UM DIA ANTES!') 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)))) 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))) 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` ) console.log('AGENDAMENTO ENVIO MENSAGEM1: ', `${dateSendMessage} ${timeBefore}:00`)
} else if (statusChatEndId === '2'){ } else if (statusChatEndId === '2') {
console.log('AGENDAMENTO ENVIO MENSAGEM2: ', startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`)) ) 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': `${dateSendMessage} ${timeBefore}:00`, 'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1 'message': textArea1
} }
@ -288,80 +290,82 @@ const timerPickerValue = (data) => {
useEffect(()=>{ useEffect(() => {
const hoursBeforeAvalible = (timer) =>{ const hoursBeforeAvalible = (timer) => {
let hours = [] let hours = []
let hour = 1 let hour = 1
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', startDate ) console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', startDate)
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> dateCurrentFormated: ', dateCurrentFormated() ) console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> dateCurrentFormated: ', dateCurrentFormated())
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ',typeof(startDate) ) console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', typeof (startDate))
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ',(startDate) ) console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', (startDate))
if(typeof(startDate)==='string' && startDate.trim().length>0 && startDate === dateCurrentFormated()){ if (typeof (startDate) === 'string' && startDate.trim().length > 0 && startDate === dateCurrentFormated()) {
console.log('HOJE++++') console.log('HOJE++++')
while(subHours(timer, hour).getHours()>=6 && while (subHours(timer, hour).getHours() >= 6 &&
subHours(timer, hour).getHours()>=new Date().getHours() && subHours(timer, hour).getHours() >= new Date().getHours() &&
subHours(timer, hour).getHours()<=20){ subHours(timer, hour).getHours() <= 20) {
console.log('******** TIMER: ', formatedTimeHour(subHours(timer,hour))) console.log('******** TIMER: ', formatedTimeHour(subHours(timer, hour)))
hours.push({value: formatedTimeHour(subHours(timer,hour)), label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO`}) 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)
}
hour++;
} }
if (hours.length > 1) {
if(new Date(startDate) > addDays(new Date(), 1) ){ console.log('entrou----------------------: ', hours.length)
hours.pop()
hours.push({value: formatedTimeHour(timerPicker) , label: `24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO`}) setCurrency(hours[0].value)
}
console.log('#subDays: ', dateCurrentFormated( new Date(subDays(new Date(startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}:00`))), 1)))) else {
setCurrency(null)
} }
console.log('hourshourshourshourshourshourshourshourshourshourshourshours ', hours) }
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)
}
}
return {time: hours, hour:hour} 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 }
} }
@ -371,7 +375,7 @@ const timerPickerValue = (data) => {
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time) setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
},[timerPicker, startDate]) }, [timerPicker, startDate])
@ -389,193 +393,206 @@ const timerPickerValue = (data) => {
// Get from child 1 // Get from child 1
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);
}; };
const handleCheckBoxChange = (event) => {
//console.log('event.target.checked: ', event.target.checked)
setChecked(event.target.checked);
};
const handleChangeHourBefore = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value); const handleChangeHourBefore = (event) => {
// var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0); console.log('textFihandleChangeHourBefore: ', event.target.value);
// console.log('textFihandleChangeHourBefore matchedTime: ',matchedTime); // var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
setCurrency(event.target.value); // console.log('textFihandleChangeHourBefore matchedTime: ',matchedTime);
}; setCurrency(event.target.value);
};
return ( return (
<Dialog <Dialog
open={open} open={open}
onClose={handleCancel} onClose={handleCancel}
// fullWidth={true} // fullWidth={true}
// maxWidth={true} // maxWidth={true}
disableEscapeKeyDown disableEscapeKeyDown
scroll={scroll} scroll={scroll}
aria-labelledby="scroll-dialog-title" aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description" aria-describedby="scroll-dialog-description"
> >
<DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle> <DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'body'}> <DialogContent dividers={scroll === 'body'}>
<DialogContentText <DialogContentText
id="scroll-dialog-description" id="scroll-dialog-description"
ref={descriptionElementRef} ref={descriptionElementRef}
tabIndex={-1} tabIndex={-1}
> >
</DialogContentText> </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}
textBoxFieldSelected={'1'} textBoxFieldSelected={'1'}
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 }
})}/> })} />
</Item> </Item>
</Box> </Box>
{statusChatEndId==='2' && {statusChatEndId === '2' &&
<Item> <Item>
<span>Lembrete</span> <span>Lembrete</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'}/></Item> <Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'} /></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'}/></Item> <Item><TimerPickerSelect func={timerPickerValue} title={'Hora'} /></Item>
</Box> </Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}> <Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Item> <Item>
<TextareaAutosize <TextareaAutosize
aria-label="minimum height" aria-label="minimum height"
minRows={3} minRows={3}
value={textArea1} value={textArea1}
placeholder={'Mensagem de envio para cliente'} placeholder={'Mensagem de envio para cliente'}
onChange={ handleChange} onChange={handleChange}
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
</Item> </Item>
</Box> </Box>
</Item> </Item>
} }
{statusChatEndId==='3' && {statusChatEndId === '3' &&
<Item> <Item>
<span>Agendamento</span> <span>Agendamento</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}> <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'}/></Item> <Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'} /></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'}/></Item> <Item><TimerPickerSelect func={timerPickerValue} title={'Hora'} /></Item>
</Box> </Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}> <Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Item> <Item>
{currencyHourBefore && startDate && typeof(startDate)==='string' && startDate.trim().length > 0 && currenciesTimeBefore.length > 0 && {currencyHourBefore && startDate && typeof (startDate) === 'string' && startDate.trim().length > 0 && currenciesTimeBefore.length > 0 &&
<TextFieldSelectHourBefore <TextFieldSelectHourBefore
id="outlined-select-currency" id="outlined-select-currency"
disabled={startDate.length>0 ? false : true} disabled={startDate.length > 0 ? false : true}
select select
label="Enviar mensagem para o cliente" label="Enviar mensagem para o cliente"
value={currencyHourBefore} value={currencyHourBefore}
size="small" size="small"
onChange={handleChangeHourBefore} onChange={handleChangeHourBefore}
> >
{currenciesTimeBefore.map((option) => ( {currenciesTimeBefore.map((option) => (
<MenuItem key={option.value} value={option.value}> <MenuItem key={option.value} value={option.value}>
{option.label} {option.label}
</MenuItem> </MenuItem>
))} ))}
</TextFieldSelectHourBefore> </TextFieldSelectHourBefore>
} }
</Item> </Item>
<Item> <Item>
<TextareaAutosize <TextareaAutosize
aria-label="minimum height" aria-label="minimum height"
minRows={3} minRows={3}
value={textArea1} value={textArea1}
placeholder={'Mensagem de envio para o cliente'} placeholder={'Mensagem de envio para o cliente'}
onChange={ handleChange} onChange={handleChange}
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
</Item> </Item>
</Box> </Box>
</Item> </Item>
} }
{schedulesContact.length>0 && {schedulesContact.length > 0 &&
<div></div> <div></div>
} }
</Box> </Box>
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<div style={{marginRight:'50px'}}> <div>
<Button onClick={handleCancel}>Cancelar</Button> <FormControlLabel
</div> control={<Checkbox checked={checked} onChange={handleCheckBoxChange} />}
<Button onClick={handleChatEnd}>Ok</Button> label="Mensagem de encerramento de atendimento"
</DialogActions> />
</Dialog> </div>
<div style={{ marginRight: '50px' }}>
<Button onClick={handleCancel}>Cancelar</Button>
</div>
<Button onClick={handleChatEnd}>Ok</Button>
</DialogActions>
</Dialog>
); );
} }

View File

@ -74,7 +74,13 @@ let columns = [
{ {
key: 'ticket.status', key: 'ticket.status',
label: 'Status', label: 'Status',
}] },
{
key: 'ticket.statusChatEnd',
label: 'Status de encerramento',
}
]
// //
@ -290,12 +296,12 @@ let columnsData = [
{ title: 'Contato', field: 'contact.number' }, { title: 'Contato', field: 'contact.number' },
{ title: 'Nome', field: 'contact.name' }, { title: 'Nome', field: 'contact.name' },
{ title: 'Assunto', field: 'queue.name' }, { title: 'Assunto', field: 'queue.name' },
{ title: 'Status', field: 'status' },
{ title: 'Criado', field: 'createdAt' },
{
title: 'Atualizado', field: 'updatedAt',
}]; { title: 'Status', field: 'status' },
{ title: 'Criado', field: 'createdAt' },
//{title: 'Atualizado', field: 'updatedAt'},
{title: 'Status de encerramento', field: 'statusChatEnd'}];
const Report = () => { const Report = () => {