From 137a135a5ea138c4ee97fc16b1086f508daa823e Mon Sep 17 00:00:00 2001 From: Tiel Coder Date: Wed, 18 Nov 2026 18:44:22 +0000 Subject: [PATCH] unit(D8): optimistic grid editor + toast (assign/clear reverts on failure) --- src/app/(app)/schedule/page.tsx | 25 +++++- src/components/app/schedule-grid-editor.tsx | 98 +++++++++++++++++++++ src/components/app/schedule-grid.tsx | 68 +++++++++++++- src/components/app/toast.tsx | 31 +++++++ src/db/volunteers.ts | 26 ++++++ 5 files changed, 242 insertions(+), 6 deletions(-) create mode 100644 src/components/app/schedule-grid-editor.tsx create mode 100644 src/components/app/toast.tsx create mode 100644 src/db/volunteers.ts diff --git a/src/app/(app)/schedule/page.tsx b/src/app/(app)/schedule/page.tsx index 1359068..7d1c9cb 100644 --- a/src/app/(app)/schedule/page.tsx +++ b/src/app/(app)/schedule/page.tsx @@ -1,13 +1,21 @@ import { gridForWeek, defaultWeekStart } from "@/db/grid"; +import { activeVolunteers } from "@/db/volunteers"; import { WeekNav } from "@/components/app/week-nav"; import { ScheduleGrid } from "@/components/app/schedule-grid"; +import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor"; +import { auth } from "@/auth/config"; +import { hasPermission } from "@/auth/permissions"; +import type { SystemRole } from "@/auth/roles"; +import { db } from "@/db"; export const metadata = { title: "Schedule" }; /** - * 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. + * Scheduling grid (unit D7, extended by D8). Read-only for volunteers; the + * interactive optimistic editor for anyone with `schedule.publish` + * (coordinator + admin). Week 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, @@ -23,6 +31,11 @@ export default async function SchedulePage({ const week = await gridForWeek(weekStart); + const session = await auth(); + const role = (session?.user as { systemRole: SystemRole } | null | undefined) + ?.systemRole; + const canEdit = role ? hasPermission(role, "schedule.publish") : false; + return (
@@ -33,7 +46,11 @@ export default async function SchedulePage({
- + {canEdit ? ( + + ) : ( + + )}
); } diff --git a/src/components/app/schedule-grid-editor.tsx b/src/components/app/schedule-grid-editor.tsx new file mode 100644 index 0000000..428080a --- /dev/null +++ b/src/components/app/schedule-grid-editor.tsx @@ -0,0 +1,98 @@ +"use client"; + +import { useRef, useState } from "react"; +import { ScheduleGrid, type VolunteerOption } from "@/components/app/schedule-grid"; +import { Toast } from "@/components/app/toast"; +import type { GridAssignment, GridWeek } from "@/db/grid"; + +/** Deep-copy `week` with `slotId`'s assignments replaced (an optimistic edit). */ +function withSlotAssignments( + week: GridWeek, + slotId: string, + assignments: GridAssignment[], +): GridWeek { + return { + ...week, + instances: week.instances.map((inst) => ({ + ...inst, + slots: inst.slots.map((slot) => + slot.id === slotId ? { ...slot, assignments } : slot, + ), + })), + }; +} + +/** + * Optimistic grid editor (unit D8). + * + * Wraps the read-only grid for coordinators/admins. Each assign/clear is + * applied to state at once (the cell updates immediately), then POSTed to + * /api/assignments. On a non-2xx the cell reverts to the last confirmed week + * and an error toast shows the server's message. Volunteers keep the read-only + * grid (the schedule page only mounts this for `schedule.publish`), so the + * optimistic layer is the only place this state lives. + */ +export function ScheduleGridEditor({ + week, + volunteers, +}: { + week: GridWeek; + volunteers: VolunteerOption[]; +}) { + const [display, setDisplay] = useState(week); + const committed = useRef(week); + const [toast, setToast] = useState<{ message: string; kind: "error" | "success" } | null>(null); + + const post = async (payload: { + action: "assign" | "clear"; + slotId: string; + userId?: string; + }) => { + const res = await fetch("/api/assignments", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(payload), + }); + let error: string | undefined; + try { + const data = (await res.json()) as { error?: string }; + error = data.error; + } catch { + // non-JSON body — fall through to the default message + } + if (!res.ok) { + setDisplay(committed.current); + setToast({ message: error ?? "Could not save. Please try again.", kind: "error" }); + } else { + committed.current = display; + setToast({ message: payload.action === "clear" ? "Assignment cleared" : "Assignment proposed", kind: "success" }); + } + }; + + const onAssign = async (slotId: string, userId: string) => { + const volunteer = volunteers.find((v) => v.id === userId); + if (!volunteer) return; + const optimistic = withSlotAssignments(display, slotId, [ + { userId, displayName: volunteer.displayName, status: "proposed" }, + ]); + setDisplay(optimistic); + await post({ action: "assign", slotId, userId }); + }; + + const onClear = async (slotId: string) => { + setDisplay(withSlotAssignments(display, slotId, [])); + await post({ action: "clear", slotId }); + }; + + return ( + <> + + + + ); +} diff --git a/src/components/app/schedule-grid.tsx b/src/components/app/schedule-grid.tsx index 78f7e7e..951d70a 100644 --- a/src/components/app/schedule-grid.tsx +++ b/src/components/app/schedule-grid.tsx @@ -1,14 +1,26 @@ +"use client"; + import { type GridInstance, type GridSlot, type GridWeek } from "@/db/grid"; import { Badge } from "@/components/ui/badge"; import { StateMessage } from "@/components/app/state-message"; +/** A user the assign picker can offer (unit D8). */ +export interface VolunteerOption { + id: string; + displayName: string; +} + /** - * Read-only scheduling grid (unit D7, ARCHITECTURE §5.8.4). + * 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. + * + * Optional `volunteers` + `onAssign`/`onClear` turn a cell into an assign / + * clear control (unit D8). When they are omitted the grid is read-only, so the + * D7 read-only grid is byte-for-byte unchanged. */ function formatWeekday(iso: string): string { @@ -73,7 +85,43 @@ function SlotCell({ slot }: { slot: GridSlot }) { ); } -export function ScheduleGrid({ week }: { week: GridWeek }) { +function VolunteerSelect({ + volunteers, + onChange, +}: { + volunteers: VolunteerOption[]; + onChange: (userId: string) => void; +}) { + return ( + + ); +} + +export function ScheduleGrid({ + week, + volunteers, + onAssign, + onClear, +}: { + week: GridWeek; + volunteers?: VolunteerOption[]; + onAssign?: (slotId: string, userId: string) => void; + onClear?: (slotId: string) => void; +}) { if (week.instances.length === 0) { return ( s.roleSlug === position.slug, ); + const assignment = slot?.assignments.at(0); return ( {slot ? (
+ {!slot.isTraineeSlot && assignment && onClear && ( + + )} + {!slot.isTraineeSlot && !assignment && onAssign && volunteers && ( + onAssign(slot.id, userId)} + /> + )} {callTimeLabel(slot) && ( call {callTimeLabel(slot)} diff --git a/src/components/app/toast.tsx b/src/components/app/toast.tsx new file mode 100644 index 0000000..8c8e06c --- /dev/null +++ b/src/components/app/toast.tsx @@ -0,0 +1,31 @@ +"use client"; + +/** + * Optimistic-action toast (unit D8). + * + * A fixed-bottom, screen-reader-live status line the grid editor shows while an + * assign/clear mutation is in flight or after it fails. Kept tiny: the editor + * owns the message/kind state and renders this when a message is present. + */ +export function Toast({ + message, + kind, +}: { + message: string | null; + kind: "error" | "success" | null; +}) { + if (!message || !kind) return null; + return ( +
+ {message} +
+ ); +} diff --git a/src/db/volunteers.ts b/src/db/volunteers.ts new file mode 100644 index 0000000..0d86024 --- /dev/null +++ b/src/db/volunteers.ts @@ -0,0 +1,26 @@ +import { eq, sql } from "drizzle-orm"; +import { users } from "@/db/schema"; + +/** + * Active users (id + display name) for the assign picker (unit D8). + * + * D8's assign control lists every active user; skill gating (rules 6/13) and + * ranking live on the picker in D6/D9/D10, not here. `display_name` falls back + * to first + last so a user with no display name still reads sensibly. + */ +const userName = sql`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`; + +export interface VolunteerOption { + id: string; + displayName: string; +} + +export async function activeVolunteers( + db: typeof import("@/db").db, +): Promise { + return db + .select({ id: users.id, displayName: userName }) + .from(users) + .where(eq(users.status, "active")) + .orderBy(users.lastName, users.firstName); +}