unit(D8): optimistic grid editor + toast (assign/clear reverts on failure)
This commit is contained in:
@@ -1,13 +1,21 @@
|
|||||||
import { gridForWeek, defaultWeekStart } from "@/db/grid";
|
import { gridForWeek, defaultWeekStart } from "@/db/grid";
|
||||||
|
import { activeVolunteers } from "@/db/volunteers";
|
||||||
import { WeekNav } from "@/components/app/week-nav";
|
import { WeekNav } from "@/components/app/week-nav";
|
||||||
import { ScheduleGrid } from "@/components/app/schedule-grid";
|
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" };
|
export const metadata = { title: "Schedule" };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Scheduling grid (unit D7). Read-only: rows = instances, cols = positions,
|
* Scheduling grid (unit D7, extended by D8). Read-only for volunteers; the
|
||||||
* with week navigation via `?week=YYYY-MM-DD` (a Sunday). Defaults to the week
|
* interactive optimistic editor for anyone with `schedule.publish`
|
||||||
* of the earliest upcoming published instance so a seeded DB shows data at once.
|
* (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({
|
export default async function SchedulePage({
|
||||||
searchParams,
|
searchParams,
|
||||||
@@ -23,6 +31,11 @@ export default async function SchedulePage({
|
|||||||
|
|
||||||
const week = await gridForWeek(weekStart);
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -33,7 +46,11 @@ export default async function SchedulePage({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<WeekNav weekStart={weekStart} />
|
<WeekNav weekStart={weekStart} />
|
||||||
|
{canEdit ? (
|
||||||
|
<ScheduleGridEditor week={week} volunteers={await activeVolunteers(db)} />
|
||||||
|
) : (
|
||||||
<ScheduleGrid week={week} />
|
<ScheduleGrid week={week} />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<GridWeek>(week);
|
||||||
|
const committed = useRef<GridWeek>(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 (
|
||||||
|
<>
|
||||||
|
<ScheduleGrid
|
||||||
|
week={display}
|
||||||
|
volunteers={volunteers}
|
||||||
|
onAssign={onAssign}
|
||||||
|
onClear={onClear}
|
||||||
|
/>
|
||||||
|
<Toast message={toast?.message ?? null} kind={toast?.kind ?? null} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,14 +1,26 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
import { type GridInstance, type GridSlot, type GridWeek } from "@/db/grid";
|
import { type GridInstance, type GridSlot, type GridWeek } from "@/db/grid";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { StateMessage } from "@/components/app/state-message";
|
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
|
* Rows = service instances, columns = active positions (roles). Each cell is
|
||||||
* one slot: the assigned volunteer (with status) when filled, or "Open" when
|
* 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
|
* 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.
|
* 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 {
|
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 (
|
||||||
|
<select
|
||||||
|
className="mt-0.5 rounded-md border border-border bg-background px-1 py-0.5 text-xs text-foreground"
|
||||||
|
aria-label="Assign volunteer"
|
||||||
|
defaultValue=""
|
||||||
|
onChange={(e) => {
|
||||||
|
if (e.target.value) onChange(e.target.value);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Assign</option>
|
||||||
|
{volunteers.map((v) => (
|
||||||
|
<option key={v.id} value={v.id}>
|
||||||
|
{v.displayName}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
if (week.instances.length === 0) {
|
||||||
return (
|
return (
|
||||||
<StateMessage
|
<StateMessage
|
||||||
@@ -121,11 +169,27 @@ export function ScheduleGrid({ week }: { week: GridWeek }) {
|
|||||||
const slot = inst.slots.find(
|
const slot = inst.slots.find(
|
||||||
(s) => s.roleSlug === position.slug,
|
(s) => s.roleSlug === position.slug,
|
||||||
);
|
);
|
||||||
|
const assignment = slot?.assignments.at(0);
|
||||||
return (
|
return (
|
||||||
<td key={position.slug} className="px-3 py-2 text-center">
|
<td key={position.slug} className="px-3 py-2 text-center">
|
||||||
{slot ? (
|
{slot ? (
|
||||||
<div className="flex flex-col items-center gap-0.5">
|
<div className="flex flex-col items-center gap-0.5">
|
||||||
<SlotCell slot={slot} />
|
<SlotCell slot={slot} />
|
||||||
|
{!slot.isTraineeSlot && assignment && onClear && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => onClear(slot.id)}
|
||||||
|
className="text-[11px] text-muted-foreground underline hover:text-foreground"
|
||||||
|
>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{!slot.isTraineeSlot && !assignment && onAssign && volunteers && (
|
||||||
|
<VolunteerSelect
|
||||||
|
volunteers={volunteers}
|
||||||
|
onChange={(userId) => onAssign(slot.id, userId)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{callTimeLabel(slot) && (
|
{callTimeLabel(slot) && (
|
||||||
<span className="text-[11px] text-muted-foreground">
|
<span className="text-[11px] text-muted-foreground">
|
||||||
call {callTimeLabel(slot)}
|
call {callTimeLabel(slot)}
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<div
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
className={`fixed bottom-4 left-1/2 z-50 -translate-x-1/2 max-w-md px-4 py-2 rounded-md shadow-md text-sm font-medium ${
|
||||||
|
kind === "error"
|
||||||
|
? "bg-destructive text-destructive-foreground"
|
||||||
|
: "bg-muted text-foreground"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||||
|
|
||||||
|
export interface VolunteerOption {
|
||||||
|
id: string;
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function activeVolunteers(
|
||||||
|
db: typeof import("@/db").db,
|
||||||
|
): Promise<VolunteerOption[]> {
|
||||||
|
return db
|
||||||
|
.select({ id: users.id, displayName: userName })
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.status, "active"))
|
||||||
|
.orderBy(users.lastName, users.firstName);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user