All files / libs/payout-definition/periods/shared/src/lib periods.utils.ts

93.98% Statements 328/349
85.89% Branches 67/78
100% Functions 21/21
93.98% Lines 328/349

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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 3501x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x     2x 2x 2x 2x 2x 2x 1x 1x 4x 4x 4x 4x     4x 4x 4x 1x 4x 1x 4x 1x 4x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 2x 2x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 5x 2x 2x 5x 5x 1x 1x 1x 1x 9x 9x 9x     9x 2x 2x 9x 9x 9x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 16x 1x     1x 1x 1x 1x 16x 1x 1x 16x 1x 1x 16x 1x 1x 16x 1x 1x 1x 1x 1x 1x 1x 16x 1x 1x 1x 1x 1x 1x 1x 16x 1x 1x 1x 16x 8x 2x 2x 2x 2x 2x 8x 2x 2x 2x 2x 2x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 16x 12x 16x             12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 16x       16x       12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 3x 1x 1x 3x 1x 1x 3x   3x 3x 3x 3x 3x 1x 1x 3x 1x 1x 3x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 22x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import {
  eachMonthOfInterval,
  eachQuarterOfInterval,
  eachYearOfInterval,
  endOfMonth,
  endOfQuarter,
  endOfYear,
} from 'date-fns';
import { isNumber, range } from 'lodash-es';
 
import { toDate, toTimestamp, type TimeWindow, type UnixTimestampInSeconds } from '@amalia/ext/dates';
import { dayjs } from '@amalia/ext/dayjs';
import { PeriodFrequencyEnum, RelativePeriodKeyword, type Period } from '@amalia/payout-definition/periods/types';
 
const convertTimestampToUtcDate = (timestamp: number | null): Date | null => {
  if (!timestamp) {
    return null;
  }
  // https://stackoverflow.com/questions/34050389/remove-timezone-from-a-moment-js-object
  return dayjs
    .utc(timestamp, 'X')
    .add(-1 * dayjs().utcOffset(), 'm')
    .toDate();
};
 
export const formatPeriodName = (periodFrequency: PeriodFrequencyEnum, date: Date | UnixTimestampInSeconds): string => {
  let dayjsInput = date;
 
  // Convert to UNIX timestamps if needed
  if (isNumber(dayjsInput) && dayjsInput > 100_000 && dayjsInput < 9_999_999_999) {
    dayjsInput *= 1000;
  }
 
  switch (periodFrequency) {
    case PeriodFrequencyEnum.year:
      return dayjs.utc(dayjsInput).format('YYYY');
    case PeriodFrequencyEnum.quarter:
      return dayjs.utc(dayjsInput).format('[Q]Q YYYY');
    case PeriodFrequencyEnum.month:
      return dayjs.utc(dayjsInput).format('MMMM YYYY');
    default:
      return '';
  }
};
 
/**
 * Given a date and a frequency, returns the startDate and endDate that includes the date.
 *
 * @param periodFrequency
 * @param date
 */
export const getDateRangeBoundaries = (
  periodFrequency: PeriodFrequencyEnum | null | undefined,
  date: Date | null,
): { startDate: number | null; endDate: number | null } => {
  if (!date || !periodFrequency || periodFrequency === PeriodFrequencyEnum.null) {
    return { startDate: null, endDate: null };
  }
 
  return {
    startDate: dayjs.utc(date).startOf(periodFrequency).unix(),
    endDate: dayjs.utc(date).endOf(periodFrequency).unix(),
  };
};
 
/**
 * Tells if a string is a period keyword or not
 * @param str
 * @returns
 */
export const isRelativePeriodKeyword = (str: string) => {
  if (Object.keys(RelativePeriodKeyword).includes(str)) {
    return true;
  }
  return /^YEAR:\d{4}$/u.test(str) || /^QUARTER:Q\d\/\d{4}$/u.test(str);
};
 
const roundNumberAccordingToSign = (nb: number) => (nb > 0 ? Math.floor(nb) : Math.ceil(nb));
 
export const getDatePeriodIndex = (frequency: PeriodFrequencyEnum, date: Date, referenceDate: Date): number => {
  let diff = dayjs.utc(date).startOf('month').diff(dayjs.utc(referenceDate).startOf('month'), 'months');
 
  if (frequency === PeriodFrequencyEnum.year) {
    diff /= 12;
  }
  if (frequency === PeriodFrequencyEnum.quarter) {
    diff /= 3;
  }
 
  return roundNumberAccordingToSign(diff);
};
 
export const getTimestampPeriodIndex = (
  frequency: PeriodFrequencyEnum,
  timestamp: number,
  referenceDate: Date,
): number => getDatePeriodIndex(frequency, dayjs.utc(timestamp, 'X').toDate(), referenceDate);
 
/**
 * Find periods for a period relative keyword
 * @param frequency
 * @param referenceDate
 * @param keyword
 * @returns
 */
export const findPeriodRelativeNumbersForRelativeKeyword = (
  frequency: PeriodFrequencyEnum,
  referenceDate: Date,
  keyword: string,
): { range: number[]; startDate: number | null; endDate: number | null } => {
  let nbMonthsToFetch = 0;
  let nbMonthsToShift = 0;
 
  // Keywords that links to one relative period
  switch (keyword) {
    case RelativePeriodKeyword.CURRENT_PERIOD:
      return {
        range: [0],
        ...getDateRangeBoundaries(frequency, referenceDate),
      };
    case RelativePeriodKeyword.LAST_PERIOD:
      if (frequency === PeriodFrequencyEnum.null) {
        throw new Error('Cannot go to last period if the company is not using periods.');
      }
      return {
        range: [-1],
        ...getDateRangeBoundaries(frequency, dayjs.utc(referenceDate).add(-1, frequency).toDate()),
      };
    case RelativePeriodKeyword.LAST_3_MONTHS:
      nbMonthsToFetch = 3;
      break;
    case RelativePeriodKeyword.LAST_6_MONTHS:
      nbMonthsToFetch = 6;
      break;
    case RelativePeriodKeyword.LAST_12_MONTHS:
      nbMonthsToFetch = 12;
      break;
    case RelativePeriodKeyword.LAST_YEAR:
      nbMonthsToFetch = 12;
      // we want to fetch the 12 months from the end of past year
      nbMonthsToShift = dayjs
        .utc(referenceDate)
        .startOf('month')
        .diff(dayjs.utc(referenceDate).add(-1, 'year').endOf('year').startOf('month'), 'months');
      break;
    case RelativePeriodKeyword.CURRENT_YEAR:
      nbMonthsToFetch = 12;
      // We want to fetch the 12 months from the end of current year
      nbMonthsToShift = dayjs
        .utc(referenceDate)
        .startOf('month')
        .diff(dayjs.utc(referenceDate).endOf('year').startOf('month'), 'months');
      break;
    case RelativePeriodKeyword.YEAR_TO_DATE:
      // we want to fetch the n months from date, n is equal to the number of months passed from date to start of year = number of month of date
      nbMonthsToFetch = Number.parseInt(dayjs.utc(referenceDate).format('M'), 10);
      break;
    default:
      if (/^YEAR:\d{4}$/u.test(keyword)) {
        nbMonthsToFetch = 12;
        nbMonthsToShift = dayjs
          .utc(referenceDate)
          .startOf('month')
          .diff(dayjs.utc(keyword.replace('YEAR:', ''), 'YYYY').endOf('year').startOf('month'), 'months');
      } else if (/^QUARTER:Q\d\/\d{4}$/u.test(keyword)) {
        nbMonthsToFetch = 3;
        nbMonthsToShift = dayjs
          .utc(referenceDate)
          .startOf('month')
          .diff(dayjs.utc(keyword.replace('QUARTER:', ''), '[Q]Q/YYYY').endOf('quarter').startOf('month'), 'months');
      } else if (/^SEMESTER:S[12]\/\d{4}$/u.test(keyword)) {
        const match = /^SEMESTER:S(?<semester>[12])\/(?<year>\d{4})$/u.exec(keyword);
        const semester = match?.groups?.['semester'];
        const year = match?.groups?.['year'];
 
        nbMonthsToFetch = 6;
        nbMonthsToShift = dayjs
          .utc(referenceDate)
          .startOf('month')
          .diff(
            dayjs
              .utc(semester === '1' ? `Q2/${year}` : `Q4/${year}`, '[Q]Q/YYYY')
              .endOf('quarter')
              .startOf('month'),
            'months',
          );
      } else {
        throw new Error(`Cannot recognize period relative keyword ${keyword}`);
      }
  }
 
  if (nbMonthsToFetch === 0) {
    return {
      range: [],
      startDate: null,
      endDate: null,
    };
  }
 
  const startDate = dayjs
    .utc(referenceDate)
    .subtract(nbMonthsToShift + nbMonthsToFetch - 1, 'month')
    .startOf('month')
    .unix();
 
  const endDate = dayjs.utc(referenceDate).subtract(nbMonthsToShift, 'month').endOf('month').unix();
 
  // Here we have the number of months to fetch. If the company frequency is different,
  // We need to divide it with the ratio of months that is in each interval of the frequency (1 quarter = 3 months)
  let nbOfPeriodsToFetch = nbMonthsToFetch;
  let nbOfPeriodsToShift = nbMonthsToShift;
 
  if (frequency === PeriodFrequencyEnum.year) {
    nbOfPeriodsToFetch /= 12;
    nbOfPeriodsToShift /= 12;
  }
  if (frequency === PeriodFrequencyEnum.quarter) {
    nbOfPeriodsToFetch /= 3;
    nbOfPeriodsToShift /= 3;
  }
 
  // nbPeriodsToFetch tells how many periods we need to fetch (CURRENT_YEAR = 12 months)
  // nbPeriodsToShift tells the number of periods we have from the last month of the previous list to the current period
  return {
    range: range(-1 * roundNumberAccordingToSign(nbOfPeriodsToFetch) + 1, 1).map(
      (n) => n - roundNumberAccordingToSign(nbOfPeriodsToShift),
    ),
    startDate,
    endDate,
  };
};
 
export const isLastQuarterOfYear = (period: Period): boolean => dayjs(period.startDate, 'X').quarter() === 4;
 
export const isLastMonthOfYear = (period: Period): boolean => dayjs(period.startDate, 'X').month() === 11;
 
export const isLastMonthOfQuarter = (period: Period): boolean => (dayjs(period.startDate, 'X').month() + 1) % 3 === 0;
 
/**
 * Retrieve date relative to a period date:
 * - you can retrieve the previous or next period,
 * - Example:
 *    current period is April,
 *    frequency is quarter,
 *    and diff is -1,
 *    => then you will get the previous quarter, which is January
 * @param period
 * @param frequency
 * @param diff
 * @param periodMarker
 */
export const findRelativePeriodDate = (
  period: Period,
  frequency: PeriodFrequencyEnum,
  diff: number,
  periodMarker: 'endDate' | 'startDate' = 'startDate',
) => {
  const referenceDate = dayjs(period[periodMarker], 'X').toDate();
 
  // Calculate the number of months we need to offset the date.
  let monthDiff: number;
  switch (frequency) {
    case PeriodFrequencyEnum.year:
      monthDiff = diff * 12;
      break;
    case PeriodFrequencyEnum.quarter:
      monthDiff = diff * 3;
      break;
    case PeriodFrequencyEnum.month:
      monthDiff = diff;
      break;
    case PeriodFrequencyEnum.null:
      throw new Error('Cannot find next period of a company that does not use periods');
  }
 
  // This gives us a reference for the period we're looking for.
  return dayjs.utc(referenceDate).add(monthDiff, 'months').toDate();
};
 
export const getPeriodMarkerDate = (marker: 'end' | 'start', period?: Period) => {
  if (!period) {
    return null;
  }
  if (marker === 'start') {
    return convertTimestampToUtcDate(period.startDate);
  }
  return convertTimestampToUtcDate(period.endDate);
};
 
export const formatPeriodMarkerDate = (
  period: Period,
  format: string = 'YYYY-MM-DD',
  marker: 'end' | 'start' = 'start',
): string => {
  if (marker === 'start') {
    return dayjs.utc(period.startDate, 'X').format(format);
  }
 
  return dayjs.utc(period.endDate, 'X').format(format);
};
 
export const getRelativePeriodString = (timestamp: number, offset: number, frequency: PeriodFrequencyEnum): string =>
  dayjs
    .utc(timestamp, 'X')
    .add(offset, frequency === PeriodFrequencyEnum.month ? 'months' : 'quarters')
    .format('YYYY-MM-DD');
 
export const getPeriodStringFromUserDate = (selectedDate: Date): string =>
  dayjs
    .utc(selectedDate)
    .add(-1 * selectedDate.getTimezoneOffset(), 'm')
    .format('YYYY-MM-DD');
 
export const getPeriodDateFromUserDate = (selectedDate: Date): UnixTimestampInSeconds =>
  dayjs
    .utc(selectedDate)
    .add(-1 * selectedDate.getTimezoneOffset(), 'm')
    .unix();
 
export const getUserDateFromPeriodDate = (timestamp: UnixTimestampInSeconds): Date => {
  const date = dayjs.utc(timestamp, 'X').toDate();
  return dayjs(date).add(date.getTimezoneOffset(), 'm').toDate();
};
 
export const getCurrentPeriodInListOfPeriods = (
  periodsList: Period[],
  frequency: PeriodFrequencyEnum,
  currentDate: Date,
): Period | undefined =>
  periodsList.find(
    (p) =>
      p.frequency === frequency && p.startDate <= toTimestamp(currentDate) && p.endDate >= toTimestamp(currentDate),
  );
 
export const getWindows = (boundaries: TimeWindow): Record<PeriodFrequencyEnum, TimeWindow[] | null> => {
  const dateFnsInterval = { start: toDate(boundaries.start), end: toDate(boundaries.end) };
 
  const getInterval = (eachCallback: typeof eachMonthOfInterval, endOfCallback: typeof endOfMonth): TimeWindow[] => {
    const starts = eachCallback(dateFnsInterval);
    return starts.map((start) => ({ start: toTimestamp(start), end: toTimestamp(endOfCallback(start)) }));
  };
 
  return {
    [PeriodFrequencyEnum.null]: null,
    [PeriodFrequencyEnum.month]: getInterval(eachMonthOfInterval, endOfMonth),
    [PeriodFrequencyEnum.quarter]: getInterval(eachQuarterOfInterval, endOfQuarter),
    [PeriodFrequencyEnum.year]: getInterval(eachYearOfInterval, endOfYear),
  };
};