All files / src/domains/hr/leave/encashment encashment.service.ts

0% Statements 0/38
0% Branches 0/28
0% Functions 0/5
0% Lines 0/34

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                                                                                                                                                                                                                                                     
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  LeaveEncashmentPolicy,
  LeaveEncashmentRequest,
  LeaveEncashmentTransaction,
} from '../schemas';
import { LeaveBalanceEngine } from '../balance/leave-balance.engine';
 
@Injectable()
export class EncashmentService {
  private readonly logger = new Logger(EncashmentService.name);
 
  constructor(
    @InjectModel(LeaveEncashmentPolicy.name)
    private policyModel: Model<LeaveEncashmentPolicy>,
    @InjectModel(LeaveEncashmentRequest.name)
    private requestModel: Model<LeaveEncashmentRequest>,
    @InjectModel(LeaveEncashmentTransaction.name)
    private txnModel: Model<LeaveEncashmentTransaction>,
    private balanceEngine: LeaveBalanceEngine,
  ) {}
 
  async createPolicy(tenantId: string, dto: any, userId: string) {
    return this.policyModel.create({ ...dto, tenantId, createdBy: userId });
  }
 
  async submitRequest(tenantId: string, dto: any, userId: string) {
    const policy = await this.policyModel
      .findOne({ _id: dto.policyId, tenantId })
      .exec();
    if (!policy) throw new NotFoundException('Encashment policy not found');
 
    // Validate balance
    const available = await this.balanceEngine.computeAvailableBalance(
      tenantId,
      dto.employeeId,
      dto.leaveTypeId,
      dto.leavePeriodId,
    );
    const remainingAfter = available - dto.requestedDays;
    if (
      policy.minRemainingBalance &&
      remainingAfter < policy.minRemainingBalance
    ) {
      throw new NotFoundException(
        `Must retain at least ${policy.minRemainingBalance} days balance`,
      );
    }
    if (dto.requestedDays > policy.maxEncashmentDays) {
      throw new NotFoundException(
        `Maximum ${policy.maxEncashmentDays} days can be encashed`,
      );
    }
 
    return this.requestModel.create({
      ...dto,
      tenantId,
      status: policy.approvalRequired ? 'pending' : 'approved',
      requestedByUser: userId,
    });
  }
 
  async approveEncashment(tenantId: string, requestId: string, userId: string) {
    const request = await this.requestModel
      .findOne({ _id: requestId, tenantId })
      .exec();
    if (!request) throw new NotFoundException('Encashment request not found');
 
    request.status = 'approved';
    request.approvedDays = request.requestedDays;
    request.approvedBy = userId;
    request.approvedAt = new Date();
 
    const account = await this.balanceEngine.ensureAccount(
      tenantId,
      request.employeeId,
      request.leaveTypeId,
      request.leavePeriodId,
    );
    const ledger = await this.balanceEngine.writeLedger({
      tenantId,
      employeeId: request.employeeId,
      leaveTypeId: request.leaveTypeId,
      leavePeriodId: request.leavePeriodId,
      accountId: account._id.toString(),
      transactionType: 'Encashment',
      quantity: -request.requestedDays,
      unit: request.unit,
      effectiveDate: new Date().toISOString().split('T')[0],
      sourceEntityType: 'EncashmentRequest',
      sourceEntityId: request._id.toString(),
      idempotencyKey: `encashment:${request._id}`,
      createdBy: userId,
    });
 
    request.ledgerId = ledger._id.toString();
    await request.save();
 
    await this.txnModel.create({
      tenantId,
      requestId: request._id.toString(),
      employeeId: request.employeeId,
      leaveTypeId: request.leaveTypeId,
      quantity: request.requestedDays,
      unit: request.unit,
      ledgerId: ledger._id.toString(),
      transactionType: 'debit',
    });
 
    return request;
  }
 
  async rejectEncashment(tenantId: string, requestId: string, reason: string) {
    return this.requestModel.findOneAndUpdate(
      { _id: requestId, tenantId },
      { $set: { status: 'rejected', rejectionReason: reason } },
      { new: true },
    );
  }
}