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 | import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { EventBusService } from '../../../platform/events/event-bus.service'; import { CustomerOnboarding, CrmOnboardingChecklistItem, OnboardingTemplate, CustomerHealthScore, } from '../schemas/contract-onboarding.schema'; @Injectable() export class OnboardingService { private readonly logger = new Logger(OnboardingService.name); constructor( @InjectModel(CustomerOnboarding.name) private readonly onboardingModel: Model<CustomerOnboarding>, @InjectModel(CrmOnboardingChecklistItem.name) private readonly checklistModel: Model<CrmOnboardingChecklistItem>, @InjectModel(OnboardingTemplate.name) private readonly templateModel: Model<OnboardingTemplate>, @InjectModel(CustomerHealthScore.name) private readonly healthModel: Model<CustomerHealthScore>, private readonly eventBusService: EventBusService, ) {} async createOnboarding( tenantId: Types.ObjectId, data: Partial<CustomerOnboarding>, templateId?: string, ): Promise<CustomerOnboarding> { const onboarding = await this.onboardingModel.create({ ...data, tenantId }); // Apply template if specified if (templateId) { const template = await this.templateModel .findOne({ _id: templateId, tenantId }) .exec(); if (template) { for (const item of template.items) { await this.checklistModel.create({ tenantId, onboardingId: onboarding._id, itemName: item.itemName, description: item.description, sortOrder: item.sortOrder, required: item.required, dependsOn: item.dependsOn, status: 'pending', }); } } } await this.eventBusService.publish( 'crm.onboarding.created', { onboardingId: onboarding._id, accountId: data.accountId }, tenantId.toString(), ); return onboarding; } async getOnboardingById( tenantId: Types.ObjectId, onboardingId: string, ): Promise<CustomerOnboarding> { const onboarding = await this.onboardingModel .findOne({ _id: onboardingId, tenantId }) .exec(); if (!onboarding) throw new NotFoundException('Onboarding not found'); return onboarding; } async getOnboardingByAccount( tenantId: Types.ObjectId, accountId: string, ): Promise<CustomerOnboarding | null> { return this.onboardingModel .findOne({ tenantId, accountId: new Types.ObjectId(accountId) }) .exec(); } async getChecklistItems( tenantId: Types.ObjectId, onboardingId: string, ): Promise<CrmOnboardingChecklistItem[]> { return this.checklistModel .find({ tenantId, onboardingId: new Types.ObjectId(onboardingId) }) .sort({ sortOrder: 1 }) .exec(); } async updateChecklistItem( tenantId: Types.ObjectId, itemId: string, updates: Partial<CrmOnboardingChecklistItem>, ): Promise<CrmOnboardingChecklistItem> { const item = await this.checklistModel .findOneAndUpdate( { _id: itemId, tenantId }, { $set: updates }, { new: true }, ) .exec(); if (!item) throw new NotFoundException('Checklist item not found'); if (updates.status === 'completed') { (item as any).completedAt = new Date(); await item.save(); } // Recalculate completion percentage await this.recalculateCompletion(tenantId, item.onboardingId.toString()); return item; } private async recalculateCompletion( tenantId: Types.ObjectId, onboardingId: string, ): Promise<void> { const items = await this.checklistModel .find({ tenantId, onboardingId: new Types.ObjectId(onboardingId) }) .exec(); const total = items.length; const completed = items.filter( (i) => i.status === 'completed' || i.status === 'skipped', ).length; const percentage = total > 0 ? Math.round((completed / total) * 100) : 0; const status = percentage >= 100 ? 'completed' : 'in_progress'; await this.onboardingModel .findOneAndUpdate( { _id: onboardingId, tenantId }, { $set: { completionPercentage: percentage, status } }, ) .exec(); if (status === 'completed') { await this.eventBusService.publish( 'crm.onboarding.completed', { onboardingId }, tenantId.toString(), ); } } // ── TEMPLATES ── async createTemplate( tenantId: Types.ObjectId, data: Partial<OnboardingTemplate>, ): Promise<OnboardingTemplate> { return this.templateModel.create({ ...data, tenantId }); } async listTemplates(tenantId: Types.ObjectId): Promise<OnboardingTemplate[]> { return this.templateModel.find({ tenantId, active: true }).exec(); } // ── HEALTH SCORES ── async calculateHealthScore( tenantId: Types.ObjectId, accountId: string, ): Promise<CustomerHealthScore> { // Simplified health calculation — in production, this would aggregate from multiple data sources const score = await this.healthModel .findOneAndUpdate( { tenantId, accountId: new Types.ObjectId(accountId) }, { $set: { tenantId, accountId: new Types.ObjectId(accountId), lastCalculatedAt: new Date(), }, }, { new: true, upsert: true }, ) .exec(); return score; } async getHealthScore( tenantId: Types.ObjectId, accountId: string, ): Promise<CustomerHealthScore | null> { return this.healthModel .findOne({ tenantId, accountId: new Types.ObjectId(accountId) }) .exec(); } async updateHealthScore( tenantId: Types.ObjectId, accountId: string, updates: Partial<CustomerHealthScore>, ): Promise<CustomerHealthScore> { const previous = await this.healthModel .findOne({ tenantId, accountId: new Types.ObjectId(accountId) }) .exec(); const previousStatus = previous?.status; const score = await this.healthModel .findOneAndUpdate( { tenantId, accountId: new Types.ObjectId(accountId) }, { $set: { ...updates, lastCalculatedAt: new Date() } }, { new: true, upsert: true }, ) .exec(); if (previousStatus && previousStatus !== score.status) { await this.eventBusService.publish( 'crm.health_score.changed', { accountId, previousStatus, newStatus: score.status, }, tenantId.toString(), ); } return score; } async getAtRiskAccounts( tenantId: Types.ObjectId, ): Promise<CustomerHealthScore[]> { return this.healthModel .find({ tenantId, status: { $in: ['at_risk', 'critical'] } }) .sort({ overallScore: 1 }) .exec(); } } |