penisularhr / src / modules / cron / insert-long-service.service.ts
insert-long-service.service.ts
Raw
/* eslint-disable no-await-in-loop */
/* eslint-disable @typescript-eslint/naming-convention */
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import moment from 'moment';

import { IncentiveName } from '../../constants';
import { EmployeeService } from '../employee/employee.service';
import { IncentiveRecordService } from '../incentive/incentive-record.service';

@Injectable()
export class InsertLongService {
  constructor(
    private employeeService: EmployeeService,
    private incentiveService: IncentiveRecordService,
  ) {}

  isCronRunning = false;

  @Cron('0 50 23 * * *') //Everyday check 1 time
  async insertLongService() {
    if (this.isCronRunning === true) {
      return;
    }

    // Get the current date
    const today = moment.utc();

    // Check if today is the last day of the month
    const isEndOfMonth = today.isSame(today.endOf('month'), 'day');

    if (!isEndOfMonth) {
      return;
    }

    this.isCronRunning = true;

    const employees = await this.employeeService.findManyWithoutPagination({
      isActive: true,
    });

    if (employees.length === 0) {
      this.isCronRunning = false;

      return;
    }

    for (const employee of employees) {
      if (employee.dateResign && moment.utc().toDate() > employee.dateResign) {
        continue;
      }

      await this.incentiveService.createOrUpdateIncentiveByFunction(employee, {
        date: moment.utc().toDate(),
        incentiveName: IncentiveName.LONG_SERVICE,
      });
    }

    this.isCronRunning = false;
  }
}