# Code coverage report for modules/onboarding/onboarding.service.ts

# All files / modules/onboarding onboarding.service.ts

96.96% Statements 64/66
77.27% Branches 17/22
100% Functions 8/8
96.87% Lines 62/64

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
    2641x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x
    16x

    16x

    16x

    16x

    16x
    16x
    16x

    10x

    10x
    1x

    9x

    9x

    9x

    9x

    9x

    9x

    6x

    6x
    1x

    5x
    2x

    3x

    3x

    3x
    1x

    2x

    2x
    2x

    2x

    2x

    2x

    2x

    9x
    1x

    8x

    9x

    9x

    9x

    9x

    9x

    9x

    9x
    5x

    4x
    1x

    3x

    1x

    2x

    2x
    2x

    2x

     import { Injectable, Logger, BadRequestException } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { Tenant } from '../tenants/entities/tenant.entity';
    import { User } from '../auth/entities/user.entity';
    import { Token } from '../auth/entities/token.entity';
    import { Subscription } from '../billing/entities/subscription.entity';
    import { EmailService } from '../email/services/email.service';
    import { AuditService, CreateAuditLogParams } from '../audit/services/audit.service';
    import { AuditAction } from '../audit/entities/audit-log.entity';
    import {
      OnboardingStatusDto,
      CompanyDataDto,
      TeamDataDto,
      PlanDataDto,
      CompleteOnboardingResponseDto,
    } from './dto';

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

      constructor(
        @InjectRepository(Tenant)
        private readonly tenantRepository: Repository<Tenant>,
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        @InjectRepository(Token)
        private readonly tokenRepository: Repository<Token>,
        @InjectRepository(Subscription)
        private readonly subscriptionRepository: Repository<Subscription>,
        private readonly emailService: EmailService,
        private readonly auditService: AuditService,
      ) {}

      /**
       * Get the current onboarding status for a tenant
       */
      async getStatus(tenantId: string): Promise<OnboardingStatusDto> {
        const tenant = await this.tenantRepository.findOne({
          where: { id: tenantId },
        });

        if (!tenant) {
          throw new BadRequestException('Tenant not found');
        }

        // Get team data
        const teamData = await this.getTeamData(tenantId);

        // Get plan data
        const planData = await this.getPlanData(tenantId);

        // Get company data
        const companyData = this.getCompanyData(tenant);

        // Calculate current step
        const step = this.calculateStep(companyData, teamData, planData, tenant);

        // Check if completed
        const completed = tenant.status === 'active';

        return {
          step,
          completed,
          data: {
            company: companyData,
            team: teamData,
            plan: planData,
          },
        };
      }

      /**
       * Complete the onboarding process
       */
      async completeOnboarding(
        tenantId: string,
        userId: string,
      ): Promise<CompleteOnboardingResponseDto> {
        const tenant = await this.tenantRepository.findOne({
          where: { id: tenantId },
        });

        if (!tenant) {
          throw new BadRequestException('Tenant not found');
        }

        // Verify tenant is in pending/trial state
        if (tenant.status === 'active') {
          return {
            success: true,
            redirectUrl: '/dashboard',
          };
        }

        Iif (tenant.status !== 'trial' && tenant.status !== 'suspended' && tenant.status !== 'canceled') {
          throw new BadRequestException('Tenant is not in a valid state for onboarding completion');
        }

        // Get the user for sending welcome email
        const user = await this.userRepository.findOne({
          where: { id: userId, tenant_id: tenantId },
        });

        if (!user) {
          throw new BadRequestException('User not found');
        }

        // Store old values for audit
        const oldStatus = tenant.status;

        // Update tenant status to active
        tenant.status = 'active';
        await this.tenantRepository.save(tenant);

        // Log to audit
        await this.auditService.createAuditLog({
          tenant_id: tenantId,
          user_id: userId,
          action: AuditAction.UPDATE,
          entity_type: 'tenant',
          entity_id: tenantId,
          old_values: { status: oldStatus },
          new_values: { status: 'active' },
          description: 'Onboarding completed',
        });

        // Send welcome email
        await this.sendWelcomeEmail(user, tenant);

        this.logger.log(`Onboarding completed for tenant ${tenantId}`);

        return {
          success: true,
          redirectUrl: '/dashboard',
        };
      }

      /**
       * Get company data from tenant
       */
      private getCompanyData(tenant: Tenant): CompanyDataDto | null {
        if (!tenant.name || !tenant.slug) {
          return null;
        }

        return {
          name: tenant.name,
          slug: tenant.slug,
          logo_url: tenant.logo_url,
          settings: tenant.settings,
        };
      }

      /**
       * Get team data (invitations sent and members joined)
       */
      private async getTeamData(tenantId: string): Promise<TeamDataDto> {
        // Count invitations sent (tokens with type 'invitation')
        const invitesSent = await this.tokenRepository.count({
          where: {
            tenant_id: tenantId,
            token_type: 'invitation',
          },
        });

        // Count members joined (users in the tenant excluding the owner)
        const membersJoined = await this.userRepository.count({
          where: {
            tenant_id: tenantId,
            status: 'active',
          },
        });

        // Subtract 1 for the owner if there's at least one member
        const actualMembersJoined = membersJoined > 1 ? membersJoined - 1 : 0;

        return {
          invitesSent,
          membersJoined: actualMembersJoined,
        };
      }

      /**
       * Get plan data (subscription status)
       */
      private async getPlanData(tenantId: string): Promise<PlanDataDto> {
        const subscription = await this.subscriptionRepository.findOne({
          where: { tenant_id: tenantId },
          order: { created_at: 'DESC' },
        });

        return {
          selected: !!subscription,
          planId: subscription?.plan_id || null,
        };
      }

      /**
       * Calculate the current onboarding step
       * Step 1: Company info
       * Step 2: Team invitations
       * Step 3: Plan selection
       * Step 4: Complete
       */
      private calculateStep(
        companyData: CompanyDataDto | null,
        teamData: TeamDataDto,
        planData: PlanDataDto,
        tenant: Tenant,
      ): number {
        // If onboarding is already complete, return step 4
        if (tenant.status === 'active') {
          return 4;
        }

        // Step 1: Company info
        if (!companyData) {
          return 1;
        }

        // Step 2: Team invitations (optional, but track if done)
        // For step calculation, if company is done, move to step 2
        // The user can skip this step

        // Step 3: Plan selection
        if (!planData.selected) {
          // If company info is filled, we're at step 2 or 3
          // Check if we should be at step 2 (invite) or step 3 (plan)
          // For simplicity, if company is done but no plan, return step 3
          return 3;
        }

        // All prerequisites done, ready for completion
        return 4;
      }

      /**
       * Send welcome email to user
       */
      private async sendWelcomeEmail(user: User, tenant: Tenant): Promise<void> {
        try {
          await this.emailService.sendTemplateEmail({
            to: {
              email: user.email,
              name: user.first_name || undefined,
            },
            templateKey: 'welcome',
            variables: {
              userName: user.first_name || user.email,
              appName: 'Template SaaS',
              tenantName: tenant.name,
            },
          });

          this.logger.log(`Welcome email sent to ${user.email}`);
        } catch (error) {
          // Log error but don't fail the onboarding completion
          this.logger.error(`Failed to send welcome email to ${user.email}`, error.stack);
        }
      }
    }