All files / src/domains/hr/numbering numbering.service.ts

0% Statements 0/26
0% Branches 0/16
0% Functions 0/4
0% Lines 0/24

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                                                                                                             
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  EmployeeNumberingRule,
  EmployeeNumberSequence,
} from './schemas/numbering.schema';
 
@Injectable()
export class EmployeeNumberingService {
  constructor(
    @InjectModel(EmployeeNumberingRule.name)
    private readonly ruleModel: Model<EmployeeNumberingRule>,
    @InjectModel(EmployeeNumberSequence.name)
    private readonly sequenceModel: Model<EmployeeNumberSequence>,
  ) {}
 
  async getRule(tenantId: string) {
    let rule = await this.ruleModel.findOne({ tenantId }).exec();
    if (!rule) {
      rule = await this.ruleModel.create({ tenantId });
    }
    return rule;
  }
 
  async updateRule(tenantId: string, data: any) {
    const rule = await this.getRule(tenantId);
    Object.assign(rule, data);
    return rule.save();
  }
 
  async generateNextNumber(tenantId: string): Promise<string> {
    const rule = await this.getRule(tenantId);
    const dateKey = rule.resetYearly
      ? new Date().getFullYear().toString()
      : 'GLOBAL';
 
    const sequence = await this.sequenceModel.findOneAndUpdate(
      { tenantId, key: dateKey },
      { $inc: { currentSequence: 1 } },
      { new: true, upsert: true, setDefaultsOnInsert: true },
    );
 
    let nextValue = sequence.currentSequence;
    if (nextValue === 1 && rule.startSequence > 1) {
      nextValue = rule.startSequence;
      sequence.currentSequence = nextValue;
      await sequence.save();
    }
 
    const paddedStr = nextValue.toString().padStart(rule.padding, '0');
    return `${rule.prefix}${paddedStr}${rule.suffix}`;
  }
}