From 10819163e9cfe04cbbd8c269b50d8c1f48a379d0 Mon Sep 17 00:00:00 2001 From: adriano Date: Thu, 14 Jul 2022 20:00:35 -0300 Subject: [PATCH] =?UTF-8?q?Finaliza=C3=A7=C3=A3o=20do=20recurso=20de=20res?= =?UTF-8?q?tore=20e=20notifica=C3=A7=C3=A3o=20na=20primeira=20mensagem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/.wwebjs_auth/sessions/1657314170.txt | 1 - backend/src/controllers/MessageController.ts | 3 -- .../src/helpers/SetTicketMessagesAsRead.ts | 42 ++++++++++++++++++- .../WbotServices/wbotMessageListener.ts | 18 +++++--- frontend/src/components/MessagesList/index.js | 4 +- .../components/NotificationsPopOver/index.js | 18 ++++---- .../src/components/TicketListItem/index.js | 8 ++++ frontend/src/components/TicketsList/index.js | 31 ++++++++++++-- frontend/src/hooks/useWhatsApps/index.js | 2 +- 9 files changed, 101 insertions(+), 26 deletions(-) delete mode 100644 backend/.wwebjs_auth/sessions/1657314170.txt diff --git a/backend/.wwebjs_auth/sessions/1657314170.txt b/backend/.wwebjs_auth/sessions/1657314170.txt deleted file mode 100644 index 22950ec..0000000 --- a/backend/.wwebjs_auth/sessions/1657314170.txt +++ /dev/null @@ -1 +0,0 @@ -Whatsapp id: 33 | Fri Jul 08 2022 15:02:50 GMT-0300 (Brasilia Standard Time) \ No newline at end of file diff --git a/backend/src/controllers/MessageController.ts b/backend/src/controllers/MessageController.ts index d752323..bfcac7a 100644 --- a/backend/src/controllers/MessageController.ts +++ b/backend/src/controllers/MessageController.ts @@ -37,9 +37,6 @@ export const index = async (req: Request, res: Response): Promise => { export const store = async (req: Request, res: Response): Promise => { - - - const { ticketId } = req.params; const { body, quotedMsg }: MessageData = req.body; const medias = req.files as Express.Multer.File[]; diff --git a/backend/src/helpers/SetTicketMessagesAsRead.ts b/backend/src/helpers/SetTicketMessagesAsRead.ts index 27fbf6c..379f18a 100644 --- a/backend/src/helpers/SetTicketMessagesAsRead.ts +++ b/backend/src/helpers/SetTicketMessagesAsRead.ts @@ -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 => { await Message.update( @@ -17,8 +26,13 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise => { await ticket.update({ unreadMessages: 0 }); - try { - const wbot = await GetTicketWbot(ticket); + try { + + const wbot = await GetTicketWbot(ticket); + + // test del + // throw new Error('Throw makes it go boom!') + // await wbot.sendSeen(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`); @@ -26,6 +40,30 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise => { 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(); diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 3b9b488..4098244 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -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, @@ -45,6 +48,7 @@ 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"; // @@ -782,25 +786,27 @@ const handleMessage = async ( logger.error(`Error handling whatsapp message: Err: ${err}`); //Solução para contornar erro de sessão - if ((`${err}`).includes(" Evaluation failed: r ")) { + 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('ENTROU NO RESTORE...') + + console.log('wbotMessageListener.ts - ENTROU NO RESTORE...') let timestamp = Math.floor(Date.now() / 1000) - fs.writeFile(`${sourcePath}/${timestamp}.txt`, `Whatsapp id: ${whatsapp.id} | ${log}`, (error)=>{}); + 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') + + console.log('...PASSOU O RESTORE - wbotMessageListener.ts ') } } diff --git a/frontend/src/components/MessagesList/index.js b/frontend/src/components/MessagesList/index.js index d3a61de..0344c7b 100644 --- a/frontend/src/components/MessagesList/index.js +++ b/frontend/src/components/MessagesList/index.js @@ -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(); } diff --git a/frontend/src/components/NotificationsPopOver/index.js b/frontend/src/components/NotificationsPopOver/index.js index 411b4d2..29fb824 100644 --- a/frontend/src/components/NotificationsPopOver/index.js +++ b/frontend/src/components/NotificationsPopOver/index.js @@ -61,9 +61,9 @@ 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) + // console.log('ticketIdRef: ',ticketIdRef, ' | lastRef: ',lastRef) useEffect(() => { @@ -82,7 +82,7 @@ const NotificationsPopOver = () => { useEffect(() => { - console.log('888888888888888888888888888888888888888888888888888888888888888888') + // console.log('888888888888888888888888888888888888888888888888888888888888888888') ticketIdRef.current = ticketIdUrl; }, [ticketIdUrl]); @@ -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 => { @@ -194,6 +198,7 @@ const NotificationsPopOver = () => { return [data.ticket, ...prevState]; }); + const shouldNotNotificate = (data.message.ticketId === ticketIdRef.current && document.visibilityState === "visible") || (data.ticket.userId && data.ticket.userId !== user?.id) || @@ -201,8 +206,7 @@ const NotificationsPopOver = () => { if (shouldNotNotificate) return; - //console.log('PASSOU!!!!!!!') - + //console.log('PASSOU!!!!!!!') handleNotifications(data); } @@ -289,8 +293,8 @@ const NotificationsPopOver = () => { onClose={handleClickAway} > - {notifications.length === 0 ? ( - + {notifications.length === 0 ? ( + {i18n.t("notifications.noTickets")} ) : ( diff --git a/frontend/src/components/TicketListItem/index.js b/frontend/src/components/TicketListItem/index.js index 8ddff74..f7460bf 100644 --- a/frontend/src/components/TicketListItem/index.js +++ b/frontend/src/components/TicketListItem/index.js @@ -221,6 +221,14 @@ const TicketListItem = ({ ticket }) => { badge: classes.badgeStyle, }} /> + + {/* */} } /> diff --git a/frontend/src/components/TicketsList/index.js b/frontend/src/components/TicketsList/index.js index bae4c01..1fb3263 100644 --- a/frontend/src/components/TicketsList/index.js +++ b/frontend/src/components/TicketsList/index.js @@ -73,10 +73,13 @@ const useStyles = makeStyles(theme => ({ const reducer = (state, action) => { if (action.type === "LOAD_TICKETS") { - const newTickets = action.payload; - + const newTickets = action.payload; + 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, }); } }); diff --git a/frontend/src/hooks/useWhatsApps/index.js b/frontend/src/hooks/useWhatsApps/index.js index 30a6aa9..19e8717 100644 --- a/frontend/src/hooks/useWhatsApps/index.js +++ b/frontend/src/hooks/useWhatsApps/index.js @@ -115,7 +115,7 @@ const useWhatsApps = () => { socket.on("whatsappSessionMonit", data => { if (data.action === "update") { - console.log('data.whatsappSessionSize: ', data.whatsappSessionSize) + // console.log('data.whatsappSessionSize: ', data.whatsappSessionSize) dispatch({ type: "UPDATE_WHATSAPPS_SESSION_MONIT", payload: data.whatsappSessionSize }); }