mirror of
https://github.com/Sea-Haven-Industries/shoc-frontend-new.git
synced 2026-09-30 08:03:13 +00:00
73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
import { DEFAULT_DASHBOARD_RANGE } from "@/domain/dashboard/types/dashboard-range";
|
|
import type {
|
|
DashboardRangeKey,
|
|
DashboardRangeParams,
|
|
} from "@/domain/dashboard/types/dashboard-range";
|
|
|
|
export const BUSINESS_TIME_ZONE = "America/New_York";
|
|
|
|
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
|
|
export function businessTodayIso(now: Date = new Date()): string {
|
|
return new Intl.DateTimeFormat("en-CA", {
|
|
timeZone: BUSINESS_TIME_ZONE,
|
|
year: "numeric",
|
|
month: "2-digit",
|
|
day: "2-digit",
|
|
}).format(now);
|
|
}
|
|
|
|
export function isIsoDate(value: string): boolean {
|
|
return ISO_DATE_PATTERN.test(value);
|
|
}
|
|
|
|
export function addDaysIso(isoDate: string, days: number): string {
|
|
const [year, month, day] = isoDate.split("-").map(Number);
|
|
const shifted = new Date(Date.UTC(year, month - 1, day + days));
|
|
return shifted.toISOString().slice(0, 10);
|
|
}
|
|
|
|
export function mondayOf(isoDate: string): string {
|
|
const [year, month, day] = isoDate.split("-").map(Number);
|
|
const weekday = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
|
|
return addDaysIso(isoDate, -((weekday + 6) % 7));
|
|
}
|
|
|
|
export function monthStartIso(isoDate: string): string {
|
|
return `${isoDate.slice(0, 7)}-01`;
|
|
}
|
|
|
|
export function monthEndIso(isoDate: string): string {
|
|
const year = Number(isoDate.slice(0, 4));
|
|
const month = Number(isoDate.slice(5, 7));
|
|
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
return `${isoDate.slice(0, 7)}-${String(lastDay).padStart(2, "0")}`;
|
|
}
|
|
|
|
function shiftMonthsIso(isoDate: string, months: number): string {
|
|
const year = Number(isoDate.slice(0, 4));
|
|
const month = Number(isoDate.slice(5, 7));
|
|
const shifted = new Date(Date.UTC(year, month - 1 + months, 1));
|
|
return `${shifted.getUTCFullYear()}-${String(shifted.getUTCMonth() + 1).padStart(2, "0")}-01`;
|
|
}
|
|
|
|
export function dashboardRangeParams(
|
|
range: DashboardRangeKey = DEFAULT_DASHBOARD_RANGE,
|
|
today: string = businessTodayIso(),
|
|
): DashboardRangeParams {
|
|
switch (range) {
|
|
case "today":
|
|
return { dateFrom: today, dateTo: today };
|
|
case "this-week": {
|
|
const monday = mondayOf(today);
|
|
return { dateFrom: monday, dateTo: addDaysIso(monday, 4) };
|
|
}
|
|
case "last-3-months":
|
|
return {
|
|
dateFrom: monthStartIso(shiftMonthsIso(today, -2)),
|
|
dateTo: monthEndIso(today),
|
|
};
|
|
case "all-time":
|
|
return {};
|
|
}
|
|
}
|