# All files / services/whatsapp CloudMessageSender.js

0% Statements 0/80
0% Branches 0/52
0% Functions 0/5
0% Lines 0/79

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

     const axios = require('axios');
    const fs = require('fs');
    const FormData = require('form-data');
    const { pool } = require('../../config/database');
    const { logInfo, logError } = require('../../core/whatsapp/LogContext');

    const buildHeaders = (accessToken) => ({
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    });

    const sendCloudRequest = async (account, payload) => {
      const response = await axios.post(
        `https://graph.facebook.com/v18.0/${account.phone_number_id}/messages`,
        payload,
        { headers: buildHeaders(account.access_token) }
      );
      const messageId = response?.data?.messages?.[0]?.id || null;
      return { messageId };
    };

    const uploadCloudMedia = async (account, media) => {
      const formData = new FormData();
      formData.append('file', fs.createReadStream(media.filePath), {
        filename: media.fileName,
        contentType: media.mimeType
      });
      formData.append('type', media.mimeType);
      formData.append('messaging_product', 'whatsapp');

      const response = await axios.post(
        `https://graph.facebook.com/v18.0/${account.phone_number_id}/media`,
        formData,
        {
          headers: {
            'Authorization': `Bearer ${account.access_token}`,
            ...formData.getHeaders()
          },
          timeout: 45000,
          maxContentLength: 50 * 1024 * 1024,
          maxBodyLength: 50 * 1024 * 1024
        }
      );
      return response?.data?.id || null;
    };

    const resolveAccount = async (tenantId, accountId) => {
      const [rows] = await pool.execute(
        'SELECT * FROM whatsapp_cloud_accounts WHERE id = ? AND tenant_id = ? LIMIT 1',
        [accountId, tenantId]
      );
      return rows?.[0] || null;
    };

    const send = async ({ tenantId, item, metadata }) => {
      const accountId = metadata.accountId;
      const logBase = {
        tenant_id: tenantId,
        message_id: item.id,
        module: 'cloud_sender',
        event: 'send'
      };

      if (!accountId) {
        logError('Cloud send failed: missing accountId', {
          ...logBase,
          step: 'validate',
          error: 'Missing accountId'
        });
        return { success: false, error: 'Missing accountId' };
      }

      const account = await resolveAccount(tenantId, accountId);
      if (!account?.access_token || !account?.phone_number_id) {
        logError('Cloud send failed: account invalid', {
          ...logBase,
          step: 'resolve_account',
          error: 'Account not found or missing credentials'
        });
        return { success: false, error: 'Account not found or missing credentials' };
      }

      const to = item.phone_number;
      const type = item.message_type || 'text';
      const payload = metadata.payload || null;

      try {
        if (type === 'text') {
          const bodyText = item.content || '';
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: 'text',
            text: { body: bodyText }
          };
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud text sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (type === 'reaction' && payload?.reaction) {
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: 'reaction',
            reaction: payload.reaction
          };
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud reaction sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (type === 'interactive' && payload?.interactive) {
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: 'interactive',
            interactive: payload.interactive
          };
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud interactive sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (type === 'products' && payload?.interactive) {
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: 'interactive',
            interactive: payload.interactive
          };
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud products sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (type === 'cta' && payload?.interactive) {
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: 'interactive',
            interactive: payload.interactive
          };
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud CTA sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (type === 'media' && payload?.media) {
          const mediaId = await uploadCloudMedia(account, payload.media);
          if (!mediaId) {
            return { success: false, error: 'Media upload failed' };
          }
          const mediaType = payload.media.mediaType;
          const messagePayload = {
            messaging_product: 'whatsapp',
            to,
            type: mediaType,
            [mediaType]: {
              id: mediaId
            }
          };
          if (payload.media.caption && mediaType !== 'audio') {
            messagePayload[mediaType].caption = payload.media.caption;
          }
          const { messageId } = await sendCloudRequest(account, messagePayload);
          logInfo('Cloud media sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        if (payload?.raw) {
          const { messageId } = await sendCloudRequest(account, payload.raw);
          logInfo('Cloud raw payload sent', { ...logBase, step: 'sent' });
          return { success: true, messageId };
        }

        return { success: false, error: 'Unsupported message type' };
      } catch (error) {
        logError('Cloud send error', {
          ...logBase,
          step: 'error',
          error: error.message || String(error)
        });
        return { success: false, error: error.message || String(error) };
      }
    };

    module.exports = { send };