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 DeleteTicketService from "../services/TicketServices/DeleteTicketService";
import ListTicketsService from "../services/TicketServices/ListTicketsService";
import ListTicketsService from "../services/TicketServices/ListTicketsService";
import ShowTicketService from "../services/TicketServices/ShowTicketService";
import UpdateTicketService from "../services/TicketServices/UpdateTicketService";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import ShowStatusChatEndService from '../services/StatusChatEndService/ShowStatusChatEndService'
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import {isScheduling} from "../helpers/CheckSchedulingReminderNotify"
import CreateSchedulingNotifyService from "../services/SchedulingNotifyServices/CreateSchedulingNotifyService";
import ListSchedulingNotifyContactService from "../services/SchedulingNotifyServices/ListSchedulingNotifyContactService";
import { isScheduling } from "../helpers/CheckSchedulingReminderNotify"
import ptBR from 'date-fns/locale/pt-BR';
import { splitDateTime } from "../helpers/SplitDateTime";
import format from 'date-fns/format';
type IndexQuery = {
searchParam: string;
@ -36,10 +37,10 @@ interface TicketData {
status: string;
queueId: number;
userId: number;
}
}
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
import ListStatusChatEndService from "../services/StatusChatEndService/ListStatusChatEndService";
import Ticket from "../models/Ticket";
import ShowUserServiceReport from "../services/UserServices/ShowUserServiceReport";
import TicketEmiterSumOpenClosedByUser from "../helpers/OnlineReporEmiterInfoByUser";
@ -56,15 +57,15 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
unlimited
} = req.query as IndexQuery;
const userId = req.user.id;
const userId = req.user.id;
let queueIds: number[] = [];
if (queueIdsStringified) {
queueIds = JSON.parse(queueIdsStringified);
}
}
const { tickets, count, hasMore } = await ListTicketsService({
searchParam,
@ -77,7 +78,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
withUnreadMessages,
unlimited
});
return res.status(200).json({ tickets, count, hasMore });
};
@ -88,28 +89,28 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
// console.log(
// `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();
// 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);
};
export const show = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params;
const contact = await ShowTicketService(ticketId);
const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" });
//////////////////
const schedulesContact = await ListSchedulingNotifyContactService(contact.contact.number);
/////////////////
const { statusChatEnd, count, hasMore } = await ListStatusChatEndService({ searchParam: "", pageNumber: "1" });
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 userOldInfo = await Ticket.findByPk(ticketId)
const userOldInfo = await Ticket.findByPk(ticketId)
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({
ticketData:{'status': status, 'userId': userId},
ticketData: { 'status': status, 'userId': userId, 'statusChatEnd': statusChatEndName.name },
ticketId
});
///////////////////////////////
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
const { farewellMessage } = whatsapp;
console.log('------- scheduleData.farewellMessage: ', scheduleData.farewellMessage)
if (farewellMessage) {
await SendWhatsAppMessage({ body: farewellMessage, ticket });
}
///////////////////////////////
if (scheduleData.farewellMessage) {
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('*** schedulingTime: ', scheduleData.schedulingTime)
if(isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)){
if (isScheduling(scheduleData.schedulingDate, scheduleData.schedulingTime)) {
console.log('*** É AGENDAMENTO!')
}
else{
else {
console.log('*** É LEMBRETE!')
}
const schedulingNotifyCreate = await CreateSchedulingNotifyService(
{
ticketId: scheduleData.ticketId,
statusChatEndId: scheduleData.statusChatEndId,
schedulingDate: scheduleData.schedulingDate,
statusChatEndId: scheduleData.statusChatEndId,
schedulingDate: scheduleData.schedulingDate,
schedulingTime: scheduleData.schedulingTime,
message: scheduleData.message
message: scheduleData.message
}
)
)
}
ticket2 = ticket
}
else{
else {
const ticketData: TicketData = req.body;
@ -216,23 +223,23 @@ export const update = async ( req: Request, res: Response ): Promise<Response> =
ticket2 = ticket
}
}
// 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){
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate)
}
if (userOldInfo.userId) {
}
TicketEmiterSumOpenClosedByUser(userOldInfo.userId.toString(), dateToday.fullDate, dateToday.fullDate)
}
//
}
//
return res.status(200).json(ticket2);
};
@ -273,7 +280,7 @@ export const remove = async (
res: Response
): Promise<Response> => {
const { ticketId } = req.params;
const ticket = await DeleteTicketService(ticketId);
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,
HasOne,
AutoIncrement,
Default
Default,
DataType
} from "sequelize-typescript";
import Contact from "./Contact";
@ -41,6 +42,9 @@ class Ticket extends Model<Ticket> {
@Column
isGroup: boolean;
@Column
statusChatEnd: string;
@CreatedAt
createdAt: Date;

View File

@ -60,7 +60,7 @@ const ShowMessageReport = async (id: string | number, startDate: string, endDate
where: where_clause_user,
required:true,
attributes: ['id', 'status'],
attributes: ['id', 'status', 'statusChatEnd'],
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 ,
//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"]],
include: [

View File

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

View File

@ -1,34 +1,35 @@
import React, { useState, useEffect, useRef, useReducer } from 'react';
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import DialogTitle from '@mui/material/DialogTitle';
import PropTypes from 'prop-types';
import Box from '@mui/material/Box';
import SelectField from "../../Report/SelectField";
import DatePicker from '../../Report/DatePicker'
import TimerPickerSelect from '../TimerPickerSelect'
import TextareaAutosize from '@mui/material/TextareaAutosize';
import Box from '@mui/material/Box';
import SelectField from "../../Report/SelectField";
import DatePicker from '../../Report/DatePicker'
import TimerPickerSelect from '../TimerPickerSelect'
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 MenuItem from '@mui/material/MenuItem';
import MenuItem from '@mui/material/MenuItem';
import api from "../../../services/api";
import toastError from "../../../errors/toastError";
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from "@mui/material/FormControlLabel";
import api from "../../../services/api";
import toastError from "../../../errors/toastError";
const reducer = (state, action) => {
const reducer = (state, action) => {
if (action.type === "LOAD_SCHEDULES") {
const schedulesContact = action.payload;
const newSchedules= [];
const newSchedules = [];
schedulesContact.forEach((schedule) => {
const scheduleIndex = state.findIndex((s) => s.id === schedule.id);
@ -56,10 +57,10 @@ const reducer = (state, action) => {
}
};
const Item = (props) => {
const { sx, ...other } = props;
return (
<Box
@ -89,65 +90,67 @@ Item.propTypes = {
PropTypes.func,
PropTypes.object,
]),
};
};
const Modal = (props) => {
const Modal = (props) => {
// const [clientSchedules, dispatch] = useReducer(reducer, []);
// const [selectedSchedule, setSelectedSchedule] = useState(null);
const [open, setOpen] = useState(true);
const [scroll, /*setScroll*/] = useState('body');
const [statusChatEndId, setStatusChatEnd] = useState(null)
const [startDate, setDatePicker] = useState(new Date())
const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState()
const [schedulesContact, dispatch] = useReducer(reducer, []);
const [statusChatEndId, setStatusChatEnd] = useState(null)
const [startDate, setDatePicker] = useState(new Date())
const [timerPicker, setTimerPicker] = useState(new Date())
const [textArea1, setTextArea1] = useState()
const [schedulesContact, dispatch] = useReducer(reducer, []);
const [currencyHourBefore, setCurrency] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const [currenciesTimeBefore, setCurrenciesTimeBefore] = useState(null);
const [checked, setChecked] = useState(false);
const handleCancel = (event, reason) => {
if (reason && reason === "backdropClick")
return;
if (reason && reason === "backdropClick")
return;
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 });
} catch (err) {
toastError(err);
toastError(err);
}
})();
}, [props]);
function formatedTimeHour(timer){
return `${timer.getHours().toString().padStart(2, '0')}:${timer.getMinutes().toString().padStart(2, '0')}`
}, [props]);
function formatedTimeHour(timer) {
return `${timer.getHours().toString().padStart(2, '0')}:${timer.getMinutes().toString().padStart(2, '0')}`
}
function formatedFullCurrentDate(){
let dateCurrent = new Date()
function formatedFullCurrentDate() {
let dateCurrent = new Date()
let day = dateCurrent.getDate().toString().padStart(2, '0');
let month = (dateCurrent.getMonth()+1).toString().padStart(2, '0');
let year = dateCurrent.getFullYear();
return `${year}-${month}-${day}`;
let month = (dateCurrent.getMonth() + 1).toString().padStart(2, '0');
let year = dateCurrent.getFullYear();
return `${year}-${month}-${day}`;
}
// const handleDeleteSchedule = async (scheduleId) => {
// try {
@ -161,217 +164,218 @@ const Modal = (props) => {
// };
// Get from child 2
const datePickerValue = (data) => {
console.log('datePickerValue: ',(data));
setDatePicker(data)
const datePickerValue = (data) => {
console.log('datePickerValue: ', (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');
let month = (date.getMonth()+1).toString().padStart(2, '0');
let year = date.getFullYear();
return `${year}-${month}-${day}`
// Get from child 3
const timerPickerValue = (data) => {
console.log('timerPickerValue: ', (data));
setTimerPicker(data)
}
const handleChatEnd = (event, reason) => {
let dataSendServer = {'statusChatEndId': statusChatEndId}
}
if (reason && reason === "backdropClick")
return;
const dateCurrentFormated = (dateF = null) => {
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)
if( startDate.trim().length === 0){
if (startDate.trim().length === 0) {
alert('Selecione uma data atual ou futura!')
return
}
else if(textArea1 && textArea1.trim().length<5){
alert('Mensagem muito curta!')
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!')
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))){
alert('Horário menor ou igual horário atual!')
return
(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))) {
alert('Horário menor ou igual horário atual!')
return
}
else if((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(new Date(timerPicker).getHours() < 6)){
else if ((new Date(timerPicker).getHours() > 20 && new Date(timerPicker).getMinutes() > 0) ||
(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')
return
}
}
let dateSendMessage = startDate
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!')
return
}
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))
{
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('MENSAGEM SERÁ ENVIA NO DIA: ', 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 = {
'statusChatEndId': statusChatEndId,
'schedulingDate': startDate+' '+formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}`))+':00',
'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1
dataSendServer = {
'statusChatEndId': statusChatEndId,
'schedulingDate': startDate + ' ' + formatedTimeHour(new Date(`${startDate} ${timerPicker.getHours()}:${timerPicker.getMinutes()}`)) + ':00',
'schedulingTime': `${dateSendMessage} ${timeBefore}:00`,
'message': textArea1
}
}
props.func(dataSendServer)
}
props.func(dataSendServer)
setOpen(false);
};
useEffect(()=>{
const hoursBeforeAvalible = (timer) =>{
useEffect(() => {
const hoursBeforeAvalible = (timer) => {
let hours = []
let hour = 1
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 &&
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', startDate)
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> dateCurrentFormated: ', dateCurrentFormated())
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', typeof (startDate))
console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>> startDate: ', (startDate))
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 (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(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))))
if (hours.length > 1) {
console.log('entrou----------------------: ', hours.length)
hours.pop()
setCurrency(hours[0].value)
}
else {
setCurrency(null)
}
console.log('hourshourshourshourshourshourshourshourshourshourshourshours ', hours)
return {time: hours, hour:hour}
}
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])
setCurrenciesTimeBefore(hoursBeforeAvalible(timerPicker).time)
}, [timerPicker, startDate])
@ -389,193 +393,206 @@ const timerPickerValue = (data) => {
// Get from child 1
const textFieldSelect = (data) => {
console.log('textFieldSelect: ',data);
setStatusChatEnd(data)
}
const textFieldSelect = (data) => {
console.log('textFieldSelect: ', data);
setStatusChatEnd(data)
const handleChange = (event) => {
setTextArea1(event.target.value);
};
}
const handleChangeHourBefore = (event) => {
const handleChange = (event) => {
console.log('textFihandleChangeHourBefore: ',event.target.value);
// var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
setTextArea1(event.target.value);
// 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}
aria-labelledby="scroll-dialog-title"
aria-describedby="scroll-dialog-description"
>
const handleChangeHourBefore = (event) => {
<DialogTitle id="scroll-dialog-title">{props.modal_header}</DialogTitle>
<DialogContent dividers={scroll === 'body'}>
console.log('textFihandleChangeHourBefore: ', event.target.value);
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
</DialogContentText>
// var matchedTime = currenciesTimeBefore.filter(i => i.label.indexOf('24 HORAS ANTES DO HORÁRIO DO AGENDAMENTO') >= 0);
<Box
sx={{
width: 500,
height: '100%',
// backgroundColor: 'primary.dark',
// '&:hover': {backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7],},
}}>
// console.log('textFihandleChangeHourBefore matchedTime: ',matchedTime);
<Box sx={{
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}
})}/>
setCurrency(event.target.value);
</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)' }}>
<Item><DatePicker func={datePickerValue} minDate={true} startEmpty={true} title={'Data'}/></Item>
<Item><TimerPickerSelect func={timerPickerValue} title={'Hora'}/></Item>
</Box>
<DialogContentText
id="scroll-dialog-description"
ref={descriptionElementRef}
tabIndex={-1}
>
</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],},
}}>
<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>
<Box sx={{
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>
<TextareaAutosize
aria-label="minimum height"
minRows={3}
value={textArea1}
placeholder={'Mensagem de envio para o cliente'}
onChange={ handleChange}
style={{ width: '100%' }}
/>
</Item>
</Item>
</Box>
</Box>
</Item>
}
{statusChatEndId === '2' &&
{schedulesContact.length>0 &&
<div></div>
}
</Box>
</DialogContent>
<DialogActions>
<div style={{marginRight:'50px'}}>
<Button onClick={handleCancel}>Cancelar</Button>
</div>
<Button onClick={handleChatEnd}>Ok</Button>
</DialogActions>
</Dialog>
<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>
}
{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',
label: 'Status',
}]
},
{
key: 'ticket.statusChatEnd',
label: 'Status de encerramento',
}
]
//
@ -290,12 +296,12 @@ let columnsData = [
{ title: 'Contato', field: 'contact.number' },
{ title: 'Nome', field: 'contact.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 = () => {