All files / libs/payout-definition/periods/components/src/lib useFormattedPeriodName.ts

86.27% Statements 44/51
90% Branches 9/10
100% Functions 2/2
86.27% Lines 44/51

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 521x 1x 1x 1x 1x 1x 1x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x               2x 2x 2x 2x 2x 2x 1x 4x 4x 4x 4x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x  
import { useMemo } from 'react';
 
import { convertTimestampToDate, formatDate } from '@amalia/ext/dates';
import { findRelativePeriodDate, getDateRangeBoundaries } from '@amalia/payout-definition/periods/shared';
import { PeriodFrequencyEnum, type Period } from '@amalia/payout-definition/periods/types';
 
export const getFormattedPeriodName = (period?: Period | null) => {
  if (!period) {
    return {
      currentPeriodShortLabel: null,
      currentPeriodLongLabel: null,
      previousPeriodShortLabel: null,
      previousPeriodLongLabel: null,
    };
  }
 
  const boundaries = getDateRangeBoundaries(period.frequency, convertTimestampToDate(period.startDate));
 
  // Should never happen but just in case
  if (!boundaries.endDate) {
    return {
      currentPeriodShortLabel: null,
      currentPeriodLongLabel: null,
      previousPeriodShortLabel: null,
      previousPeriodLongLabel: null,
    };
  }
 
  const currentPeriodDate = convertTimestampToDate(boundaries.endDate);
  const previousPeriodDate = findRelativePeriodDate(period, period.frequency, -1, 'endDate');
 
  const currentPeriodLongLabel =
    period.frequency === PeriodFrequencyEnum.quarter
      ? formatDate(currentPeriodDate, '[Q]Q YYYY')
      : formatDate(currentPeriodDate, 'MMMM YYYY');
 
  const previousPeriodLongLabel =
    period.frequency === PeriodFrequencyEnum.quarter
      ? formatDate(previousPeriodDate, '[Q]Q YYYY')
      : formatDate(previousPeriodDate, 'MMMM YYYY');
 
  return {
    currentPeriodShortLabel: formatDate(currentPeriodDate, 'MM/YYYY'),
    currentPeriodLongLabel,
    previousPeriodShortLabel: formatDate(previousPeriodDate, 'MM/YYYY'),
    previousPeriodLongLabel,
  };
};
 
export const useFormattedPeriodName = (period?: Period | null) =>
  useMemo(() => getFormattedPeriodName(period), [period]);