All files / src/domains/hr/leave/optional-holiday optional-holiday.service.ts

0% Statements 0/20
0% Branches 0/16
0% Functions 0/4
0% Lines 0/18

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                                                                                                                                                           
import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  OptionalHolidayAllowance,
  EmployeeOptionalHolidaySelection,
} from '../schemas';
 
@Injectable()
export class OptionalHolidayService {
  constructor(
    @InjectModel(OptionalHolidayAllowance.name)
    private allowanceModel: Model<OptionalHolidayAllowance>,
    @InjectModel(EmployeeOptionalHolidaySelection.name)
    private selectionModel: Model<EmployeeOptionalHolidaySelection>,
  ) {}
 
  async selectHoliday(tenantId: string, employeeId: string, dto: any) {
    const allowance = await this.allowanceModel
      .findOne({
        tenantId,
        leavePeriodId: dto.leavePeriodId,
        status: 'active',
      })
      .exec();
 
    if (!allowance) {
      throw new BadRequestException(
        'No active optional holiday allowance configured for this period',
      );
    }
 
    if (
      allowance.selectionDeadline &&
      new Date().toISOString().split('T')[0] > allowance.selectionDeadline
    ) {
      throw new BadRequestException(
        'Optional holiday selection deadline has passed',
      );
    }
 
    const currentCount = await this.selectionModel.countDocuments({
      tenantId,
      employeeId,
      allowanceId: allowance._id.toString(),
      status: { $ne: 'cancelled' },
    });
 
    if (currentCount >= allowance.maxSelections) {
      throw new BadRequestException(
        `Maximum optional holiday selections limit reached (${allowance.maxSelections})`,
      );
    }
 
    return this.selectionModel.create({
      tenantId,
      employeeId,
      allowanceId: allowance._id.toString(),
      holidayId: dto.holidayId,
      holidayDate: dto.holidayDate,
      status: 'selected',
      selectedAt: new Date(),
    });
  }
 
  async getSelections(tenantId: string, employeeId: string) {
    return this.selectionModel.find({ tenantId, employeeId }).exec();
  }
 
  async cancelSelection(tenantId: string, employeeId: string, id: string) {
    return this.selectionModel.findOneAndUpdate(
      { _id: id, tenantId, employeeId },
      { $set: { status: 'cancelled', cancelReason: 'Cancelled by employee' } },
      { new: true },
    );
  }
}