All files / src/platform/registration registration.service.ts

0% Statements 0/91
0% Branches 0/62
0% Functions 0/7
0% Lines 0/85

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import {
  Injectable,
  BadRequestException,
  ConflictException,
  NotFoundException,
  Logger,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import * as crypto from 'crypto';
import * as bcrypt from 'bcrypt';
import { UserVerificationToken } from './schemas/verification.schema';
import { TenantProvisioningService } from '../provisioning/provisioning.service';
import { Tenant } from '../tenants/schemas/tenant.schema';
import { User } from '../user/schemas/user.schema';
import { Subscription } from '../subscriptions/schemas/subscription.schema';
import { NotificationService } from '../notifications/notification.service';
import { EventBusService } from '../events/event-bus.service';
 
@Injectable()
export class CompanyRegistrationService {
  private readonly logger = new Logger(CompanyRegistrationService.name);
 
  constructor(
    @InjectModel(UserVerificationToken.name)
    private readonly tokenModel: Model<UserVerificationToken>,
    @InjectModel(Tenant.name) private readonly tenantModel: Model<Tenant>,
    @InjectModel(User.name) private readonly userModel: Model<User>,
    @InjectModel(Subscription.name)
    private readonly subscriptionModel: Model<Subscription>,
    private readonly provisioning: TenantProvisioningService,
    private readonly notification: NotificationService,
    private readonly eventBus: EventBusService,
  ) {}
 
  async checkEmail(email: string): Promise<{ available: boolean }> {
    const user = await this.userModel.findOne({ email }).lean().exec();
    return { available: !user };
  }
 
  async checkSubdomain(subdomain: string): Promise<{ available: boolean }> {
    const tenant = await this.tenantModel
      .findOne({ slug: subdomain })
      .lean()
      .exec();
    return { available: !tenant };
  }
 
  async registerCompany(body: any): Promise<any> {
    const normalizedEmail = body.workEmail.toLowerCase().trim();
 
    // Check if email or subdomain already exists
    const emailCheck = await this.checkEmail(normalizedEmail);
    if (!emailCheck.available)
      throw new ConflictException('Work email already registered');
 
    const subdomainCheck = await this.checkSubdomain(body.requestedSubdomain);
    if (!subdomainCheck.available)
      throw new ConflictException('Subdomain already taken');
 
    const passwordHash = await bcrypt.hash(body.password, 10);
 
    // Create Saga Provisioning Execution
    const exec = await this.provisioning.createExecution({
      subdomain: body.requestedSubdomain,
      ownerEmail: normalizedEmail,
      ownerFirstName: body.ownerFirstName,
      ownerLastName: body.ownerLastName,
      ownerPasswordHash: passwordHash,
      companyName: body.companyName,
      planKey: body.selectedPlan || 'starter',
      billingCycle: body.billingCycle || 'monthly',
    });
 
    // Run provisioning steps in background
    await this.provisioning.run(exec.executionId);
 
    // Fetch ownerId created during provisioning steps
    const execDetails = await this.provisioning.getExecution(exec.executionId);
    const userId = execDetails.ownerId;
 
    // Generate Verification Token
    const rawToken = crypto.randomBytes(32).toString('hex');
    const tokenHash = crypto
      .createHash('sha256')
      .update(rawToken)
      .digest('hex');
 
    await this.tokenModel.create({
      userId,
      tokenHash,
      expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours expiry
    });
 
    // Queue Welcome / Verification email using Notification Engine
    // We register a notification trigger for "user.email-verification.requested"
    await this.notification.trigger({
      tenantId: execDetails.tenantId,
      userId,
      templateName: 'user.verification',
      variables: {
        firstName: body.ownerFirstName,
        verificationLink: `${process.env.APP_BASE_URL || 'http://localhost:3000'}/api/v1/auth/verify-email?token=${rawToken}`,
      },
    });
 
    await this.eventBus.publish(
      'platform.company.registration-started.v1',
      {
        email: normalizedEmail,
        subdomain: body.requestedSubdomain,
      },
      execDetails.tenantId,
    );
 
    return {
      success: true,
      message: 'Verification email sent. Please check your inbox.',
    };
  }
 
  async verifyEmail(token: string): Promise<any> {
    const tokenHash = crypto.createHash('sha256').update(token).digest('hex');
    const tokenRecord = await this.tokenModel.findOne({ tokenHash }).exec();
 
    if (!tokenRecord) {
      throw new BadRequestException('Invalid or expired verification token');
    }
 
    if (tokenRecord.expiresAt < new Date()) {
      throw new BadRequestException('Verification token has expired');
    }
 
    const userId = tokenRecord.userId;
    const user = await this.userModel.findById(userId).exec();
    if (!user) throw new NotFoundException('User profile not found');
 
    if (user.isActive) {
      return { success: true, message: 'Email already verified previously.' };
    }
 
    // Activate User
    user.isActive = true;
    await user.save();
 
    // Activate Tenant
    const tenant = await this.tenantModel.findById(user.tenantId).exec();
    if (tenant) {
      tenant.isActive = true;
      await tenant.save();
    }
 
    // Activate Subscription
    await this.subscriptionModel
      .updateOne({ tenantId: user.tenantId }, { $set: { status: 'trialing' } })
      .exec();
 
    // Remove token record
    await tokenRecord.deleteOne();
 
    await this.eventBus.publish(
      'platform.user.email-verified.v1',
      {
        userId,
        tenantId: user.tenantId,
      },
      user.tenantId,
    );
 
    await this.eventBus.publish(
      'platform.tenant.activated.v1',
      {
        tenantId: user.tenantId,
      },
      user.tenantId,
    );
 
    return {
      success: true,
      message: 'Account verified and activated successfully!',
    };
  }
 
  async resendVerification(email: string): Promise<any> {
    const user = await this.userModel
      .findOne({ email: email.toLowerCase().trim() })
      .lean()
      .exec();
    if (!user) throw new NotFoundException('User profile not found');
    if (user.isActive) throw new BadRequestException('Email already verified');
 
    // Rate-limit check
    const existingToken = await this.tokenModel
      .findOne({ userId: (user as any)._id.toString() })
      .exec();
    if (existingToken) {
      if (existingToken.resendCount >= 5) {
        throw new BadRequestException(
          'Too many verification resend attempts. Please contact support.',
        );
      }
      existingToken.resendCount += 1;
      existingToken.expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
      await existingToken.save();
    }
 
    const rawToken = crypto.randomBytes(32).toString('hex');
    const tokenHash = crypto
      .createHash('sha256')
      .update(rawToken)
      .digest('hex');
 
    if (!existingToken) {
      await this.tokenModel.create({
        userId: (user as any)._id.toString(),
        tokenHash,
        expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
      });
    } else {
      await this.tokenModel
        .updateOne(
          { userId: (user as any)._id.toString() },
          { $set: { tokenHash } },
        )
        .exec();
    }
 
    await this.notification.trigger({
      tenantId: user.tenantId,
      userId: (user as any)._id.toString(),
      templateName: 'user.verification',
      variables: {
        firstName: user.firstName,
        verificationLink: `${process.env.APP_BASE_URL || 'http://localhost:3000'}/api/v1/auth/verify-email?token=${rawToken}`,
      },
    });
 
    return { success: true, message: 'Verification link resent successfully.' };
  }
 
  async getVerificationStatus(userId: string): Promise<any> {
    const user = await this.userModel.findById(userId).lean().exec();
    if (!user) throw new NotFoundException('User profile not found');
    return { isVerified: user.isActive };
  }
}