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
+1 -1
View File
@@ -5,7 +5,7 @@ import path from "path";
export type Role = "admin" | "supervisor" | "staff" | "user";
export type Seed = {
users: Record<Role, { id: string; name: string; email: string; token: string }>;
events: { free: string; paid: string; course: string; dropIn: string; conference: string; kids: string };
events: { free: string; paid: string; course: string; dropIn: string; conference: string; kids: string; serving: string };
campuses: Record<"north" | "south", { id: string; slug: string }>;
northTicketQr: string;
course: { sessions: { id: string; label: string }[]; ticketId: string; qrCode: string };
+9 -1
View File
@@ -88,6 +88,14 @@ async function seed(url) {
price: 0, isHidden: true, createdById: users.supervisor.id,
},
});
// Volunteer rosters (volunteers.spec.ts): on today, hidden.
const serving = await prisma.event.create({
data: {
title: 'E2E Serving Sunday', description: 'Volunteer rosters for the tests.', startDate: new Date(Date.now() - 60 * 60 * 1000), endDate: new Date(Date.now() + 6 * 60 * 60 * 1000),
price: 0, isHidden: true, createdById: users.supervisor.id,
eventOptions: { create: [{ name: 'Entry', price: 0, isMainTicket: true }] },
},
});
const paid = await prisma.event.create({
data: {
campusId: south.id,
@@ -181,7 +189,7 @@ async function seed(url) {
const out = {
users: Object.fromEntries(Object.entries(users).map(([k, u]) => [k, { id: u.id, name: u.name, email: u.email, token: generateToken(u.id, u.role, u.tokenVersion || 0) }])),
events: { free: free.id, paid: paid.id, course: course.id, dropIn: dropIn.id, conference: conference.id, kids: kids.id },
events: { free: free.id, paid: paid.id, course: course.id, dropIn: dropIn.id, conference: conference.id, kids: kids.id, serving: serving.id },
campuses: { north: { id: north.id, slug: north.slug }, south: { id: south.id, slug: south.slug } },
northTicketQr: northTicket.qrCode,
course: { sessions: course.sessions.map(s => ({ id: s.id, label: s.label })), ticketId: ticket.id, qrCode: ticket.qrCode },
+65
View File
@@ -0,0 +1,65 @@
import { test, expect, seed, loginAs, API } from "./fixtures";
// Volunteer rosters (1.46.0): a supervisor adds a role and switches the free volunteer ticket on,
// a user signs up, can't make it and asks for cover, staff take the place over, then check in by
// scanning the event's QR code. "E2E Serving Sunday" is seeded hidden and on today.
test.describe.serial("volunteer rosters", () => {
test("a supervisor adds a role and switches the volunteer ticket on", async ({ page }) => {
await loginAs(page, "supervisor");
await page.goto(`/dashboard/supervisor/volunteers?event=${seed().events.serving}`);
await page.getByRole("button", { name: "Add a role" }).click();
await page.getByLabel("Role name").fill("Welcome team");
await page.getByLabel("People needed").fill("1");
await page.getByRole("button", { name: "Add role" }).click();
await expect(page.getByTestId("roster-role")).toContainText("Welcome team");
await expect(page.getByTestId("roster-totals")).toContainText("0 of 1");
await page.getByRole("tab", { name: "Volunteer ticket" }).click();
await page.getByRole("button", { name: /Add a free "Volunteer" ticket/ }).click();
await expect(page.getByLabel("Volunteer ticket")).not.toHaveValue("");
});
test("the volunteer ticket isn't offered publicly", async ({ request }) => {
const res = await request.get(`${API}/api/events/${seed().events.serving}`);
const ev = await res.json();
expect(ev.eventOptions.map((o: { name: string }) => o.name)).toEqual(["Entry"]);
});
test("a user signs up, then asks for cover", async ({ page }) => {
await loginAs(page, "user");
await page.goto(`/dashboard/user/serving?event=${seed().events.serving}`);
await page.getByTestId("open-role").filter({ hasText: "Welcome team" }).getByRole("button", { name: "Sign up" }).click();
await expect(page.getByRole("status")).toContainText("you're on the roster");
const shift = page.getByTestId("my-shift").filter({ hasText: "Welcome team" });
await expect(shift).toContainText("free volunteer ticket");
page.once("dialog", d => d.accept("Away that weekend"));
await shift.getByRole("button", { name: "Can't make it" }).click();
await expect(shift).toContainText("Cover requested");
});
test("staff take the place over, then check in with the QR code", async ({ page, request }) => {
await loginAs(page, "staff");
await page.goto("/dashboard/user/serving");
const cover = page.getByTestId("cover-request").filter({ hasText: "Welcome team" });
await expect(cover).toContainText("Away that weekend");
await cover.getByRole("button", { name: "Take over" }).click();
await expect(page.getByRole("status")).toContainText("taken over Welcome team");
await expect(page.getByTestId("my-shift").filter({ hasText: "Welcome team" })).toBeVisible();
// The QR code on the wall holds this; a phone camera opens the check-in page.
const qr = await request.get(`${API}/api/volunteers/manage/events/${seed().events.serving}/qr`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } });
const { qr: code } = await qr.json();
await page.goto(`/serve/check-in?code=${encodeURIComponent(code)}`);
await expect(page.getByTestId("volunteer-checked-in")).toContainText("Welcome team");
});
test("the roster shows who took over and checked in", async ({ page }) => {
await loginAs(page, "supervisor");
await page.goto(`/dashboard/supervisor/volunteers?event=${seed().events.serving}`);
const volunteer = page.getByTestId("roster-volunteer");
await expect(volunteer).toContainText(seed().users.staff.name);
await expect(volunteer).toContainText("(QR)");
await expect(page.getByTestId("roster-totals")).toContainText("1 checked in");
});
});
@@ -109,6 +109,11 @@ const ACTION_LABELS: Record<string, string> = {
kids_wrong_code: "Wrong pickup code entered",
kids_custody_notes_changed: "Child's custody notes changed",
kids_offline_sync: "Offline kids desk synced",
volunteer_settings_updated: "Volunteer ticket changed",
volunteer_roles_changed: "Serving role added, changed or deleted",
volunteer_assigned: "Volunteer put on a roster",
volunteer_removed: "Volunteer taken off a roster",
volunteer_checked_in_manual: "Volunteer checked in by hand",
};
interface AuditLogEntry {
@@ -9,7 +9,7 @@ import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, ClipboardList,
UserPlus, FileText, MessageCircle, BarChart2, Mail, Wallet, DoorOpen, History, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck, Inbox,
Baby,
Baby, HandHeart,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -33,6 +33,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/allocations", label: "Rooms & groups", description: "Put attendees into rooms, groups or buses", icon: BedDouble },
{ href: "/dashboard/staff/kids", label: "Kids check-in", description: "Check children in and out with pickup codes", icon: Baby },
{ href: "/dashboard/supervisor/kids", label: "Kids check-in setup", description: "Switch it on for an event and set up the rooms", icon: Baby },
{ href: "/dashboard/supervisor/volunteers", label: "Volunteer rosters", description: "Serving roles, who serves where, check-ins and hours", icon: HandHeart },
{ href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session, and certificates", icon: ClipboardCheck },
{ href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks },
@@ -6,7 +6,7 @@ import { useRouter } from "next/navigation";
import { apiFetch } from "@/lib/api";
import { useStableState } from "@/hooks/useStableState";
import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import { QrCode, Ticket, Activity, UserCheck, Clock, Users, ClipboardCheck, Baby } from "lucide-react";
import { QrCode, Ticket, Activity, UserCheck, Clock, Users, ClipboardCheck, Baby, HandHeart } from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import type { DashboardStats, RecentScan, ScanStats } from "@/types";
@@ -17,6 +17,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/staff/event-tickets", label: "Event tickets & printing", description: "Browse event tickets and print lists", icon: Ticket },
{ href: "/dashboard/staff/my-groups", label: "My groups", description: "Rooms and groups you lead", icon: Users },
{ href: "/dashboard/staff/kids", label: "Kids check-in", description: "Check children in and out with pickup codes", icon: Baby },
{ href: "/dashboard/staff/volunteers", label: "Volunteers", description: "Who is serving today, check-ins and the check-in QR code", icon: HandHeart },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session of an event", icon: ClipboardCheck },
] as const;
@@ -0,0 +1,71 @@
"use client";
import React, { useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { formatDate } from "@/lib/date";
import { useDismissingState } from "@/hooks/useDismissingState";
import { BackLink } from "@/components/shared/BackLink";
import { RosterSheet } from "@/components/volunteers/RosterSheet";
import { CheckInQr } from "@/components/volunteers/CheckInQr";
import { HandHeart } from "lucide-react";
import type { RosterEvent } from "@/lib/volunteers";
/** Staff → Volunteers: the roster on the day — who's here, ticking people in, and the check-in QR code. */
export default function StaffVolunteersPage() {
const { token } = useAuth();
const [events, setEvents] = useState<RosterEvent[] | null>(null);
const [eventId, setEventId] = useState("");
const [showQr, setShowQr] = useState(false);
const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
useEffect(() => {
if (!token) return;
apiFetch<RosterEvent[]>("/api/volunteers/manage/events", { authToken: token })
.then(list => {
setEvents(list);
const now = Date.now();
const current = list.find(e => new Date(e.endDate).getTime() >= now);
if (current) setEventId(current.id);
})
.catch(e => setMsg({ type: "err", text: errorMessage(e) || "Could not load events" }));
}, [token, setMsg]);
const event = events?.find(e => e.id === eventId);
return (
<div className="max-w-4xl mx-auto w-full p-6">
<div className="flex items-center gap-3 mb-4 print:hidden">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><HandHeart className="w-5 h-5 text-brand-600" /></div>
<div>
<BackLink href="/dashboard" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Volunteers</h1>
<p className="text-sm text-gray-500">Who&apos;s serving today, and checking them in</p>
</div>
</div>
{events && !events.length && <div className="p-3 border rounded bg-amber-50 text-amber-800 text-sm">No events have volunteer rosters yet. A supervisor adds serving roles under Supervisor → Volunteer rosters.</div>}
{events && events.length > 0 && (
<div className="flex flex-wrap gap-2 items-end print:hidden">
<label className="text-sm">
<span className="block text-xs text-gray-500 mb-1">Event</span>
<select className="border rounded-lg px-3 py-2 text-sm min-w-[14rem]" value={eventId} onChange={e => setEventId(e.target.value)}>
{!eventId && <option value="">Choose an event…</option>}
{events.map(e => <option key={e.id} value={e.id}>{e.title} · {formatDate(new Date(e.startDate))}</option>)}
</select>
</label>
{eventId && <button onClick={() => setShowQr(q => !q)} className="px-3 py-2 rounded-lg border text-sm">{showQr ? "Show the roster" : "Show the check-in QR code"}</button>}
</div>
)}
{msg && <div role="status" className={`mt-3 p-3 rounded-lg text-sm print:hidden ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
<div className="mt-4">
{eventId && (showQr
? <CheckInQr token={token} eventId={eventId} title={event?.title || ""} />
: <RosterSheet token={token} eventId={eventId} canEdit={false} onMessage={setMsg} />)}
</div>
</div>
);
}
@@ -9,7 +9,7 @@ import { useVisiblePolling } from "@/hooks/useVisiblePolling";
import {
Calendar, Banknote, Gift, Users, Ticket, QrCode, DoorOpen, Wallet,
UserPlus, FileText, MessageCircle, BarChart2, Mail, TicketPercent, ShieldCheck, ListChecks, WifiOff, BedDouble, Filter, ClipboardCheck,
Baby,
Baby, HandHeart,
} from "lucide-react";
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
@@ -30,6 +30,7 @@ const QUICK_ACTIONS = [
{ href: "/dashboard/supervisor/allocations", label: "Rooms & groups", description: "Put attendees into rooms, groups or buses", icon: BedDouble },
{ href: "/dashboard/staff/kids", label: "Kids check-in", description: "Check children in and out with pickup codes", icon: Baby },
{ href: "/dashboard/supervisor/kids", label: "Kids check-in setup", description: "Switch it on for an event and set up the rooms", icon: Baby },
{ href: "/dashboard/supervisor/volunteers", label: "Volunteer rosters", description: "Serving roles, who serves where, check-ins and hours", icon: HandHeart },
{ href: "/dashboard/supervisor/offline-scans", label: "Offline scanning", description: "Devices scanning offline and their synced scans", icon: WifiOff },
{ href: "/dashboard/supervisor/attendance", label: "Attendance", description: "Who came to each session, and certificates", icon: ClipboardCheck },
{ href: "/dashboard/supervisor/waitlist", label: "Waitlist", description: "People waiting for sold-out tickets", icon: ListChecks },
@@ -0,0 +1,154 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { formatDate } from "@/lib/date";
import { useDismissingState } from "@/hooks/useDismissingState";
import { BackLink } from "@/components/shared/BackLink";
import { RosterSheet } from "@/components/volunteers/RosterSheet";
import { CheckInQr } from "@/components/volunteers/CheckInQr";
import { HandHeart } from "lucide-react";
import { hoursText, type HoursRow, type RosterEvent } from "@/lib/volunteers";
type Settings = {
event: { id: string; title: string; volunteerOptionId: string | null };
options: { id: string; name: string; price: number }[];
kidsRooms: { id: string; name: string }[];
};
type Tab = "roster" | "qr" | "ticket" | "hours";
const TABS: { id: Tab; label: string }[] = [
{ id: "roster", label: "Roster" },
{ id: "qr", label: "Check-in QR" },
{ id: "ticket", label: "Volunteer ticket" },
{ id: "hours", label: "Hours served" },
];
/** Supervisor → Volunteer rosters: serving roles per event or session, people, check-in QR, volunteer ticket, hours. */
export default function VolunteerRostersPage() {
const { token } = useAuth();
const [events, setEvents] = useState<RosterEvent[]>([]);
const [eventId, setEventId] = useState("");
const [tab, setTab] = useState<Tab>("roster");
const [settings, setSettings] = useState<Settings | null>(null);
const [hours, setHours] = useState<HoursRow[] | null>(null);
const [hoursAll, setHoursAll] = useState(true);
const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (!token) return;
apiFetch<RosterEvent[]>("/api/volunteers/manage/events?all=1", { authToken: token })
.then(list => {
setEvents(list);
const wanted = new URLSearchParams(window.location.search).get("event");
if (wanted && list.some(e => e.id === wanted)) setEventId(wanted);
})
.catch(e => setMsg({ type: "err", text: errorMessage(e) || "Could not load events" }));
}, [token, setMsg]);
const loadSettings = useCallback(async () => {
if (!token || !eventId) { setSettings(null); return; }
try {
setSettings(await apiFetch<Settings>(`/api/volunteers/manage/events/${eventId}/settings`, { authToken: token }));
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" });
}
}, [token, eventId, setMsg]);
useEffect(() => { loadSettings(); }, [loadSettings]);
useEffect(() => {
if (!token || tab !== "hours") return;
setHours(null);
apiFetch<HoursRow[]>(`/api/volunteers/manage/hours${!hoursAll && eventId ? `?eventId=${eventId}` : ""}`, { authToken: token })
.then(setHours)
.catch(e => setMsg({ type: "err", text: errorMessage(e) || "Could not load hours" }));
}, [token, tab, hoursAll, eventId, setMsg]);
const saveTicket = async (optionId: string | null, ok: string) => {
setBusy(true);
try {
setSettings(await apiFetch<Settings>(`/api/volunteers/manage/events/${eventId}/settings`, { method: "PUT", authToken: token, body: { optionId } }));
setMsg({ type: "ok", text: ok });
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not save" });
} finally {
setBusy(false);
}
};
const event = events.find(e => e.id === eventId);
return (
<div className="max-w-4xl mx-auto w-full p-6">
<div className="flex items-center gap-3 mb-4 print:hidden">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><HandHeart className="w-5 h-5 text-brand-600" /></div>
<div>
<BackLink href="/dashboard" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Volunteer rosters</h1>
<p className="text-sm text-gray-500">Who serves where, for an event or each session</p>
</div>
</div>
<label className="text-sm block max-w-md print:hidden">
<span className="block text-xs text-gray-500 mb-1">Event</span>
<select className="w-full border rounded-lg px-3 py-2 text-sm" value={eventId} onChange={e => setEventId(e.target.value)}>
<option value="">Choose an event…</option>
{events.map(e => <option key={e.id} value={e.id}>{e.title} · {formatDate(new Date(e.startDate))}{e.roles ? ` · ${e.roles} role${e.roles === 1 ? "" : "s"}` : ""}</option>)}
</select>
</label>
{msg && <div role="status" className={`mt-3 p-3 rounded-lg text-sm print:hidden ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
<div className="flex flex-wrap gap-1 mt-4 border-b print:hidden" role="tablist">
{TABS.map(t => (
<button key={t.id} role="tab" aria-selected={tab === t.id} onClick={() => setTab(t.id)} className={`px-3 py-2 text-sm -mb-px border-b-2 ${tab === t.id ? "border-brand-600 text-brand-700 font-medium" : "border-transparent text-gray-500"}`}>{t.label}</button>
))}
</div>
<div className="mt-4">
{tab !== "hours" && !eventId && <p className="text-sm text-gray-500">Choose an event.</p>}
{tab === "roster" && eventId && (
<p className="text-xs text-gray-500 mb-3 print:hidden">
Sign-up link to share: <span className="font-mono select-all break-all" data-testid="signup-link">{`${typeof window !== "undefined" ? window.location.origin : ""}/dashboard/user/serving?event=${eventId}`}</span>
</p>
)}
{tab === "roster" && eventId && <RosterSheet token={token} eventId={eventId} canEdit kidsRooms={settings?.kidsRooms || []} onMessage={setMsg} />}
{tab === "qr" && eventId && <CheckInQr token={token} eventId={eventId} title={event?.title || ""} />}
{tab === "ticket" && eventId && settings && (
<section className="border rounded-xl p-4 bg-white shadow-sm space-y-3">
<h2 className="font-semibold">Free volunteer ticket</h2>
<p className="text-sm text-gray-600">Off unless you choose a ticket. When it&apos;s on, everyone on this event&apos;s roster gets a free place on it (shown in their My Events), unless they already have a ticket. It&apos;s never offered to the public, and it&apos;s given back when they leave the roster.</p>
<div className="flex flex-wrap gap-2 items-center">
<select aria-label="Volunteer ticket" className="border rounded-lg px-3 py-2 text-sm" value={settings.event.volunteerOptionId || ""} disabled={busy}
onChange={e => saveTicket(e.target.value || null, e.target.value ? "Volunteers get a free place on this ticket." : "No free volunteer ticket.")}>
<option value="">Off — no free ticket</option>
{settings.options.map(o => <option key={o.id} value={o.id}>{o.name}{o.price ? ` (R${o.price})` : " (free)"}</option>)}
</select>
{!settings.event.volunteerOptionId && <button disabled={busy} onClick={() => saveTicket("new", "Added a free \"Volunteer\" ticket — volunteers get a place on it.")} className="px-3 py-2 rounded-lg border text-sm">Add a free &quot;Volunteer&quot; ticket</button>}
</div>
<p className="text-xs text-gray-500">Places already given stay when you switch it off.</p>
</section>
)}
{tab === "hours" && (
<section className="space-y-3">
<div className="flex gap-4 text-sm">
<label className="inline-flex items-center gap-1"><input type="radio" checked={hoursAll} onChange={() => setHoursAll(true)} /> All events</label>
<label className="inline-flex items-center gap-1"><input type="radio" checked={!hoursAll} disabled={!eventId} onChange={() => setHoursAll(false)} /> This event only</label>
</div>
<p className="text-xs text-gray-500">Shifts people checked in for, counted at the shift&apos;s length.</p>
{!hours && <div className="text-sm text-gray-500">Loading…</div>}
{hours && hours.length === 0 && <p className="text-sm text-gray-500">No checked-in shifts yet.</p>}
{hours && hours.length > 0 && (
<table className="w-full text-sm border rounded-xl overflow-hidden bg-white">
<thead className="bg-gray-50 text-left text-xs text-gray-500"><tr><th className="p-2">Volunteer</th><th className="p-2">Shifts</th><th className="p-2">Events</th><th className="p-2">Hours</th></tr></thead>
<tbody>{hours.map(h => <tr key={h.userId} className="border-t"><td className="p-2">{h.name}</td><td className="p-2">{h.shifts}</td><td className="p-2">{h.events}</td><td className="p-2 font-medium">{hoursText(h.hours)}</td></tr>)}</tbody>
</table>
)}
</section>
)}
</div>
</div>
);
}
@@ -0,0 +1,186 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { formatDate } from "@/lib/date";
import { useDismissingState } from "@/hooks/useDismissingState";
import { BackLink } from "@/components/shared/BackLink";
import { CheckCircle2, HandHeart, QrCode, Repeat } from "lucide-react";
import type { CoverRequest, MySlot, Roster, ServingEvent } from "@/lib/volunteers";
type Mine = { slots: MySlot[]; cover: CoverRequest[]; events: ServingEvent[] };
type Msg = { type: "ok" | "err"; text: string } | null;
const btn = "px-3 py-1.5 rounded-lg text-sm border disabled:opacity-50";
/** My account → Serving: my shifts, cover requests I could take, and events looking for volunteers. */
export default function ServingPage() {
const { token } = useAuth();
const [data, setData] = useState<Mine | null>(null);
const [msg, setMsg] = useDismissingState<Msg>(null);
const [busy, setBusy] = useState(false);
const [openEvent, setOpenEvent] = useState<string>("");
const [roster, setRoster] = useState<Roster | null>(null);
const load = useCallback(async () => {
if (!token) return;
try {
setData(await apiFetch<Mine>("/api/volunteers/me", { authToken: token }));
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load your shifts" });
}
}, [token, setMsg]);
useEffect(() => { load(); }, [load]);
// ?event=<id>: the sign-up link a supervisor shares (works for hidden events too).
useEffect(() => {
const wanted = new URLSearchParams(window.location.search).get("event");
if (wanted) setOpenEvent(wanted);
}, []);
const loadRoster = useCallback(async (id: string) => {
if (!token || !id) { setRoster(null); return; }
try {
setRoster(await apiFetch<Roster>(`/api/volunteers/events/${id}`, { authToken: token }));
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Could not load the roles" });
}
}, [token, setMsg]);
useEffect(() => { loadRoster(openEvent); }, [openEvent, loadRoster]);
const call = async (fn: () => Promise<unknown>, ok: string) => {
setBusy(true);
try {
await fn();
setMsg({ type: "ok", text: ok });
await Promise.all([load(), openEvent ? loadRoster(openEvent) : null]);
} catch (e) {
setMsg({ type: "err", text: errorMessage(e) || "Something went wrong" });
} finally {
setBusy(false);
}
};
const askCover = (s: MySlot) => {
const note = prompt(`Ask the other volunteers to take over ${s.role.name}? The first to accept takes your place. Add a note (optional):`, "");
if (note === null) return;
call(() => apiFetch(`/api/volunteers/slots/${s.slotId}/swap`, { method: "POST", authToken: token, body: { note } }), "Cover requested — you stay on the roster until someone takes over.");
};
const withdraw = (s: MySlot) => confirm(`Withdraw from ${s.role.name} at ${s.event.title}? The organisers will be told.`)
&& call(() => apiFetch(`/api/volunteers/slots/${s.slotId}`, { method: "DELETE", authToken: token }), "You're off the roster for this shift.");
const upcoming = (data?.slots || []).filter(s => !s.past);
const past = (data?.slots || []).filter(s => s.past);
return (
<div className="max-w-3xl mx-auto w-full p-6 space-y-6">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><HandHeart className="w-5 h-5 text-brand-600" /></div>
<div>
<BackLink href="/dashboard/user" />
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Serving</h1>
<p className="text-sm text-gray-500">Your volunteer shifts, and events looking for people to serve</p>
</div>
</div>
{msg && <div role="status" className={`p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
{!data && <div className="text-sm text-gray-500">Loading…</div>}
{data && (
<section className="space-y-3">
<h2 className="font-semibold">My shifts</h2>
{upcoming.length === 0 && <p className="text-sm text-gray-500">You&apos;re not on any roster yet. Sign up for a role below.</p>}
{upcoming.map(s => (
<div key={s.slotId} className="border rounded-xl p-4 bg-white shadow-sm" data-testid="my-shift">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<div className="font-semibold">{s.role.name} <span className="font-normal text-gray-500">· {s.event.title}</span></div>
<div className="text-sm text-gray-600">{s.role.sessionLabel ? `${s.role.sessionLabel} · ` : ""}{s.shift.text}{s.event.location ? ` · ${s.event.location}` : ""}</div>
{s.role.kidsRoom && <div className="text-xs text-gray-500">Kids room: {s.role.kidsRoom}</div>}
{s.role.description && <div className="text-xs text-gray-500 mt-1">{s.role.description}</div>}
{s.hasTicket && <div className="text-xs text-gray-500 mt-1">Your free volunteer ticket is in My Events.</div>}
</div>
{s.checkedInAt
? <span className="inline-flex items-center gap-1 text-sm text-green-700"><CheckCircle2 className="w-4 h-4" /> Checked in</span>
: s.swapId && <span className="text-xs px-2 py-0.5 rounded-full bg-amber-100 text-amber-800">Cover requested</span>}
</div>
{s.canCheckIn && <p className="mt-2 text-sm text-brand-700 flex items-center gap-1"><QrCode className="w-4 h-4" /> When you arrive, scan the volunteer check-in QR code with your phone&apos;s camera.</p>}
{!s.checkedInAt && (
<div className="mt-3 flex flex-wrap gap-2">
{s.swapId
? <button disabled={busy} onClick={() => call(() => apiFetch(`/api/volunteers/swaps/${s.swapId}`, { method: "DELETE", authToken: token }), "Cover request cancelled.")} className={btn}>I can make it after all</button>
: <button disabled={busy} onClick={() => askCover(s)} className={`${btn} inline-flex items-center gap-1`}><Repeat className="w-4 h-4" /> Can&apos;t make it</button>}
<button disabled={busy} onClick={() => withdraw(s)} className={`${btn} text-gray-600`}>Withdraw</button>
</div>
)}
</div>
))}
{past.length > 0 && (
<details className="text-sm">
<summary className="cursor-pointer text-gray-500">Last week ({past.length})</summary>
<ul className="mt-1 space-y-0.5 text-gray-600">
{past.map(s => <li key={s.slotId}>{s.role.name} · {s.event.title} · {s.shift.text}{s.checkedInAt ? " · served" : ""}</li>)}
</ul>
</details>
)}
</section>
)}
{data && data.cover.length > 0 && (
<section className="space-y-3">
<h2 className="font-semibold">Can you take over?</h2>
{data.cover.map(c => (
<div key={c.swapId} className="border border-amber-300 rounded-xl p-4 bg-amber-50 flex flex-wrap items-center justify-between gap-3" data-testid="cover-request">
<div>
<div className="font-semibold">{c.role.name} <span className="font-normal text-gray-600">· {c.event.title}</span></div>
<div className="text-sm text-gray-700">{c.role.sessionLabel ? `${c.role.sessionLabel} · ` : ""}{c.shift.text}</div>
<div className="text-xs text-gray-600">{c.from || "A volunteer"} can&apos;t make it{c.note ? `: “${c.note}”` : ""}</div>
</div>
<button disabled={busy} onClick={() => call(() => apiFetch(`/api/volunteers/swaps/${c.swapId}/accept`, { method: "POST", authToken: token }), `You've taken over ${c.role.name} — thank you!`)} className="px-3 py-1.5 rounded-lg text-sm bg-brand-600 text-white disabled:opacity-50">Take over</button>
</div>
))}
</section>
)}
{data && (
<section className="space-y-3">
<h2 className="font-semibold">Serve at an event</h2>
{data.events.length === 0 && !openEvent && <p className="text-sm text-gray-500">No events are looking for volunteers right now.</p>}
{(data.events.length > 0 || openEvent) && (
<label className="text-sm block max-w-md">
<span className="block text-xs text-gray-500 mb-1">Event</span>
<select className="w-full border rounded-lg px-3 py-2 text-sm" value={openEvent} onChange={e => setOpenEvent(e.target.value)}>
<option value="">Choose an event…</option>
{roster && !data.events.some(e => e.id === roster.event.id) && <option value={roster.event.id}>{roster.event.title} · {formatDate(new Date(roster.event.startDate))}</option>}
{data.events.map(e => <option key={e.id} value={e.id}>{e.title} · {formatDate(new Date(e.startDate))} ({e.roles} role{e.roles === 1 ? "" : "s"})</option>)}
</select>
</label>
)}
{roster && roster.event.id === openEvent && (
<div className="space-y-2">
{roster.roles.filter(r => !r.past).map(r => (
<div key={r.id} className="border rounded-xl p-3 bg-white flex flex-wrap items-center justify-between gap-3" data-testid="open-role">
<div>
<div className="font-medium">{r.name}{r.kidsRoom ? <span className="text-xs text-gray-500"> · kids room {r.kidsRoom.name}</span> : null}</div>
<div className="text-sm text-gray-600">{r.sessionLabel ? `${r.sessionLabel} · ` : ""}{r.shift.text}</div>
{r.description && <div className="text-xs text-gray-500">{r.description}</div>}
<div className="text-xs text-gray-500">{r.filled} of {r.needed} signed up</div>
</div>
{r.mine
? <span className="inline-flex items-center gap-1 text-sm text-green-700"><CheckCircle2 className="w-4 h-4" /> You&apos;re serving</span>
: r.coverNeeded.length > 0
? <button disabled={busy} onClick={() => call(() => apiFetch(`/api/volunteers/swaps/${r.coverNeeded[0].swapId}/accept`, { method: "POST", authToken: token }), `You've taken over ${r.name} — thank you!`)} className="px-3 py-1.5 rounded-lg text-sm bg-brand-600 text-white disabled:opacity-50">Take over a place</button>
: r.full
? <span className="text-sm text-gray-500">Full</span>
: <button disabled={busy} onClick={() => call(() => apiFetch(`/api/volunteers/roles/${r.id}/sign-up`, { method: "POST", authToken: token }), `Thank you — you're on the roster for ${r.name}.`)} className="px-3 py-1.5 rounded-lg text-sm bg-brand-600 text-white disabled:opacity-50">Sign up</button>}
</div>
))}
{roster.roles.every(r => r.past) && <p className="text-sm text-gray-500">All shifts at this event are over.</p>}
</div>
)}
</section>
)}
</div>
);
}
@@ -0,0 +1,74 @@
"use client";
import React, { Suspense, useEffect, useRef, useState } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { errorMessage } from "@/lib/utils";
import { CheckCircle2, HandHeart } from "lucide-react";
type Result = { event: { id: string; title: string }; checkedIn: { role: string; kidsRoom: string | null }[]; already: string[] };
/** Where the volunteer check-in QR code leads: checks the signed-in volunteer in for today's shifts. */
function CheckIn() {
const code = useSearchParams().get("code") || "";
const { user, token, loading } = useAuth();
const [result, setResult] = useState<Result | null>(null);
const [error, setError] = useState<string | null>(code ? null : "This check-in link is incomplete — scan the QR code again.");
const sent = useRef(false);
useEffect(() => {
if (!code || loading || !token || sent.current) return;
sent.current = true;
apiFetch<Result>("/api/volunteers/check-in", { method: "POST", authToken: token, body: { qr: code } })
.then(setResult)
.catch(e => setError(errorMessage(e) || "Couldn't check you in."));
}, [code, loading, token]);
if (error) return <div className="border rounded-xl p-4 bg-red-50 text-red-800 text-sm" role="alert">{error} <Link href="/dashboard/user/serving" className="underline">My shifts</Link></div>;
if (loading) return <div className="text-sm text-gray-600">Loading…</div>;
if (!user) {
const back = `/serve/check-in?code=${encodeURIComponent(code)}`;
return (
<div className="border rounded-xl p-5 bg-white shadow-sm space-y-3">
<p className="text-sm text-gray-700">Log in to check in for your volunteer shift.</p>
<Link href={`/login?redirect=${encodeURIComponent(back)}`} className="inline-block px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium">Log in</Link>
</div>
);
}
if (!result) return <div className="text-sm text-gray-600">Checking you in…</div>;
return (
<div className="border rounded-xl p-5 bg-white shadow-sm space-y-3" data-testid="volunteer-checked-in">
<div className="flex items-center gap-2 text-green-700 font-semibold"><CheckCircle2 className="w-6 h-6" /> Thank you for serving, {user.name?.split(" ")[0]}!</div>
<p className="text-sm text-gray-700">You&apos;re checked in at <strong>{result.event.title}</strong>:</p>
<ul className="text-sm text-gray-800 list-disc pl-5">
{result.checkedIn.map(c => <li key={c.role}>{c.role}{c.kidsRoom ? ` — you're on duty in ${c.kidsRoom}` : ""}</li>)}
{result.already.map(r => <li key={r}>{r} (already checked in)</li>)}
</ul>
<Link href="/dashboard/user/serving" className="text-sm text-brand-600 hover:underline">My shifts</Link>
</div>
);
}
export default function VolunteerCheckInPage() {
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-1 px-4 py-10 max-w-xl mx-auto w-full">
<div className="flex items-center gap-3 mb-4">
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
<HandHeart className="w-5 h-5 text-brand-600" />
</div>
<h1 className="text-2xl font-semibold text-gray-900">Volunteer check-in</h1>
</div>
<Suspense fallback={<div className="text-sm text-gray-600">Loading…</div>}>
<CheckIn />
</Suspense>
</main>
<Footer />
</div>
);
}
@@ -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>
);
}
@@ -35,6 +35,7 @@ import { staffEventTicketsHelpContent } from "./staff-event-tickets";
import { staffTicketScanningHelpContent } from "./staff-ticket-scanning";
import { userFormsHelpContent } from "./user-forms";
import { kidsDeskHelpContent, kidsRoomsHelpContent, kidsSetupHelpContent, userKidsHelpContent } from "./kids";
import { staffVolunteersHelpContent, userServingHelpContent, volunteerRostersHelpContent } from "./volunteers";
type HelpRegistryEntry = {
/** Unique, stable identifier for this guide. */
@@ -181,6 +182,21 @@ const REGISTRY: HelpRegistryEntry[] = [
matches: pathname => pathname === "/dashboard/user/kids",
content: userKidsHelpContent,
},
{
slug: "supervisor-volunteers",
matches: pathname => pathname === "/dashboard/supervisor/volunteers",
content: volunteerRostersHelpContent,
},
{
slug: "staff-volunteers",
matches: pathname => pathname === "/dashboard/staff/volunteers",
content: staffVolunteersHelpContent,
},
{
slug: "user-serving",
matches: pathname => pathname === "/dashboard/user/serving",
content: userServingHelpContent,
},
{
slug: "staff-my-groups",
matches: pathname => pathname === "/dashboard/staff/my-groups",
@@ -0,0 +1,113 @@
import React from "react";
import { Baby, BarChart2, CheckCircle2, ClipboardList, HandHeart, QrCode, Repeat, Ticket, UserPlus } from "lucide-react";
import { GuideItem } from "@/components/shared/GuideItem";
import type { HelpContent } from "./types";
/** Help content for /dashboard/supervisor/volunteers (setting up rosters). */
export const volunteerRostersHelpContent: HelpContent = {
title: "Volunteer rosters",
subtitle: "Plan who serves where, for an event or each session.",
tabs: [
{
key: "roles",
label: "Roles",
icon: ClipboardList,
content: (
<div className="space-y-4">
<p>Pick the event and tap &quot;Add a role&quot;: Welcome, Parking, Kids, Sound, Kitchen… with the number of people needed. On an event with sessions, each role is for one session — add the roles to every session that needs them. Rosters never repeat by themselves.</p>
<GuideItem icon={HandHeart} title="Shift times" tone="brand">
Leave the times empty and the role covers the session&apos;s (or event&apos;s) times. Give times for shifts like setting up before the service. Nobody can be in two roles at the same time, so give times when one person does two jobs one after the other.
</GuideItem>
<GuideItem icon={Baby} title="Kids rooms" tone="amber">
When kids check-in is set up for the event, link a role to a kids room. Its volunteers count as leaders on duty in that room once they check in, for the room&apos;s ratio. The room screen also lists who is rostered but not in yet.
</GuideItem>
</div>
),
},
{
key: "people",
label: "People",
icon: UserPlus,
content: (
<div className="space-y-4">
<p>Anyone with an account can sign up for a role that isn&apos;t full, under My account → Serving. You can also put someone on a role with the person button — even when it&apos;s full. They&apos;re told either way, and get a reminder the day before their shift.</p>
<GuideItem icon={Repeat} title="Swaps" tone="gray">
A volunteer who can&apos;t make it asks for cover. The event&apos;s other volunteers are told, and the first to accept takes the place straight away — nobody needs to approve it. The event&apos;s notification recipients get an email about every swap, and when someone withdraws.
</GuideItem>
<p>Delete a role or take someone off with the bin or ✕ — the volunteers are told. Once someone has checked in, they stay on (it counts for hours served).</p>
</div>
),
},
{
key: "day",
label: "On the day",
icon: QrCode,
content: (
<div className="space-y-4">
<p>Show or print the &quot;Check-in QR&quot; and put it up where volunteers arrive. They scan it with their phone&apos;s camera, log in, and are checked in for their shifts that day. Staff can also tick people in on the roster (Staff → Volunteers), and undo it.</p>
<GuideItem icon={CheckCircle2} title="The roster sheet" tone="green">
Each role shows who is serving, their phone number, and when they checked in (QR or by whom). &quot;Print&quot; gives a paper sheet with tick boxes.
</GuideItem>
</div>
),
},
{
key: "ticket",
label: "Ticket and hours",
icon: Ticket,
content: (
<div className="space-y-4">
<GuideItem icon={Ticket} title="Free volunteer ticket" tone="brand">
Off by default. Choose a ticket of the event (or add a free &quot;Volunteer&quot; ticket) and everyone on the roster gets a free place on it, unless they already have a ticket. It&apos;s never offered to the public and is given back when they leave the roster.
</GuideItem>
<GuideItem icon={BarChart2} title="Hours served" tone="gray">
Hours per person over all events (or one), counting the shifts they checked in for at the shift&apos;s length.
</GuideItem>
</div>
),
},
],
};
/** Help content for /dashboard/staff/volunteers (the roster on the day). */
export const staffVolunteersHelpContent: HelpContent = {
title: "Volunteers",
subtitle: "Who is serving today, and checking them in.",
tabs: [
{
key: "day",
label: "On the day",
icon: CheckCircle2,
content: (
<div className="space-y-4">
<p>Pick the event. The roster shows every role, who is on it, and who has checked in. Volunteers check themselves in by scanning the check-in QR code — tap &quot;Show the check-in QR code&quot; to put it on a screen. Someone without a phone? Tap &quot;Check in&quot; next to their name.</p>
<p>Volunteers in a role linked to a kids room count as leaders on duty in that room once they&apos;re checked in. Undoing a check-in takes them off duty.</p>
</div>
),
},
],
};
/** Help content for /dashboard/user/serving. */
export const userServingHelpContent: HelpContent = {
title: "Serving",
subtitle: "Your volunteer shifts.",
tabs: [
{
key: "shifts",
label: "Your shifts",
icon: HandHeart,
content: (
<div className="space-y-4">
<p>Choose an event under &quot;Serve at an event&quot; and sign up for a role that has space. You&apos;ll get a reminder the day before. When you arrive, scan the volunteer check-in QR code with your phone&apos;s camera.</p>
<GuideItem icon={Repeat} title="Can't make it?" tone="amber">
Tap &quot;Can&apos;t make it&quot;. The other volunteers at the event are asked to take over, and you stay on the roster until someone does — then you&apos;re told. If you can make it after all, cancel the request. You can also withdraw; the organisers are told.
</GuideItem>
<GuideItem icon={Ticket} title="Volunteer ticket" tone="gray">
Some events give volunteers a free ticket. It shows in My Events.
</GuideItem>
</div>
),
},
],
};
+4 -1
View File
@@ -11,7 +11,10 @@ export type KidsFamily = { id: string; name: string; parents: KidsParent[]; chil
export type KidsRoom = {
id: string; name: string; minAge: number | null; maxAge: number | null; capacity: number | null; ratio: number | null; order: number;
leaderNames: string[]; leaderIds: string[]; children: number; leaders: number; leadersNeeded: number; full: boolean; overRatio: boolean;
leaderNames: string[]; leaderIds: string[];
/** Volunteers rostered for the room (1.46.0); they count as leaders once checked in. */
rostered: { userId: string; name: string; checkedIn: boolean }[];
children: number; leaders: number; leadersNeeded: number; full: boolean; overRatio: boolean;
};
export type KidsCheckIn = {
id: string; childId: string | null; name: string; firstName: string; age: number | null; roomId: string | null; code: string;
@@ -0,0 +1,69 @@
/** Volunteer rosters (1.46.0): shared types and helpers for the Serving, roster and check-in pages. */
export type Shift = { startsAt: string; endsAt: string; text: string; hours?: number };
export type RosterVolunteer = {
slotId: string; userId: string; name: string; phone: string | null; email: string | null;
assignedBy: string | null; checkedInAt: string | null; checkedInBy: string | null; checkInMethod: "qr" | "manual" | null;
swapOpen: boolean; hasTicket: boolean;
};
export type ServingRole = {
id: string; eventId: string; sessionId: string | null; sessionLabel: string | null;
name: string; description: string; startsAt: string | null; endsAt: string | null;
shift: Shift & { hours: number }; kidsRoom: { id: string; name: string } | null; order: number; past: boolean;
needed: number; filled: number; open: number; full: boolean;
mine: { slotId: string; checkedInAt: string | null; swapId: string | null } | null;
coverNeeded: { swapId: string; note: string }[];
/** Staff only. */
volunteers?: RosterVolunteer[];
};
export type Roster = {
event: { id: string; title: string; startDate: string; endDate: string; scheduleType: string; location: string | null; kidsCheckIn: boolean };
sessions: { id: string; label: string; startsAt: string; endsAt: string }[];
roles: ServingRole[];
totals: { needed: number; filled: number; checkedIn: number; fillRate: number | null };
};
export type MySlot = {
slotId: string;
role: { id: string; name: string; description: string; sessionLabel: string | null; kidsRoom: string | null };
event: { id: string; title: string; location: string | null };
shift: Shift & { hours: number };
checkedInAt: string | null; canCheckIn: boolean; past: boolean; swapId: string | null; hasTicket: boolean;
};
export type CoverRequest = {
swapId: string; note: string; from: string | null;
role: { id: string; name: string; sessionLabel: string | null };
event: { id: string; title: string };
shift: Shift;
};
export type ServingEvent = { id: string; title: string; startDate: string; endDate: string; location: string | null; roles: number };
export type RosterEvent = { id: string; title: string; startDate: string; endDate: string; scheduleType: string; campusId: string | null; roles: number };
export type HoursRow = { userId: string; name: string; shifts: number; hours: number; events: number };
/** The page the volunteer check-in QR code opens (phone cameras open it straight away). */
export function checkInUrl(qr: string): string {
const origin = typeof window !== "undefined" ? window.location.origin : "";
return `${origin}/serve/check-in?code=${encodeURIComponent(qr)}`;
}
/** A Date as the value of a datetime-local input (local time), or "". */
export function toLocalInput(iso: string | null | undefined): string {
if (!iso) return "";
const d = new Date(iso);
const pad = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** A datetime-local value as an ISO string, or null when empty. */
export function fromLocalInput(v: string): string | null {
return v ? new Date(v).toISOString() : null;
}
export const hoursText = (h: number) => `${h % 1 === 0 ? h : h.toFixed(2).replace(/0$/, "")} h`;