From 75fd79fc8d38e0170a4c155849b4cbed3ef6c621 Mon Sep 17 00:00:00 2001
From: adriano <adriano08andra@hotmail.com>
Date: Wed, 20 Jul 2022 12:34:12 -0300
Subject: [PATCH] =?UTF-8?q?Desabilita=C3=A7=C3=A3o=20do=20recurso=20de=20p?=
 =?UTF-8?q?esquisar=20relatorio=20a=20partir=20de=20datas=20anteriores=20a?=
 =?UTF-8?q?=20atual.=20Desabilita=C3=A7=C3=A3o=20do=20metodo=20que=20verif?=
 =?UTF-8?q?ica=20o=20bot=20para=20intera=C3=A7=C3=A3o=20com=20o=20usuario?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 backend/src/controllers/MessageController.ts  | 27 ++++++++-
 .../controllers/WhatsAppSessionController.ts  |  3 +-
 backend/src/libs/wbot.ts                      | 10 +++-
 .../FindOrCreateTicketService.ts              |  6 +-
 .../WbotServices/SendWhatsAppMedia.ts         |  6 +-
 .../WbotServices/wbotMessageListener.ts       | 56 +++++++------------
 frontend/src/pages/Report/index.js            | 10 ++--
 7 files changed, 66 insertions(+), 52 deletions(-)

diff --git a/backend/src/controllers/MessageController.ts b/backend/src/controllers/MessageController.ts
index bfcac7a..84c7cf3 100644
--- a/backend/src/controllers/MessageController.ts
+++ b/backend/src/controllers/MessageController.ts
@@ -47,13 +47,36 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
 
   if (medias) {
     await Promise.all(
-      medias.map(async (media: Express.Multer.File) => {
+      medias.map(async (media: Express.Multer.File) => { 
+
+        console.log(`\n >>>>>>>>>> SENDING MESSAGE MEDIA
+        Parcial ticket info and media: 
+        ticket.id: ${ticket.id}
+        ticket.status: ${ticket.status}
+        ticket.whatsapp.id: ${ticket.whatsappId}
+        ticket.contact.number: ${ticket.contact.number}
+        ticket.contact.name: ${ticket.contact.name}
+        ticket.contact.profilePicUrl: ${ticket.contact.profilePicUrl}
+        ticket.user.id: ${ticket.user.id}
+        ticket.user.name: ${ticket.user.name}
+        media:`, media,'\n')
+
         await SendWhatsAppMedia({ media, ticket });
       })
     );
   } else {
 
-    console.log('------- quotedMsg: ', quotedMsg, ' | ticket: ', ticket)
+    console.log(`\n >>>>>>>>>> SENDING MESSAGE
+    Parcial ticket info: 
+    ticket.id: ${ticket.id}
+    ticket.status: ${ticket.status}
+    ticket.whatsapp.id: ${ticket.whatsappId}
+    ticket.contact.number: ${ticket.contact.number}
+    ticket.contact.name: ${ticket.contact.name}
+    ticket.contact.profilePicUrl: ${ticket.contact.profilePicUrl}
+    ticket.user.id: ${ticket.user.id}
+    ticket.user.name: ${ticket.user.name}\n`)
+    
 
     await SendWhatsAppMessage({ body, ticket, quotedMsg });
   }
diff --git a/backend/src/controllers/WhatsAppSessionController.ts b/backend/src/controllers/WhatsAppSessionController.ts
index 62c645f..596c5de 100644
--- a/backend/src/controllers/WhatsAppSessionController.ts
+++ b/backend/src/controllers/WhatsAppSessionController.ts
@@ -44,7 +44,8 @@ const restart = async (req: Request, res: Response): Promise<Response> => {
 
   const whatsapp = await ShowWhatsAppService(whatsappId);
 
-  restartWhatsSession(whatsapp, true)
+  // restartWhatsSession(whatsapp, true)
+  restartWhatsSession(whatsapp)
 
   return res.status(200).json({ message: "Starting session." });
 };
diff --git a/backend/src/libs/wbot.ts b/backend/src/libs/wbot.ts
index a3cdfdb..079022b 100644
--- a/backend/src/libs/wbot.ts
+++ b/backend/src/libs/wbot.ts
@@ -35,7 +35,7 @@ const syncUnreadMessages = async (wbot: Session) => {
       });
 
       for (const msg of unreadMessages) {
-        console.log('--BACKEND MSG: ', msg)
+        // console.log('--BACKEND MSG: ', msg)
         await handleMessage(msg, wbot);
       }
 
@@ -59,9 +59,15 @@ export const initWbot = async (whatsapp: Whatsapp, backupSessionRestore: boolean
 
 
       //NOVA OPÇÃO MD
+      // const wbot: Session = new Client({
+      //   session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }),
+      //   puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
+      // });
+
+      // usando instancia do chrome
       const wbot: Session = new Client({
         session: sessionCfg, authStrategy: new LocalAuth({ clientId: 'bd_' + whatsapp.id }),
-        puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || undefined },
+        puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN ||  '/usr/bin/google-chrome-stable'  },
       });
 
 
diff --git a/backend/src/services/TicketServices/FindOrCreateTicketService.ts b/backend/src/services/TicketServices/FindOrCreateTicketService.ts
index 1166db3..35d2c8a 100644
--- a/backend/src/services/TicketServices/FindOrCreateTicketService.ts
+++ b/backend/src/services/TicketServices/FindOrCreateTicketService.ts
@@ -27,8 +27,10 @@ const FindOrCreateTicketService = async (
     
 
   const { queues, greetingMessage } = await ShowWhatsAppService(whatsappId);   
-     
-  const botInfo = await BotIsOnQueue('botqueue') 
+  
+  //Habilitar esse caso queira usar o bot
+  // const botInfo = await BotIsOnQueue('botqueue') 
+  const botInfo = {isOnQueue: false}
  
       
 
diff --git a/backend/src/services/WbotServices/SendWhatsAppMedia.ts b/backend/src/services/WbotServices/SendWhatsAppMedia.ts
index 455d5c3..bb64bd3 100644
--- a/backend/src/services/WbotServices/SendWhatsAppMedia.ts
+++ b/backend/src/services/WbotServices/SendWhatsAppMedia.ts
@@ -18,11 +18,7 @@ const SendWhatsAppMedia = async ({
 
     const newMedia = MessageMedia.fromFilePath(media.path);
 
-    const sentMessage = await wbot.sendMessage(
-      `${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`,
-      newMedia,
-      { sendAudioAsVoice: true }
-    );
+    const sentMessage = await wbot.sendMessage(`${ticket.contact.number}@${ticket.isGroup ? "g" : "c"}.us`, newMedia, { sendAudioAsVoice: true });
 
     await ticket.update({ lastMessage: media.filename });
 
diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts
index 4098244..961fb99 100644
--- a/backend/src/services/WbotServices/wbotMessageListener.ts
+++ b/backend/src/services/WbotServices/wbotMessageListener.ts
@@ -186,9 +186,9 @@ const verifyQueue = async (
   let selectedOption = null;
   let choosenQueue = null
 
-
-  const botInfo = await BotIsOnQueue('botqueue')
-
+  //Habilitar esse caso queira usar o bot
+  // const botInfo = await BotIsOnQueue('botqueue')  
+   const botInfo = {isOnQueue: false, botQueueId: 0, userIdBot: 0}
 
   if (botInfo.isOnQueue) {
 
@@ -376,11 +376,21 @@ const handleMessage = async (
       msgContact = await wbot.getContactById(msg.to);
     } else {
 
-      msgContact = await msg.getContact();
+      msgContact = await msg.getContact(); 
 
-      //console.log('-----msgContact TESTE MSG: ', msgContact, '  |  msg.body: ', msg.body)
+      // console.log('-----msgContact TESTE MSG2: ', msgContact, '  |  msg: ', msg)
 
-      console.log('-----msgContact TESTE MSG2: ', msgContact, '  |  msg: ', msg)
+      console.log(`\n <<<<<<<<<< RECEIVING MESSAGE: 
+      Parcial msg and msgContact info: 
+      msgContact.name: ${msgContact.name}
+      msgContact.pushname: ${msgContact.pushname}
+      msgContact.shortName: ${msgContact.shortName}
+      msg.id.fromMe: ${msg.id.fromMe}
+      msg.id.id: ${msg.id.id}
+      msg.body: ${msg.body}
+      msg.type: ${msg.type}
+      msg.from: ${msg.from}
+      msg.to: ${msg.to}\n`)
 
     }
 
@@ -448,8 +458,10 @@ const handleMessage = async (
 
 
     // O bot interage com o cliente e encaminha o atendimento para fila de atendende quando o usuário escolhe a opção falar com atendente
-
-    const botInfo = await BotIsOnQueue('botqueue')
+    
+    //Habilitar esse caso queira usar o bot
+    // const botInfo = await BotIsOnQueue('botqueue')
+      const botInfo = {isOnQueue: false, botQueueId: 0, userIdBot: 0}
 
     if (botInfo.isOnQueue && !msg.fromMe && ticket.userId == botInfo.userIdBot) {
 
@@ -752,33 +764,7 @@ const handleMessage = async (
 
     // 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)
-
-    // const sourcePath = path.join(__dirname,`../../../.wwebjs_auth/sessions/`, `session-bd_${wbot.id}`)
-    // const destPath =  path.join(__dirname,`../../../.wwebjs_auth/`, `session-bd_${wbot.id}`)
-
-    // console.log('================sourcePath: ', sourcePath)
-    // console.log('================sourcePath: ', destPath) 
-
-    // removeWbot(33)
-
-    // await removeDir(destPath) 
-
-    // copyFolder(sourcePath, destPath) 
-
-    // await StartWhatsAppSession(whatsapp);
-
-    // console.log('RESTARTING SESSION...')         
-    //
+    // } 
 
 
   } catch (err) {
diff --git a/frontend/src/pages/Report/index.js b/frontend/src/pages/Report/index.js
index 9912cf2..4b5d94d 100644
--- a/frontend/src/pages/Report/index.js
+++ b/frontend/src/pages/Report/index.js
@@ -639,7 +639,7 @@ const Report = () => {
               return { 'value': obj.id, 'label': obj.name }
             })} /></Item>
 
-            <Item><DatePicker1 func={datePicker1Value} minDate={false} startEmpty={false} title={'Data inicio'} /></Item>
+            <Item><DatePicker1 func={datePicker1Value} minDate={true} startEmpty={false} title={'Data inicio'} /></Item>
             <Item><DatePicker2 func={datePicker2Value} minDate={false} startEmpty={false} title={'Data fim'} /></Item>
 
             <Item sx={{ display: 'grid', gridColumn: '4 / 5', }}>
@@ -650,14 +650,14 @@ const Report = () => {
 
               {reportOption === '1' &&
 
-                <div>
-                  <Button
-                    variant="contained"
+                <div> 
+                  {/* <Button
+                    variant="contained" 
                     color="primary"
                     onClick={(e) => handleCSVMessages()}
                   >
                     {"CSV ALL"}
-                  </Button>
+                  </Button> */}
 
                   <div>
                     <CSVLink