# All files / modules/notifications/services notifications.service.ts

90.72% Statements 88/97
68.18% Branches 30/44
100% Functions 14/14
95.45% Lines 84/88

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
    3452x
    2x
    2x
    2x

    2x

    2x
    20x

    20x

    20x

    20x
    20x

    4x

    4x

    4x
    2x
    2x
    2x

    4x
    2x
    2x

    2x
    1x
    1x
    1x

    1x
    1x

    2x

    4x

    2x

    2x
    1x

    1x
    1x

    1x
    1x
    1x
    1x
    1x

    1x

    2x

    2x

    2x
    1x

    2x

    2x

    2x

    2x

    2x
    1x

    1x
    1x

    1x

    1x

    1x

    2x

    2x
    1x

    1x

    1x

    2x

    2x
    1x

    1x

    3x

    3x
    1x

    1x

    3x

    1x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    2x

    2x

    1x
    1x

    1x

    1x

     import { Injectable, NotFoundException, Logger } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository, LessThan } from 'typeorm';
    import {
      Notification,
      NotificationTemplate,
      UserNotificationPreference,
    } from '../entities';
    import {
      CreateNotificationDto,
      SendTemplateNotificationDto,
      UpdatePreferencesDto,
    } from '../dto';
    import { EmailService } from '@modules/email';

    @Injectable()
    export class NotificationsService {
      private readonly logger = new Logger(NotificationsService.name);

      constructor(
        @InjectRepository(Notification)
        private readonly notificationRepository: Repository<Notification>,
        @InjectRepository(NotificationTemplate)
        private readonly templateRepository: Repository<NotificationTemplate>,
        @InjectRepository(UserNotificationPreference)
        private readonly preferenceRepository: Repository<UserNotificationPreference>,
        private readonly emailService: EmailService,
      ) {}

      // ==================== Notifications ====================

      async create(
        dto: CreateNotificationDto,
        tenantId: string,
      ): Promise<Notification> {
        const notification = this.notificationRepository.create({
          user_id: dto.userId,
          tenant_id: tenantId,
          type: dto.type || 'info',
          channel: dto.channel || 'in_app',
          title: dto.title,
          message: dto.message,
          data: dto.data || null,
          action_url: dto.actionUrl || null,
          delivery_status: 'pending',
        });

        const saved = await this.notificationRepository.save(notification);

        // If in_app, mark as delivered immediately
        if (saved.channel === 'in_app') {
          saved.delivery_status = 'delivered';
          saved.sent_at = new Date();
          await this.notificationRepository.save(saved);
        }

        // For email, send via EmailService
        if (saved.channel === 'email' && dto.email) {
          try {
            const result = await this.emailService.sendEmail({
              to: { email: dto.email, name: dto.userName },
              subject: saved.title,
              html: this.formatEmailHtml(saved.title, saved.message, saved.action_url),
              text: saved.message,
              metadata: { notificationId: saved.id },
            });

            if (result.success) {
              saved.delivery_status = 'delivered';
              saved.sent_at = new Date();
              this.logger.log(`Email sent to ${dto.email}: ${result.messageId}`);
            } else {
              saved.delivery_status = 'failed';
              this.logger.error(`Failed to send email to ${dto.email}: ${result.error}`);
            }
            await this.notificationRepository.save(saved);
          } catch (error) {
            this.logger.error(`Email delivery error: ${error.message}`);
            saved.delivery_status = 'failed';
            await this.notificationRepository.save(saved);
          }
        }

        // TODO: For push/sms, implement respective services

        return saved;
      }

      async sendFromTemplate(
        dto: SendTemplateNotificationDto,
        tenantId: string,
      ): Promise<Notification> {
        const template = await this.templateRepository.findOne({
          where: { code: dto.templateCode, is_active: true },
        });

        if (!template) {
          throw new NotFoundException(`Template '${dto.templateCode}' no encontrado`);
        }

        // Replace variables in template
        let message = template.body;
        let subject = template.subject || '';

        if (dto.variables) {
          for (const [key, value] of Object.entries(dto.variables)) {
            const regex = new RegExp(`{{${key}}}`, 'g');
            message = message.replace(regex, String(value));
            subject = subject.replace(regex, String(value));
          }
        }

        return this.create(
          {
            userId: dto.userId,
            channel: template.channel as any,
            title: subject || template.name,
            message,
            data: { templateCode: dto.templateCode, variables: dto.variables },
          },
          tenantId,
        );
      }

      async findAllForUser(
        userId: string,
        tenantId: string,
        options: { page?: number; limit?: number; unreadOnly?: boolean } = {},
      ): Promise<{ data: Notification[]; total: number; unread: number }> {
        const { page = 1, limit = 20, unreadOnly = false } = options;

        const whereCondition: any = {
          user_id: userId,
          tenant_id: tenantId,
          channel: 'in_app', // Only in-app notifications for listing
        };

        if (unreadOnly) {
          whereCondition.is_read = false;
        }

        const [data, total] = await this.notificationRepository.findAndCount({
          where: whereCondition,
          order: { created_at: 'DESC' },
          skip: (page - 1) * limit,
          take: limit,
        });

        const unread = await this.notificationRepository.count({
          where: {
            user_id: userId,
            tenant_id: tenantId,
            channel: 'in_app',
            is_read: false,
          },
        });

        return { data, total, unread };
      }

      async markAsRead(
        notificationId: string,
        userId: string,
        tenantId: string,
      ): Promise<Notification> {
        const notification = await this.notificationRepository.findOne({
          where: { id: notificationId, user_id: userId, tenant_id: tenantId },
        });

        if (!notification) {
          throw new NotFoundException('Notificación no encontrada');
        }

        notification.is_read = true;
        notification.read_at = new Date();

        return this.notificationRepository.save(notification);
      }

      async markAllAsRead(userId: string, tenantId: string): Promise<number> {
        const result = await this.notificationRepository.update(
          {
            user_id: userId,
            tenant_id: tenantId,
            is_read: false,
          },
          {
            is_read: true,
            read_at: new Date(),
          },
        );

        return result.affected || 0;
      }

      async delete(
        notificationId: string,
        userId: string,
        tenantId: string,
      ): Promise<void> {
        const result = await this.notificationRepository.delete({
          id: notificationId,
          user_id: userId,
          tenant_id: tenantId,
        });

        if (result.affected === 0) {
          throw new NotFoundException('Notificación no encontrada');
        }
      }

      async getUnreadCount(userId: string, tenantId: string): Promise<number> {
        return this.notificationRepository.count({
          where: {
            user_id: userId,
            tenant_id: tenantId,
            channel: 'in_app',
            is_read: false,
          },
        });
      }

      // ==================== Templates ====================

      async findAllTemplates(): Promise<NotificationTemplate[]> {
        return this.templateRepository.find({
          where: { is_active: true },
          order: { category: 'ASC', code: 'ASC' },
        });
      }

      async findTemplateByCode(code: string): Promise<NotificationTemplate> {
        const template = await this.templateRepository.findOne({
          where: { code, is_active: true },
        });

        if (!template) {
          throw new NotFoundException(`Template '${code}' no encontrado`);
        }

        return template;
      }

      // ==================== Preferences ====================

      async getPreferences(
        userId: string,
        tenantId: string,
      ): Promise<UserNotificationPreference> {
        let preferences = await this.preferenceRepository.findOne({
          where: { user_id: userId, tenant_id: tenantId },
        });

        // Create default preferences if not exist
        if (!preferences) {
          preferences = this.preferenceRepository.create({
            user_id: userId,
            tenant_id: tenantId,
            email_enabled: true,
            push_enabled: true,
            in_app_enabled: true,
            sms_enabled: false,
            marketing_emails: true,
            product_updates: true,
            security_alerts: true,
          });
          await this.preferenceRepository.save(preferences);
        }

        return preferences;
      }

      async updatePreferences(
        userId: string,
        tenantId: string,
        dto: UpdatePreferencesDto,
      ): Promise<UserNotificationPreference> {
        let preferences = await this.getPreferences(userId, tenantId);

        if (dto.emailEnabled !== undefined) preferences.email_enabled = dto.emailEnabled;
        if (dto.pushEnabled !== undefined) preferences.push_enabled = dto.pushEnabled;
        Iif (dto.inAppEnabled !== undefined) preferences.in_app_enabled = dto.inAppEnabled;
        Iif (dto.smsEnabled !== undefined) preferences.sms_enabled = dto.smsEnabled;
        Iif (dto.marketingEmails !== undefined) preferences.marketing_emails = dto.marketingEmails;
        Iif (dto.productUpdates !== undefined) preferences.product_updates = dto.productUpdates;
        Iif (dto.securityAlerts !== undefined) preferences.security_alerts = dto.securityAlerts;
        Iif (dto.categoryPreferences !== undefined) {
          preferences.category_preferences = dto.categoryPreferences;
        }

        return this.preferenceRepository.save(preferences);
      }

      // ==================== Email Formatting ====================

      private formatEmailHtml(
        title: string,
        message: string,
        actionUrl?: string | null,
      ): string {
        const actionButton = actionUrl
          ? `<p style="margin-top: 20px;">
               <a href="${actionUrl}"
                  style="display: inline-block; padding: 12px 24px; background-color: #3b82f6; color: white; text-decoration: none; border-radius: 6px; font-weight: 500;">
                 Ver más
               </a>
             </p>`
          : '';

        return `
          <!DOCTYPE html>
          <html>
            <head>
              <meta charset="utf-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
            </head>
            <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #374151; padding: 20px; max-width: 600px; margin: 0 auto;">
              <div style="background-color: #f9fafb; border-radius: 8px; padding: 24px;">
                <h2 style="color: #111827; margin-top: 0;">${title}</h2>
                <p style="color: #4b5563; margin-bottom: 16px;">${message}</p>
                ${actionButton}
              </div>
              <p style="color: #9ca3af; font-size: 12px; margin-top: 24px; text-align: center;">
                Este es un mensaje automático de Template SaaS
              </p>
            </body>
          </html>
        `;
      }

      // ==================== Cleanup ====================

      async cleanupOldNotifications(daysToKeep: number = 30): Promise<number> {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);

        const result = await this.notificationRepository.delete({
          created_at: LessThan(cutoffDate),
          is_read: true,
        });

        return result.affected || 0;
      }
    }