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 | import { Injectable, BadRequestException } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { Asset, DepreciationSchedule, DepreciationRun } from '../schemas'; import { EventBusService } from '../../../platform/events/event-bus.service'; @Injectable() export class AssetDepreciationService { constructor( @InjectModel(Asset.name) private readonly assetModel: Model<Asset>, @InjectModel(DepreciationSchedule.name) private readonly scheduleModel: Model<DepreciationSchedule>, @InjectModel(DepreciationRun.name) private readonly runModel: Model<DepreciationRun>, private readonly eventBus: EventBusService ) {} async calculateAssetPeriodDepreciation( tenantId: string, asset: Asset, fiscalYearId: string, periodNumber: number ): Promise<DepreciationSchedule | null> { if (asset.status !== 'capitalized' && asset.status !== 'assigned' && asset.status !== 'under_maintenance') { return null; } const nbv = asset.currentBookValueMinor; if (nbv <= asset.residualValueMinor) { return null; // Already reached residual floor - do not depreciate further } let depAmount = 0; if (asset.depreciationMethod === 'Straight Line') { // Monthly straight line: (capitalizationCost - residualValue) / usefulLife const depreciableAmount = asset.capitalizationCostMinor - asset.residualValueMinor; depAmount = Math.round(depreciableAmount / asset.usefulLifeMonths); } else if (asset.depreciationMethod === 'Written Down Value') { // WDV: book value * WDV rate (e.g. 15% per annum, monthly rate = 15/12 = 1.25%) const ratePerMonth = 0.15 / 12; depAmount = Math.round(nbv * ratePerMonth); } else { return null; // No depreciation } // Floor constraint check: net book value cannot fall below residual value if (nbv - depAmount < asset.residualValueMinor) { depAmount = nbv - asset.residualValueMinor; } if (depAmount <= 0) return null; const schedule = new this.scheduleModel({ tenantId, assetId: asset._id, fiscalYearId, periodNumber, depreciationAmountMinor: depAmount, bookValueBeforeMinor: nbv, bookValueAfterMinor: nbv - depAmount, status: 'pending' }); return schedule.save(); } async executeDepreciationRun( tenantId: string, fiscalYearId: string, periodNumber: number, userId: string ): Promise<DepreciationRun> { const count = await this.runModel.countDocuments({ tenantId }).exec(); const runNumber = `DEP-RUN-${String(count + 1).padStart(6, '0')}`; // Find all active assets to depreciate const assets = await this.assetModel.find({ tenantId, status: { $in: ['capitalized', 'assigned', 'under_maintenance'] } }).exec(); let totalRunDepreciation = 0; const schedules: DepreciationSchedule[] = []; for (const asset of assets) { const schedule = await this.calculateAssetPeriodDepreciation(tenantId, asset, fiscalYearId, periodNumber); if (schedule) { totalRunDepreciation += schedule.depreciationAmountMinor; schedules.push(schedule); } } if (totalRunDepreciation === 0) { throw new BadRequestException('No assets are eligible for depreciation posting in this period.'); } const run = new this.runModel({ tenantId, runNumber, fiscalYearId, periodNumber, totalDepreciationMinor: totalRunDepreciation, status: 'posting_ready' }); await run.save(); // Link schedules to run in mock db logic or save for (const s of schedules) { s.status = 'pending'; await s.save(); } // Trigger Finance posting handshake await this.eventBus.publish('asset.depreciation-posting-ready.v1', { runId: run._id.toString(), runNumber: run.runNumber, tenantId, totalDepreciationMinor: totalRunDepreciation, fiscalYearId, periodNumber, userId }, tenantId); return run; } async handleFinanceDepreciationPosted(tenantId: string, runId: string): Promise<DepreciationRun> { const run = await this.runModel.findOne({ _id: runId, tenantId }).exec(); if (!run) throw new Error('Depreciation run not found'); run.status = 'posted'; run.postedAt = new Date(); await run.save(); // Reconcile and update asset book values const schedules = await this.scheduleModel.find({ tenantId, fiscalYearId: run.fiscalYearId, periodNumber: run.periodNumber, status: 'pending' }).exec(); for (const s of schedules) { s.status = 'posted'; await s.save(); // Deduct from Asset book value await this.assetModel.updateOne( { _id: s.assetId }, { $inc: { accumulatedDepreciationMinor: s.depreciationAmountMinor, currentBookValueMinor: -s.depreciationAmountMinor } } ); } return run; } } |