// Week maths for the board, always in Bangkok time (UTC+7, no DST). const TZ_OFFSET_MS = 7 * 60 * 60 * 1000; const dayKeyFmt = new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: "Asia/Bangkok" }); /** "YYYY-MM-DD" of an instant, in Bangkok. */ export function bkkDayKey(d: Date): string { return dayKeyFmt.format(d); } /** UTC instant of 00:00 Bangkok on the given day key. */ export function bkkMidnight(dayKey: string): Date { const [y, m, d] = dayKey.split("-").map(Number); return new Date(Date.UTC(y, m - 1, d) - TZ_OFFSET_MS); } export function addDays(dayKey: string, n: number): string { const [y, m, d] = dayKey.split("-").map(Number); const t = new Date(Date.UTC(y, m - 1, d + n)); return t.toISOString().slice(0, 10); } /** Monday of the week containing dayKey. */ export function weekStartOf(dayKey: string): string { const [y, m, d] = dayKey.split("-").map(Number); const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay(); // 0 = Sunday return addDays(dayKey, -((dow + 6) % 7)); } export function parseWeekParam(w: string | undefined): string { if (isDayKey(w)) return weekStartOf(w!); return weekStartOf(bkkDayKey(new Date())); } export function isDayKey(value: string | undefined): boolean { if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false; const date = new Date(`${value}T00:00:00Z`); return !Number.isNaN(date.getTime()) && date.toISOString().slice(0, 10) === value; } /** Actual publication takes precedence over the owner's provisional plan. */ export function postBoardDate(post: { status: string; scheduledPublishAt: Date | null; plannedAt: Date | null; updatedAt: Date }): Date | null { if (post.status === "PUBLISHED") return post.scheduledPublishAt ?? post.updatedAt; return post.scheduledPublishAt ?? post.plannedAt; }