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
+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);
}