# Code coverage report for modules/notifications/services/push-notification.service.ts

# All files / modules/notifications/services push-notification.service.ts

100% Statements 82/82
97.14% Branches 34/35
100% Functions 9/9
100% Lines 79/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
    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
    2541x

    1x
    1x
    1x
    1x
    1x

    1x
    41x
    41x

    41x

    41x

    41x

    41x
    41x
    41x

    41x
    37x
    37x
    34x
    34x

    3x

    4x

    3x

    2x
    1x

    1x

    8x
    1x
    1x

    7x

    7x
    1x
    1x

    6x
    6x

    6x
    8x

    8x

    8x
    6x

    6x

    20x
    20x

    20x

    13x
    13x

    13x
    2x

    13x

    7x

    7x
    2x

    2x
    2x

    7x
    1x

    7x

    4x
    1x
    1x

    3x

    3x

    3x
    3x

    3x
    4x
    4x
    3x

    1x

    3x

    3x

    9x
    9x

    7x
    1x

    6x
    5x

    1x

    2x

     import {
      Injectable,
      Logger,
      OnModuleInit,
    } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import * as webpush from 'web-push';
    import { UserDevice, NotificationLog } from '../entities';

    export interface PushPayload {
      title: string;
      body: string;
      icon?: string;
      badge?: string;
      url?: string;
      data?: Record<string, any>;
      actions?: Array<{ action: string; title: string }>;
    }

    export interface SendResult {
      deviceId: string;
      success: boolean;
      error?: string;
      statusCode?: number;
    }

    @Injectable()
    export class PushNotificationService implements OnModuleInit {
      private readonly logger = new Logger(PushNotificationService.name);
      private isConfigured = false;

      constructor(
        private readonly configService: ConfigService,
        @InjectRepository(UserDevice)
        private readonly deviceRepository: Repository<UserDevice>,
        @InjectRepository(NotificationLog)
        private readonly logRepository: Repository<NotificationLog>,
      ) {}

      onModuleInit() {
        const vapidPublicKey = this.configService.get<string>('VAPID_PUBLIC_KEY');
        const vapidPrivateKey = this.configService.get<string>('VAPID_PRIVATE_KEY');
        const vapidSubject = this.configService.get<string>(
          'VAPID_SUBJECT',
          'mailto:admin@example.com',
        );

        if (vapidPublicKey && vapidPrivateKey) {
          try {
            webpush.setVapidDetails(vapidSubject, vapidPublicKey, vapidPrivateKey);
            this.isConfigured = true;
            this.logger.log('Web Push configured with VAPID keys');
          } catch (error) {
            this.logger.error(`Failed to configure Web Push: ${error.message}`);
          }
        } else {
          this.logger.warn(
            'VAPID keys not configured. Push notifications will be disabled.',
          );
        }
      }

      isEnabled(): boolean {
        return this.isConfigured;
      }

      getVapidPublicKey(): string | null {
        if (!this.isConfigured) {
          return null;
        }
        return this.configService.get<string>('VAPID_PUBLIC_KEY') || null;
      }

      async sendToUser(
        userId: string,
        tenantId: string,
        payload: PushPayload,
        notificationId?: string,
      ): Promise<SendResult[]> {
        if (!this.isConfigured) {
          this.logger.warn('Push notifications not configured, skipping send');
          return [];
        }

        const devices = await this.deviceRepository.find({
          where: { user_id: userId, tenant_id: tenantId, is_active: true },
        });

        if (devices.length === 0) {
          this.logger.debug(`No active devices found for user ${userId}`);
          return [];
        }

        const results: SendResult[] = [];
        const pushPayload = JSON.stringify({
          title: payload.title,
          body: payload.body,
          icon: payload.icon || '/icon-192.png',
          badge: payload.badge || '/badge-72.png',
          url: payload.url || '/',
          data: payload.data,
          actions: payload.actions || [
            { action: 'view', title: 'Ver' },
            { action: 'dismiss', title: 'Descartar' },
          ],
        });

        for (const device of devices) {
          const result = await this.sendToDevice(
            device,
            pushPayload,
            notificationId,
          );
          results.push(result);
        }

        const successCount = results.filter((r) => r.success).length;
        this.logger.log(
          `Push sent to user ${userId}: ${successCount}/${results.length} successful`,
        );

        return results;
      }

      async sendToDevice(
        device: UserDevice,
        payload: string,
        notificationId?: string,
      ): Promise<SendResult> {
        try {
          const subscription = JSON.parse(device.device_token);

          await webpush.sendNotification(subscription, payload);

          // Update last used
          device.last_used_at = new Date();
          await this.deviceRepository.save(device);

          // Log success
          if (notificationId) {
            await this.logRepository.save({
              notification_id: notificationId,
              channel: 'push',
              status: 'sent',
              provider: 'web-push',
              device_id: device.id,
              delivered_at: new Date(),
            });
          }

          return {
            deviceId: device.id,
            success: true,
          };
        } catch (error) {
          const statusCode = error.statusCode;

          // Handle expired subscriptions
          if (statusCode === 410 || statusCode === 404) {
            this.logger.warn(
              `Device ${device.id} subscription expired (${statusCode}), marking inactive`,
            );
            device.is_active = false;
            await this.deviceRepository.save(device);
          }

          // Log failure
          if (notificationId) {
            await this.logRepository.save({
              notification_id: notificationId,
              channel: 'push',
              status: 'failed',
              provider: 'web-push',
              device_id: device.id,
              error_code: statusCode?.toString(),
              error_message: error.message,
            });
          }

          return {
            deviceId: device.id,
            success: false,
            error: error.message,
            statusCode,
          };
        }
      }

      async sendBroadcast(
        tenantId: string,
        payload: PushPayload,
      ): Promise<{ total: number; successful: number; failed: number }> {
        if (!this.isConfigured) {
          this.logger.warn('Push notifications not configured, skipping broadcast');
          return { total: 0, successful: 0, failed: 0 };
        }

        const devices = await this.deviceRepository.find({
          where: { tenant_id: tenantId, is_active: true },
        });

        const pushPayload = JSON.stringify({
          title: payload.title,
          body: payload.body,
          icon: payload.icon || '/icon-192.png',
          badge: payload.badge || '/badge-72.png',
          url: payload.url || '/',
          data: payload.data,
        });

        let successful = 0;
        let failed = 0;

        for (const device of devices) {
          const result = await this.sendToDevice(device, pushPayload);
          if (result.success) {
            successful++;
          } else {
            failed++;
          }
        }

        this.logger.log(
          `Broadcast to tenant ${tenantId}: ${successful}/${devices.length} successful`,
        );

        return {
          total: devices.length,
          successful,
          failed,
        };
      }

      validateSubscription(subscriptionJson: string): boolean {
        try {
          const subscription = JSON.parse(subscriptionJson);

          if (!subscription.endpoint) {
            return false;
          }

          if (!subscription.keys?.p256dh || !subscription.keys?.auth) {
            return false;
          }

          return true;
        } catch {
          return false;
        }
      }
    }