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 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { LeaveAccrualRule, LeaveAccrualSchedule, LeaveAccrualExecution, LeaveAccrualExecutionItem, EmployeeLeaveAccount, } from '../schemas'; import { LeaveBalanceEngine } from '../balance/leave-balance.engine'; @Injectable() export class LeaveAccrualEngine { private readonly logger = new Logger(LeaveAccrualEngine.name); constructor( @InjectModel(LeaveAccrualRule.name) private ruleModel: Model<LeaveAccrualRule>, @InjectModel(LeaveAccrualSchedule.name) private scheduleModel: Model<LeaveAccrualSchedule>, @InjectModel(LeaveAccrualExecution.name) private executionModel: Model<LeaveAccrualExecution>, @InjectModel(LeaveAccrualExecutionItem.name) private itemModel: Model<LeaveAccrualExecutionItem>, @InjectModel(EmployeeLeaveAccount.name) private accountModel: Model<EmployeeLeaveAccount>, private balanceEngine: LeaveBalanceEngine, ) {} async createRule(tenantId: string, dto: any) { return this.ruleModel.create({ ...dto, tenantId }); } async getRules(tenantId: string, policyId: string) { return this.ruleModel.find({ tenantId, policyId }).exec(); } /** * Execute accrual for all employees in a tenant for the given date. * Idempotent — if execution for this schedule+date already ran, skip. */ async executeAccrual( tenantId: string, scheduleId: string, executionDate: string, isDryRun: boolean, triggeredBy: string, ) { const idempotencyKey = `accrual:${tenantId}:${scheduleId}:${executionDate}`; // Check if already executed const existing = await this.executionModel.findOne({ tenantId, idempotencyKey, }); if (existing && existing.status === 'completed') { this.logger.log(`Accrual already executed: ${idempotencyKey}`); return existing; } const execution = await this.executionModel.findOneAndUpdate( { tenantId, scheduleId, executionDate }, { $setOnInsert: { tenantId, scheduleId, executionDate, idempotencyKey, status: 'running', isDryRun, triggeredBy, startedAt: new Date(), }, }, { upsert: true, new: true }, ); const schedule = await this.scheduleModel .findOne({ _id: scheduleId }) .exec(); if (!schedule) { execution.status = 'failed'; execution.errorMessage = 'Schedule not found'; await execution.save(); return execution; } const rule = await this.ruleModel.findOne({ _id: schedule.ruleId }).exec(); if (!rule) { execution.status = 'failed'; execution.errorMessage = 'Rule not found'; await execution.save(); return execution; } // Fetch all employees with an account for this rule's leaveType const accounts = await this.accountModel .find({ tenantId, leaveTypeId: rule.leaveTypeId, status: 'active', }) .exec(); execution.totalEmployees = accounts.length; await execution.save(); let processedCount = 0; let failedCount = 0; for (const account of accounts) { try { const accrualAmount = await this.computeAccrualAmount(rule, account); if (accrualAmount <= 0) { await this.itemModel.create({ tenantId, executionId: execution._id.toString(), employeeId: account.employeeId, leaveTypeId: account.leaveTypeId, status: isDryRun ? 'dry-run' : 'skipped', accrualAmount, }); continue; } if (!isDryRun) { const ledger = await this.balanceEngine.writeLedger({ tenantId, employeeId: account.employeeId, leaveTypeId: account.leaveTypeId, leavePeriodId: account.leavePeriodId, accountId: account._id.toString(), transactionType: 'Accrual', quantity: accrualAmount, unit: rule.unit, effectiveDate: executionDate, sourceEntityType: 'AccrualExecution', sourceEntityId: execution._id.toString(), idempotencyKey: `accrual-item:${execution._id}:${account.employeeId}:${account.leaveTypeId}`, createdBy: 'system', }); await this.itemModel.create({ tenantId, executionId: execution._id.toString(), employeeId: account.employeeId, leaveTypeId: account.leaveTypeId, status: 'success', accrualAmount, ledgerId: ledger._id.toString(), }); } else { await this.itemModel.create({ tenantId, executionId: execution._id.toString(), employeeId: account.employeeId, leaveTypeId: account.leaveTypeId, status: 'dry-run', accrualAmount, }); } processedCount++; } catch (err) { this.logger.error( `Accrual failed for ${account.employeeId}: ${err.message}`, ); await this.itemModel.create({ tenantId, executionId: execution._id.toString(), employeeId: account.employeeId, leaveTypeId: account.leaveTypeId, status: 'failed', accrualAmount: 0, errorMessage: err.message, }); failedCount++; } } execution.status = 'completed'; execution.processedCount = processedCount; execution.failedCount = failedCount; execution.completedAt = new Date(); await execution.save(); await this.scheduleModel.findOneAndUpdate( { _id: scheduleId }, { $set: { lastRunAt: new Date(), lastRunResult: 'completed' } }, ); return execution; } private async computeAccrualAmount( rule: LeaveAccrualRule, account: EmployeeLeaveAccount, ): Promise<number> { let amount = rule.accrualAmount; // Apply max balance cap if (rule.maximumBalanceCap) { const current = account.accruedBalance + account.openingBalance - account.consumedBalance; if (current >= rule.maximumBalanceCap) return 0; amount = Math.min(amount, rule.maximumBalanceCap - current); } // Apply rounding if (rule.roundingRule === 'Floor') amount = Math.floor(amount); else if (rule.roundingRule === 'Ceil') amount = Math.ceil(amount); else if (rule.roundingRule === 'Round') amount = Math.round(amount); return amount; } async getExecutionReport(tenantId: string, executionId: string) { const execution = await this.executionModel .findOne({ _id: executionId, tenantId }) .exec(); const items = await this.itemModel.find({ tenantId, executionId }).exec(); return { execution, items }; } } |