All files / src/domains/hr/attendance/engine engine.service.ts

0% Statements 0/62
0% Branches 0/61
0% Functions 0/7
0% Lines 0/60

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 227 228 229 230 231                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  AttendancePunch,
  AttendanceDailyRecord,
  AttendanceCalculation,
  AttendanceException,
  AttendanceSession,
  AttendanceBreak,
} from '../schemas';
 
@Injectable()
export class AttendanceCalculationEngine {
  private readonly logger = new Logger(AttendanceCalculationEngine.name);
 
  constructor(
    @InjectModel(AttendancePunch.name)
    private punchModel: Model<AttendancePunch>,
    @InjectModel(AttendanceSession.name)
    private sessionModel: Model<AttendanceSession>,
    @InjectModel(AttendanceBreak.name)
    private breakModel: Model<AttendanceBreak>,
    @InjectModel(AttendanceDailyRecord.name)
    private dailyRecordModel: Model<AttendanceDailyRecord>,
    @InjectModel(AttendanceCalculation.name)
    private calcLogModel: Model<AttendanceCalculation>,
    @InjectModel(AttendanceException.name)
    private exceptionModel: Model<AttendanceException>,
  ) {}
 
  /**
   * Main entry point to calculate attendance for an employee on a specific date
   */
  async calculateDailyAttendance(
    tenantId: string,
    employeeId: string,
    targetDate: string,
  ) {
    this.logger.log(
      `Calculating attendance for ${employeeId} on ${targetDate}`,
    );
 
    // 1. Fetch Inputs
    // - Punches for the date
    // - Shift Assignment for the date
    // - Attendance Policy for the employee
    // - Holiday Calendar / Work Week definitions for the date
    // (Mocking the fetches for policy/shift in this implementation stub)
 
    const punches = await this.punchModel
      .find({
        tenantId,
        employeeId,
        attendanceDate: targetDate,
        corrected: false, // Only active punches
      })
      .sort({ timestamp: 1 })
      .exec();
 
    // Mock policy & shift (would be fetched from respective services)
    const mockPolicy = {
      lateMarkEnabled: true,
      lateGraceMinutes: 15,
      earlyDepartureMarkEnabled: true,
      earlyDepartureGraceMinutes: 15,
      minimumWorkMinutes: 240,
      fullDayMinutes: 480,
      halfDayMinutes: 240,
      absentWhenNoPunch: true,
    };
    const mockShift = {
      startTime: '09:00',
      endTime: '18:00',
      totalScheduledMinutes: 480,
      unpaidBreakMinutes: 60,
    };
 
    // 2. Process Sessions & Breaks
    // If we have 0 punches and it's a working day
    if (punches.length === 0) {
      return this.handleNoPunches(tenantId, employeeId, targetDate, mockPolicy);
    }
 
    // Pair punches into sessions
    const { sessions, firstIn, lastOut, totalWorkedMinutes } =
      this.pairPunches(punches);
 
    // 3. Determine Late / Early (Step 11)
    let lateMinutes = 0;
    let earlyDepartureMinutes = 0;
 
    if (firstIn) {
      // Mock calculation against 09:00 Shift
      const shiftStartStr = `${targetDate}T${mockShift.startTime}:00`;
      const shiftStart = new Date(shiftStartStr);
      const inDiff = (firstIn.getTime() - shiftStart.getTime()) / 60000;
      if (inDiff > mockPolicy.lateGraceMinutes) {
        lateMinutes = inDiff;
      }
    }
 
    if (lastOut) {
      const shiftEndStr = `${targetDate}T${mockShift.endTime}:00`;
      const shiftEnd = new Date(shiftEndStr);
      const outDiff = (shiftEnd.getTime() - lastOut.getTime()) / 60000;
      if (outDiff > mockPolicy.earlyDepartureGraceMinutes) {
        earlyDepartureMinutes = outDiff;
      }
    }
 
    // 4. Calculate Status
    let status = 'Present';
    if (totalWorkedMinutes < mockPolicy.minimumWorkMinutes) {
      status = 'Absent';
    } else if (totalWorkedMinutes < mockPolicy.fullDayMinutes) {
      status = 'Half Day';
    }
 
    // 5. Calculate Overtime (Step 13)
    let overtimeMinutes = 0;
    if (totalWorkedMinutes > mockShift.totalScheduledMinutes) {
      overtimeMinutes = totalWorkedMinutes - mockShift.totalScheduledMinutes;
    }
 
    // 6. Save Daily Record
    const record = await this.dailyRecordModel.findOneAndUpdate(
      { tenantId, employeeId, attendanceDate: targetDate },
      {
        scheduledStart: new Date(`${targetDate}T${mockShift.startTime}:00`),
        scheduledEnd: new Date(`${targetDate}T${mockShift.endTime}:00`),
        firstCheckIn: firstIn,
        lastCheckOut: lastOut,
        workedMinutes: totalWorkedMinutes,
        scheduledMinutes: mockShift.totalScheduledMinutes,
        lateMinutes,
        earlyDepartureMinutes,
        overtimeMinutes,
        attendanceStatus: status,
        dayType: 'Working day',
        calculatedAt: new Date(),
      },
      { upsert: true, new: true },
    );
 
    // 7. Generate Exceptions (Late/Early)
    if (lateMinutes > 0) {
      await this.logException(
        tenantId,
        employeeId,
        targetDate,
        'Late Arrival',
        lateMinutes,
      );
    }
    if (earlyDepartureMinutes > 0) {
      await this.logException(
        tenantId,
        employeeId,
        targetDate,
        'Early Departure',
        earlyDepartureMinutes,
      );
    }
 
    // 8. Log Calculation Run
    await this.calcLogModel.create({
      tenantId,
      employeeId,
      attendanceDate: targetDate,
      snapshotData: { punchesCount: punches.length, record: record.toObject() },
    });
 
    return record;
  }
 
  private handleNoPunches(
    tenantId: string,
    employeeId: string,
    targetDate: string,
    policy: any,
  ) {
    // Determine if it's a Weekly Off, Holiday, or Working Day.
    // If Working Day and absentWhenNoPunch is true => Absent.
    // Simplifying for this implementation.
    return this.dailyRecordModel.findOneAndUpdate(
      { tenantId, employeeId, attendanceDate: targetDate },
      {
        workedMinutes: 0,
        attendanceStatus: policy.absentWhenNoPunch ? 'Absent' : 'Missed Punch',
        calculatedAt: new Date(),
      },
      { upsert: true, new: true },
    );
  }
 
  private pairPunches(punches: AttendancePunch[]) {
    // A simplified pairing logic. Real engine handles multi-sessions, out-of-order, missed punches.
    const ins = punches.filter(
      (p) => p.punchType === 'Check In' || p.punchType === 'Site In',
    );
    const outs = punches.filter(
      (p) => p.punchType === 'Check Out' || p.punchType === 'Site Out',
    );
 
    const firstIn = ins.length > 0 ? ins[0].timestamp : null;
    const lastOut = outs.length > 0 ? outs[outs.length - 1].timestamp : null;
 
    let totalWorkedMinutes = 0;
    if (firstIn && lastOut && lastOut > firstIn) {
      totalWorkedMinutes = (lastOut.getTime() - firstIn.getTime()) / 60000;
    }
 
    return { sessions: [], firstIn, lastOut, totalWorkedMinutes };
  }
 
  private async logException(
    tenantId: string,
    employeeId: string,
    date: string,
    type: string,
    minutes: number,
  ) {
    await this.exceptionModel.findOneAndUpdate(
      { tenantId, employeeId, attendanceDate: date, exceptionType: type },
      { minutes, severity: minutes > 60 ? 'High' : 'Low' },
      { upsert: true },
    );
  }
}