Volunteer rosters: serving, roster and check-in pages, help, e2e

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-28 03:59:52 +02:00
co-authored by Claude Opus 5.5
parent a9f13a1b0a
commit 4166096706
19 changed files with 1023 additions and 7 deletions
@@ -84,6 +84,7 @@ export function RoomBoard({ board, token, roomId, onChanged, onMessage }: Props)
<RoomStatusBadges room={r} />
</div>
{r.leaderNames.length > 0 && <div className="text-xs text-gray-500 mb-2 flex items-center gap-1"><Users className="w-3.5 h-3.5" /> On duty: {r.leaderNames.join(", ")}</div>}
{(r.rostered || []).some(v => !v.checkedIn) && <div className="text-xs text-gray-500 mb-2">Rostered, not checked in yet: {r.rostered.filter(v => !v.checkedIn).map(v => v.name).join(", ")}</div>}
{inRoom.length === 0 && <p className="text-sm text-gray-500">No children in this room.</p>}
<div className="grid sm:grid-cols-2 gap-3">
{inRoom.map(c => (
@@ -2,7 +2,7 @@
import React, { useState } from "react";
import Link from "next/link";
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, Lock, Baby, type LucideIcon } from "lucide-react";
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, Lock, Baby, HandHeart, type LucideIcon } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { RoleBadge, type Role } from "@/components/shared/RoleBadge";
import { UserAvatar } from "@/components/shared/UserAvatar";
@@ -13,6 +13,7 @@ const navLinks: { href: string; label: string; icon: LucideIcon; roles?: string[
{ href: "/dashboard/user", label: "My Events", icon: Calendar, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/profile", label: "Profile & Security", icon: User, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/kids", label: "Kids", icon: Baby, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/serving", label: "Serving", icon: HandHeart, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/user/privacy", label: "Privacy", icon: Lock, roles: ["user", "staff", "supervisor", "admin"] },
{ href: "/dashboard/staff", label: "Staff", icon: LayoutDashboard, roles: ["staff"] },
{ href: "/dashboard/supervisor", label: "Supervisor", icon: LayoutDashboard, roles: ["supervisor"] },
@@ -0,0 +1,33 @@
"use client";
import React, { useEffect, useState } from "react";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { QrImage } from "@/components/shared/QrImage";
import { Printer } from "lucide-react";
import { checkInUrl } from "@/lib/volunteers";
/** The event's volunteer check-in QR code, to show on a screen or print and put up at the venue. */
export function CheckInQr({ token, eventId, title }: { token: string | null; eventId: string; title: string }) {
const [qr, setQr] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!token || !eventId) return;
setQr(null);
apiFetch<{ qr: string }>(`/api/volunteers/manage/events/${eventId}/qr`, { authToken: token })
.then(r => setQr(r.qr))
.catch(e => setError(errorMessage(e) || "Could not load the QR code"));
}, [token, eventId]);
if (error) return <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>;
return (
<div className="border rounded-xl p-6 bg-white shadow-sm text-center space-y-3">
<h2 className="text-xl font-semibold">Volunteers: check in here</h2>
<p className="text-sm text-gray-600">{title}</p>
{qr ? <QrImage value={checkInUrl(qr)} size={320} alt="Volunteer check-in QR code" className="mx-auto w-64 h-64" /> : <div className="mx-auto w-64 h-64 bg-gray-100 animate-pulse" />}
<p className="text-sm text-gray-700">Scan with your phone&apos;s camera and log in — you&apos;re checked in for your shifts today.</p>
<button onClick={() => window.print()} className="print:hidden px-3 py-1.5 rounded-lg border text-sm inline-flex items-center gap-1"><Printer className="w-4 h-4" /> Print</button>
</div>
);
}
@@ -0,0 +1,214 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { CheckCircle2, Pencil, Plus, Printer, Trash2, UserPlus, X } from "lucide-react";
import { fromLocalInput, toLocalInput, type Roster, type ServingRole } from "@/lib/volunteers";
type Msg = { type: "ok" | "err"; text: string };
type Props = {
token: string | null;
eventId: string;
/** Supervisors: add, change and delete roles, put people on and take them off. */
canEdit: boolean;
kidsRooms?: { id: string; name: string }[];
onMessage: (m: Msg) => void;
};
type Draft = { name: string; needed: string; sessionId: string; startsAt: string; endsAt: string; description: string; kidsRoomId: string };
const EMPTY: Draft = { name: "", needed: "1", sessionId: "", startsAt: "", endsAt: "", description: "", kidsRoomId: "" };
const inputCls = "w-full border rounded-lg px-2 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500";
const time = (iso: string) => new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const toDraft = (r: ServingRole): Draft => ({
name: r.name, needed: String(r.needed), sessionId: r.sessionId || "", startsAt: toLocalInput(r.startsAt), endsAt: toLocalInput(r.endsAt),
description: r.description, kidsRoomId: r.kidsRoom?.id || "",
});
/** The roster for one event: roles with their volunteers and check-ins (and, for supervisors, editing). */
export function RosterSheet({ token, eventId, canEdit, kidsRooms = [], onMessage }: Props) {
const [roster, setRoster] = useState<Roster | null>(null);
const [busy, setBusy] = useState(false);
const [editing, setEditing] = useState<string | "new" | null>(null);
const [draft, setDraft] = useState<Draft>(EMPTY);
const [assignFor, setAssignFor] = useState<string | null>(null);
const [query, setQuery] = useState("");
const [found, setFound] = useState<{ id: string; name: string; email: string }[]>([]);
const load = useCallback(async (log = false) => {
if (!token || !eventId) return;
try {
setRoster(await apiFetch<Roster>(`/api/volunteers/manage/events/${eventId}${log ? "?log=1" : ""}`, { authToken: token }));
} catch (e) {
onMessage({ type: "err", text: errorMessage(e) || "Could not load the roster" });
}
}, [token, eventId, onMessage]);
// Opening the roster writes the access log (it shows contact details); refreshes don't.
useEffect(() => { setRoster(null); load(true); }, [load]);
useVisiblePolling(() => { load(); }, 30000, !!token && !!eventId);
const run = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
try {
await fn();
onMessage({ type: "ok", text: ok });
await load();
return true;
} catch (e) {
onMessage({ type: "err", text: errorMessage(e) || "Something went wrong" });
return false;
} finally {
setBusy(false);
}
};
const body = (d: Draft) => ({
name: d.name, needed: Number(d.needed) || 1, description: d.description,
...(roster?.event.scheduleType === "sessions" ? { sessionId: d.sessionId } : {}),
startsAt: fromLocalInput(d.startsAt), endsAt: fromLocalInput(d.endsAt), kidsRoomId: d.kidsRoomId || null,
});
const saveRole = () => run(
() => editing === "new"
? apiFetch(`/api/volunteers/manage/events/${eventId}/roles`, { method: "POST", authToken: token, body: body(draft) })
: apiFetch(`/api/volunteers/manage/roles/${editing}`, { method: "PUT", authToken: token, body: body(draft) }),
editing === "new" ? "Role added." : "Role saved.",
).then(ok => { if (ok) { setEditing(null); setDraft(EMPTY); } });
const deleteRole = (r: ServingRole) => confirm(`Delete ${r.name}?${r.filled ? ` The ${r.filled} volunteer${r.filled === 1 ? "" : "s"} on it will be told.` : ""}`)
&& run(() => apiFetch(`/api/volunteers/manage/roles/${r.id}`, { method: "DELETE", authToken: token }), "Role deleted.");
const search = async () => {
if (!token || query.trim().length < 2) return;
try {
const res = await apiFetch<{ data: { id: string; name: string; email: string }[] }>(`/api/users?search=${encodeURIComponent(query.trim())}&limit=8&isActive=true`, { authToken: token });
setFound(res.data);
} catch (e) {
onMessage({ type: "err", text: errorMessage(e) || "Search failed" });
}
};
const assign = (roleId: string, u: { id: string; name: string }) => run(
() => apiFetch(`/api/volunteers/manage/roles/${roleId}/assign`, { method: "POST", authToken: token, body: { userId: u.id } }),
`${u.name} is on the roster.`,
).then(ok => { if (ok) { setAssignFor(null); setQuery(""); setFound([]); } });
const roleForm = (
<div className="border rounded-xl p-4 bg-gray-50 space-y-2" data-testid="role-form">
<div className="grid sm:grid-cols-[2fr_1fr] gap-2">
<label className="text-xs text-gray-500">Role<input aria-label="Role name" className={inputCls} value={draft.name} onChange={e => setDraft({ ...draft, name: e.target.value })} placeholder="Welcome, Parking, Sound…" /></label>
<label className="text-xs text-gray-500">People needed<input aria-label="People needed" className={inputCls} inputMode="numeric" value={draft.needed} onChange={e => setDraft({ ...draft, needed: e.target.value })} /></label>
</div>
{roster?.event.scheduleType === "sessions" && (
<label className="text-xs text-gray-500 block">Session
<select aria-label="Session" className={inputCls} value={draft.sessionId} onChange={e => setDraft({ ...draft, sessionId: e.target.value })}>
<option value="">Choose…</option>
{roster.sessions.map(s => <option key={s.id} value={s.id}>{s.label} · {new Date(s.startsAt).toLocaleDateString()}</option>)}
</select>
</label>
)}
<div className="grid sm:grid-cols-2 gap-2">
<label className="text-xs text-gray-500">Shift starts (optional)<input aria-label="Shift starts" type="datetime-local" className={inputCls} value={draft.startsAt} onChange={e => setDraft({ ...draft, startsAt: e.target.value })} /></label>
<label className="text-xs text-gray-500">Shift ends (optional)<input aria-label="Shift ends" type="datetime-local" className={inputCls} value={draft.endsAt} onChange={e => setDraft({ ...draft, endsAt: e.target.value })} /></label>
</div>
<label className="text-xs text-gray-500 block">What it involves (optional)<input aria-label="Description" className={inputCls} value={draft.description} onChange={e => setDraft({ ...draft, description: e.target.value })} /></label>
{kidsRooms.length > 0 && (
<label className="text-xs text-gray-500 block">Kids room (volunteers count as leaders on duty there once they check in)
<select aria-label="Kids room" className={inputCls} value={draft.kidsRoomId} onChange={e => setDraft({ ...draft, kidsRoomId: e.target.value })}>
<option value="">Not a kids room</option>
{kidsRooms.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
</select>
</label>
)}
<p className="text-xs text-gray-500">Without shift times the role covers the {roster?.event.scheduleType === "sessions" ? "session" : "event"}&apos;s times. Nobody can be in two roles at the same time.</p>
<div className="flex gap-2">
<button disabled={busy || !draft.name.trim()} onClick={saveRole} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm disabled:opacity-50">{editing === "new" ? "Add role" : "Save role"}</button>
<button disabled={busy} onClick={() => { setEditing(null); setDraft(EMPTY); }} className="px-3 py-1.5 rounded-lg border text-sm">Cancel</button>
</div>
</div>
);
if (!roster) return <div className="text-sm text-gray-500">Loading the roster…</div>;
const groups = roster.event.scheduleType === "sessions"
? roster.sessions.map(s => ({ key: s.id, label: `${s.label} · ${new Date(s.startsAt).toLocaleDateString()}`, roles: roster.roles.filter(r => r.sessionId === s.id) })).filter(g => g.roles.length || canEdit)
: [{ key: "all", label: "", roles: roster.roles }];
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="text-sm text-gray-700" data-testid="roster-totals">
<strong>{roster.totals.filled}</strong> of {roster.totals.needed} places filled{roster.totals.fillRate != null ? ` (${roster.totals.fillRate}%)` : ""} · <strong>{roster.totals.checkedIn}</strong> checked in
</div>
<div className="flex gap-2 print:hidden">
{canEdit && editing === null && <button onClick={() => { setDraft(EMPTY); setEditing("new"); }} className="px-3 py-1.5 rounded-lg bg-brand-600 text-white text-sm inline-flex items-center gap-1"><Plus className="w-4 h-4" /> Add a role</button>}
<button onClick={() => window.print()} className="px-3 py-1.5 rounded-lg border text-sm inline-flex items-center gap-1"><Printer className="w-4 h-4" /> Print</button>
</div>
</div>
{editing === "new" && roleForm}
{roster.roles.length === 0 && editing === null && <p className="text-sm text-gray-500">No serving roles yet.{canEdit ? " Add the first one." : ""}</p>}
{groups.map(g => (
<div key={g.key} className="space-y-3">
{g.label && <h3 className="text-sm font-semibold text-gray-700">{g.label}</h3>}
{g.roles.map(r => editing === r.id ? <React.Fragment key={r.id}>{roleForm}</React.Fragment> : (
<section key={r.id} className="border rounded-xl p-4 bg-white shadow-sm break-inside-avoid" data-testid="roster-role">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<h4 className="font-semibold">{r.name} <span className={`ml-1 text-xs px-2 py-0.5 rounded-full ${r.filled >= r.needed ? "bg-green-100 text-green-800" : "bg-amber-100 text-amber-800"}`}>{r.filled}/{r.needed}</span></h4>
<div className="text-sm text-gray-600">{r.shift.text} · {r.shift.hours} h{r.kidsRoom ? ` · kids room ${r.kidsRoom.name}` : ""}</div>
{r.description && <div className="text-xs text-gray-500">{r.description}</div>}
</div>
{canEdit && (
<div className="flex gap-1 print:hidden">
<button aria-label={`Put someone on ${r.name}`} onClick={() => { setAssignFor(assignFor === r.id ? null : r.id); setFound([]); setQuery(""); }} className="p-1.5 rounded-lg border"><UserPlus className="w-4 h-4" /></button>
<button aria-label={`Edit ${r.name}`} onClick={() => { setDraft(toDraft(r)); setEditing(r.id); }} className="p-1.5 rounded-lg border"><Pencil className="w-4 h-4" /></button>
<button aria-label={`Delete ${r.name}`} disabled={busy} onClick={() => deleteRole(r)} className="p-1.5 rounded-lg border"><Trash2 className="w-4 h-4" /></button>
</div>
)}
</div>
{assignFor === r.id && (
<div className="mt-3 border rounded-lg p-3 bg-gray-50 space-y-2 print:hidden">
<div className="flex gap-2">
<input aria-label="Find a person" className={inputCls} value={query} onChange={e => setQuery(e.target.value)} onKeyDown={e => e.key === "Enter" && search()} placeholder="Name, email or phone" />
<button onClick={search} className="px-3 py-1.5 rounded-lg border text-sm">Find</button>
</div>
{found.map(u => (
<button key={u.id} disabled={busy} onClick={() => assign(r.id, u)} className="block w-full text-left text-sm px-2 py-1 rounded hover:bg-white">
{u.name} <span className="text-gray-500">{u.email}</span>
</button>
))}
</div>
)}
{(r.volunteers || []).length > 0 ? (
<ul className="mt-3 divide-y text-sm">
{r.volunteers!.map(vl => (
<li key={vl.slotId} className="py-1.5 flex flex-wrap items-center justify-between gap-2" data-testid="roster-volunteer">
<div>
<span className="font-medium">{vl.name}</span>
<span className="text-gray-500">{vl.phone ? ` · ${vl.phone}` : ""}{vl.email && !vl.phone ? ` · ${vl.email}` : ""}</span>
{vl.swapOpen && <span className="ml-2 text-xs px-2 py-0.5 rounded-full bg-amber-100 text-amber-800">looking for cover</span>}
{vl.assignedBy && <span className="ml-2 text-xs text-gray-400">added by {vl.assignedBy}</span>}
</div>
<div className="flex items-center gap-2">
{vl.checkedInAt
? <span className="inline-flex items-center gap-1 text-green-700 text-xs"><CheckCircle2 className="w-4 h-4" /> {time(vl.checkedInAt)} {vl.checkInMethod === "qr" ? "(QR)" : `(${vl.checkedInBy || "staff"})`}</span>
: <span className="text-xs text-gray-400 print:inline hidden">☐</span>}
<span className="print:hidden flex gap-1">
{vl.checkedInAt
? <button disabled={busy} onClick={() => run(() => apiFetch(`/api/volunteers/manage/slots/${vl.slotId}/check-in`, { method: "POST", authToken: token, body: { undo: true } }), "Check-in undone.")} className="text-xs px-2 py-1 rounded-lg border">Undo</button>
: <button disabled={busy} onClick={() => run(() => apiFetch(`/api/volunteers/manage/slots/${vl.slotId}/check-in`, { method: "POST", authToken: token }), `${vl.name} checked in.`)} className="text-xs px-2 py-1 rounded-lg border">Check in</button>}
{canEdit && !vl.checkedInAt && <button aria-label={`Take ${vl.name} off ${r.name}`} disabled={busy} onClick={() => confirm(`Take ${vl.name} off ${r.name}? They'll be told.`) && run(() => apiFetch(`/api/volunteers/manage/slots/${vl.slotId}`, { method: "DELETE", authToken: token }), `${vl.name} is off the roster.`)} className="text-xs p-1 rounded-lg border"><X className="w-3.5 h-3.5" /></button>}
</span>
</div>
</li>
))}
</ul>
) : <p className="mt-2 text-sm text-gray-500">Nobody yet.</p>}
</section>
))}
</div>
))}
</div>
);
}