All files / libs/ext/dates/src/lib dates.utils.ts

98.95% Statements 283/286
89.55% Branches 60/67
76.92% Functions 20/26
98.95% Lines 283/286

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 2871x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x     2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 5x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 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 1x 3x 1x 3x 1x 3x   3x 3x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 6x 6x 6x 6x 2x 2x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 3x 7x 3x 7x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 4x 5x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 5x 5x 3x 3x 2x 6x 6x 6x 1x 1x 4x 4x 1x 1x 1x 1x 1x  
import { type ConfigType, type ConfigTypeMap } from 'dayjs';
import { isNil } from 'lodash-es';
 
import { dayjs } from '@amalia/ext/dayjs';
 
import { type UnixTimestampInSeconds } from '../index';
 
export interface DateInput {
  momentInput?: ConfigTypeMap['objectSupport'];
 
  timestamp?: number;
}
 
const getDateInput = (dateInput: DateInput) => {
  if (!dateInput.momentInput && !dateInput.timestamp) {
    throw new Error('Missing parameter');
  }
 
  return dateInput.momentInput || dateInput.timestamp;
};
 
export const formatUnixTimestamp = (unixTimeStamp: number) => dayjs.unix(unixTimeStamp).format('YYYY-MM-DD');
 
export const checkUnixTimestampBeforeFormat = (unixTimestamp: number | null) =>
  unixTimestamp ? formatUnixTimestamp(unixTimestamp) : null;
 
export const endOfMonthTimestamp = (dateInput: DateInput) => {
  const input = getDateInput(dateInput);
 
  return dayjs.utc(input).endOf('month').unix();
};
 
export const startOfMonthTimestamp = (dateInput: DateInput) => {
  const input = getDateInput(dateInput);
 
  return dayjs.utc(input).startOf('month').unix();
};
 
export const endOfDayTimestamp = (date: Date) => dayjs.utc(date).endOf('day').unix();
 
export const dateIsInAssignmentRange = (
  timestamp: number,
  assignment: { effectiveAsOf?: number | null; effectiveUntil?: number | null },
) =>
  (!assignment.effectiveAsOf || assignment.effectiveAsOf <= timestamp) &&
  (!assignment.effectiveUntil || timestamp < assignment.effectiveUntil);
 
/**
 * Check if two periods overlap.
 */
export const doPeriodsOverlap = (
  firstPeriod: { startDate?: number | null; endDate?: number | null },
  secondPeriod: { startDate?: number | null; endDate?: number | null },
): boolean => {
  const firstStartBoundary = firstPeriod.startDate || 0;
  const firstEndBoundary = firstPeriod.endDate || Infinity;
 
  const secondStartBoundary = secondPeriod.startDate || 0;
  const secondEndBoundary = secondPeriod.endDate || Infinity;
 
  const isFirstStartDateInRange = firstStartBoundary <= secondStartBoundary && secondStartBoundary <= firstEndBoundary;
  const isFirstEndDateInRange = firstStartBoundary <= secondEndBoundary && secondEndBoundary <= firstEndBoundary;
 
  const isSecondStartDateInRange = secondStartBoundary <= firstStartBoundary && firstStartBoundary <= secondEndBoundary;
  const isSecondEndDateInRange = secondStartBoundary <= firstEndBoundary && firstEndBoundary <= secondEndBoundary;
 
  return isFirstStartDateInRange || isFirstEndDateInRange || isSecondStartDateInRange || isSecondEndDateInRange;
};
 
export const fromNow = (date: Date | string) => dayjs(date).fromNow();
 
export type DateFormat =
  | '[Q]Q YY'
  | '[Q]Q YYYY'
  | '[Q]Q'
  | 'dddd'
  | 'HH:mm:ss'
  | 'L'
  | 'll'
  | 'LLL'
  | 'lll'
  | 'MM/YYYY'
  | 'MMM YY'
  | 'MMM'
  | 'MMMM YYYY'
  | 'YYYY-MM-DD HH:mm:ss'
  | 'YYYY-MM-DD'
  | 'YYYY-MM-DDTHH:mm:ss'
  | 'YYYY-MM-DDTHH:mm:ssZ'
  | 'YYYY';
 
export const formatDate = (date: NonNullable<ConfigType>, format: DateFormat) => dayjs.utc(date).format(format);
 
export const isValidDate = (dateString: string, format: DateFormat) => dayjs(dateString, format, true).isValid();
 
export const reformatDateString = (dateString: string, oldFormat: DateFormat, newFormat: DateFormat) =>
  dayjs(dateString, oldFormat).format(newFormat);
 
export const convertTimestampToDate = (timestamp: number) => dayjs.utc(timestamp, 'X').toDate();
 
export const convertUtcTimestampToDate = (timestamp?: number): string | undefined =>
  timestamp ? dayjs.utc(timestamp, 'X').format('YYYY-MM-DD') : undefined;
 
export const convertDateToUtcTimestamp = (
  date: Date | string | null,
  boundary: 'end' | 'start',
  _strict: boolean = false,
): number | null => {
  switch (true) {
    case !date:
      return null;
    case boundary === 'start':
      return (typeof date === 'string' ? dayjs.utc(date, 'YYYY-MM-DD', true) : dayjs.utc(date)).startOf('day').unix();
    case boundary === 'end':
      return (typeof date === 'string' ? dayjs.utc(date, 'YYYY-MM-DD', true) : dayjs.utc(date)).endOf('day').unix();
    default:
      throw new Error('Invalid date');
  }
};
 
export 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 function convertYYYYMMDDToUtcTimestamp(date: string): UnixTimestampInSeconds;
export function convertYYYYMMDDToUtcTimestamp(date: null): null;
export function convertYYYYMMDDToUtcTimestamp(date: string | null): UnixTimestampInSeconds | null {
  if (!date) {
    return null;
  }
 
  const momentDate = dayjs.utc(date, 'YYYY-MM-DD', true);
 
  if (!momentDate.isValid()) {
    throw new Error('Date is not in YYYY-MM-DD format');
  }
 
  return momentDate.unix();
}
 
export type ShiftDateUnits = 'days' | 'months' | 'weeks';
 
export const shiftDate = (datesString: string, offset: number, unit: ShiftDateUnits, format: string = 'YYYY-MM-DD') =>
  dayjs(datesString, format).add(offset, unit).format(format);
 
/**
 * Get startDate en endDate of a year in timestamp format
 * @param year
 * @returns
 */
export const getTimestampRangeOfYear = (year: number) => {
  const startDate = dayjs.utc({ year }).startOf('year').unix();
  const endDate = dayjs.utc({ year }).endOf('year').unix();
 
  return {
    startDate,
    endDate,
  };
};
 
/**
 * Get startDate en endDate of a month in timestamp format
 * @param year
 * @param month
 * @returns
 */
export const getTimestampRangeOfMonth = (year: number, month: number) => {
  const startDate = dayjs
    .utc({ year, month: month - 1 })
    .startOf('month')
    .unix();
  const endDate = dayjs
    .utc({ year, month: month - 1 })
    .endOf('month')
    .unix();
 
  return {
    startDate,
    endDate,
  };
};
 
/**
 * Get startDate en endDate of a quarter in timestamp format
 * @param year
 * @param quarter
 * @returns
 */
export const getTimestampRangeOfQuarter = (year: number, quarter: number) => {
  const startDate = dayjs.utc({ year }).quarter(quarter).startOf('quarter').unix();
  const endDate = dayjs.utc({ year }).quarter(quarter).endOf('quarter').unix();
 
  return {
    startDate,
    endDate,
  };
};
 
export const isDateRangeValid = (
  startDate?: Date | UnixTimestampInSeconds | null,
  endDate?: Date | UnixTimestampInSeconds | null,
): boolean => {
  if (!startDate || !endDate) {
    return true;
  }
 
  return dayjs(startDate).isSameOrBefore(endDate);
};
 
/**
 * Verify the timestamp is in UTC and match the start/end of a day.
 *
 * Based on the assumption that we don't have anything that has a granularity smaller than a day.
 *
 * @param timestamp
 * @param boundary
 */
export const isValidDateBoundary = (timestamp: number, boundary: 'END' | 'START'): boolean => {
  const momentObject = dayjs.utc(timestamp, 'X');
 
  switch (boundary) {
    case 'START':
      return momentObject.hour() === 0 && momentObject.minute() === 0 && momentObject.second() === 0;
    case 'END':
      return momentObject.hour() === 23 && momentObject.minute() === 59 && momentObject.second() === 59;
    default:
      throw new Error('Operation not supported');
  }
};
 
export const isDateValid = (date: Date) => date instanceof Date && !!date.getTime();
 
/**
 * Compare two dates, check if they are equal (in the tolerance).
 *
 * @param date1
 * @param date2
 * @param tolerance
 */
export const datesAreTheSame = (date1?: Date | null, date2?: Date | null, tolerance: number = 1000) => {
  if (!date1 && !date2) {
    return true;
  }
 
  if (!date1 || !date2) {
    return false;
  }
 
  return Math.abs(date1.getTime() - date2.getTime()) < tolerance;
};
 
/**
 * The calculation engine returns dates in two different formats, either a unix
 * timestamp (in case it's a result of a calculation), or date/date-time (fields from
 * the object definition. This function parse any input and returns a JS Date object.
 *
 * @param date
 */
export const dateFromCalculationEngineToJsDate = (date: number | string | null): Date => {
  if (isNil(date)) {
    throw new Error(`Cannot parse date ${date}`);
  }
 
  const momentObject = Number.isNaN(+date)
    ? // For the rest it should be a properly formatted date or date-time string.
      dayjs.utc(date)
    : // Case where the calculation engine returned a unix timestamp.
      dayjs.utc(date, 'X');
 
  if (!momentObject.isValid()) {
    throw new Error(`Cannot parse date ${date}`);
  }
  return momentObject.toDate();
};
 
export interface TimeWindow {
  start: UnixTimestampInSeconds;
  end: UnixTimestampInSeconds;
}