D7: read-only schedule grid UI (rows=instances, cols=positions, week nav)

Server-component schedule page backed by a pure data layer (src/db/grid.ts):
gridForWeek() returns positions + instances (->slots->assignments), and
defaultWeekStart() defaults to the earliest upcoming published instance so a
seeded DB shows data on first load. Week nav via ?week=YYYY-MM-DD (server
rendered, no client state).

Fixes two latent bugs that kept the grid empty/incorrect:
- tz: weekdayInTz()/nextSundaysInTz() built Date.UTC(y,mo-1,d) from a LOCAL
  date string and read its weekday; for America/New_York (UTC-5) UTC midnight
  lands the previous evening, so the seed materialized instances on Mondays and
  the default week was off by one. weekdayInTz now builds the local-midnight
  instant via utcOffsetMs; nextSundaysInTz uses weekdayInTz + addDaysISO.
- grid: occursOn (date mode) was run through dateInTimezone(), reinterpreting
  the UTC instant as wall-clock and shifting a day early; now extracts the UTC
  calendar date directly (occursOnISO).
- schedule-grid: <table className=... collapse ...> set visibility: collapse
  (Tailwind 'collapse'), hiding the whole grid server-rendered-but-invisible;
  changed to border-collapse.

E2E: new schedule-grid.spec.ts + shell.spec.ts grid assertion. Full suite green:
tsc, eslint, 178 unit tests, next build, 6/6 Playwright.
This commit is contained in:
Tiel Coder
2026-11-18 16:19:17 +00:00
parent 13aafc231f
commit 6982a8040d
8 changed files with 567 additions and 21 deletions
+36
View File
@@ -566,6 +566,42 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e
---
## D7 — Read-only grid UI — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** Grid UI, read-only: rows = instances, cols = positions, week nav. Done when: E2E renders a seeded week; no console errors. Depends on D1–D6 (all committed).
**Status:** DONE. All code written; typecheck + eslint + unit (178) + `next build` green; **full Playwright E2E green (6/6)** and committed. Two further latent bugs were found and fixed this session (see Decisions/Blockers).
**Delivered:**
- `src/lib/tz.ts` — added `CHURCH_TIMEZONE`, `addDaysISO(dateStr, days)` (calendar-safe ISO ± days), `weekStartOn(dateStr, tz)` (Sunday of the week containing a date). **Fixed a pre-existing bug:** `weekdayInTz()` returned `undefined` because `partsInTz()` never emitted a `weekday` part; added `weekday: "short"` to its Intl format and made `weekdayInTz` return `WEEKDAYS.indexOf(label)` (0=Sun..6=Sat). This also corrects `nextSundaysInTz`, which relied on the same missing part (seed was producing instances on wrong dates).
- **Fixed a second latent bug (this session):** `weekdayInTz()` and `nextSundaysInTz()` both built `new Date(Date.UTC(y, mo-1, d))` from a *local* date string and read its weekday — for a negative-offset zone like `America/New_York`, UTC midnight lands on the *previous* evening, so the weekday (and thus the seed's Sundays and the grid's default week) was off by one. The seed had materialized instances on **Mondays** (11-23/11-30) instead of Sundays. `weekdayInTz` now builds the instant for **local** midnight via `utcOffsetMs`; `nextSundaysInTz` now uses `weekdayInTz` + the calendar-safe `addDaysISO`. Verified: today Wed 2026-11-18 → next Sundays 2026-11-22 / 2026-11-29; `weekStartOn("2026-11-18")` = 2026-11-15.
- `src/db/grid.ts` — pure data layer for the grid. `gridForWeek(weekStart)` returns `{ weekStart, weekEnd, positions[], instances[] }` (instances → slots → assignments → user display names). `defaultWeekStart()` returns the Sunday of the earliest upcoming published instance so a seeded DB shows data on first load. `occursOn` is a `date`-mode column → returned as a UTC-midnight instant; the grid now extracts the **UTC calendar date directly** (`occursOnISO`, via `getUTCFullYear/getUTCMonth/getUTCDate`) instead of running it through `dateInTimezone(...)` (which reinterprets the UTC instant as wall-clock and shifts a day early in negative-offset zones). `gridForWeek` filters `gte`/`lte` on `Date` objects (UTC midnight).
- `src/components/app/week-nav.tsx` — prev/next week anchor links to `?week=YYYY-MM-DD` (server-rendered, no client state).
- `src/components/app/schedule-grid.tsx` — semantic `<table>`: header row = active positions (by sortOrder), one row per instance, each cell = slot (assigned volunteer + status badge, or "Open", trainee slots shown as shadow). Empty state via `StateMessage`.
- **Fixed a bug (this session):** the `<table>` used the Tailwind class `collapse`, which sets `visibility: collapse` (hides the whole table) — the grid rendered server-side but was invisible in the browser, so E2E saw an empty grid. Changed to `border-collapse` (the intended border-collapsing utility).
- `src/app/(app)/schedule/page.tsx` — replaced the placeholder. Async server component, `searchParams: Promise<{ week?: string }>`. Validates `?week=`, falls back to `defaultWeekStart()`, fetches and renders nav + grid.
- `e2e/schedule-grid.spec.ts` — new: renders a seeded week, asserts role column headers + an instance row + prev/next nav, captures console + page errors and fails if any. Week-nav test asserts URL + re-render.
- `e2e/shell.spec.ts` — updated the schedule assertion from the old placeholder ("Nothing scheduled yet") to the grid (role headers + service name).
**Verification (all green):**
- `tsc --noEmit` ✓ · `eslint .` ✓ · `vitest run` ✓ (**178** tests, 21 files) · `next build` ✓.
- **Playwright E2E: 6/6 passing** — `e2e/schedule-grid.spec.ts` (2) + `e2e/shell.spec.ts` (4, incl. health + unauth redirect).
- Live `/schedule` renders the seeded week `2026-11-22 – 2026-11-28` with Audio/Livestream/Slides columns and both Sunday services; label reads `Sun, Nov 22 · Sunday 9:00 AM`.
- DB re-seeded after the tz fix (reset instances/slots/assignments): 4 instances on Sundays (11-22, 11-29) / 12 slots / 12 assignments / 3 roles.
**Decisions:**
- **Read-only grid = server component, no API route.** A read-only grid doesn't need a client data layer; the page queries `src/db/grid.ts` directly and renders. D8 (mutate) will add its own client + routes.
- **Week nav via URL param, not client state.** `?week=YYYY-MM-DD` survives reload/share and needs no JS — simplest robust approach for a read-only grid.
- **Default week = earliest upcoming published instance.** So a freshly seeded DB shows data immediately instead of an empty state.
- **`occursOn` compared as `Date`, not string.** The column is `date({ mode: "date" })`; `gte`/`lte` take `Date` objects (UTC midnight). Returned to the UI as the **UTC calendar date** (`occursOnISO`), not `dateInTimezone(...)` — reinterpreting the UTC instant as wall-clock shifts a day early in negative-offset zones.
- **Fixed `weekdayInTz` rather than working around it.** `weekStartOn` needs the weekday; the underlying `partsInTz` gap was a latent bug affecting the seed too, so fixing it at the source is correct. The UTC-midnight reconstruction bug was the same class of issue and is fixed the same way (build the local-midnight instant).
**Blockers found (now resolved):**
- `RangeError: Invalid time value` on `/schedule` was drizzle serializing an `Invalid Date` from `defaultWeekStart()`, which returned `NaN-NaN-NaN` because `weekdayInTz()` returned `undefined` (no `weekday` part in `partsInTz`). Fixed by adding `weekday: "short"` to `partsInTz` and returning `WEEKDAYS.indexOf(label)`.
- **`collapse` Tailwind class hid the grid.** `<table className="min-w-full collapse text-sm">` set `visibility: collapse` — the grid rendered server-side (curl confirmed) but was invisible in the browser, so E2E saw an empty grid. Changed to `border-collapse`.
---
## D1 — Service CRUD + `expandRRULE()` — DONE 2026-11-18
**Scope (from BUILD-PLAN.md):** service CRUD + `expandRRULE()` (weekly / biweekly / monthly-nth). Done when: `pnpm test recurrence` green on 5 named cases — spring-forward Sunday, fall-back Sunday, monthly-nth across a year boundary, cancelled instance not regenerated, biweekly phase stable. ARCHITECTURE §4.3 / §5.1 / §5.8.3.
+72
View File
@@ -0,0 +1,72 @@
import { test, expect, type Page } from "@playwright/test";
const BASE = "http://localhost:3000";
/**
* Dev console transport: request a magic link, then complete it in the browser
* context so the Auth.js session cookie is set for the navigation under test.
*/
async function signInAs(page: Page, email: string) {
const res = await page.request.post(`${BASE}/api/dev/magic-link`, {
data: { email },
});
expect(res.ok(), "magic-link request should succeed").toBe(true);
const body = (await res.json()) as { url?: string };
expect(body.url, "magic-link should return a sign-in url").toBeTruthy();
await page.goto(body.url!);
await expect(page).toHaveURL(/complete/);
}
/**
* Unit D7 — read-only scheduling grid. Done when: renders a seeded week; no
* console errors. Captures console + page errors and fails the test if any are
* logged while the grid is mounted.
*/
test.describe("schedule grid", () => {
test("renders a seeded week with no console errors", async ({ page }) => {
const errors: string[] = [];
page.on("console", (msg) => {
if (msg.type() === "error") errors.push(msg.text());
});
page.on("pageerror", (err) => errors.push(`page error: ${err.message}`));
await page.setViewportSize({ width: 1024, height: 768 });
await signInAs(page, `e2e-grid-${Date.now()}@example.com`);
await page.goto(`${BASE}/schedule`);
await expect(page).toHaveURL(`${BASE}/schedule`);
// Grid header: one column per active position.
await expect(page.getByRole("columnheader", { name: "Audio", exact: true })).toBeVisible();
await expect(page.getByRole("columnheader", { name: "Livestream", exact: true })).toBeVisible();
await expect(page.getByRole("columnheader", { name: "Slides", exact: true })).toBeVisible();
// At least one seeded instance row renders. The row label is
// "<weekday> · <service name>", so match the service name as a substring.
await expect(page.getByText("Sunday 9:00 AM", { exact: false })).toBeVisible();
// Week navigation controls are present.
await expect(page.getByRole("link", { name: /Prev/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Next/ })).toBeVisible();
// No console or page errors while the grid is mounted.
expect(errors, `unexpected console/page errors: ${errors.join("; ")}`).toEqual([]);
});
test("week navigation changes the URL and the rendered week", async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 768 });
await signInAs(page, `e2e-grid-nav-${Date.now()}@example.com`);
await page.goto(`${BASE}/schedule`);
await expect(page.getByText("Sunday 9:00 AM", { exact: false })).toBeVisible();
const before = page.url();
await page.getByRole("link", { name: /Next/ }).click();
await expect(page).toHaveURL(/week=/);
// The URL carries the target week; the grid re-renders server-side.
expect(page.url()).not.toBe(before);
await expect(page.getByText("Sunday 9:00 AM")).toBeVisible();
});
});
+4 -2
View File
@@ -40,8 +40,10 @@ test.describe("app shell", () => {
"page",
);
// Empty state renders inside the shell.
await expect(page.getByText("Nothing scheduled yet")).toBeVisible();
// The schedule grid renders (unit D7): role columns and an instance row.
await expect(page.getByText("Audio")).toBeVisible();
await expect(page.getByText("Livestream")).toBeVisible();
await expect(page.getByText("Slides")).toBeVisible();
});
test("shows the desktop rail inside the shell at desktop width", async ({ page }) => {
+33 -10
View File
@@ -1,16 +1,39 @@
import { StateMessage } from "@/components/app/state-message";
import { gridForWeek, defaultWeekStart } from "@/db/grid";
import { WeekNav } from "@/components/app/week-nav";
import { ScheduleGrid } from "@/components/app/schedule-grid";
export const metadata = { title: "Schedule" };
export default function SchedulePage() {
/**
* Scheduling grid (unit D7). Read-only: rows = instances, cols = positions,
* with week navigation via `?week=YYYY-MM-DD` (a Sunday). Defaults to the week
* of the earliest upcoming published instance so a seeded DB shows data at once.
*/
export default async function SchedulePage({
searchParams,
}: {
searchParams: Promise<{ week?: string }>;
}) {
const { week: paramWeek } = await searchParams;
// Validate the param is a YYYY-MM-DD string; fall back to the default week.
const weekStart =
typeof paramWeek === "string" && /^\d{4}-\d{2}-\d{2}$/.test(paramWeek)
? paramWeek
: await defaultWeekStart();
const week = await gridForWeek(weekStart);
return (
<>
<h1 className="text-lg font-semibold tracking-tight">Schedule</h1>
<p className="text-sm text-muted-foreground">Your upcoming slots and what to do the day of service.</p>
<StateMessage
title="Nothing scheduled yet"
description="Slots confirmed for you will show up here, with call times and a way to add them to your calendar."
/>
</>
<div className="space-y-4">
<div>
<h1 className="text-lg font-semibold tracking-tight">Schedule</h1>
<p className="text-sm text-muted-foreground">
Service instances for the week and who is on each position.
</p>
</div>
<WeekNav weekStart={weekStart} />
<ScheduleGrid week={week} />
</div>
);
}
+147
View File
@@ -0,0 +1,147 @@
import { type GridInstance, type GridSlot, type GridWeek } from "@/db/grid";
import { Badge } from "@/components/ui/badge";
import { StateMessage } from "@/components/app/state-message";
/**
* Read-only scheduling grid (unit D7, ARCHITECTURE §5.8.4).
*
* Rows = service instances, columns = active positions (roles). Each cell is
* one slot: the assigned volunteer (with status) when filled, or "Open" when
* not. Rendered as a semantic table so it is keyboard- and screen-reader
* navigable. Pure presentation — it receives the week's data as a prop.
*/
function formatWeekday(iso: string): string {
const [y, mo, d] = iso.split("-").map(Number);
const dt = new Date(Date.UTC(y, mo - 1, d));
return new Intl.DateTimeFormat("en-US", {
weekday: "short",
month: "short",
day: "numeric",
}).format(dt);
}
function instanceLabel(inst: GridInstance): string {
return `${formatWeekday(inst.occursOn)} · ${inst.serviceName}`;
}
function callTimeLabel(slot: GridSlot): string {
if (!slot.callTime) return "";
return new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
hour: "2-digit",
minute: "2-digit",
}).format(slot.callTime);
}
function SlotCell({ slot }: { slot: GridSlot }) {
const assignment = slot.assignments.at(0);
if (slot.isTraineeSlot) {
return (
<div className="space-y-1">
<span className="text-xs font-medium text-muted-foreground">
Trainee slot
</span>
{assignment && (
<div className="flex items-center gap-1.5">
<span className="text-sm text-foreground">{assignment.displayName}</span>
<Badge variant="outline">shadow</Badge>
</div>
)}
</div>
);
}
if (assignment) {
return (
<div className="space-y-1">
<span className="text-sm font-medium text-foreground">
{assignment.displayName}
</span>
<Badge
variant={assignment.status === "confirmed" ? "default" : "secondary"}
>
{assignment.status}
</Badge>
</div>
);
}
return (
<span className="text-xs font-medium text-muted-foreground">Open</span>
);
}
export function ScheduleGrid({ week }: { week: GridWeek }) {
if (week.instances.length === 0) {
return (
<StateMessage
title="No instances this week"
description="There are no published service instances for this week. Pick a different week or wait for an admin to publish."
/>
);
}
return (
<div className="overflow-x-auto rounded-md border border-border">
<table className="min-w-full border-collapse text-sm">
<thead className="border-b border-border bg-muted/40">
<tr>
<th
scope="col"
className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-tight text-muted-foreground"
>
When
</th>
{week.positions.map((position) => (
<th
key={position.slug}
scope="col"
className="px-3 py-2 text-center text-xs font-semibold uppercase tracking-tight text-muted-foreground"
>
{position.name}
</th>
))}
</tr>
</thead>
<tbody>
{week.instances.map((inst) => (
<tr
key={inst.id}
className="border-b border-border last:border-b-0 hover:bg-muted/30"
>
<th
scope="row"
className="whitespace-nowrap px-3 py-2 text-left text-xs font-semibold text-foreground"
>
{instanceLabel(inst)}
</th>
{week.positions.map((position) => {
const slot = inst.slots.find(
(s) => s.roleSlug === position.slug,
);
return (
<td key={position.slug} className="px-3 py-2 text-center">
{slot ? (
<div className="flex flex-col items-center gap-0.5">
<SlotCell slot={slot} />
{callTimeLabel(slot) && (
<span className="text-[11px] text-muted-foreground">
call {callTimeLabel(slot)}
</span>
)}
</div>
) : (
<span className="text-xs text-muted-foreground">—</span>
)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { addDaysISO } from "@/lib/tz";
/**
* Week navigation for the scheduling grid (unit D7). Plain anchor links to
* `?week=` so the current week survives reload and share — no client state.
* `aria-current` marks the active label; prev/next move ±7 days.
*/
export function WeekNav({ weekStart }: { weekStart: string }) {
const weekEnd = addDaysISO(weekStart, 6);
const prev = addDaysISO(weekStart, -7);
const next = addDaysISO(weekStart, 7);
return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<a
href={`/schedule?week=${prev}`}
className="rounded-md border border-border px-3 py-1.5 text-sm font-medium hover:bg-muted"
>
← Prev
</a>
<a
href={`/schedule?week=${next}`}
className="rounded-md border border-border px-3 py-1.5 text-sm font-medium hover:bg-muted"
>
Next →
</a>
</div>
<div
className="text-sm font-semibold tracking-tight text-foreground"
aria-label="Week of"
>
{weekStart} – {weekEnd}
</div>
</div>
);
}
+202
View File
@@ -0,0 +1,202 @@
/**
* Grid data — unit D7 (ARCHITECTURE §5.8.4).
*
* The read-only scheduling grid: rows = service instances, cols = active
* positions (roles, by `sort_order`), each cell = one slot with its
* assignment. This module is the single data source for the grid — the page
* fetches a week and the component renders it. Pure data, no JSX.
*/
import { and, eq, gte, lte } from "drizzle-orm";
import { db } from "@/db";
import {
assignments,
roles,
serviceInstances,
services,
slots,
users,
} from "@/db/schema";
import { addDaysISO, CHURCH_TIMEZONE, dateInTimezone, weekStartOn } from "@/lib/tz";
export interface GridAssignment {
userId: string;
displayName: string;
status: string;
}
export interface GridSlot {
id: string;
roleId: string;
roleSlug: string;
roleName: string;
slotIndex: number;
callTime: Date | null;
status: string;
isTraineeSlot: boolean;
assignments: GridAssignment[];
}
export interface GridInstance {
id: string;
serviceId: string;
serviceName: string;
/** Local date (YYYY-MM-DD) the service occurs. */
occursOn: string;
startsAt: Date;
titleOverride: string | null;
status: string;
slots: GridSlot[];
}
export interface GridPosition {
slug: string;
name: string;
colorHex: string | null;
}
export interface GridWeek {
weekStart: string;
weekEnd: string;
positions: GridPosition[];
instances: GridInstance[];
}
/**
* Grid data for one week (Sunday–Saturday). `weekStart` is a YYYY-MM-DD
* Sunday. Instances are ordered by date then start time; slots within an
* instance by slot index; positions by role sort order.
*/
function occursOnISO(d: Date): string {
const y = d.getUTCFullYear();
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
const day = String(d.getUTCDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
/**
* The `occurs_on` column stores a church-local calendar date. Drizzle returns a
* `date` column as UTC midnight of that date, so the local date *is* the UTC
* calendar date. Extract it directly rather than running it through
* `dateInTimezone`, which would reinterpret the UTC-midnight instant as a wall
* clock in the church timezone and shift the date a day early (e.g. 2026-11-23
* stored as 2026-11-23T00:00:00Z would render as 2026-11-22 in America/New_York).
*/
export async function gridForWeek(weekStart: string): Promise<GridWeek> {
const weekEnd = addDaysISO(weekStart, 6);
const weekStartDate = new Date(`${weekStart}T00:00:00Z`);
const weekEndDate = new Date(`${weekEnd}T00:00:00Z`);
const instances = await db
.select()
.from(serviceInstances)
.where(
and(
gte(serviceInstances.occursOn, weekStartDate),
lte(serviceInstances.occursOn, weekEndDate),
),
)
.orderBy(serviceInstances.occursOn, serviceInstances.startsAt);
const roleRows = await db
.select()
.from(roles)
.where(eq(roles.active, true))
.orderBy(roles.sortOrder);
const positions: GridPosition[] = roleRows.map((r) => ({
slug: r.slug,
name: r.name,
colorHex: r.colorHex,
}));
const roleBySlug = new Map(positions.map((p) => [p.slug, p]));
const serviceById = new Map(
(await db.select().from(services)).map((s) => [s.id, s.name]),
);
const result: GridInstance[] = [];
for (const inst of instances) {
const slotRows = await db
.select()
.from(slots)
.where(eq(slots.serviceInstanceId, inst.id))
.orderBy(slots.slotIndex);
const slotsOut: GridSlot[] = [];
for (const slot of slotRows) {
const role = roleBySlug.get(slot.roleId);
const assignRows = await db
.select()
.from(assignments)
.where(eq(assignments.slotId, slot.id));
const assignmentsOut: GridAssignment[] = [];
for (const a of assignRows) {
const [user] = await db
.select()
.from(users)
.where(eq(users.id, a.userId));
assignmentsOut.push({
userId: a.userId,
displayName: user?.displayName ?? "",
status: a.status,
});
}
slotsOut.push({
id: slot.id,
roleId: slot.roleId,
roleSlug: role?.slug ?? "",
roleName: role?.name ?? "",
slotIndex: slot.slotIndex,
callTime: slot.callTime,
status: slot.status,
isTraineeSlot: slot.isTraineeSlot,
assignments: assignmentsOut,
});
}
result.push({
id: inst.id,
serviceId: inst.serviceId,
serviceName: serviceById.get(inst.serviceId) ?? "",
occursOn: inst.occursOn
? occursOnISO(inst.occursOn)
: "",
startsAt: inst.startsAt ?? new Date(),
titleOverride: inst.titleOverride ?? null,
status: inst.status,
slots: slotsOut,
});
}
return { weekStart, weekEnd, positions, instances: result };
}
/**
* The Sunday that starts the week of the earliest published instance at/after
* today — the grid's default week, so a freshly seeded DB shows data on first
* load. Falls back to the current week when there is no upcoming instance.
*/
export async function defaultWeekStart(): Promise<string> {
const todayStart = new Date(
`${dateInTimezone(new Date(), CHURCH_TIMEZONE)}T00:00:00Z`,
);
const [earliest] = await db
.select({ occursOn: serviceInstances.occursOn })
.from(serviceInstances)
.where(
and(
eq(serviceInstances.status, "published"),
gte(serviceInstances.occursOn, todayStart),
),
)
.orderBy(serviceInstances.occursOn)
.limit(1);
if (!earliest?.occursOn) {
return weekStartOn(
dateInTimezone(new Date(), CHURCH_TIMEZONE),
CHURCH_TIMEZONE,
);
}
return weekStartOn(occursOnISO(earliest.occursOn), CHURCH_TIMEZONE);
}
+35 -9
View File
@@ -11,6 +11,7 @@ function partsInTz(date: Date, timeZone: string): Record<string, string> {
year: "numeric",
month: "2-digit",
day: "2-digit",
weekday: "short",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
@@ -63,10 +64,22 @@ export function dateInTimezone(date: Date, timeZone: string): string {
return `${year}-${month}-${day}`;
}
/** The church's local timezone — the source of truth for scheduling. */
export const CHURCH_TIMEZONE = "America/New_York";
/** Weekday (0=Sun..6=Sat) of a local date string in `timeZone`. */
export function weekdayInTz(dateStr: string, timeZone: string): number {
const [y, mo, d] = dateStr.split("-").map(Number);
return partsInTz(new Date(Date.UTC(y, mo - 1, d)), timeZone).weekday as unknown as number;
// `dateStr` is a calendar date *in* `timeZone`. Build the instant for local
// midnight there (not UTC midnight, which for a negative-offset zone like
// America/New_York lands on the previous evening and reports the wrong day),
// then read its weekday in that zone.
const utcMidnight = new Date(Date.UTC(y, mo - 1, d));
const localMidnight = new Date(
utcMidnight.getTime() - utcOffsetMs(utcMidnight, timeZone),
);
const weekdayLabel = partsInTz(localMidnight, timeZone).weekday as string;
return WEEKDAYS.indexOf(weekdayLabel);
}
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
@@ -77,18 +90,31 @@ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
*/
export function nextSundaysInTz(count: number, timeZone: string): string[] {
const today = dateInTimezone(new Date(), timeZone);
const [ty, tm, td] = today.split("-").map(Number);
const weekday = WEEKDAYS.indexOf(partsInTz(new Date(Date.UTC(ty, tm - 1, td)), timeZone).weekday as unknown as string);
const weekday = weekdayInTz(today, timeZone);
const daysUntilNextSunday = weekday === 0 ? 7 : 7 - weekday;
const out: string[] = [];
for (let k = 0; k < count; k++) {
const target = new Date(Date.UTC(ty, tm - 1, td));
target.setUTCDate(target.getUTCDate() + daysUntilNextSunday + k * 7);
const y = target.getUTCFullYear();
const m = String(target.getUTCMonth() + 1).padStart(2, "0");
const d = String(target.getUTCDate()).padStart(2, "0");
out.push(`${y}-${m}-${d}`);
// addDaysISO is calendar-safe (crosses month/year boundaries) and operates
// purely on the local date string, so no UTC-midnight shift creeps in.
out.push(addDaysISO(today, daysUntilNextSunday + k * 7));
}
return out;
}
/** YYYY-MM-DD `days` after a YYYY-MM-DD string (calendar-safe across months). */
export function addDaysISO(dateStr: string, days: number): string {
const [y, mo, d] = dateStr.split("-").map(Number);
const target = new Date(Date.UTC(y, mo - 1, d));
target.setUTCDate(target.getUTCDate() + days);
const y2 = target.getUTCFullYear();
const m = String(target.getUTCMonth() + 1).padStart(2, "0");
const day = String(target.getUTCDate()).padStart(2, "0");
return `${y2}-${m}-${day}`;
}
/** YYYY-MM-DD of the Sunday that starts the week containing `dateStr`. */
export function weekStartOn(dateStr: string, timeZone: string): string {
const weekday = weekdayInTz(dateStr, timeZone);
return addDaysISO(dateStr, -weekday);
}