All files / controllers EvolutionWebhookController.js

0% Statements 0/158
0% Branches 0/57
0% Functions 0/7
0% Lines 0/158

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * EvolutionWebhookController.js
 * 
 * Controller for handling Evolution API webhooks
 * Processes incoming events from Evolution API
 * 
 * @module controllers/EvolutionWebhookController
 */
 
const { logger } = require('../config/logger');
const EvolutionInstance = require('../models/EvolutionInstance');
const eventBus = require('../core/whatsapp/EventBus');
const Events = require('../core/whatsapp/CoreEvents');
 
/**
 * Evolution Webhook Controller
 * Handles incoming webhooks from Evolution API
 */
class EvolutionWebhookController {
  /**
   * Handle webhook from Evolution API
   * POST /api/webhooks/evolution/:tenantId
   */
  static async handleWebhook(req, res) {
    try {
      console.log('\n\nπŸ””πŸ””πŸ”” WEBHOOK RECEIVED πŸ””πŸ””πŸ””');
      console.log('═══════════════════════════════════════════════════════════');
      console.log('⏰ Timestamp:', new Date().toISOString());
      console.log('πŸ“ Tenant ID:', req.params.tenantId);
      console.log('πŸ“¨ Event:', req.body.event);
      console.log('πŸ“± Instance:', req.body.instance);
      console.log('\nπŸ“‹ Headers:');
      console.log(JSON.stringify(req.headers, null, 2));
      console.log('\nπŸ“¦ Body completo:');
      console.log(JSON.stringify(req.body, null, 2));
      console.log('═══════════════════════════════════════════════════════════\n');
      
      const tenantId = parseInt(req.params.tenantId);
      const event = req.body.event;
      const data = req.body.data || req.body;
 
      logger.info('πŸ”” Evolution webhook received', { 
        tenantId, 
        event,
        instance: data.instance,
        bodyKeys: Object.keys(req.body),
        dataKeys: Object.keys(data),
        fullBody: JSON.stringify(req.body).substring(0, 500)
      });
 
      // Acknowledge webhook immediately
      res.status(200).json({ success: true });
 
      // Process webhook asynchronously - pass instance name from root level
      await this.processWebhook(tenantId, event, data, req.body.instance);
 
    } catch (error) {
      logger.error('Error handling Evolution webhook', { 
        error: error.message,
        stack: error.stack,
        body: req.body
      });
      
      // Still return 200 to prevent Evolution API from retrying
      res.status(200).json({ success: false, error: error.message });
    }
  }
 
  /**
   * Process webhook event
   * @param {number} tenantId - Tenant ID
   * @param {string} event - Event type
   * @param {Object} data - Event data
   * @param {string} instanceNameFromRoot - Instance name from root level
   */
  static async processWebhook(tenantId, event, data, instanceNameFromRoot) {
    try {
      console.log('\nπŸ”„ PROCESSANDO WEBHOOK:');
      console.log('   Tenant ID:', tenantId);
      console.log('   Event:', event);
      console.log('   Instance (root):', instanceNameFromRoot);
      console.log('   Instance (data):', data.instance);
      
      // Instance name can be at root level or inside data
      const instanceName = instanceNameFromRoot || data.instance;
 
      if (!instanceName) {
        console.log('❌ ERRO: Webhook sem nome de instÒncia');
        console.log('   Data keys:', Object.keys(data));
        logger.warn('Webhook received without instance name', { tenantId, event, dataKeys: Object.keys(data) });
        return;
      }
 
      console.log('   βœ… Instance name:', instanceName);
      console.log('   πŸ” Buscando instΓ’ncia no banco...');
 
      // Get instance from database
      const instance = await EvolutionInstance.getByEvolutionId(instanceName);
 
      if (!instance) {
        console.log('   ❌ ERRO: InstÒncia não encontrada no banco');
        logger.warn('Instance not found for webhook', { tenantId, instanceName, event });
        return;
      }
 
      console.log('   βœ… InstΓ’ncia encontrada:', instance.id, '-', instance.instance_name);
      console.log('   πŸ“Œ Tipo de evento:', event);
 
      // Handle different event types
      switch (event) {
        case 'QRCODE_UPDATED':
        case 'qrcode.updated':
          console.log('   πŸ“± Processando QR Code...');
          await this.handleQRCodeUpdate(instance, data);
          break;
 
        case 'CONNECTION_UPDATE':
        case 'connection.update':
          console.log('   πŸ”Œ Processando atualizaΓ§Γ£o de conexΓ£o...');
          await this.handleConnectionUpdate(instance, data);
          break;
 
        case 'MESSAGES_UPSERT':
        case 'messages.upsert':
          console.log('   πŸ’¬ Processando mensagem recebida...');
          await this.handleMessageReceived(instance, data);
          break;
 
        case 'MESSAGES_UPDATE':
        case 'messages.update':
          console.log('   ✏️ Processando atualização de mensagem...');
          await this.handleMessageUpdate(instance, data);
          break;
 
        case 'SEND_MESSAGE':
        case 'send.message':
          console.log('   πŸ“€ Processando mensagem enviada...');
          await this.handleMessageSent(instance, data);
          break;
 
        default:
          console.log('   ⚠️ Evento não tratado:', event);
          logger.info('Unhandled webhook event', { event, instanceName });
      }
      
      console.log('   βœ… Webhook processado com sucesso!\n');
 
    } catch (error) {
      console.error('   ❌ ERRO ao processar webhook:', error.message);
      logger.error('Error processing webhook', { 
        tenantId,
        event,
        error: error.message,
        stack: error.stack
      });
    }
  }
 
  /**
   * Handle QR code update
   * @param {Object} instance - Instance data
   * @param {Object} data - Event data
   */
  static async handleQRCodeUpdate(instance, data) {
    try {
      const qrCode = data.qrcode || data.qr || data.base64 || data.code;
 
      logger.info('QR code update received', { 
        instanceId: instance.id, 
        hasQrCode: !!qrCode,
        dataKeys: Object.keys(data)
      });
 
      if (!qrCode) {
        logger.warn('QR code update without QR data', { instanceId: instance.id, data });
        return;
      }
 
      logger.info('Updating QR code in database', { instanceId: instance.id });
 
      // Update instance with new QR code
      await EvolutionInstance.update(instance.id, {
        qr_code: qrCode,
        status: 'qr_code'
      });
 
      // Emit Socket.IO event to tenant
      const io = global.io;
      if (io) {
        const tenantNamespace = io.of(`/tenant/${instance.tenant_id}`);
        logger.info('Emitting QR code to socket', { 
          tenantId: instance.tenant_id,
          instanceId: instance.id 
        });
        
        // Emit both event names for compatibility
        tenantNamespace.emit('whatsapp-qr-updated', {
          instanceId: instance.id,
          instanceName: instance.instance_name,
          qrCode: qrCode
        });
        
        tenantNamespace.emit('qr-code', {
          instanceId: instance.id,
          instanceName: instance.instance_name,
          qrCode: qrCode
        });
      } else {
        logger.warn('Socket.IO not available');
      }
 
    } catch (error) {
      logger.error('Error handling QR code update', { 
        instanceId: instance.id,
        error: error.message
      });
    }
  }
 
  /**
   * Handle connection status update
   * @param {Object} instance - Instance data
   * @param {Object} data - Event data
   */
  static async handleConnectionUpdate(instance, data) {
    try {
      const state = data.state || data.status;
      const phoneNumber = data.phoneNumber || data.phone;
 
      logger.info('Connection status updated', { 
        instanceId: instance.id,
        state,
        phoneNumber
      });
 
      // Map Evolution API states to our status
      const statusMap = {
        'open': 'connected',
        'connecting': 'connecting',
        'close': 'disconnected',
        'qr': 'qr_code'
      };
 
      const newStatus = statusMap[state] || 'disconnected';
 
      // Update instance
      const updateData = { status: newStatus };
      
      if (phoneNumber) {
        updateData.phone_number = phoneNumber;
      }
 
      if (newStatus === 'connected') {
        updateData.last_connected_at = new Date().toISOString().slice(0, 19).replace('T', ' ');
        updateData.error_message = null;
        updateData.qr_code = null;
 
        // Fetch profile picture from Evolution API
        try {
          logger.info('Fetching profile picture for connected instance', { 
            instanceId: instance.id,
            evolutionInstanceId: instance.evolution_instance_id 
          });
 
          const instanceInfo = await EvolutionAPIService.getInstanceInfo(instance.evolution_instance_id);
          
          if (instanceInfo) {
            if (instanceInfo.profilePicUrl) {
              updateData.profile_picture_url = instanceInfo.profilePicUrl;
              logger.info('Profile picture URL saved', { 
                instanceId: instance.id,
                profilePicUrl: instanceInfo.profilePicUrl 
              });
            }
            
            if (instanceInfo.profileName) {
              updateData.profile_name = instanceInfo.profileName;
              logger.info('Profile name saved', { 
                instanceId: instance.id,
                profileName: instanceInfo.profileName 
              });
            }
          }
        } catch (profileError) {
          logger.error('Error fetching profile picture', {
            instanceId: instance.id,
            error: profileError.message
          });
          // Don't fail the connection update if profile fetch fails
        }
      }
 
      await EvolutionInstance.update(instance.id, updateData);
 
      // Emit Socket.IO event to tenant
      const io = global.io;
      if (io) {
        const tenantNamespace = io.of(`/tenant/${instance.tenant_id}`);
        
        const eventData = {
          instanceId: instance.id,
          instanceName: instance.instance_name,
          status: newStatus,
          phoneNumber: phoneNumber,
          profilePictureUrl: updateData.profile_picture_url,
          profileName: updateData.profile_name
        };
        
        // Emit multiple event names for compatibility
        tenantNamespace.emit('whatsapp-status-changed', eventData);
        tenantNamespace.emit('connection-update', eventData);
        
        logger.info('Emitted connection status to socket', { 
          tenantId: instance.tenant_id,
          instanceId: instance.id,
          status: newStatus
        });
      }
 
    } catch (error) {
      logger.error('Error handling connection update', { 
        instanceId: instance.id,
        error: error.message
      });
    }
  }
 
  /**
   * Handle incoming message
   * @param {Object} instance - Instance data
   * @param {Object} data - Event data
   */
  static async handleMessageReceived(instance, data) {
    try {
      console.log('\n      πŸ“¨ PROCESSANDO MENSAGEM RECEBIDA:');
      console.log('      Instance ID:', instance.id);
      console.log('      Tenant ID:', instance.tenant_id);
      console.log('      Data keys:', Object.keys(data));
      console.log('      Has messages:', !!data.messages);
      console.log('      Message count:', data.messages?.length || 0);
      
      logger.info('Message received via Evolution webhook', { 
        instanceId: instance.id,
        tenantId: instance.tenant_id,
        dataKeys: Object.keys(data),
        hasMessages: !!data.messages,
        messageCount: data.messages?.length || 0,
        fullData: JSON.stringify(data).substring(0, 1000)
      });
 
      // Transform Evolution API message format to our format
      const messages = data.messages || [data];
      
      console.log('      πŸ“‹ Total de mensagens a processar:', messages.length);
 
      for (const message of messages) {
        console.log('\n      ➑️ Processando mensagem:');
        console.log('         Message keys:', Object.keys(message));
        console.log('         Message type:', message.messageType);
        console.log('         Has key:', !!message.key);
        console.log('         Remote JID:', message.key?.remoteJid);
        console.log('         From me:', message.key?.fromMe);
        
        // Ignorar mensagens enviadas por nΓ³s
        if (message.key?.fromMe) {
          console.log('         ⏭️ Ignorando mensagem enviada por nós');
          continue;
        }
        
        logger.info('Emitting message to event bus', {
          instanceId: instance.id,
          messageKeys: Object.keys(message),
          messageType: message.messageType,
          hasKey: !!message.key,
          keyRemoteJid: message.key?.remoteJid
        });
 
        console.log('         πŸš€ Emitindo para o event bus...');
 
        // Emit to event bus for processing
        eventBus.emit(Events.MESSAGE_RECEIVED, {
          channel: 'evolution',
          tenantId: instance.tenant_id,
          instanceId: instance.id,
          sessionId: instance.evolution_instance_id,
          upsert: {
            messages: [message],
            type: 'notify'
          },
          message: message
        });
        
        console.log('         βœ… Mensagem emitida para o event bus');
      }
      
      console.log('      βœ… Todas as mensagens processadas\n');
 
    } catch (error) {
      console.error('      ❌ ERRO ao processar mensagem:', error.message);
      console.error('      Stack:', error.stack);
      logger.error('Error handling message received', { 
        instanceId: instance.id,
        error: error.message,
        stack: error.stack
      });
    }
  }
 
  /**
   * Handle message update (read, delivered, etc.)
   * @param {Object} instance - Instance data
   * @param {Object} data - Event data
   */
  static async handleMessageUpdate(instance, data) {
    try {
      logger.info('Message update received', { 
        instanceId: instance.id,
        update: data
      });
 
      // Emit Socket.IO event to tenant
      const io = global.io;
      if (io) {
        const tenantNamespace = io.of(`/tenant/${instance.tenant_id}`);
        tenantNamespace.emit('whatsapp-message-update', {
          instanceId: instance.id,
          update: data
        });
      }
 
    } catch (error) {
      logger.error('Error handling message update', { 
        instanceId: instance.id,
        error: error.message
      });
    }
  }
 
  /**
   * Handle message sent confirmation
   * @param {Object} instance - Instance data
   * @param {Object} data - Event data
   */
  static async handleMessageSent(instance, data) {
    try {
      logger.info('Message sent confirmation', { 
        instanceId: instance.id,
        messageId: data.key?.id
      });
 
      // Emit Socket.IO event to tenant
      const io = global.io;
      if (io) {
        const tenantNamespace = io.of(`/tenant/${instance.tenant_id}`);
        tenantNamespace.emit('whatsapp-message-sent', {
          instanceId: instance.id,
          messageId: data.key?.id,
          status: 'sent'
        });
      }
 
    } catch (error) {
      logger.error('Error handling message sent', { 
        instanceId: instance.id,
        error: error.message
      });
    }
  }
}
 
module.exports = EvolutionWebhookController;