# Code coverage report for modules/email/services/email.service.ts

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

82.05% Statements 96/117
59.57% Branches 56/94
78.26% Functions 18/23
82.88% Lines 92/111

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
    4336x
    6x

    6x
    22x

    22x

    22x

    22x

    22x
    22x
    22x
    22x

    22x

    22x
    22x
    22x

    22x
    22x
    22x
    22x
    22x

    22x

    22x
    20x

    2x

    22x

    19x

    1x

    2x

    28x

    28x
    1x
    1x
    1x

    27x
    27x

    26x

    1x

    2x
    2x

    5x

    5x
    5x
    1x

    4x
    4x
    4x

    4x

    2x

    2x
    2x
    3x
    3x
    18x

    3x

    2x

    26x

    1x

    1x

    26x
    26x

    26x
    8x

    26x
    1x

    26x

    26x
    2x
    2x

    24x

    24x

    1x

    1x

    1x

    5x

    5x

    12x

    12x
    42x
    42x

    12x

    1x

    12x

    2x
    2x
    2x

    2x

    2x
    2x
    2x
    2x

    4x

    3x

     import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import { SendEmailDto, SendTemplateEmailDto, EmailAddressDto, AttachmentDto } from '../dto';

    export type EmailProvider = 'sendgrid' | 'ses' | 'smtp';

    export interface EmailResult {
      success: boolean;
      messageId?: string;
      provider: EmailProvider;
      error?: string;
    }

    interface SendGridAttachment {
      content: string;
      filename: string;
      type?: string;
      disposition?: string;
    }

    interface SendGridPersonalization {
      to: { email: string; name?: string }[];
      cc?: { email: string; name?: string }[];
      bcc?: { email: string; name?: string }[];
    }

    interface SendGridMessage {
      personalizations: SendGridPersonalization[];
      from: { email: string; name?: string };
      reply_to?: { email: string; name?: string };
      subject: string;
      content: { type: string; value: string }[];
      attachments?: SendGridAttachment[];
    }

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

      // SendGrid
      private sendgridApiKey: string;

      // AWS SES
      private sesRegion: string;
      private sesAccessKeyId: string;
      private sesSecretAccessKey: string;

      // SMTP
      private smtpHost: string;
      private smtpPort: number;
      private smtpUser: string;
      private smtpPassword: string;
      private smtpSecure: boolean;

      // Common
      private fromEmail: string;
      private fromName: string;
      private replyTo: string;

      constructor(private configService: ConfigService) {}

      onModuleInit() {
        const emailConfig = this.configService.get('email');

        this.provider = emailConfig?.provider || 'sendgrid';
        this.fromEmail = emailConfig?.from || 'noreply@example.com';
        this.fromName = emailConfig?.fromName || 'Template SaaS';
        this.replyTo = emailConfig?.replyTo || '';

        // SendGrid config
        this.sendgridApiKey = emailConfig?.sendgridApiKey || '';

        // AWS SES config
        this.sesRegion = emailConfig?.sesRegion || 'us-east-1';
        this.sesAccessKeyId = emailConfig?.sesAccessKeyId || '';
        this.sesSecretAccessKey = emailConfig?.sesSecretAccessKey || '';

        // SMTP config
        this.smtpHost = emailConfig?.smtpHost || '';
        this.smtpPort = emailConfig?.smtpPort || 587;
        this.smtpUser = emailConfig?.smtpUser || '';
        this.smtpPassword = emailConfig?.smtpPassword || '';
        this.smtpSecure = emailConfig?.smtpSecure || false;

        // Check if configured
        this.isConfigured = this.checkConfiguration();

        if (this.isConfigured) {
          this.logger.log(`Email service initialized with provider: ${this.provider}`);
        } else {
          this.logger.warn('Email service not configured - emails will be logged only');
        }
      }

      private checkConfiguration(): boolean {
        switch (this.provider) {
          case 'sendgrid':
            return !!this.sendgridApiKey;
          case 'ses':
            return !!(this.sesAccessKeyId && this.sesSecretAccessKey);
          case 'smtp':
            return !!(this.smtpHost && this.smtpUser && this.smtpPassword);
          default:
            return false;
        }
      }

      async sendEmail(dto: SendEmailDto): Promise<EmailResult> {
        this.logger.debug(`Sending email to ${dto.to.email}: ${dto.subject}`);

        if (!this.isConfigured) {
          this.logger.warn('Email not configured, logging email instead');
          this.logEmail(dto);
          return {
            success: true,
            messageId: `mock-${Date.now()}`,
            provider: this.provider,
          };
        }

        try {
          switch (this.provider) {
            case 'sendgrid':
              return await this.sendViaSendGrid(dto);
            case 'ses':
              return await this.sendViaSES(dto);
            case 'smtp':
              return await this.sendViaSMTP(dto);
            default:
              throw new Error(`Unknown email provider: ${this.provider}`);
          }
        } catch (error) {
          this.logger.error(`Failed to send email: ${error.message}`, error.stack);
          return {
            success: false,
            provider: this.provider,
            error: error.message,
          };
        }
      }

      async sendTemplateEmail(dto: SendTemplateEmailDto): Promise<EmailResult> {
        // TODO: Integrate with notification_templates table
        // For now, we'll use a simple template rendering approach
        const { templateKey, variables, ...emailData } = dto;

        const template = await this.getTemplate(templateKey);
        if (!template) {
          return {
            success: false,
            provider: this.provider,
            error: `Template not found: ${templateKey}`,
          };
        }

        const renderedSubject = this.renderTemplate(template.subject, variables || {});
        const renderedHtml = this.renderTemplate(template.html, variables || {});
        const renderedText = template.text
          ? this.renderTemplate(template.text, variables || {})
          : undefined;

        return this.sendEmail({
          ...emailData,
          subject: renderedSubject,
          html: renderedHtml,
          text: renderedText,
        });
      }

      async sendBulkEmails(emails: SendEmailDto[]): Promise<EmailResult[]> {
        const results: EmailResult[] = [];

        // Process in batches of 10
        const batchSize = 10;
        for (let i = 0; i < emails.length; i += batchSize) {
          const batch = emails.slice(i, i + batchSize);
          const batchResults = await Promise.all(
            batch.map((email) => this.sendEmail(email)),
          );
          results.push(...batchResults);
        }

        return results;
      }

      // SendGrid implementation
      private async sendViaSendGrid(dto: SendEmailDto): Promise<EmailResult> {
        const message: SendGridMessage = {
          personalizations: [
            {
              to: [{ email: dto.to.email, name: dto.to.name }],
              ...(dto.cc?.length && {
                cc: dto.cc.map((c) => ({ email: c.email, name: c.name })),
              }),
              ...(dto.bcc?.length && {
                bcc: dto.bcc.map((b) => ({ email: b.email, name: b.name })),
              }),
            },
          ],
          from: { email: this.fromEmail, name: this.fromName },
          ...(this.replyTo && { reply_to: { email: this.replyTo } }),
          subject: dto.subject,
          content: [],
        };

        if (dto.text) {
          message.content.push({ type: 'text/plain', value: dto.text });
        }
        if (dto.html) {
          message.content.push({ type: 'text/html', value: dto.html });
        }

        if (dto.attachments?.length) {
          message.attachments = dto.attachments.map((a) => ({
            content: a.content,
            filename: a.filename,
            type: a.contentType,
            disposition: 'attachment',
          }));
        }

        const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${this.sendgridApiKey}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(message),
        });

        if (!response.ok) {
          const errorBody = await response.text();
          throw new Error(`SendGrid error: ${response.status} - ${errorBody}`);
        }

        const messageId = response.headers.get('x-message-id') || `sg-${Date.now()}`;

        return {
          success: true,
          messageId,
          provider: 'sendgrid',
        };
      }

      // AWS SES implementation using AWS SDK v3 pattern (fetch-based)
      private async sendViaSES(dto: SendEmailDto): Promise<EmailResult> {
        // Using AWS SES v2 API via HTTPS
        const endpoint = `https://email.${this.sesRegion}.amazonaws.com/v2/email/outbound-emails`;

        const body = {
          FromEmailAddress: `${this.fromName} <${this.fromEmail}>`,
          Destination: {
            ToAddresses: [`${dto.to.name || ''} <${dto.to.email}>`],
            ...(dto.cc?.length && {
              CcAddresses: dto.cc.map((c) => `${c.name || ''} <${c.email}>`),
            }),
            ...(dto.bcc?.length && {
              BccAddresses: dto.bcc.map((b) => `${b.name || ''} <${b.email}>`),
            }),
          },
          Content: {
            Simple: {
              Subject: { Data: dto.subject },
              Body: {
                ...(dto.text && { Text: { Data: dto.text } }),
                ...(dto.html && { Html: { Data: dto.html } }),
              },
            },
          },
          ...(this.replyTo && { ReplyToAddresses: [this.replyTo] }),
        };

        // AWS Signature V4 signing would be needed here
        // For production, use @aws-sdk/client-sesv2
        // This is a simplified implementation
        const timestamp = new Date().toISOString().replace(/[:-]|\.\d{3}/g, '');
        const date = timestamp.slice(0, 8);

        const headers = {
          'Content-Type': 'application/json',
          'X-Amz-Date': timestamp,
          'Host': `email.${this.sesRegion}.amazonaws.com`,
        };

        // Note: In production, implement proper AWS Signature V4 signing
        // or use @aws-sdk/client-sesv2
        this.logger.warn('AWS SES: Using simplified implementation - consider using @aws-sdk/client-sesv2');

        const response = await fetch(endpoint, {
          method: 'POST',
          headers: {
            ...headers,
            // AWS credentials would need proper signature
            'X-Amz-Security-Token': '', // Add if using temporary credentials
          },
          body: JSON.stringify(body),
        });

        Iif (!response.ok) {
          const errorBody = await response.text();
          throw new Error(`SES error: ${response.status} - ${errorBody}`);
        }

        const result = await response.json();

        return {
          success: true,
          messageId: result.MessageId || `ses-${Date.now()}`,
          provider: 'ses',
        };
      }

      // SMTP implementation using nodemailer-compatible approach
      private async sendViaSMTP(dto: SendEmailDto): Promise<EmailResult> {
        // For SMTP, we need nodemailer - this is a placeholder
        // In production, install nodemailer and use it here
        this.logger.warn('SMTP: Requires nodemailer package - install with: npm install nodemailer');

        // Fallback to logging
        this.logEmail(dto);

        return {
          success: true,
          messageId: `smtp-${Date.now()}`,
          provider: 'smtp',
        };
      }

      // Template handling
      private async getTemplate(
        templateKey: string,
      ): Promise<{ subject: string; html: string; text?: string } | null> {
        // TODO: Fetch from notification_templates table
        // For now, return built-in templates
        const templates: Record<string, { subject: string; html: string; text?: string }> = {
          welcome: {
            subject: 'Welcome to {{appName}}!',
            html: `
              <h1>Welcome, {{userName}}!</h1>
              <p>Thank you for joining {{appName}}. We're excited to have you on board.</p>
              <p>Get started by exploring our features.</p>
              <p>Best regards,<br/>The {{appName}} Team</p>
            `,
            text: 'Welcome, {{userName}}! Thank you for joining {{appName}}.',
          },
          password_reset: {
            subject: 'Reset your password - {{appName}}',
            html: `
              <h1>Password Reset Request</h1>
              <p>Hi {{userName}},</p>
              <p>We received a request to reset your password. Click the link below to proceed:</p>
              <p><a href="{{resetLink}}">Reset Password</a></p>
              <p>This link expires in {{expiresIn}}.</p>
              <p>If you didn't request this, please ignore this email.</p>
            `,
            text: 'Hi {{userName}}, Reset your password here: {{resetLink}}',
          },
          invitation: {
            subject: "You've been invited to {{tenantName}}",
            html: `
              <h1>You're Invited!</h1>
              <p>{{inviterName}} has invited you to join {{tenantName}} on {{appName}}.</p>
              <p><a href="{{inviteLink}}">Accept Invitation</a></p>
              <p>This invitation expires in {{expiresIn}}.</p>
            `,
            text: "You've been invited to {{tenantName}}. Accept here: {{inviteLink}}",
          },
          notification: {
            subject: '{{title}}',
            html: `
              <h2>{{title}}</h2>
              <p>{{message}}</p>
              {{#if actionUrl}}
              <p><a href="{{actionUrl}}">{{actionText}}</a></p>
              {{/if}}
            `,
            text: '{{title}}: {{message}}',
          },
        };

        return templates[templateKey] || null;
      }

      private renderTemplate(
        template: string,
        variables: Record<string, any>,
      ): string {
        let result = template;

        // Simple variable replacement: {{variableName}}
        for (const [key, value] of Object.entries(variables)) {
          const regex = new RegExp(`\\{\\{${key}\\}\\}`, 'g');
          result = result.replace(regex, String(value ?? ''));
        }

        // Handle conditional blocks: {{#if condition}}...{{/if}}
        result = result.replace(
          /\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,
          (_, condition, content) => {
            return variables[condition] ? content : '';
          },
        );

        return result;
      }

      private logEmail(dto: SendEmailDto): void {
        this.logger.log('=== EMAIL (NOT SENT - NO PROVIDER CONFIGURED) ===');
        this.logger.log(`To: ${dto.to.email}`);
        Iif (dto.cc?.length) {
          this.logger.log(`CC: ${dto.cc.map((c) => c.email).join(', ')}`);
        }
        Iif (dto.bcc?.length) {
          this.logger.log(`BCC: ${dto.bcc.map((b) => b.email).join(', ')}`);
        }
        this.logger.log(`Subject: ${dto.subject}`);
        this.logger.log(`Body (text): ${dto.text?.substring(0, 200) || '(none)'}`);
        this.logger.log(`Body (html): ${dto.html?.substring(0, 200) || '(none)'}`);
        this.logger.log('================================================');
      }

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

      getProvider(): EmailProvider {
        return this.provider;
      }
    }