Merge pull request #1 from AdrianoRobson/frontend

Frontend
pull/2/head
Renato Di Giacomo 2022-07-20 12:16:50 -03:00 committed by GitHub
commit 390772eb91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 542 additions and 437 deletions

View File

@ -37,9 +37,6 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
export const store = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params;
const { body, quotedMsg }: MessageData = req.body;
const medias = req.files as Express.Multer.File[];

View File

@ -44,7 +44,7 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
const whatsapp = await ShowWhatsAppService(whatsappId);
await restartWhatsSession(whatsapp)
restartWhatsSession(whatsapp, true)
return res.status(200).json({ message: "Starting session." });
};

View File

@ -10,7 +10,7 @@ const fsPromises = require("fs/promises");
const fs = require('fs')
// Restart session
export const restartWhatsSession = async (whatsapp: Whatsapp) => {
export const restartWhatsSession = async (whatsapp: Whatsapp, backupSession: boolean = false) => {
console.log('RESTARTING THE whatsapp.id: ', whatsapp.id)
@ -34,6 +34,6 @@ export const restartWhatsSession = async (whatsapp: Whatsapp) => {
console.log('RESTARTING SESSION...')
await StartWhatsAppSession(whatsapp);
await StartWhatsAppSession(whatsapp, backupSession);
}

View File

@ -1,8 +1,17 @@
import path from "path";
import { getIO } from "../libs/socket";
import Message from "../models/Message";
import Ticket from "../models/Ticket";
import ShowWhatsAppService from "../services/WhatsappService/ShowWhatsAppService";
import { logger } from "../utils/logger";
import GetTicketWbot from "./GetTicketWbot";
import fs from 'fs';
import { restartWhatsSession } from "./RestartWhatsSession";
import { Session } from "@sentry/types";
import { splitDateTime } from "./SplitDateTime";
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await Message.update(
@ -18,14 +27,43 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
await ticket.update({ unreadMessages: 0 });
try {
const wbot = await GetTicketWbot(ticket);
await wbot.sendSeen(
`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`
);
// test del
// throw new Error('Throw makes it go boom!')
//
await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`);
} catch (err) {
logger.warn(
`Could not mark messages as read. Maybe whatsapp session disconnected? Err: ${err}`
);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r") && ticket.whatsappId) {
const sourcePath = path.join(__dirname,`../../.wwebjs_auth/sessions`)
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
if (whatsapp && whatsapp.status == 'CONNECTED') {
console.log('SetTicketMessagesAsRead.ts - ENTROU NO RESTORE...')
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_SetTicketMessagesAsRead.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: SetTicketMessagesAsRead.ts \nError: ${err}`, (error)=>{});
await restartWhatsSession(whatsapp)
console.log('...PASSOU O RESTORE - SetTicketMessagesAsRead.ts ')
}
}
}
const io = getIO();

View File

@ -10,6 +10,7 @@ const fs = require('fs')
import { copyFolder } from "../helpers/CopyFolder";
import path from "path";
import { number } from "yup";
import { removeDir } from "../helpers/DeleteDirectory";
interface Session extends Client {
id?: number;
@ -43,7 +44,7 @@ const syncUnreadMessages = async (wbot: Session) => {
}
};
export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean = false): Promise<Session> => {
return new Promise((resolve, reject) => {
try {
const io = getIO();
@ -59,23 +60,6 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
});
//OPÇÃO DEFAULT NAO MD
// const wbot: Session = new Client({session: sessionCfg,
// puppeteer: {executablePath: process.env.CHROME_BIN || undefined
// }
// });
//OPÇÃO MD ANTIGO COM ERRO
// const io = getIO();
// const sessionName = whatsapp.name;
// const SESSION_FILE_PATH = './session.json'
// let sessionCfg
// if(fs.existsSync(SESSION_FILE_PATH)){
// sessionCfg = require(SESSION_FILE_PATH)
// }
// const wbot: Session = new Client({ puppeteer: { headless: true }, clientId: 'bd_'+whatsapp.id})
wbot.initialize();
@ -169,9 +153,13 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(' whatsIndex: ', whatsIndex)
if (whatsIndex !== -1) {
if (whatsIndex !== -1 || backupSessionRestore) {
if (whatsIndex !== -1) {
backupSession.splice(whatsIndex, 1);
}
setTimeout(async () => {
@ -179,6 +167,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
const destPath = path.join(__dirname, `../../.wwebjs_auth/sessions`, `session-bd_${whatsapp.id}`)
if (fs.existsSync(path.join(__dirname, `../../.wwebjs_auth/sessions`))) {
await removeDir(destPath)
// copy the good session for backup dir
copyFolder(sourcePath, destPath)
}
@ -189,9 +180,9 @@ export const initWbot = async (whatsapp: Whatsapp): Promise<Session> => {
console.log(` COPIOU backup whatsapp.id ---------------------------------->${whatsapp.id}`)
}, 30000);
}, 55000);
console.log(' PASSOU NO TIMEOUT!')
console.log(' PASSOU NO TIMEOUT whatsapp.id: ',whatsapp.id)
}

View File

@ -5,7 +5,7 @@ import { getIO } from "../../libs/socket";
import wbotMonitor from "./wbotMonitor";
import { logger } from "../../utils/logger";
export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> => {
export const StartWhatsAppSession = async (whatsapp: Whatsapp, backupSession: boolean = false): Promise<void> => {
await whatsapp.update({ status: "OPENING" });
const io = getIO();
@ -15,7 +15,7 @@ export const StartWhatsAppSession = async (whatsapp: Whatsapp): Promise<void> =>
});
try {
const wbot = await initWbot(whatsapp);
const wbot = await initWbot(whatsapp, backupSession);
wbotMessageListener(wbot);
wbotMonitor(wbot, whatsapp);
} catch (err) {

View File

@ -7,6 +7,9 @@ import { copyFolder } from "../../helpers/CopyFolder";
import { removeDir } from "../../helpers/DeleteDirectory";
import path from 'path';
import { format } from "date-fns";
import ptBR from 'date-fns/locale/pt-BR';
import {
Contact as WbotContact,
Message as WbotMessage,
@ -44,6 +47,8 @@ import data_ura from './ura'
import msg_client_transfer from './ura_msg_transfer'
import final_message from "./ura_final_message";
import SendWhatsAppMessage from "./SendWhatsAppMessage";
import Whatsapp from "../../models/Whatsapp";
import { splitDateTime } from "../../helpers/SplitDateTime";
//
@ -185,7 +190,7 @@ const verifyQueue = async (
const botInfo = await BotIsOnQueue('botqueue')
if(botInfo.isOnQueue){
if (botInfo.isOnQueue) {
choosenQueue = await ShowQueueService(botInfo.botQueueId);
@ -195,7 +200,7 @@ const verifyQueue = async (
selectedOption = 1;
choosenQueue = queues[+selectedOption - 1];
}
else{
else {
selectedOption = msg.body;
@ -211,9 +216,9 @@ const verifyQueue = async (
if (choosenQueue) {
// Atualizando o status do ticket para mostrar notificação para o atendente da fila escolhida pelo usuário. De queueChoice para pending
if(queues.length > 1 && !botInfo.isOnQueue){
if (queues.length > 1 && !botInfo.isOnQueue) {
await ticket.update({status: "pending" });
await ticket.update({ status: "pending" });
}
//
@ -227,10 +232,10 @@ const verifyQueue = async (
let botOptions = ''
// O bot abre a mensagem na fila para atender o usuario
if(botInfo.isOnQueue){
if (botInfo.isOnQueue) {
await UpdateTicketService({
ticketData:{ status: 'open', userId: botInfo.userIdBot },
ticketData: { status: 'open', userId: botInfo.userIdBot },
ticketId: ticket.id
});
@ -240,10 +245,10 @@ const verifyQueue = async (
let body = ''
if(botOptions.length > 0){
if (botOptions.length > 0) {
body = `\u200e${choosenQueue.greetingMessage}\n\n${botOptions}\n${final_message.msg}`;
}
else{
else {
body = `\u200e${choosenQueue.greetingMessage}`;
}
@ -255,12 +260,12 @@ const verifyQueue = async (
//test del transfere o atendimento se entrar na ura infinita
let ticket_message = await ShowTicketMessage(ticket.id, false);
if(ticket_message.length > 10){
if (ticket_message.length > 10) {
await UpdateTicketService({ ticketData: {status: 'pending', queueId: queues[0].id }, ticketId: ticket.id });
await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues[0].id }, ticketId: ticket.id });
}
else{
else {
let options = "";
@ -306,30 +311,30 @@ const isValidMsg = (msg: WbotMessage): boolean => {
};
const queuesOutBot =async (wbot:Session, botId: string | number) => {
const queuesOutBot = async (wbot: Session, botId: string | number) => {
const { queues, greetingMessage } = await ShowWhatsAppService(wbot.id!);
const indexQueue = queues.findIndex((q) => q.id == botId)
if(indexQueue != -1){
if (indexQueue != -1) {
queues.splice(indexQueue, 1)
}
return {queues, greetingMessage}
return { queues, greetingMessage }
}
const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: Session) =>{
const botTransferTicket = async (queues: Queue, ticket: Ticket, contact: Contact, wbot: Session) => {
await ticket.update({ userId: null });
await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues.id }, ticketId: ticket.id});
await UpdateTicketService({ ticketData: { status: 'pending', queueId: queues.id }, ticketId: ticket.id });
}
const botSendMessage = (ticket:Ticket, contact:Contact, wbot: Session, msg: string) => {
const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: string) => {
const debouncedSentMessage = debounce(
@ -353,6 +358,8 @@ const handleMessage = async (
return;
}
try {
let msgContact: WbotContact;
let groupContact: Contact | undefined;
@ -398,7 +405,7 @@ const handleMessage = async (
const contact = await verifyContact(msgContact);
if ( unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
const ticket = await FindOrCreateTicketService(
contact,
@ -414,7 +421,7 @@ const handleMessage = async (
// console.log('>>>>>>>>>>>>>> ticket.whatsappId: ', ticket.whatsappId)
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen
if(wbot.id != ticket.whatsappId){
if (wbot.id != ticket.whatsappId) {
await ticket.update({ whatsappId: wbot.id });
}
//
@ -444,10 +451,10 @@ const handleMessage = async (
const botInfo = await BotIsOnQueue('botqueue')
if( botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot){
if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) {
if(msg.body === '0'){
if (msg.body === '0') {
const queue = await ShowQueueService(ticket.queue.id);
@ -460,7 +467,7 @@ const handleMessage = async (
botSendMessage(ticket, contact, wbot, `${greetingMessage}\n\n${options}\n${final_message.msg}`)
}
else{
else {
// Pega as ultimas 9 opções numericas digitadas pelo cliente em orde DESC
@ -471,11 +478,11 @@ const handleMessage = async (
let ura_length = data_ura.length
let indexAttendant = data_ura.findIndex((u) => u.atendente )
let indexAttendant = data_ura.findIndex((u) => u.atendente)
let opt_user_attendant = '-1'
if(indexAttendant != -1){
if (indexAttendant != -1) {
opt_user_attendant = data_ura[indexAttendant].id
}
@ -483,7 +490,7 @@ const handleMessage = async (
let ticket_message = await ShowTicketMessage(ticket.id, true, ura_length, `^[0-${ura_length}}]$`);
if(ticket_message.length > 1){
if (ticket_message.length > 1) {
lastOption = ticket_message[1].body
@ -491,17 +498,17 @@ const handleMessage = async (
const queues = queuesWhatsGreetingMessage.queues
if(queues.length > 1){
if (queues.length > 1) {
const index_opt_user_attendant = ticket_message.findIndex((q) => q.body == opt_user_attendant)
const index0 = ticket_message.findIndex((q) => q.body == '0')
if(index_opt_user_attendant != -1){
if (index_opt_user_attendant != -1) {
if(index0 > -1 && index0 < index_opt_user_attendant){
if (index0 > -1 && index0 < index_opt_user_attendant) {
lastOption = ''
}
else{
else {
lastOption = opt_user_attendant
}
}
@ -518,15 +525,15 @@ const handleMessage = async (
//console.log('¨¨¨¨¨¨¨¨¨¨¨¨¨¨ MSG.BODY: ', msg.body , ' | opt_user_attendant: ',opt_user_attendant, ' | lastOption: ', lastOption)
// È numero
if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= data_ura.length) ) {
if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= data_ura.length)) {
const indexUra = data_ura.findIndex((ura) => ura.id == msg.body.trim())
if(indexUra != -1){
if (indexUra != -1) {
if(data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant){
if (data_ura[indexUra].id != opt_user_attendant && lastOption != opt_user_attendant) {
@ -535,15 +542,15 @@ const handleMessage = async (
// test del
let next = true
let indexAux = ticket_message.findIndex((e)=>e.body=='0')
let indexAux = ticket_message.findIndex((e) => e.body == '0')
let listMessage = null
if(indexAux!=-1){
if (indexAux != -1) {
listMessage = ticket_message.slice(0, indexAux)
}
else{
else {
listMessage = ticket_message
@ -552,12 +559,12 @@ const handleMessage = async (
let id = ''
let subUra = null
if(listMessage.length > 1){
if (listMessage.length > 1) {
id = listMessage[listMessage.length-1].body
subUra = data_ura.filter((e)=>e.id == id )[0]
id = listMessage[listMessage.length - 1].body
subUra = data_ura.filter((e) => e.id == id)[0]
if(subUra && (!subUra.subOptions || subUra.subOptions.length == 0)){
if (subUra && (!subUra.subOptions || subUra.subOptions.length == 0)) {
listMessage.pop()
@ -566,22 +573,22 @@ const handleMessage = async (
}
if(listMessage.length > 1){
if (listMessage.length > 1) {
id = listMessage[listMessage.length-1].body
subUra = data_ura.filter((e)=>e.id == id )[0]
id = listMessage[listMessage.length - 1].body
subUra = data_ura.filter((e) => e.id == id)[0]
if(subUra.subOptions && subUra.subOptions.length > 0){
if (subUra.subOptions && subUra.subOptions.length > 0) {
if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= subUra.subOptions?.length) && subUra.subOptions ) {
if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= subUra.subOptions?.length) && subUra.subOptions) {
if(subUra.subOptions[+msg.body - 1].responseToClient){
if (subUra.subOptions[+msg.body - 1].responseToClient) {
botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].responseToClient}`)
}
else{
else {
botSendMessage(ticket, contact, wbot, `*${subUra.option}*\n\n${subUra.subOptions[+msg.body - 1].subOpt}`)
}
@ -589,18 +596,18 @@ const handleMessage = async (
const queues = queuesWhatsGreetingMessage.queues
if(queues.length>0){
if (queues.length > 0) {
await botTransferTicket(queues[0], ticket, contact, wbot)
}
else{
else {
console.log('NO QUEUE!')
}
}
else{
else {
let options = "";
let subOptions:any[] = subUra.subOptions
let subOptions: any[] = subUra.subOptions
subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` });
@ -616,12 +623,12 @@ const handleMessage = async (
//
if(next){
if(data_ura[indexUra].subOptions && data_ura[indexUra].subOptions.length > 0){
if (next) {
if (data_ura[indexUra].subOptions && data_ura[indexUra].subOptions.length > 0) {
let options = "";
let option = data_ura[indexUra].option
let subOptions:any[] = data_ura[indexUra].subOptions
let subOptions: any[] = data_ura[indexUra].subOptions
let description = data_ura[indexUra].description
subOptions?.forEach((s, index) => { options += `*${index + 1}* - ${s.subOpt}\n` });
@ -631,14 +638,14 @@ const handleMessage = async (
botSendMessage(ticket, contact, wbot, `*${option}*\n\n${body}\n\n *0* - Voltar ao menu principal`)
}
else{
else {
//test del deletar isso (Usar somente na hit)
if(data_ura[indexUra].closeChat){
if (data_ura[indexUra].closeChat) {
const {ticket :res} = await UpdateTicketService({
ticketData:{'status': 'closed', 'userId': botInfo.userIdBot}, ticketId: ticket.id
const { ticket: res } = await UpdateTicketService({
ticketData: { 'status': 'closed', 'userId': botInfo.userIdBot }, ticketId: ticket.id
});
///////////////////////////////
@ -652,7 +659,7 @@ const handleMessage = async (
///////////////////////////////
}
else{
else {
botSendMessage(ticket, contact, wbot, `${data_ura[indexUra].description}\n\n *0* - Voltar ao menu principal`)
}
//
@ -664,14 +671,14 @@ const handleMessage = async (
}
}
else if(data_ura[indexUra].id == opt_user_attendant){
else if (data_ura[indexUra].id == opt_user_attendant) {
const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId)
const queues = queuesWhatsGreetingMessage.queues
// Se fila for maior que 1 exibi as opções fila para atendimento humano
if(queues.length > 1){
if (queues.length > 1) {
let options = "";
@ -686,7 +693,7 @@ const handleMessage = async (
botSendMessage(ticket, contact, wbot, body)
} // Para situações onde há apenas uma fila com exclusão da fila do bot, já direciona o cliente para essa fila de atendimento humano
else if(queues.length == 1){
else if (queues.length == 1) {
await botTransferTicket(queues[0], ticket, contact, wbot)
@ -694,20 +701,20 @@ const handleMessage = async (
}
}
else if (lastOption == opt_user_attendant){
else if (lastOption == opt_user_attendant) {
const queuesWhatsGreetingMessage = await queuesOutBot(wbot, botInfo.botQueueId)
const queues = queuesWhatsGreetingMessage.queues
// É numero
if( !Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= queues.length) ) {
if (!Number.isNaN(Number(msg.body.trim())) && (+msg.body >= 0 && +msg.body <= queues.length)) {
await botTransferTicket(queues[+msg.body - 1], ticket, contact, wbot)
botSendMessage(ticket, contact, wbot, `${msg_client_transfer.msg}`)
}
else{
else {
botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções de atendimento\n\n*0* - Voltar ao menu principal`)
@ -718,15 +725,15 @@ const handleMessage = async (
}
}
else{
else {
// É numero
if(!Number.isNaN(Number(msg.body.trim()))){
if (!Number.isNaN(Number(msg.body.trim()))) {
botSendMessage(ticket, contact, wbot, `Opção numérica inválida!\nDigite um dos números mostrados no menu de opções\n\n*0* - Voltar ao menu principal`)
}
else{
else {
botSendMessage(ticket, contact, wbot, `Digite um número válido disponível no menu de opções\n\n*0* - Voltar ao menu principal`)
@ -741,6 +748,17 @@ const handleMessage = async (
//
// test del
// if (msg.body.trim() == 'broken') {
// throw new Error('Throw makes it go boom!')
// }
// console.log('>>>>>>>>>>>> whatsapp.status: ', whatsapp.status)
//
// test del
// console.log('WBOT.id: ',wbot.id)
@ -767,6 +785,32 @@ const handleMessage = async (
Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`);
//Solução para contornar erro de sessão
if ((`${err}`).includes("Evaluation failed: r")) {
const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions`)
let log = new Date(new Date() + 'UTC');
const dateToday = splitDateTime(new Date(format(new Date(), 'yyyy-MM-dd HH:mm:ss', { locale: ptBR })))
const whatsapp = await ShowWhatsAppService(wbot.id!);
if (whatsapp.status == 'CONNECTED') {
console.log('wbotMessageListener.ts - ENTROU NO RESTORE...')
let timestamp = Math.floor(Date.now() / 1000)
fs.writeFile(`${sourcePath}/${timestamp}_wbotMessageListener.txt`, `Whatsapp id: ${whatsapp.id} \nDate: ${dateToday.fullDate} ${dateToday.fullTime} \nFile: wbotMessageListener.ts \nError: ${err}`, (error)=>{});
await restartWhatsSession(whatsapp)
console.log('...PASSOU O RESTORE - wbotMessageListener.ts ')
}
}
}
};

View File

@ -283,7 +283,7 @@ const reducer = (state, action) => {
state[messageIndex] = newMessage;
} else {
state.push(newMessage);
console.log(' TESTANDO NOVA MENSAGEM: ', newMessage)
// console.log(' TESTANDO NOVA MENSAGEM: ', newMessage)
}
return [...state];
@ -365,7 +365,7 @@ const MessagesList = ({ ticketId, isGroup }) => {
if (data.action === "create") {
dispatch({ type: "ADD_MESSAGE", payload: data.message });
console.log('* NOVA MENSAGEM CAP: ', data.message)
// console.log('* NOVA MENSAGEM CAP: ', data.message)
scrollToBottom();
}

View File

@ -61,7 +61,7 @@ const NotificationsPopOver = () => {
const { handleLogout } = useContext(AuthContext);
const [lastRef] = useState(+history.location.pathname.split("/")[2])
// const [lastRef] = useState(+history.location.pathname.split("/")[2])
// console.log('ticketIdRef: ',ticketIdRef, ' | lastRef: ',lastRef)
@ -168,12 +168,16 @@ const NotificationsPopOver = () => {
});
socket.on("appMessage", data => {
// console.log('******************* DATA: ', data)
if (
data.action === "create" &&
!data.message.read &&
(data.ticket.userId === user?.id || !data.ticket.userId)
) {
// console.log('entrou.............')
setNotifications(prevState => {
@ -195,6 +199,7 @@ const NotificationsPopOver = () => {
});
const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") ||
(data.ticket.userId && data.ticket.userId !== user?.id) ||
data.ticket.isGroup || !data.ticket.userId;
@ -203,7 +208,6 @@ const NotificationsPopOver = () => {
//console.log('PASSOU!!!!!!!')
handleNotifications(data);
}
});

View File

@ -221,6 +221,14 @@ const TicketListItem = ({ ticket }) => {
badge: classes.badgeStyle,
}}
/>
{/* <Badge
className={classes.newMessagesCount}
badgeContent={ticket.unreadMessages}
classes={{
badge: classes.badgeStyle,
}}
/> */}
</span>
}
/>

View File

@ -77,6 +77,9 @@ const reducer = (state, action) => {
newTickets.forEach(ticket => {
// console.log('* ticket.unreadMessages: ',ticket.unreadMessages)
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
@ -105,6 +108,8 @@ const reducer = (state, action) => {
if (action.type === "UPDATE_TICKET") {
const ticket = action.payload;
// console.log('++++++++++++ UPDATE_TICKET: ',ticket)
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
state[ticketIndex] = ticket;
@ -116,12 +121,26 @@ const reducer = (state, action) => {
}
if (action.type === "UPDATE_TICKET_UNREAD_MESSAGES") {
const ticket = action.payload;
const message = action.payload.message
const ticket = action.payload.ticket;
const ticketIndex = state.findIndex(t => t.id === ticket.id);
if (ticketIndex !== -1) {
// console.log('>>>>>> ticketIndex: ', ticketIndex)
// console.log('&&&&&&& UPDATE_TICKET_UNREAD_MESSAGES ticket: ',ticket, ' |\n MESSAGE: ', message)
if(!message.fromMe){
ticket.unreadMessages +=1
}
state[ticketIndex] = ticket;
state.unshift(state.splice(ticketIndex, 1)[0]);
} else {
state.unshift(ticket);
}
@ -227,9 +246,13 @@ const TicketsList = (props) => {
socket.on("appMessage", data => {
if (data.action === "create" && shouldUpdateTicket(data.ticket)) {
// console.log('((((((((((((((((((( DATA.MESSAGE: ', data.message)
dispatch({
type: "UPDATE_TICKET_UNREAD_MESSAGES",
payload: data.ticket,
// payload: data.ticket,
payload: data,
});
}
});