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 | import { Injectable, BadRequestException, NotFoundException, Logger, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import * as bcrypt from 'bcrypt'; import { TenantProvisioningExecution, TenantProvisioningStep, } from './schemas/provisioning.schema'; import { Tenant } from '../tenants/schemas/tenant.schema'; import { User } from '../user/schemas/user.schema'; import { SubscriptionPlan, SubscriptionPlanVersion, } from '../subscriptions/schemas/subscription-plan.schema'; import { Subscription } from '../subscriptions/schemas/subscription.schema'; import { TenantModuleLicense } from '../auth/schemas/module.schema'; import { FeatureFlag } from '../feature-flags/schemas/feature-flag.schema'; import { UniversalSetting } from '../settings/schemas/universal-setting.schema'; import { Folder } from '../documents/schemas/storage.schema'; import { PolicyDefinition } from '../permissions/schemas/permission.schema'; import { AuditLogService } from '../audit/audit-log.service'; import { EventBusService } from '../events/event-bus.service'; @Injectable() export class TenantProvisioningService { private readonly logger = new Logger(TenantProvisioningService.name); constructor( @InjectModel(TenantProvisioningExecution.name) private readonly execModel: Model<TenantProvisioningExecution>, @InjectModel(TenantProvisioningStep.name) private readonly stepModel: Model<TenantProvisioningStep>, @InjectModel(Tenant.name) private readonly tenantModel: Model<Tenant>, @InjectModel(User.name) private readonly userModel: Model<User>, @InjectModel(SubscriptionPlan.name) private readonly planModel: Model<SubscriptionPlan>, @InjectModel(SubscriptionPlanVersion.name) private readonly planVersionModel: Model<SubscriptionPlanVersion>, @InjectModel(Subscription.name) private readonly subscriptionModel: Model<Subscription>, @InjectModel(TenantModuleLicense.name) private readonly licenseModel: Model<TenantModuleLicense>, @InjectModel(FeatureFlag.name) private readonly featureFlagModel: Model<FeatureFlag>, @InjectModel(UniversalSetting.name) private readonly settingModel: Model<UniversalSetting>, @InjectModel(Folder.name) private readonly folderModel: Model<Folder>, @InjectModel(PolicyDefinition.name) private readonly policyModel: Model<PolicyDefinition>, private readonly auditLog: AuditLogService, private readonly eventBus: EventBusService, ) {} async createExecution(params: { subdomain: string; ownerEmail: string; ownerFirstName: string; ownerLastName: string; ownerPasswordHash: string; companyName: string; planKey: string; billingCycle?: string; }): Promise<any> { // Prevent duplicate registrations const existing = await this.execModel .findOne({ subdomain: params.subdomain }) .exec(); if (existing && existing.status !== 'failed') { throw new BadRequestException( `Provisioning execution or subdomain already active: ${params.subdomain}`, ); } const plan = await this.planModel .findOne({ key: params.planKey, isActive: true }) .lean() .exec(); if (!plan) throw new BadRequestException( `Subscription plan key not found: ${params.planKey}`, ); const exec = await this.execModel.create({ subdomain: params.subdomain, ownerEmail: params.ownerEmail, status: 'pending', metadata: params, }); return { executionId: (exec as any)._id.toString(), status: 'pending' }; } async run(executionId: string): Promise<void> { const exec = await this.execModel.findById(executionId).exec(); if (!exec) throw new NotFoundException('Provisioning execution not found'); exec.status = 'running'; await exec.save(); const metadata = exec.metadata; const steps = [ 'CREATE_TENANT', 'CREATE_OWNER', 'INITIALIZE_SUBSCRIPTION', 'INITIALIZE_MODULE_LICENSES', 'INITIALIZE_SETTINGS', 'INITIALIZE_FEATURE_FLAGS', 'INITIALIZE_DOCUMENTS_FOLDERS', 'INITIALIZE_POLICIES', 'PUBLISH_EVENTS', ]; let tenantId = exec.tenantId; let ownerId = exec.ownerId; for (const stepName of steps) { // Check if step completed previously let step = await this.stepModel.findOne({ executionId, stepName }).exec(); if (step && step.status === 'completed') { continue; } if (!step) { step = await this.stepModel.create({ executionId, stepName, status: 'running', }); } else { step.status = 'running'; await step.save(); } try { if (stepName === 'CREATE_TENANT') { // Check if subdomain is already used const existingTenant = await this.tenantModel .findOne({ slug: metadata.subdomain }) .lean() .exec(); if (existingTenant) { tenantId = (existingTenant as any)._id.toString(); } else { const newTenant = await this.tenantModel.create({ name: metadata.companyName, slug: metadata.subdomain, domain: `${metadata.subdomain}.bevision.io`, logo: '', favicon: '', primaryColor: '#0F172A', accentColor: '#3B82F6', isActive: false, // Inactive until email verified }); tenantId = (newTenant as any)._id.toString(); } exec.tenantId = tenantId; await exec.save(); } else if (stepName === 'CREATE_OWNER') { const existingUser = await this.userModel .findOne({ email: metadata.ownerEmail }) .lean() .exec(); if (existingUser) { ownerId = (existingUser as any)._id.toString(); } else { const newUser = await this.userModel.create({ tenantId, email: metadata.ownerEmail, passwordHash: metadata.ownerPasswordHash, firstName: metadata.ownerFirstName, lastName: metadata.ownerLastName, roles: ['ADMIN'], // Initial Owner role isActive: false, // Pending verification }); ownerId = (newUser as any)._id.toString(); } exec.ownerId = ownerId; await exec.save(); } else if (stepName === 'INITIALIZE_SUBSCRIPTION') { const plan = await this.planModel .findOne({ key: metadata.planKey }) .lean() .exec(); const version = await this.planVersionModel .findOne({ planId: (plan as any)._id.toString() }) .sort({ version: -1 }) .lean() .exec(); if (!version) throw new Error('No plan versions defined'); const existingSub = await this.subscriptionModel .findOne({ tenantId }) .lean() .exec(); if (!existingSub) { const trialDays = version.trialDurationDays || 14; await this.subscriptionModel.create({ tenantId, planVersionId: (version as any)._id.toString(), status: 'pending', // Pending email verification currentPeriodStart: new Date(), currentPeriodEnd: new Date( Date.now() + trialDays * 24 * 60 * 60 * 1000, ), autoRenew: true, trialStart: new Date(), trialEnd: new Date(Date.now() + trialDays * 24 * 60 * 60 * 1000), }); } } else if (stepName === 'INITIALIZE_MODULE_LICENSES') { const plan = await this.planModel .findOne({ key: metadata.planKey }) .lean() .exec(); const version = await this.planVersionModel .findOne({ planId: (plan as any)._id.toString() }) .sort({ version: -1 }) .lean() .exec(); if (version) { for (const moduleKey of version.allowedModuleKeys) { await this.licenseModel .findOneAndUpdate( { tenantId, moduleKey }, { tenantId, moduleKey, isActive: true }, { upsert: true }, ) .exec(); } } } else if (stepName === 'INITIALIZE_SETTINGS') { await this.settingModel.create({ tenantId, key: 'system.theme', value: { primaryColor: '#0F172A', accentColor: '#3B82F6' }, category: 'THEME', }); } else if (stepName === 'INITIALIZE_FEATURE_FLAGS') { await this.featureFlagModel.create({ tenantId, key: 'erp.analytics', name: 'Analytics Toggles', isEnabled: true, }); } else if (stepName === 'INITIALIZE_DOCUMENTS_FOLDERS') { await this.folderModel.create({ tenantId, name: 'Root', parentFolderId: null, path: '/', ownerId, }); } else if (stepName === 'INITIALIZE_POLICIES') { // Initialize owner admin permissions await this.policyModel.create({ tenantId, name: 'Admin Policy', statements: [ { effect: 'ALLOW', actions: ['*'], resources: ['*'], }, ], }); } else if (stepName === 'PUBLISH_EVENTS') { await this.eventBus.publish( 'platform.tenant.provisioning-started.v1', { tenantId, ownerId, subdomain: metadata.subdomain, }, tenantId, ); } step.status = 'completed'; step.completedAt = new Date(); await step.save(); } catch (err: any) { step.status = 'failed'; step.error = err.message || 'Unknown provisioning error'; await step.save(); exec.status = 'failed'; await exec.save(); await this.eventBus.publish( 'platform.tenant.provisioning-failed.v1', { executionId, stepName, error: step.error, }, 'SYSTEM', ); throw err; } } exec.status = 'completed'; await exec.save(); await this.eventBus.publish( 'platform.tenant.provisioned.v1', { tenantId, ownerId, subdomain: metadata.subdomain, }, tenantId, ); // Initial audit log await this.auditLog.log({ tenantId, userId: ownerId, action: 'TENANT_PROVISION', resource: 'Tenant', resourceId: tenantId, }); } async getExecutions(): Promise<any[]> { return this.execModel.find().lean().exec(); } async getExecution(id: string): Promise<any> { const exec = await this.execModel.findById(id).lean().exec(); if (!exec) throw new NotFoundException('Execution record not found'); const steps = await this.stepModel.find({ executionId: id }).lean().exec(); return { ...exec, steps }; } } |