Finalização do recurso de restore e notificação na primeira mensagem

pull/3/head
adriano 2022-07-14 20:00:35 -03:00
parent 5444baafc3
commit 10819163e9
9 changed files with 101 additions and 26 deletions

View File

@ -1 +0,0 @@
Whatsapp id: 33 | Fri Jul 08 2022 15:02:50 GMT-0300 (Brasilia Standard Time)

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

@ -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(
@ -17,8 +26,13 @@ const SetTicketMessagesAsRead = async (ticket: Ticket): Promise<void> => {
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<void> => {
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

@ -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 ')
}
}

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,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}
>
<List dense className={classes.tabContainer}>
{notifications.length === 0 ? (
<ListItem>
{notifications.length === 0 ? (
<ListItem>
<ListItemText>{i18n.t("notifications.noTickets")}</ListItemText>
</ListItem>
) : (

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

@ -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,
});
}
});

View File

@ -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 });
}