All files / src/platform/calendar working-calendar.service.ts

0% Statements 0/29
0% Branches 0/18
0% Functions 0/4
0% Lines 0/26

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                                                                                                                                 
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { WorkingCalendar } from './schemas';
 
@Injectable()
export class WorkingCalendarService {
  private readonly logger = new Logger(WorkingCalendarService.name);
 
  constructor(
    @InjectModel(WorkingCalendar.name)
    private readonly workingCalendarModel: Model<WorkingCalendar>
  ) {}
 
  /**
   * Calculates SLA elapsed working minutes between two dates.
   */
  async calculateWorkingMinutes(
    tenantId: string,
    start: Date,
    end: Date
  ): Promise<number> {
    const calendar = await this.workingCalendarModel.findOne({
      tenantId,
      status: 'active'
    }).exec();
 
    if (!calendar) {
      // Default fallback if no custom calendar exists: continuous 24/7 minutes
      return Math.round((end.getTime() - start.getTime()) / 60000);
    }
 
    let elapsedMinutes = 0;
    let scanTime = new Date(start.getTime());
 
    // Iterate minute-by-minute or in safe chunks
    const stepMs = 15 * 60000; // 15-minute chunks for efficiency
 
    while (scanTime.getTime() < end.getTime()) {
      const dayOfWeek = scanTime.getUTCDay();
      const rule = calendar.workingDays.find(d => d.dayOfWeek === dayOfWeek);
 
      if (rule && rule.isWorkingDay) {
        const timeStr = `${String(scanTime.getUTCHours()).padStart(2, '0')}:${String(scanTime.getUTCMinutes()).padStart(2, '0')}`;
        
        // Find if scanTime falls within any working shifts
        const inShift = rule.shifts.some(s => {
          if (s.crossesMidnight) {
            return timeStr >= s.startTime || timeStr <= s.endTime;
          }
          return timeStr >= s.startTime && timeStr <= s.endTime;
        });
 
        if (inShift) {
          elapsedMinutes += 15;
        }
      }
 
      scanTime = new Date(scanTime.getTime() + stepMs);
    }
 
    return elapsedMinutes;
  }
}