// Event state line for pickers (add-event-summary, BABYBOO-31). Sales dates are Malaysia local ISO strings // (no zone); compare them as Malaysia wall-clock time whatever the browser's zone. import type { Translate } from "./i18n/t"; import { malaysiaInstant } from "./malaysiaPeriod"; export type EventStateKind = "live" | "upcoming" | "ended"; const DAY_MS = 86_400_000; /** Malaysia calendar day number (days since epoch) of an instant. */ const mytDay = (d: Date) => Math.floor((d.getTime() + 8 * 3_600_000) / DAY_MS); /** Event kind without translation — used in effects that cannot accept `t`. */ export function eventKind( ev: { salesFrom?: string | null; salesTo?: string | null; status?: string | null }, now = new Date(), ): EventStateKind { // "C" = closed out after the event (stock counted and returned); it can never sell again. if (ev.status === "C") return "ended"; // "N" = deactivated in Event setup; it cannot sell whatever its dates. if (ev.status === "N") return "ended"; if (!ev.salesFrom || !ev.salesTo) return "ended"; const from = malaysiaInstant(ev.salesFrom); const to = malaysiaInstant(ev.salesTo); if (now < from) return "upcoming"; if (now > to) return "ended"; return "live"; } /** Format an ISO date as "{day} {month}" using t for the month name. */ export function dayMonth(iso: string, t: Translate): string { const [, m, d] = iso.slice(0, 10).split("-").map(Number); return t("EvtDayMonth", { day: d, month: t(`EvtMonth${m}`) }); } /** The picker's state line for an event, translated through `t`. */ export function eventState( ev: { salesFrom?: string | null; salesTo?: string | null; status?: string | null }, t: Translate, now = new Date(), ): { kind: EventStateKind; line: string; /** Live only: today's day number and the run's length. */ day?: number; days?: number } { // "C" = closed out after the event (stock counted and returned); it can never sell again. if (ev.status === "C") return { kind: "ended", line: t("EvtStateClosed") }; // "N" = deactivated in Event setup; it cannot sell whatever its dates. if (ev.status === "N") return { kind: "ended", line: t("EvtStateDeactivated") }; if (!ev.salesFrom || !ev.salesTo) return { kind: "ended", line: t("EvtStateEnded") }; const from = malaysiaInstant(ev.salesFrom); const to = malaysiaInstant(ev.salesTo); if (now < from) { return { kind: "upcoming", line: t("EvtStarts", { date: dayMonth(ev.salesFrom, t) }) }; } if (now > to) return { kind: "ended", line: t("EvtStateEnded") }; const day = mytDay(now) - mytDay(from) + 1; const days = mytDay(to) - mytDay(from) + 1; return { kind: "live", line: t("EvtLive", { day, days }), day, days }; }