All files / src/services/scan sla-config.service.ts

7.41% Statements 8/108
0% Branches 0/50
0% Functions 0/12
5.77% Lines 6/104

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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 3241x 1x 1x 1x 1x                                                   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import {bind, BindingScope} from '@loopback/core';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {SlaConfigRepository} from '@logchain/repositories/scan/sla-config.repository';
import {HolidayCalendarRepository} from '@logchain/repositories/scan/holiday-calendar.repository';
import {SlaConfig} from '@logchain/models/scan/sla-config.model';
 
export interface SlaCalculationResult {
  provider: string;
  startTime: Date;
  slaHours: number;
  deadline: Date;
  includeWeekend: boolean;
  includePublicHoliday: boolean;
  workingDays: number;
  breakdown: {
    fullDays: number;
    remainingHours: number;
  };
}
 
export interface SlaCalculationParams {
  provider: string;
  startDateTime: Date;
  countryCode?: string;
}
 
@bind({
  scope: BindingScope.TRANSIENT,
})
export class SlaConfigService {
  constructor(
    @repository(SlaConfigRepository)
    private slaRepo: SlaConfigRepository,
 
    @repository(HolidayCalendarRepository)
    private holidayRepo: HolidayCalendarRepository,
  ) {}
 
  /**
   * Calculate SLA deadline based on provider configuration.
   * Trả null (không throw) khi không tìm thấy SLA config,
   * để FE tự fallback về 72h mặc định.
   */
  async calculateSlaDeadline(params: SlaCalculationParams): Promise<SlaCalculationResult | null> {
    const {provider, startDateTime, countryCode} = params;
 
    if (!provider || !startDateTime) {
      throw new HttpErrors.BadRequest('Provider and startDateTime are required');
    }
 
    // Không tìm thấy config → trả null thay vì throw 404
    const slaConfig = await this.slaRepo.findByProviderAndCountry(provider, countryCode);
 
    if (!slaConfig) {
      console.warn(`SLA config not found for provider: ${provider}, countryCode: ${countryCode ?? 'N/A'}`);
      return null;
    }
 
    // Config bị inactive/deleted → trả null thay vì throw
    if (!slaConfig.is_active || slaConfig.is_deleted) {
      console.warn(`SLA config inactive or deleted for provider: ${provider}`);
      return null;
    }
 
    const {include_weekend, include_public_holiday, sla_hours} = slaConfig;
 
    // Case 1: Both flags true - direct clock hours addition
    if (include_weekend && include_public_holiday) {
      return this.calculateDirectClockHours(provider, startDateTime, sla_hours, slaConfig);
    }
 
    // Case 2: Both flags false - business days only (skip weekends and holidays)
    if (!include_weekend && !include_public_holiday) {
      return this.calculateBusinessDaysOnly(provider, startDateTime, sla_hours, slaConfig, countryCode);
    }
 
    // Case 3: include_weekend = true, include_public_holiday = false (skip only holidays)
    if (include_weekend && !include_public_holiday) {
      return this.calculateSkipHolidaysOnly(provider, startDateTime, sla_hours, slaConfig, countryCode);
    }
 
    // Case 4: include_weekend = false, include_public_holiday = true (skip only weekends)
    return this.calculateSkipWeekendsOnly(provider, startDateTime, sla_hours, slaConfig);
  }
 
  /**
   * Case 1: Direct clock hours (24/7)
   */
  private calculateDirectClockHours(
    provider: string,
    startDateTime: Date,
    slaHours: number,
    slaConfig: SlaConfig,
  ): SlaCalculationResult {
    const deadline = new Date(startDateTime);
    deadline.setHours(deadline.getHours() + slaHours);
 
    return {
      provider,
      startTime: startDateTime,
      slaHours,
      deadline,
      includeWeekend: true,
      includePublicHoliday: true,
      workingDays: 0,
      breakdown: {
        fullDays: Math.floor(slaHours / 24),
        remainingHours: slaHours % 24,
      },
    };
  }
 
  /**
   * Case 2: Business days only (skip weekends AND holidays)
   */
  private async calculateBusinessDaysOnly(
    provider: string,
    startDateTime: Date,
    slaHours: number,
    slaConfig: SlaConfig,
    countryCode?: string,
  ): Promise<SlaCalculationResult> {
    const currentDateTime = new Date(startDateTime);
    let remainingHours = slaHours;
    let workingDaysCount = 0;
 
    const estimatedEndDate = new Date(startDateTime);
    estimatedEndDate.setDate(estimatedEndDate.getDate() + Math.ceil(slaHours / 24) + 30);
    const holidays = await this.holidayRepo.getHolidaysInRange(startDateTime, estimatedEndDate, countryCode);
    const holidaySet = new Set(holidays.map(h => this.dateToString(h)));
 
    while (remainingHours > 0) {
      const dayOfWeek = currentDateTime.getDay();
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
      const isHoliday = holidaySet.has(this.dateToString(currentDateTime));
 
      if (isWeekend || isHoliday) {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
        continue;
      }
 
      const hoursInThisDay = Math.min(remainingHours, 24);
      remainingHours -= hoursInThisDay;
      workingDaysCount += hoursInThisDay === 24 ? 1 : 0;
 
      if (remainingHours <= 0) {
        currentDateTime.setHours(currentDateTime.getHours() + hoursInThisDay);
      } else {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
      }
    }
 
    return {
      provider,
      startTime: startDateTime,
      slaHours,
      deadline: currentDateTime,
      includeWeekend: false,
      includePublicHoliday: false,
      workingDays: workingDaysCount,
      breakdown: {
        fullDays: Math.floor(slaHours / 24),
        remainingHours: slaHours % 24,
      },
    };
  }
 
  /**
   * Case 3: Skip only holidays (include weekends)
   */
  private async calculateSkipHolidaysOnly(
    provider: string,
    startDateTime: Date,
    slaHours: number,
    slaConfig: SlaConfig,
    countryCode?: string,
  ): Promise<SlaCalculationResult> {
    const currentDateTime = new Date(startDateTime);
    let remainingHours = slaHours;
 
    const estimatedEndDate = new Date(startDateTime);
    estimatedEndDate.setDate(estimatedEndDate.getDate() + Math.ceil(slaHours / 24) + 30);
    const holidays = await this.holidayRepo.getHolidaysInRange(startDateTime, estimatedEndDate, countryCode);
    const holidaySet = new Set(holidays.map(h => this.dateToString(h)));
 
    while (remainingHours > 0) {
      const isHoliday = holidaySet.has(this.dateToString(currentDateTime));
 
      if (isHoliday) {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
        continue;
      }
 
      const hoursInThisDay = Math.min(remainingHours, 24);
      remainingHours -= hoursInThisDay;
 
      if (remainingHours <= 0) {
        currentDateTime.setHours(currentDateTime.getHours() + hoursInThisDay);
      } else {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
      }
    }
 
    return {
      provider,
      startTime: startDateTime,
      slaHours,
      deadline: currentDateTime,
      includeWeekend: true,
      includePublicHoliday: false,
      workingDays: 0,
      breakdown: {
        fullDays: Math.floor(slaHours / 24),
        remainingHours: slaHours % 24,
      },
    };
  }
 
  /**
   * Case 4: Skip only weekends (include holidays)
   */
  private calculateSkipWeekendsOnly(
    provider: string,
    startDateTime: Date,
    slaHours: number,
    slaConfig: SlaConfig,
  ): SlaCalculationResult {
    const currentDateTime = new Date(startDateTime);
    let remainingHours = slaHours;
    let workingDaysCount = 0;
 
    while (remainingHours > 0) {
      const dayOfWeek = currentDateTime.getDay();
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
 
      if (isWeekend) {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
        continue;
      }
 
      const hoursInThisDay = Math.min(remainingHours, 24);
      remainingHours -= hoursInThisDay;
      workingDaysCount += hoursInThisDay === 24 ? 1 : 0;
 
      if (remainingHours <= 0) {
        currentDateTime.setHours(currentDateTime.getHours() + hoursInThisDay);
      } else {
        currentDateTime.setDate(currentDateTime.getDate() + 1);
        currentDateTime.setHours(0, 0, 0, 0);
      }
    }
 
    return {
      provider,
      startTime: startDateTime,
      slaHours,
      deadline: currentDateTime,
      includeWeekend: false,
      includePublicHoliday: true,
      workingDays: workingDaysCount,
      breakdown: {
        fullDays: Math.floor(slaHours / 24),
        remainingHours: slaHours % 24,
      },
    };
  }
 
  /**
   * Get SLA configuration by provider (dùng cho các endpoint khác, vẫn throw nếu cần)
   */
  async getSlaConfig(provider: string, countryCode?: string): Promise<SlaConfig> {
    const config = await this.slaRepo.findByProviderAndCountry(provider, countryCode);
 
    if (!config) {
      throw new HttpErrors.NotFound(`SLA configuration not found for provider: ${provider}`);
    }
 
    return config;
  }
 
  /**
   * Get all active SLA configurations
   */
  async getAllActiveConfigs(countryCode?: string): Promise<SlaConfig[]> {
    return this.slaRepo.findActive(countryCode);
  }
 
  /**
   * Format date to YYYY-MM-DD string for comparison
   */
  private dateToString(date: Date): string {
    return date.toISOString().split('T')[0];
  }
 
  /**
   * Get remaining time until deadline
   */
  getRemainingTime(deadline: Date): {
    days: number;
    hours: number;
    minutes: number;
    isOverdue: boolean;
  } {
    const now = new Date();
    const diff = deadline.getTime() - now.getTime();
    const isOverdue = diff < 0;
 
    const absDiff = Math.abs(diff);
    const totalMinutes = Math.round(absDiff / (1000 * 60));
 
    const days = Math.floor(totalMinutes / (60 * 24));
    const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
    const minutes = totalMinutes % 60;
 
    return {days, hours, minutes, isOverdue};
  }
}