# All files / services/whatsapp WhatsAppQRHandler.js

0% Statements 0/56
0% Branches 0/21
0% Functions 0/12
0% Lines 0/56

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

     /**
     * WhatsAppQRHandler
     * Manages QR code generation and emission with tenant isolation
     *
     * @module services/whatsapp/WhatsAppQRHandler
     */

    const qrcode = require('qrcode');
    const { logger } = require('../../config/logger');

    class WhatsAppQRHandler {
      constructor(io, options = {}) {
        this.io = io;
        this.tenantQRCodes = new Map(); // Store QR codes per tenant
        this.tenantCounters = new Map(); // Store generation counters per tenant
        this.tenantTimeouts = new Map(); // Store timeouts per tenant
        this.maxQrGenerations = options.maxQrGenerations || 10;
        this.qrTimeoutDuration = options.qrTimeoutDuration || 180000; // 3 minutes
      }

      /**
       * Generate QR code for tenant
       * @param {number} tenantId - Tenant ID
       * @param {string} qrString - QR string from Baileys
       * @returns {Promise<string|null>} Base64 QR code or null
       */
      async generateQR(tenantId, qrString) {
        try {
          const currentCount = this.tenantCounters.get(tenantId) || 0;
          const newCount = currentCount + 1;
          this.tenantCounters.set(tenantId, newCount);

          logger.info('⚡ Generating QR code for tenant', {
            tenantId,
            attempt: newCount,
            maxAttempts: this.maxQrGenerations
          });

          if (newCount > this.maxQrGenerations) {
            logger.error('Maximum QR generations reached for tenant', { tenantId });
            this.emitQRStatus(tenantId, 'max_attempts_reached');
            return null;
          }

          const qrStart = Date.now();

          // Generate base64 QR code with optimized settings
          const qr = await qrcode.toDataURL(qrString, {
            errorCorrectionLevel: 'M', // Medium error correction (faster than H)
            type: 'image/png',
            quality: 0.92,
            margin: 1,
            width: 300 // Fixed width for faster generation
          });

          const qrTime = Date.now() - qrStart;
          this.tenantQRCodes.set(tenantId, qr);

          // Emit QR code directly (like 2.0 version)
          this.io.emit('qr-code', qr);

          logger.info(`✅ QR code generated and emitted in ${qrTime}ms`, {
            tenantId,
            qrLength: qr.length,
            attempt: newCount
          });

          // Set timeout for QR expiration
          this.setQRTimeout(tenantId);

          return qr;
        } catch (error) {
          logger.error('Error generating QR code for tenant', {
            tenantId,
            error: error.message
          });
          this.emitQRStatus(tenantId, 'generation_error');
          return null;
        }
      }

      /**
       * Set timeout for QR code expiration
       * @param {number} tenantId - Tenant ID
       */
      setQRTimeout(tenantId) {
        // Clear existing timeout
        const existingTimeout = this.tenantTimeouts.get(tenantId);
        if (existingTimeout) {
          clearTimeout(existingTimeout);
        }

        // Set new timeout
        const timeout = setTimeout(() => {
          logger.warn('QR code expired for tenant', { tenantId });
          this.emitQRStatus(tenantId, 'expired');
          this.tenantQRCodes.delete(tenantId);
        }, this.qrTimeoutDuration);

        this.tenantTimeouts.set(tenantId, timeout);
      }

      /**
       * Clear QR code for tenant
       * @param {number} tenantId - Tenant ID
       */
      clearQR(tenantId) {
        this.tenantQRCodes.delete(tenantId);
        this.tenantCounters.delete(tenantId);

        const timeout = this.tenantTimeouts.get(tenantId);
        if (timeout) {
          clearTimeout(timeout);
          this.tenantTimeouts.delete(tenantId);
        }

        // Emit null to clear QR code (like 2.0 version)
        this.io.emit('qr-code', null);
        logger.info('QR code cleared for tenant', { tenantId });
      }

      /**
       * Emit QR status event to tenant
       * @param {number} tenantId - Tenant ID
       * @param {string} status - Status message
       */
      emitQRStatus(tenantId, status) {
        const attempts = this.tenantCounters.get(tenantId) || 0;

        this.io.emit('qr-status', {
          status,
          tenantId,
          attempts,
          maxAttempts: this.maxQrGenerations
        });
      }

      /**
       * Get current QR code for tenant
       * @param {number} tenantId - Tenant ID
       * @returns {string|null} QR code or null
       */
      getCurrentQR(tenantId) {
        return this.tenantQRCodes.get(tenantId) || null;
      }

      /**
       * Reset QR generation counter for tenant
       * @param {number} tenantId - Tenant ID
       */
      resetCounter(tenantId) {
        this.tenantCounters.set(tenantId, 0);
        logger.info('QR generation counter reset for tenant', { tenantId });
      }

      /**
       * Check if tenant can generate more QR codes
       * @param {number} tenantId - Tenant ID
       * @returns {boolean} True if can generate
       */
      canGenerateQR(tenantId) {
        const count = this.tenantCounters.get(tenantId) || 0;
        return count < this.maxQrGenerations;
      }

      /**
       * Get QR generation stats for tenant
       * @param {number} tenantId - Tenant ID
       * @returns {Object} QR stats
       */
      getStats(tenantId) {
        return {
          tenantId,
          attempts: this.tenantCounters.get(tenantId) || 0,
          maxAttempts: this.maxQrGenerations,
          hasQR: this.tenantQRCodes.has(tenantId),
          canGenerate: this.canGenerateQR(tenantId)
        };
      }

      /**
       * Clean up tenant data
       * @param {number} tenantId - Tenant ID
       */
      cleanup(tenantId) {
        this.clearQR(tenantId);
        logger.info('QR handler cleaned up for tenant', { tenantId });
      }

      /**
       * Get all active tenants with QR codes
       * @returns {Array<number>} Array of tenant IDs
       */
      getActiveTenants() {
        return Array.from(this.tenantQRCodes.keys());
      }
    }

    module.exports = WhatsAppQRHandler;