hrms-api-org/src/utils/tenure.ts

37 lines
1.2 KiB
TypeScript

/**
* Normalize a duration sum using calendar arithmetic
* Converts excess days to months using average month length (30.4375 days)
* and excess months to years. Matches the logic used in stored procedures.
*
* @param years Total years from sum
* @param months Total months from sum
* @param days Total days from sum
* @returns Normalized { years, months, days }
*/
export function normalizeDurationSumSimple(
years: number,
months: number,
days: number,
): { years: number; months: number; days: number } {
const DAYS_PER_MONTH = 30.4375; // Average days per month in Gregorian calendar
let totalMonths = months;
let totalDays = days;
// Convert excess days to months
if (totalDays >= DAYS_PER_MONTH) {
const additionalMonths = Math.floor(totalDays / DAYS_PER_MONTH);
totalMonths += additionalMonths;
totalDays = totalDays - additionalMonths * DAYS_PER_MONTH;
}
// Convert excess months to years
let totalYears = years;
if (totalMonths >= 12) {
const additionalYears = Math.floor(totalMonths / 12);
totalYears += additionalYears;
totalMonths = totalMonths % 12;
}
return { years: totalYears, months: Math.floor(totalMonths), days: Math.floor(totalDays) };
}