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

@ -3,22 +3,23 @@ import { getIO } from "../libs/socket";
import CreateTicketService from "../services/TicketServices/CreateTicketService"; import CreateTicketService from "../services/TicketServices/CreateTicketService";
import DeleteTicketService from "../services/TicketServices/DeleteTicketService"; import DeleteTicketService from "../services/TicketServices/DeleteTicketService";
import ListTicketsService from "../services/TicketServices/ListTicketsService"; import ListTicketsService from "../services/TicketServices/ListTicketsService";
import ShowTicketService from "../services/TicketServices/ShowTicketService"; 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";
import format from 'date-fns/format'; import format from 'date-fns/format';
type IndexQuery = { type IndexQuery = {
searchParam: string; searchParam: string;
@ -36,10 +37,10 @@ interface TicketData {
status: string; status: string;
queueId: number; queueId: number;
userId: number; userId: number;
} }
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";
@ -56,15 +57,15 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
unlimited unlimited
} = req.query as IndexQuery; } = req.query as IndexQuery;
const userId = req.user.id;
const userId = req.user.id;
let queueIds: number[] = []; let queueIds: number[] = [];
if (queueIdsStringified) { if (queueIdsStringified) {
queueIds = JSON.parse(queueIdsStringified); queueIds = JSON.parse(queueIdsStringified);
} }
const { tickets, count, hasMore } = await ListTicketsService({ const { tickets, count, hasMore } = await ListTicketsService({
searchParam, searchParam,
@ -77,7 +78,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
withUnreadMessages, withUnreadMessages,
unlimited unlimited
}); });
return res.status(200).json({ tickets, count, hasMore }); return res.status(200).json({ tickets, count, hasMore });
}; };
@ -88,28 +89,28 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
// console.log( // console.log(
// `contactId: ${contactId} \n| status: ${status} \n| userId: ${userId}` // `contactId: ${contactId} \n| status: ${status} \n| userId: ${userId}`
// ) // )
// test del
let ticket = await Ticket.findOne({where: { contactId, status: 'queueChoice' } });
if(ticket){
await UpdateTicketService({ ticketData: { status: 'open',userId: userId,}, ticketId: ticket.id});
console.log('TICKET QUEUE CHOICE !!!!!!!')
}
else{
ticket = await CreateTicketService({ contactId, status, userId });
}
const io = getIO();
io.to(ticket.status).emit("ticket", {
action: "update",
ticket
});
//
// const ticket = await CreateTicketService({ contactId, status, userId }); // test del
let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } });
if (ticket) {
await UpdateTicketService({ ticketData: { status: 'open', userId: userId, }, ticketId: ticket.id });
console.log('TICKET QUEUE CHOICE !!!!!!!')
}
else {
ticket = await CreateTicketService({ contactId, status, userId });
}
const io = getIO();
io.to(ticket.status).emit("ticket", {
action: "update",
ticket
});
//
// 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", {
@ -119,21 +120,21 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
return res.status(200).json(ticket); return res.status(200).json(ticket);
}; };
export const show = async (req: Request, res: Response): Promise<Response> => { export const show = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const contact = await ShowTicketService(ticketId); const contact = await ShowTicketService(ticketId);
const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" }); const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" });
//////////////////
const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number);
/////////////////
return res.status(200).json({contact, statusChatEnd, schedulesContact}); //////////////////
const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number);
/////////////////
return res.status(200).json({ contact, statusChatEnd, schedulesContact });
}; };
@ -142,68 +143,74 @@ 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"){
const {status, userId, schedulingNotifyData} = req.body; if (req.body['status'] === "closed") {
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
if (scheduleData.statusChatEndId === '2' || scheduleData.statusChatEndId === '3') {
// lembrete
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!')
} }
const schedulingNotifyCreate = await CreateSchedulingNotifyService( const schedulingNotifyCreate = await CreateSchedulingNotifyService(
{ {
ticketId: scheduleData.ticketId, ticketId: scheduleData.ticketId,
statusChatEndId: scheduleData.statusChatEndId, statusChatEndId: scheduleData.statusChatEndId,
schedulingDate: scheduleData.schedulingDate, schedulingDate: scheduleData.schedulingDate,
schedulingTime: scheduleData.schedulingTime, schedulingTime: scheduleData.schedulingTime,
message: scheduleData.message message: scheduleData.message
} }
) )
} }
ticket2 = ticket ticket2 = ticket
} }
else{ else {
const ticketData: TicketData = req.body; const ticketData: TicketData = req.body;
@ -216,23 +223,23 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
ticket2 = ticket ticket2 = ticket
} }
// 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);
}; };
@ -273,7 +280,7 @@ export const remove = async (
res: Response res: Response
): Promise<Response> => { ): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const ticket = await DeleteTicketService(ticketId); const ticket = await DeleteTicketService(ticketId);
const io = getIO(); const io = getIO();

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

@ -1,34 +1,35 @@
import React, { useState, useEffect, useRef, useReducer } 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 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, 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 api from "../../../services/api"; import FormControlLabel from "@mui/material/FormControlLabel";
import toastError from "../../../errors/toastError";
import api from "../../../services/api";
import toastError from "../../../errors/toastError";
const reducer = (state, action) => { 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);
@ -56,10 +57,10 @@ const reducer = (state, action) => {
} }
}; };
const Item = (props) => { const Item = (props) => {
const { sx, ...other } = props; const { sx, ...other } = props;
return ( return (
<Box <Box
@ -89,65 +90,67 @@ Item.propTypes = {
PropTypes.func, PropTypes.func,
PropTypes.object, PropTypes.object,
]), ]),
}; };
const Modal = (props) => {
const Modal = (props) => {
// const [clientSchedules, dispatch] = useReducer(reducer, []); // const [clientSchedules, dispatch] = useReducer(reducer, []);
// const [selectedSchedule, setSelectedSchedule] = useState(null); // const [selectedSchedule, setSelectedSchedule] = useState(null);
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 [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);
}; };
useEffect(() => {
(async () => {
try {
const { data } = await api.get("/tickets/" + props.ticketId); useEffect(() => {
(async () => {
try {
const { data } = await api.get("/tickets/" + props.ticketId);
dispatch({ type: "LOAD_SCHEDULES", payload: data.schedulesContact }); dispatch({ type: "LOAD_SCHEDULES", payload: data.schedulesContact });
} catch (err) { } catch (err) {
toastError(err); toastError(err);
} }
})(); })();
}, [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}`;
} }
// const handleDeleteSchedule = async (scheduleId) => { // const handleDeleteSchedule = async (scheduleId) => {
// try { // try {
@ -161,217 +164,218 @@ 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 handleChatEnd = (event, reason) => { }
let dataSendServer = {'statusChatEndId': statusChatEndId}
if (reason && reason === "backdropClick") const dateCurrentFormated = (dateF = null) => {
return;
if (statusChatEndId === '2' || statusChatEndId === '3'){ 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) => {
let dataSendServer = { 'statusChatEndId': statusChatEndId, 'farewellMessage':checked }
if (reason && reason === "backdropClick")
return;
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
}
else if(textArea1 && textArea1.trim().length<5){
alert('Mensagem muito curta!')
return return
} }
else if(!textArea1){
else if (textArea1 && textArea1.trim().length < 5) {
alert('Mensagem muito curta!')
return
}
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
} }
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
} }
timeBefore = currencyHourBefore timeBefore = currencyHourBefore
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)))
}
console.log('AGENDAMENTO ENVIO MENSAGEM1: ', `${dateSendMessage} ${timeBefore}:00` ) 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`)))
} 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': `${dateSendMessage} ${timeBefore}:00`, 'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1 'message': textArea1
} }
}
}
props.func(dataSendServer)
props.func(dataSendServer)
setOpen(false); setOpen(false);
}; };
useEffect(()=>{
const hoursBeforeAvalible = (timer) =>{ useEffect(() => {
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()){
console.log('HOJE++++')
while(subHours(timer, hour).getHours()>=6 &&
subHours(timer, hour).getHours()>=new Date().getHours() && if (typeof (startDate) === 'string' && startDate.trim().length > 0 && startDate === dateCurrentFormated()) {
subHours(timer, hour).getHours()<=20){
console.log('HOJE++++')
console.log('******** TIMER: ', formatedTimeHour(subHours(timer,hour)))
while (subHours(timer, hour).getHours() >= 6 &&
hours.push({value: formatedTimeHour(subHours(timer,hour)), label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO`})
subHours(timer, hour).getHours() >= new Date().getHours() &&
hour++; subHours(timer, hour).getHours() <= 20) {
}
console.log('******** TIMER: ', formatedTimeHour(subHours(timer, hour)))
if(hours.length>1){
console.log('entrou----------------------: ', hours.length) hours.push({ value: formatedTimeHour(subHours(timer, hour)), label: `${hour} HORA ANTES DO HORÁRIO DO AGENDAMENTO` })
hours.pop()
setCurrency(hours[0].value) hour++;
}
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 (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 {
return {time: hours, hour:hour} 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)) console.log('===================================== addDays: ', addDays(new Date(), 1))
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) => { }
setTextArea1(event.target.value);
};
const handleChangeHourBefore = (event) => { const handleChange = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value); setTextArea1(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); const handleCheckBoxChange = (event) => {
}; //console.log('event.target.checked: ', event.target.checked)
setChecked(event.target.checked);
};
return (
<Dialog
open={open}
onClose={handleCancel}
// fullWidth={true}
// maxWidth={true}
disableEscapeKeyDown
scroll={scroll} const handleChangeHourBefore = (event) => {
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
<DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle> console.log('textFihandleChangeHourBefore: ', event.target.value);
<DialogContent dividers={scroll === 'body'}>
<DialogContentText // var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
</DialogContentText>
// console.log('textFihandleChangeHourBefore matchedTime: ',matchedTime);
<Box
sx={{
width: 500,
height: '100%',
// backgroundColor: 'primary.dark',
// '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],},
}}>
<Box sx={{ setCurrency(event.target.value);
display: 'grid',
}}>
<Item>
<span>Selecione uma opção para encerrar o Atendimento</span>
<SelectField func={textFieldSelect}
emptyField={false}
textBoxFieldSelected={'1'}
header={'Opções de encerramento do atendimento'}
currencies={props.statusChatEnd.map((obj)=>{
return {'value': obj.id, 'label': obj.name}
})}/>
</Item> };
</Box>
{statusChatEndId==='2' &&
<Item>
<span>Lembrete</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'}/></Item>
</Box>
<Box sx={{display: 'flex', flexDirection: 'column' }}>
<Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem de envio para cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</Item> return (
}
{statusChatEndId==='3' && <Dialog
open={open}
onClose={handleCancel}
// fullWidth={true}
// maxWidth={true}
disableEscapeKeyDown
<Item> scroll={scroll}
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
<span>Agendamento</span> <DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'body'}>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}> <DialogContentText
id="scroll-dialog-description"
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'}/></Item> ref={descriptionElementRef}
tabIndex={-1}
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'}/></Item> >
</Box> </DialogContentText>
<Box sx={{display: 'flex', flexDirection: 'column' }}> <Box
sx={{
width: 500,
height: '100%',
// backgroundColor: 'primary.dark',
// '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],},
}}>
<Box sx={{
<Item> display: 'grid',
{currencyHourBefore && startDate && typeof(startDate)==='string' && startDate.trim().length > 0 && currenciesTimeBefore.length > 0 && }}>
<TextFieldSelectHourBefore <Item>
id="outlined-select-currency" <span>Selecione uma opção para encerrar o Atendimento</span>
disabled={startDate.length>0 ? false : true}
select <SelectField func={textFieldSelect}
label="Enviar mensagem para o cliente" emptyField={false}
value={currencyHourBefore} textBoxFieldSelected={'1'}
size="small" header={'Opções de encerramento do atendimento'}
onChange={handleChangeHourBefore} currencies={props.statusChatEnd.map((obj) => {
> return { 'value': obj.id, 'label': obj.name }
{currenciesTimeBefore.map((option) => ( })} />
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextFieldSelectHourBefore>
}
</Item>
</Item>
<Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem de envio para o cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box> </Box>
</Item> {statusChatEndId === '2' &&
}
{schedulesContact.length>0 && <Item>
<div></div>
} <span>Lembrete</span>
<Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)' }}>
</Box>
</DialogContent> <Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'} /></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'} /></Item>
<DialogActions>
<div style={{marginRight:'50px'}}> </Box>
<Button onClick={handleCancel}>Cancelar</Button>
</div>
<Button onClick={handleChatEnd}>Ok</Button> <Box sx={{ display: 'flex', flexDirection: 'column' }}>
</DialogActions>
</Dialog> <Item>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem de envio para cliente'}
onChange={handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</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'} /></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'} /></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 o 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 o cliente'}
onChange={handleChange}
style={{ width: '100%' }}
/>
</Item>
</Box>
</Item>
}
{schedulesContact.length > 0 &&
<div></div>
}
</Box>
</DialogContent>
<DialogActions>
<div>
<FormControlLabel
control={<Checkbox checked={checked} onChange={handleCheckBoxChange} />}
label="Mensagem de encerramento de atendimento"
/>
</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 = () => {