All files / src/utils date.ts

100% Statements 166/166
94.82% Branches 55/58
100% Functions 23/23
100% Lines 166/166

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 350 351 352 353 354 355 356 357 358 359 360 3611x                                   1x 1x     1x     1x           1x 1x 1x   1x 1x                 1x 12x 12x 12x               1x 18x 18x 18x 18x   18x 18x 9x 8x   18x                       1x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x   4x 4x             1x 6x 6x 6x 6x 6x 6x   6x 6x               1x 2x 2x                       1x 7x 7x 7x 7x   4x 7x   7x 7x 7x         1x 9x 9x   9x 9x         1x 9x 9x 9x   1x 1x 1x 1x 1x 1x 1x 1x 3x 3x     3x 3x 3x   3x 3x 1x 3x 3x     3x 3x 3x 3x 3x   3x 3x 1x 3x 3x     3x 3x 3x   3x 3x 1x               1x 10x 10x                                         1x 21x 21x 21x 21x 21x 4x   21x 5x 5x 5x   21x 6x   21x 21x   21x 21x                               1x 8x 8x 4x 4x   4x 4x 12x 12x 4x 4x                         1x 37x 30x 30x 30x 30x 30x                           1x 6x 6x 6x 6x 6x 6x     6x     6x 6x   3x 3x   3x 3x                   1x 5x 5x 5x     5x 5x   2x 2x   2x 2x  
import {
  format,
  isAfter,
  setHours,
  setMinutes,
  differenceInCalendarDays,
  startOfDay,
  parse,
  startOfWeek,
  subWeeks,
  subMonths,
  subQuarters,
  subYears,
  startOfMonth,
  startOfQuarter,
  startOfYear,
  isSameDay,
} from 'date-fns';
import { toZonedTime } from 'date-fns-tz';
import { DateTime, Effect } from 'effect';
 
// Constants
import { DATE_FORMATS, TIME_RANGE_FORMATTER } from '@/constants/date';
 
// Types
import { ChartMode } from '@/types/chart';
 
/**
 * Returns the current year as a number.
 * Useful for dynamically displaying copyright years.
 */
export const getCurrentYear = (): number => {
  const now = Effect.runSync(DateTime.now);
  const parts = DateTime.toPartsUtc(now);
 
  return parts.year;
};
 
/**
 * Format a date string (ISO format) into a readable label.
 * Example: "2025-07-29T00:00:00.000Z" → "Tuesday, July 29th"
 *
 * @param dateStr - The ISO date string to format
 * @returns A formatted date string like "Friday, August 1st"
 */
export const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr);
  return format(date, 'EEEE, MMMM do');
};
 
/**
 * Checks if the given date string represents today.
 *
 * @param dateStr - ISO date string
 * @returns True if the date is today, false otherwise
 */
export const isToday = (dateStr: string): boolean => {
  const nowUtc = Effect.runSync(DateTime.now);
  const now = DateTime.toDate(nowUtc);
  const dateUtc = DateTime.unsafeFromDate(new Date(dateStr));
  const date = DateTime.toDate(dateUtc);
 
  return (
    now.getFullYear() === date.getFullYear() &&
    now.getMonth() === date.getMonth() &&
    now.getDate() === date.getDate()
  );
};
 
/**
 * Checks if a given date is considered expired based on:
 * - It is a past date (before today), AND
 * - The current time has passed a specific cutoff time (default: 11:30 AM local time)
 *
 * @param dateStr - An ISO date string, e.g. "2025-08-01T00:00:00.000Z"
 * @param hour - The cutoff hour (default: 11)
 * @param minute - The cutoff minute (default: 30)
 * @returns true if the date is in the past and the current time is after the cutoff; otherwise false.
 */
export const isExpiredDay = (
  dateStr: string,
  hour = 11,
  minute = 30,
  timeZone = 'Asia/Ho_Chi_Minh',
): boolean => {
  const inputDate = DateTime.toDate(DateTime.unsafeFromDate(new Date(dateStr)));
  const utcNow = DateTime.toDate(Effect.runSync(DateTime.now));
 
  const localNow = toZonedTime(utcNow, timeZone);
  const today = startOfDay(localNow);
  const limitToday = setMinutes(setHours(today, hour), minute);
  const diffInDays = differenceInCalendarDays(localNow, inputDate);
  const isAfterLimitToday = isAfter(localNow, limitToday);
 
  return diffInDays > 1 || (diffInDays === 1 && isAfterLimitToday);
};
 
/**
 * Converts a date string or Date object to an ISO date string (YYYY-MM-DD).
 * @param date A date string or Date object.
 * @returns A string in format 'YYYY-MM-DD'.
 */
export const formatDateToISODateString = (
  date: string | Date = '',
  timeZone = 'Asia/Ho_Chi_Minh',
): string => {
  const dt = DateTime.unsafeFromDate(new Date(date));
  const zoned = DateTime.unsafeMakeZoned(dt, { timeZone });
  const { year, month, day } = DateTime.toParts(zoned);
 
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
};
 
/**
 * Parse a date string with a given format
 * @param dateStr - The date string (e.g., "20250822")
 * @param formatStr - The format to parse (default: "yyyyMMdd")
 * @returns Date object
 */
export const parseDay = (dateStr: string, formatStr = 'yyyyMMdd') => {
  return parse(dateStr, formatStr, new Date());
};
 
/**
 * Formats a date string (`yyyyMMdd`) based on the selected chart mode.
 *
 * - Week & Month → "EEE dd" (e.g., "Fri 05")
 * - Quarter & Year → "MMM dd" (e.g., "Sep 05")
 *
 * @param dateString - Date in `yyyyMMdd` format (e.g., "20250905")
 * @param mode - Chart mode that determines the formatting style (default: Week)
 * @returns Formatted date string or an empty string if input is invalid
 */
export const formatDateByMode = (
  dateString?: string,
  mode: ChartMode = ChartMode.Week,
): string => {
  if (!dateString || dateString.length < 8) return '';
 
  const parsed = parse(dateString, 'yyyyMMdd', new Date());
  if (isNaN(parsed.getTime())) return '';
 
  const pattern = DATE_FORMATS[mode] ?? 'EEE dd';
  return format(parsed, pattern);
};
 
/**
 * Returns the current date/time in the given timezone.
 */
const getLocalNow = (timeZone = 'Asia/Ho_Chi_Minh') => {
  const utc = DateTime.unsafeNow();
  const jsDate = DateTime.toDate(utc);
 
  return toZonedTime(jsDate, timeZone);
};
 
/**
 * Check if a given date is after the cutoff time (e.g., 11:30 AM) in its day.
 */
const isAfterCutoff = (date: Date, hour = 11, minute = 30): boolean => {
  const cutoff = setMinutes(setHours(startOfDay(date), hour), minute);
  return isAfter(date, cutoff);
};
 
const TIME_RANGE_GENERATORS: Record<ChartMode, () => string> = {
  [ChartMode.Week]: () => {
    const lastWeekStart = startOfWeek(subWeeks(new Date(), 1), {
      weekStartsOn: 1,
    });
    return TIME_RANGE_FORMATTER.WEEK(lastWeekStart);
  },
  [ChartMode.Month]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the month → go back one more month
    const isFirstDayOfMonth = isSameDay(localNow, startOfMonth(localNow));
    const monthsBack = isFirstDayOfMonth && !isPastCutoff ? 2 : 1;
    const targetMonth = subMonths(localNow, monthsBack);
 
    return TIME_RANGE_FORMATTER.MONTH(targetMonth);
  },
  [ChartMode.Quarter]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the quarter → go back one more quarter
    const isFirstDayOfQuarter = isSameDay(localNow, startOfQuarter(localNow));
    const quartersBack = isFirstDayOfQuarter && !isPastCutoff ? 2 : 1;
    const lastQuarter = subQuarters(localNow, quartersBack);
    const year = TIME_RANGE_FORMATTER.YEAR(lastQuarter);
    const quarter = Math.floor(lastQuarter.getMonth() / 3) + 1;
 
    return `${year}Q${quarter}`;
  },
  [ChartMode.Year]: () => {
    const localNow = getLocalNow();
    const isPastCutoff = isAfterCutoff(localNow);
 
    // If it's still before 11:30 AM on the first day of the year → go back one more year
    const isFirstDayOfYear = isSameDay(localNow, startOfYear(localNow));
    const yearsBack = isFirstDayOfYear && !isPastCutoff ? 2 : 1;
    const lastYear = subYears(localNow, yearsBack);
 
    return TIME_RANGE_FORMATTER.YEAR(lastYear);
  },
};
 
/**
 * Returns the default time range string for a given chart mode.
 *
 * @param mode - ChartMode (Week, Month, Quarter, Year)
 * @returns string representing the default time range
 */
export const getDefaultTimeRange = (mode: ChartMode): string => {
  return TIME_RANGE_GENERATORS[mode]?.() ?? '';
};
 
type periodRange = {
  weeks: { from: Date; to?: Date }[];
  months: { year: number; month: number }[];
  quarters: { year: number; quarter: number }[];
  years: number[];
};
 
/**
 * Format a given set of time ranges into a comma-separated string,
 * depending on the chart mode.
 *
 * @param mode - The chart mode (Week, Month, Quarter, Year).
 * @param timeRanges - An object containing arrays of period ranges
 *   for different modes (weeks, months, quarters, years).
 *
 * @returns A comma-separated string representing the time ranges
 *   formatted for the specified chart mode.
 *  "20250908" / "202501" / "2025Q1" / "2024,2023"
 */
export const formatTimeRanges = (
  mode: ChartMode,
  timeRanges: periodRange,
): string => {
  const FORMATTERS: Record<ChartMode, () => string> = {
    [ChartMode.Week]: () =>
      timeRanges.weeks.map((w) => TIME_RANGE_FORMATTER.WEEK(w.from)).join(','),
 
    [ChartMode.Month]: () =>
      timeRanges.months
        .map((m) => `${m.year}${String(m.month + 1).padStart(2, '0')}`)
        .join(','),
 
    [ChartMode.Quarter]: () =>
      timeRanges.quarters.map((q) => `${q.year}Q${q.quarter}`).join(','),
 
    [ChartMode.Year]: () => timeRanges.years.join(','),
  };
 
  return FORMATTERS[mode]();
};
 
/**
 * Convert a year-quarter string (e.g., "2025Q1") into an array of
 * three month identifiers in "yyyyMM" format.
 *
 * @param yearQuarter - A string in the format "YYYYQ#", where # is
 *   the quarter number (1–4).
 *
 * @returns An array of strings representing the months in that quarter,
 *   each in "yyyyMM" format. Returns an empty array if the input is invalid.
 *
 * @example
 * getQuarterDate("2025Q1");
 * => ["202501", "202502", "202503"]
 */
export const getQuarterDate = (yearQuarter: string) => {
  const match = yearQuarter.match(/^(\d{4})Q([1-4])$/);
  if (!match) return [];
  const year = Number(match[1]);
  const quarter = Number(match[2]);
 
  const startMonth = (quarter - 1) * 3 + 1;
  return Array.from({ length: 3 }, (_, i) => {
    const month = startMonth + i;
    return `${year}${month.toString().padStart(2, '0')}`;
  });
};
 
/**
 * Parse a comma-separated string of time ranges into an array of trimmed strings.
 *
 * @param timeRanges - A string containing time ranges separated by commas (e.g. "2024,2023").
 * @returns An array of non-empty, trimmed time range strings.
 *
 * @example
 * parseTimeRanges("2024, 2023"); // ["2024", "2023"]
 * parseTimeRanges("2024");       // ["2024"]
 * parseTimeRanges("");           // []
 */
export const parseTimeRanges = (timeRanges: string): string[] => {
  if (!timeRanges) return [];
  return timeRanges
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
};
 
/**
 * Check if voting for a meal is currently open.
 *
 * Voting is only allowed on the current day (`isToday`)
 * and only after the specified start time (default: 11:30 AM).
 *
 * @param date - The meal's date (string or Date).
 * @param startHour - Hour of day when voting opens (default: 11).
 * @param startMinute - Minute of hour when voting opens (default: 30).
 * @param timeZone - IANA time zone string (default: "Asia/Ho_Chi_Minh").
 * @returns True if voting is allowed, false otherwise.
 */
export const isVoteOpen = (
  date: string | Date,
  startHour = 11,
  startMinute = 30,
  timeZone = 'Asia/Ho_Chi_Minh',
): boolean => {
  const mealDate = typeof date === 'string' ? new Date(date) : date;
 
  // Get the "now" in the desired timezone
  const now = toZonedTime(new Date(), timeZone);
 
  // Compare only if the mealDate is today (in that timezone)
  const mealDateStr = mealDate.toISOString();
  if (!isToday(mealDateStr)) return false;
 
  const startTime = toZonedTime(mealDate, timeZone);
  startTime.setHours(startHour, startMinute, 0, 0);
 
  return now >= startTime;
};
 
/**
 * Format a week range (Monday–Friday) into a short string.
 * Ex: { from: "2025-11-03T00:00:00+07:00", to: "2025-11-07T00:00:00+07:00" }
 * → "03.11 - 07.11"
 *
 * @param range - Object with `from` and `to` date values (Date or string)
 * @returns Formatted string in "dd.MM - dd.MM" format
 */
export const getFormattedWeekRange = ({
  from,
  to,
}: {
  from: string | Date;
  to: string | Date;
}): string => {
  if (!from || !to) return '';
 
  const fromDate = new Date(from);
  const toDate = new Date(to);
 
  return `${format(fromDate, 'dd.MM')} - ${format(toDate, 'dd.MM')}`;
};