identaçao de codigo

pull/21/head
adriano 2023-01-20 16:38:24 -03:00
parent 6673faccbb
commit 69ddcc7c50
9 changed files with 46 additions and 81 deletions

View File

@ -35,7 +35,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
return res.json({ count, messages, ticket, hasMore }); return res.json({ count, messages, ticket, hasMore });
}; };
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params; const { ticketId } = req.params;
const { body, quotedMsg }: MessageData = req.body; const { body, quotedMsg }: MessageData = req.body;
@ -43,6 +43,8 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
const ticket = await ShowTicketService(ticketId); const ticket = await ShowTicketService(ticketId);
console.log('TICKET ID: ', ticketId)
SetTicketMessagesAsRead(ticket); SetTicketMessagesAsRead(ticket);
if (medias) { if (medias) {

View File

@ -92,6 +92,7 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
export const store = async (req: Request, res: Response): Promise<Response> => { export const store = async (req: Request, res: Response): Promise<Response> => {
const { contactId, status, userId }: TicketData = req.body; const { contactId, status, userId }: TicketData = req.body;
console.log('TICKET CREATE: ', 'contactId: ', contactId, ' | status: ', status, ' | userId: ', userId)
// test del // test del
let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } }); let ticket = await Ticket.findOne({ where: { contactId, status: 'queueChoice' } });

View File

@ -238,39 +238,7 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
console.log(' PASSOU NO TIMEOUT whatsapp.id: ', whatsapp.id) console.log(' PASSOU NO TIMEOUT whatsapp.id: ', whatsapp.id)
} }
// for (let i = 0; i <= 25; i++) {
// // console.log('Send: ', i, ' | miliseconds[Math.floor(Math.random() * miliseconds.length)]): ', miliseconds[Math.floor(Math.random() * miliseconds.length)])
// try {
// let stat = await wbot.getState();
// console.log('GET WHATSAPP STATE: ', stat)
// if (stat !== 'CONNECTED') break
// await wbot.sendMessage(`5517988325936@c.us`, `*@!ping*<>${whatsapp.name}\nIndex: ${i}`);
// await new Promise(r => setTimeout(r, miliseconds[Math.floor(Math.random() * miliseconds.length)]));
// } catch (error) {
// console.log(`Error on try send menssage boot from session: ${whatsapp.name}: ${error}`)
// break
// }
// }
}); });
} catch (err) { } catch (err) {
logger.error(`${err}`); logger.error(`${err}`);

View File

@ -17,5 +17,5 @@ if (global.gc) {
} }
initIO(server); initIO(server);
// StartAllWhatsAppsSessions(); StartAllWhatsAppsSessions();
gracefulShutdown(server); gracefulShutdown(server);

View File

@ -18,6 +18,9 @@ interface Request {
} }
const CreateMessageService = async ({ messageData }: Request): Promise<Message> => { const CreateMessageService = async ({ messageData }: Request): Promise<Message> => {
console.log('UPSERT MESSAGE messageData: ', messageData)
await Message.upsert(messageData); await Message.upsert(messageData);
const message = await Message.findByPk(messageData.id, { const message = await Message.findByPk(messageData.id, {
@ -55,6 +58,9 @@ const CreateMessageService = async ({ messageData }: Request): Promise<Message>
// //
console.log('Entrou no create message')
const io = getIO(); const io = getIO();
io.to(message.ticketId.toString()) io.to(message.ticketId.toString())
.to(message.ticket.status) .to(message.ticket.status)

View File

@ -50,16 +50,14 @@ const SendWhatsAppMessage = async ({
if (quotedMsg) { if (quotedMsg) {
await GetWbotMessage(ticket, quotedMsg.id); await GetWbotMessage(ticket, quotedMsg.id);
quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg); quotedMsgSerializedId = SerializeWbotMsgId(ticket, quotedMsg);
} }
const whatsapp = await Whatsapp.findByPk(ticket.whatsappId);
const whatsapp = await Whatsapp.findByPk(ticket.whatsappId);
if (whatsapp && whatsapp.status != 'CONNECTED') { if (whatsapp && whatsapp.status != 'CONNECTED') {
let whatsapps = await wbotByUserQueue(ticket.userId) let whatsapps = await wbotByUserQueue(ticket.userId)
// console.log('whatsapps whatsapps whatsapps: ', JSON.parse(JSON.stringify(whatsapps)))
if (whatsapps.length > 0) { if (whatsapps.length > 0) {
if (whatsapps.length > 1) { if (whatsapps.length > 1) {
@ -93,9 +91,10 @@ const SendWhatsAppMessage = async ({
console.timeEnd(timetaken) console.timeEnd(timetaken)
return sentMessage; return sentMessage;
} catch (err) { } catch (err) {
const whatsapp = await ShowWhatsAppService(ticket.whatsappId); const whatsapp = await ShowWhatsAppService(ticket.whatsappId);
throw new AppError("ERR_SENDING_WAPP_MSG"); throw new AppError("ERR_SENDING_WAPP_MSG");
} }

View File

@ -159,8 +159,11 @@ const verifyMessage = async (
contact: Contact contact: Contact
) => { ) => {
console.log('Entrou no verify message...')
const quotedMsg = await verifyQuotedMessage(msg); const quotedMsg = await verifyQuotedMessage(msg);
const messageData = { const messageData = {
id: msg.id.id, id: msg.id.id,
ticketId: ticket.id, ticketId: ticket.id,
@ -175,10 +178,6 @@ const verifyMessage = async (
await ticket.update({ lastMessage: msg.body }); await ticket.update({ lastMessage: msg.body });
// TEST DEL
// await updateTicketCacheByTicketId(ticket.id, { lastMessage: msg.body, updatedAt: new Date(ticket.updatedAt).toISOString() })
//
await CreateMessageService({ messageData }); await CreateMessageService({ messageData });
}; };
@ -373,42 +372,18 @@ const botSendMessage = (ticket: Ticket, contact: Contact, wbot: Session, msg: st
// const _clear_lst = () => { // const _clear_lst = () => {
// if (lst.length <= 199) return // if (lst.length <= 199) return
// const chunk: any = Math.floor((lst.length / 2)) // const chunk: any = Math.floor((lst.length / 2))
// lst = lst.slice(chunk, chunk + lst.length); // lst = lst.slice(chunk, chunk + lst.length);
// } // }
const handleMessage = async ( const handleMessage = async (
msg: WbotMessage, msg: WbotMessage,
wbot: Session wbot: Session
): Promise<void> => { ): Promise<void> => {
// TEST DEL MULTI SESSION
// _clear_lst()
// let index = lst.findIndex((x: any) => x.id == msg.id.id)
// console.log('INDEX: ', index)
// if (index == -1) {
// lst.push({ id: msg.id.id })
// }
// else {
// console.log('IGNORED ID: ', msg.id.id)
// return
// }
// // console.log('LIST OF ID MESSAGE lst: ', lst)
// console.log('PASSOU.................................FROM: ', msg.from.split("@")[0], ' | ID: ', msg.id.id)
if (!isValidMsg(msg)) { if (!isValidMsg(msg)) {
return; return;
} }
@ -424,15 +399,21 @@ const handleMessage = async (
// media messages sent from me from cell phone, first comes with "hasMedia = false" and type = "image/ptt/etc" // media messages sent from me from cell phone, first comes with "hasMedia = false" and type = "image/ptt/etc"
// in this case, return and let this message be handled by "media_uploaded" event, when it will have "hasMedia = true" // in this case, return and let this message be handled by "media_uploaded" event, when it will have "hasMedia = true"
if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard") return; if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard") return;
msgContact = await wbot.getContactById(msg.to); msgContact = await wbot.getContactById(msg.to);
console.log('1 --------------> msgContat: ', JSON.parse(JSON.stringify(msgContact)))
console.log(' # msg.type: ', msg.type )
} else { } else {
msgContact = await msg.getContact(); msgContact = await msg.getContact();
// console.log('2 --------------> msgContat: ', JSON.parse(JSON.stringify(msgContact)))
//
console.log(`\n <<<<<<<<<< RECEIVING MESSAGE: console.log(`\n <<<<<<<<<< RECEIVING MESSAGE:
Parcial msg and msgContact info: Parcial msg and msgContact info:
msgContact.name: ${msgContact.name} msgContact.name: ${msgContact.name}
@ -449,6 +430,7 @@ const handleMessage = async (
const chat = await msg.getChat(); const chat = await msg.getChat();
console.log('----------> chat: ', JSON.parse(JSON.stringify(chat)))
if (chat.isGroup) { if (chat.isGroup) {
let msgGroupContact; let msgGroupContact;
@ -467,6 +449,8 @@ const handleMessage = async (
const contact = await verifyContact(msgContact); const contact = await verifyContact(msgContact);
console.log('----------> contact: ', JSON.parse(JSON.stringify(contact)))
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return; if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
@ -483,9 +467,6 @@ const handleMessage = async (
// Para responder para o cliente pelo mesmo whatsapp que ele enviou a mensagen // 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 }); await ticket.update({ whatsappId: wbot.id });
} }
// //
@ -819,8 +800,8 @@ const handleMessage = async (
// if (msg.body.trim() == 'broken') { // if (msg.body.trim() == 'broken') {
// throw new Error('Throw makes it go boom!') // throw new Error('Throw makes it go boom!')
// } // }
// //
} catch (err) { } catch (err) {
Sentry.captureException(err); Sentry.captureException(err);
logger.error(`Error handling whatsapp message: Err: ${err}`); logger.error(`Error handling whatsapp message: Err: ${err}`);
@ -848,7 +829,7 @@ const handleMessage = async (
} }
else if (`${err}`.includes('[object Object]')) { else if (`${err}`.includes('[object Object]')) {
await _restore(whatsapp, 'auto_object_error') await _restore(whatsapp, 'auto_object_error')
} }
@ -876,6 +857,8 @@ const handleMsgAck = async (msg: WbotMessage, ack: MessageAck) => {
} }
await messageToUpdate.update({ ack }); await messageToUpdate.update({ ack });
console.log('ACK messageToUpdate: ', JSON.parse(JSON.stringify(messageToUpdate)))
io.to(messageToUpdate.ticketId.toString()).emit("appMessage", { io.to(messageToUpdate.ticketId.toString()).emit("appMessage", {
action: "update", action: "update",
message: messageToUpdate message: messageToUpdate
@ -888,6 +871,7 @@ const handleMsgAck = async (msg: WbotMessage, ack: MessageAck) => {
}; };
const wbotMessageListener = (wbot: Session): void => { const wbotMessageListener = (wbot: Session): void => {
wbot.on("message_create", async msg => { wbot.on("message_create", async msg => {
handleMessage(msg, wbot); handleMessage(msg, wbot);
}); });

View File

@ -319,6 +319,8 @@ const MessageInput = ({ ticketStatus }) => {
quotedMsg: replyingMessage, quotedMsg: replyingMessage,
}; };
try { try {
// console.log('message: ', message)
await api.post(`/messages/${ticketId}`, message); await api.post(`/messages/${ticketId}`, message);
} catch (err) { } catch (err) {
toastError(err); toastError(err);

View File

@ -364,6 +364,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
socket.on("appMessage", (data) => { socket.on("appMessage", (data) => {
if (data.action === "create") { if (data.action === "create") {
console.log('ADD_MESSAGE: ', data.message)
dispatch({ type: "ADD_MESSAGE", payload: data.message }); dispatch({ type: "ADD_MESSAGE", payload: data.message });
scrollToBottom(); scrollToBottom();