Campus-scoped staff: frontend and e2e

Admin -> Users 'Limit to campuses'; staff campus pickers, reports, dashboards
and audience picker follow the scope (useMyCampuses); scoped people pick one
of their campuses for new events, and church-wide / other campuses' events
open read-only; 'You work with ...' note; warning before turning campuses off
while staff are limited. e2e: scanner refusal naming the campus, scoped
events list and read-only editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 17:50:03 +02:00
co-authored by Claude Opus 5.5
parent f8a567615c
commit 193cf4267a
14 changed files with 186 additions and 20 deletions
+52
View File
@@ -0,0 +1,52 @@
import { test, expect, seed, api, loginAs, API } from "./fixtures";
// Campus-scoped staff (1.44.0): the seeded staff member and supervisor are limited to E2E South
// for these tests; afterwards the limits are cleared and campuses turned off again.
test.describe("campus-scoped staff", () => {
test.beforeAll(async ({ browser }) => {
const page = await browser.newPage();
await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: true });
for (const role of ["staff", "supervisor"] as const) {
await api(page, "admin", "PUT", `/api/users/${seed().users[role].id}`, { scopedCampusIds: [seed().campuses.south.id] });
}
await page.close();
});
test.afterAll(async ({ browser }) => {
const page = await browser.newPage();
for (const role of ["staff", "supervisor"] as const) {
await api(page, "admin", "PUT", `/api/users/${seed().users[role].id}`, { scopedCampusIds: [] });
}
await api(page, "admin", "PUT", "/api/campuses/settings", { enabled: false });
await page.close();
});
test("the scanner refuses another campus's ticket and says which campus", async ({ page }) => {
const scan = (qr: string) => page.request.get(`${API}/api/tickets/scan-preview/${encodeURIComponent(qr)}`, { headers: { Authorization: `Bearer ${seed().users.staff.token}` } });
const north = await scan(seed().northTicketQr);
expect(north.status()).toBe(403);
expect((await north.json()).message).toBe("This ticket is for an event at E2E North.");
// The course is for all campuses, so it scans.
expect((await scan(seed().course.qrCode)).status()).toBe(200);
});
test("a scoped supervisor sees their campus and church-wide events, and can't edit church-wide ones", async ({ page }) => {
await loginAs(page, "supervisor");
await page.goto("/dashboard/supervisor");
await expect(page.getByText("You work with E2E South, and events for all campuses.")).toBeVisible();
await page.goto("/dashboard/supervisor/events");
await expect(page.getByText("E2E Paid Conference")).toBeVisible(); // South
await expect(page.getByText("E2E Alpha Course")).toBeVisible(); // all campuses
await expect(page.getByText("E2E Free Evening")).toBeHidden(); // North
await page.getByText("E2E Alpha Course").click();
await expect(page.getByText(/This is an event for all campuses — only admins and supervisors for every campus can change it/)).toBeVisible();
await expect(page.getByRole("button", { name: "Save Changes" })).toBeDisabled();
});
test("another campus's registrations are not found for a scoped supervisor", async ({ page }) => {
const res = await page.request.get(`${API}/api/registrations/event/${seed().events.free}`, { headers: { Authorization: `Bearer ${seed().users.supervisor.token}` } });
expect(res.status()).toBe(404);
});
});
+1
View File
@@ -7,6 +7,7 @@ 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 };
campuses: Record<"north" | "south", { id: string; slug: string }>;
northTicketQr: string;
course: { sessions: { id: string; label: string }[]; ticketId: string; qrCode: string };
unsubscribeToken: string;
newsPromptUser: { id: string; token: string };
+13
View File
@@ -160,10 +160,23 @@ async function seed(url) {
const ticket = await prisma.ticket.findFirst({ where: { eventId: course.id } });
await prisma.ticketUsage.create({ data: { ticketId: ticket.id, scannedById: users.staff.id, sessionId: course.sessions[0].id, scannedAt: course.sessions[0].startsAt } });
// A ticket for the free evening (North campus), for the campus-scoped scanner test. The admin
// holds it so it never collides with the registration tests (which use Thandi).
const freeOption = await prisma.eventOption.findFirst({ where: { eventId: free.id } });
const northReg = await prisma.registration.create({
data: {
userId: users.admin.id, eventId: free.id, status: 'paid',
registrationOptions: { create: [{ eventOptionId: freeOption.id, quantity: 1, priceSnapshot: 0, tranches: { create: [{ quantity: 1, priceSnapshot: 0 }] } }] },
},
});
await generateTicketsForRegistration(northReg.id);
const northTicket = await prisma.ticket.findFirst({ where: { registrationOption: { registrationId: northReg.id } } });
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 },
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 },
// An account that has never answered the news question (asked once after login).
newsPromptUser: await (async () => {
@@ -121,7 +121,7 @@ export default function AdminDashboardPage() {
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Welcome back{user ? `, ${user.name}` : ""} 👋</h1>
<p className="text-sm text-gray-500 mt-1">Here&apos;s what&apos;s happening with your events today.</p>
<CampusFilter value={campus} onChange={setCampus} everyLabel="All campuses (church-wide total)" className="mt-3" id="dashboard-campus" />
<CampusFilter value={campus} onChange={setCampus} everyLabel="All campuses (church-wide total)" className="mt-3" id="dashboard-campus" mine />
</div>
{!isAdmin && (
@@ -11,6 +11,7 @@ import { RoleBadge, type Role as RoleBadgeRole } from "@/components/shared/RoleB
import { errorMessage } from "@/lib/utils";
import type { Paginated } from "@/types";
import { BackLink } from "@/components/shared/BackLink";
import { useCampuses } from "@/hooks/useCampuses";
interface UserItem {
id: string;
@@ -142,14 +143,26 @@ export default function AdminUsersPage() {
}
};
const startEdit = (u: UserItem) => { setEditingId(u.id); setEditData({ ...u, password: "" }); };
const cancelEdit = () => { setEditingId(null); setEditData({}); };
// Campus-scoped staff: the campuses a supervisor/staff member is limited to (loaded per user;
// null until loaded, so an unloaded list is never saved over the real one).
const campusInfo = useCampuses();
const [scope, setScope] = useState<{ id: string; name: string }[] | null>(null);
const startEdit = (u: UserItem) => {
setEditingId(u.id); setEditData({ ...u, password: "" }); setScope(null);
apiFetch<{ scopedCampuses?: { id: string; name: string }[] }>(`/api/users/${encodeURIComponent(u.id)}`, { authToken: token! })
.then(full => setScope(full.scopedCampuses || []))
.catch(() => setScope(null));
};
const cancelEdit = () => { setEditingId(null); setEditData({}); setScope(null); };
const canBeScoped = editData.role === "staff" || editData.role === "supervisor";
// Active campuses, plus any archived one this person is still limited to.
const scopeChoices = [...campusInfo.campuses.map(c => ({ id: c.id, name: c.name })), ...(scope || []).filter(s => !campusInfo.campuses.some(c => c.id === s.id)).map(s => ({ ...s, name: `${s.name} (archived)` }))];
const saveEdit = async () => {
if (!editingId) return;
try {
setSaving(true);
const payload: Partial<UserItem> & { password?: string } = {
const payload: Partial<UserItem> & { password?: string; scopedCampusIds?: string[] } = {
name: editData.name,
email: editData.email,
role: editData.role,
@@ -160,6 +173,7 @@ export default function AdminUsersPage() {
if (editData.password && editData.password.trim().length > 0) {
payload.password = editData.password.trim();
}
if (campusInfo.enabled && canBeScoped && scope) payload.scopedCampusIds = scope.map(c => c.id);
await apiFetch(`/api/users/${encodeURIComponent(editingId)}`, {
method: "PUT", authToken: token!, body: payload,
});
@@ -518,6 +532,32 @@ export default function AdminUsersPage() {
</label>
</div>
</div>
{campusInfo.enabled && canBeScoped && (
<fieldset className="border rounded p-3">
<legend className="text-xs text-gray-600 px-1">Limit to campuses</legend>
{scope === null ? <p className="text-xs text-gray-400">Loading…</p> : (
<>
<div className="flex flex-wrap gap-x-4 gap-y-1">
{scopeChoices.map(c => (
<label key={c.id} className="flex items-center gap-1.5 text-sm">
<input
type="checkbox"
checked={scope.some(s => s.id === c.id)}
onChange={e => setScope(prev => e.target.checked ? [...(prev || []), c] : (prev || []).filter(s => s.id !== c.id))}
/>
{c.name}
</label>
))}
</div>
<p className="text-[11px] text-gray-500 mt-1">
{scope.length === 0
? "Not limited — sees every campus."
: "Sees only these campuses' events plus events for all campuses. Can't set up, cash up or refund events for all campuses, or use the site banner and payment reconciliation."}
</p>
</>
)}
</fieldset>
)}
<div>
<label className="block text-xs text-gray-600 mb-1">New password (leave blank to keep current)</label>
<input type="password" placeholder="Set new password" className="w-full border rounded px-3 py-2 text-sm" value={editData.password || ""} onChange={e => setEditData(d => ({ ...d, password: e.target.value }))} />
@@ -10,6 +10,7 @@ import { QrCode, Ticket, Activity, UserCheck, Clock, Users, ClipboardCheck } fro
import { StatCard, StatCardRow } from "@/components/shared/StatCard";
import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile";
import type { DashboardStats, RecentScan, ScanStats } from "@/types";
import { CampusScopeNote } from "@/components/shared/CampusFilter";
const QUICK_ACTIONS = [
{ href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode },
@@ -75,6 +76,7 @@ export default function StaffDashboardPage() {
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Welcome back{user ? `, ${user.name}` : ""} 👋</h1>
<p className="text-sm text-gray-500 mt-1">Here&apos;s today&apos;s scanning activity.</p>
<CampusScopeNote className="mt-2" />
</div>
{!canView && (
@@ -8,7 +8,7 @@ import { apiFetch, API_BASE } from "@/lib/api";
import { ApiImage } from "@/components/shared/ApiImage";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useCampuses } from "@/hooks/useCampuses";
import { useMyCampuses } from "@/hooks/useCampuses";
import { CampusBadge, CampusFilter, matchesCampus } from "@/components/shared/CampusFilter";
import { Calendar } from "lucide-react";
import { ChoicesEditor } from "@/components/shared/FormFieldExtras";
@@ -877,7 +877,10 @@ interface EventModalProps {
function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
const { token } = useAuth();
const { settings } = useSiteSettings();
const campusInfo = useCampuses();
const campusInfo = useMyCampuses();
// Campus-scoped: events for all campuses (and other campuses') are set up by admins and
// supervisors for every campus — the server refuses changes, so the editor says so up front.
const campusReadOnly = mode === "edit" && campusInfo.scoped && !campusInfo.campuses.some(c => c.id === ev?.campusId);
const [step, setStep] = useState<StepIdx>(0);
const [pricingSubstep, setPricingSubstep] = useState<PricingSubstep>(0);
const [saving, setSaving] = useState(false);
@@ -907,6 +910,18 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
attendanceMode: ev.attendanceMode === "pick" ? "pick" : "whole",
} : blankDraft(settings.org_address || ""));
// A campus-scoped person's new event starts at their (first) campus — they can't make
// events for all campuses — with that campus's default location if the field is still default.
useEffect(() => {
if (mode !== "create" || !campusInfo.scoped || !campusInfo.campuses.length) return;
setDraft(d => {
if (d.campusId) return d;
const first = campusInfo.campuses[0];
const isDefault = !d.location.trim() || d.location === (settings.org_address || "");
return { ...d, campusId: first.id, ...(first.defaultLocation && isDefault ? { location: first.defaultLocation } : {}) };
});
}, [mode, campusInfo.scoped, campusInfo.campuses, settings.org_address]);
// ── multi-day schedule + attendance settings ──
const [sessions, setSessions] = useState<KeyedSession[]>(() => (ev?.sessions || []).map(s => keyed(toSessionDraft(s))));
const [attendance, setAttendance] = useState<AttendanceDraft>(() => ({
@@ -1425,6 +1440,11 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
This event is closed — it can&apos;t be edited until it&apos;s reopened from the cashup page (admin only).
</div>
)}
{campusReadOnly && (
<div className="p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm">
{ev?.campusId ? "This event belongs to another campus" : "This is an event for all campuses"} — only admins and supervisors for every campus can change it. You can still work with its registrations, payments and tickets.
</div>
)}
{error && <div className="p-3 border rounded bg-red-50 text-red-700 text-sm">{error}</div>}
{changedNotice && (
<div className="p-3 border rounded bg-amber-50 border-amber-200 text-amber-900 text-sm space-y-2">
@@ -1496,7 +1516,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
upd({ campusId: e.target.value, ...(next?.defaultLocation && isDefault ? { location: next.defaultLocation } : {}) });
}}
>
<option value="">All campuses</option>
{campusInfo.scoped ? <option value="" disabled>Choose your campus…</option> : <option value="">All campuses</option>}
{campusInfo.campuses.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
{/* An archived campus stays on events that already have it. */}
{ev?.campus && !campusInfo.campuses.some(c => c.id === ev.campus!.id) && <option value={ev.campus.id}>{ev.campus.name} (archived)</option>}
@@ -1846,8 +1866,8 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) {
<button type="button" onClick={handleNext}
className="px-3 py-1.5 text-sm rounded border bg-white hover:bg-gray-50">Next →</button>
)}
<button type="button" disabled={saving || isClosed} onClick={handleSave}
title={isClosed ? "This event is closed — reopen it first to make changes" : undefined}
<button type="button" disabled={saving || isClosed || campusReadOnly} onClick={handleSave}
title={isClosed ? "This event is closed — reopen it first to make changes" : campusReadOnly ? "Only admins and supervisors for every campus can change this event" : undefined}
className="px-5 py-1.5 text-sm rounded bg-brand-600 text-white hover:bg-brand-700 disabled:opacity-50 font-medium">
{saving ? "Saving…" : "Save Changes"}
</button>
@@ -1974,7 +1994,7 @@ export default function ManageEventsPage() {
<div className="flex flex-wrap items-center gap-3 mb-4 text-sm">
<input className="border rounded px-3 py-1.5 text-sm w-48" placeholder="Search by title…" value={search} onChange={e => setSearch(e.target.value)} />
<CampusFilter value={campus} onChange={setCampus} withChurchWide />
<CampusFilter value={campus} onChange={setCampus} withChurchWide mine />
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={includePast} onChange={e => setIncludePast(e.target.checked)} /> Include past
</label>
@@ -15,7 +15,7 @@ import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActio
import { AreaTrendChart } from "@/components/charts/AreaTrendChart";
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
import type { DashboardStats, PaymentStats, RecentScan, ScanStats } from "@/types";
import { CampusFilter } from "@/components/shared/CampusFilter";
import { CampusFilter, CampusScopeNote } from "@/components/shared/CampusFilter";
const formatRand = (n: number) => `R ${(n || 0).toFixed(2)}`;
const formatRandAxis = (n: number) => `R${new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n)}`;
@@ -117,7 +117,8 @@ export default function SupervisorDashboardPage() {
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900">Welcome back{user ? `, ${user.name}` : ""} 👋</h1>
<p className="text-sm text-gray-500 mt-1">Here&apos;s what&apos;s happening with your events today.</p>
<CampusFilter value={campus} onChange={setCampus} everyLabel="All campuses (church-wide total)" className="mt-3" id="dashboard-campus" />
<CampusFilter value={campus} onChange={setCampus} everyLabel="All campuses (church-wide total)" className="mt-3" id="dashboard-campus" mine />
<CampusScopeNote className="mt-2" />
</div>
{!canView && (
@@ -13,7 +13,7 @@ type Person = { id: string; name: string; email: string };
type AdminCampus = Campus & {
archivedAt: string | null;
notifyRecipients: Person[];
_count: { events: number; homeOf: number };
_count: { events: number; homeOf: number; scopedStaff: number };
};
type Draft = {
name: string; slug: string; address: string; defaultLocation: string;
@@ -150,7 +150,12 @@ export function CampusesTab({ active }: { active: boolean }) {
} finally { setBusy(false); }
};
const toggle = (on: boolean) => run(() => apiFetch("/api/campuses/settings", { method: "PUT", authToken: token, body: { enabled: on } }), on ? "Campuses are on." : "Campuses are off — campus fields are hidden, nothing is deleted.");
const toggle = (on: boolean) => {
// Limits are ignored while campuses are off, so limited staff would see every campus.
const limited = (campuses || []).reduce((n, c) => n + (c._count.scopedStaff || 0), 0);
if (!on && limited > 0 && !window.confirm(`Some staff are limited to campuses (${limited} limit${limited === 1 ? "" : "s"} set). While campuses are off those limits are ignored and they'll see every campus. Turn campuses off?`)) return;
return run(() => apiFetch("/api/campuses/settings", { method: "PUT", authToken: token, body: { enabled: on } }), on ? "Campuses are on." : "Campuses are off — campus fields are hidden, nothing is deleted.");
};
const save = async (d: Draft, id?: string) => {
const body = { ...d, notifyRecipients: undefined, notifyRecipientIds: d.notifyRecipients.map(p => p.id) };
const ok = await run(() => id
@@ -205,7 +210,7 @@ export function CampusesTab({ active }: { active: boolean }) {
<p className="font-medium text-gray-900">{c.name}</p>
<p className="text-xs text-gray-500">
<Link href={`/campus/${c.slug}`} className="hover:underline">/campus/{c.slug}</Link>
{" · "}{c._count.events} event{c._count.events === 1 ? "" : "s"}{" · "}{c._count.homeOf} {c._count.homeOf === 1 ? "person" : "people"} call it home
{" · "}{c._count.events} event{c._count.events === 1 ? "" : "s"}{" · "}{c._count.homeOf} {c._count.homeOf === 1 ? "person" : "people"} call it home{c._count.scopedStaff ? <>{" · "}{c._count.scopedStaff} staff limited to it</> : null}
{c.address && <> · <MapPin className="inline w-3 h-3" /> {c.address}</>}
</p>
</div>
@@ -1468,6 +1468,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) {
everyLabel="All campuses (church-wide total)"
className="mb-3"
id="reports-campus"
mine
/>
<ReportsShell
@@ -4,7 +4,7 @@ import React, { useState } from "react";
import { Users } from "lucide-react";
import { apiFetch } from "@/lib/api";
import { useAuth } from "@/hooks/useAuth";
import { useCampuses } from "@/hooks/useCampuses";
import { useMyCampuses } from "@/hooks/useCampuses";
import { errorMessage } from "@/lib/utils";
/**
@@ -15,7 +15,7 @@ import { errorMessage } from "@/lib/utils";
*/
export function CampusAudiencePicker({ selectedIds, onChange }: { selectedIds: string[]; onChange: (ids: string[]) => void }) {
const { token } = useAuth();
const { enabled, campuses } = useCampuses();
const { enabled, campuses } = useMyCampuses();
const [campusId, setCampusId] = useState("");
const [registrants, setRegistrants] = useState(true);
const [busy, setBusy] = useState(false);
@@ -3,22 +3,26 @@
import React from "react";
import Link from "next/link";
import { MapPin } from "lucide-react";
import { useCampuses, type EventCampus } from "@/hooks/useCampuses";
import { useCampuses, useMyCampuses, type EventCampus } from "@/hooks/useCampuses";
/**
* A campus dropdown for lists and reports. Renders nothing while campuses are off.
* Values: "" = every campus (church-wide total), "all" = only events for all campuses
* (when `withChurchWide`), otherwise a campus id.
*/
export function CampusFilter({ value, onChange, withChurchWide = false, everyLabel = "All campuses", className = "", id = "campus-filter" }: {
export function CampusFilter({ value, onChange, withChurchWide = false, everyLabel = "All campuses", className = "", id = "campus-filter", mine = false }: {
value: string;
onChange: (value: string) => void;
withChurchWide?: boolean;
everyLabel?: string;
className?: string;
id?: string;
// Staff pages: only the campuses a campus-scoped person works with.
mine?: boolean;
}) {
const { enabled, campuses } = useCampuses();
const everyCampus = useCampuses();
const myCampuses = useMyCampuses();
const { enabled, campuses } = mine ? myCampuses : everyCampus;
if (!enabled || campuses.length === 0) return null;
return (
<label className={`inline-flex items-center gap-2 text-sm ${className}`} htmlFor={id}>
@@ -56,3 +60,15 @@ export function CampusBadge({ campus, className = "", link = false }: { campus?:
);
return link ? <Link href={`/campus/${campus.slug}`} className={cls}>{inner}</Link> : <span className={cls}>{inner}</span>;
}
/** For campus-scoped staff: which campuses they work with. Nothing for everyone else. */
export function CampusScopeNote({ className = "" }: { className?: string }) {
const { scoped, campuses } = useMyCampuses();
if (!scoped) return null;
return (
<p className={`inline-flex items-center gap-1.5 text-xs text-gray-600 bg-gray-50 border rounded-full px-3 py-1 ${className}`}>
<MapPin className="w-3.5 h-3.5" aria-hidden />
You work with {campuses.map(c => c.name).join(", ") || "your campuses"}, and events for all campuses.
</p>
);
}
@@ -2,6 +2,7 @@
import { useEffect, useState } from "react";
import { apiFetch } from "@/lib/api";
import { useAuth } from "@/hooks/useAuth";
export type Campus = {
id: string;
@@ -53,3 +54,15 @@ export function useCampuses() {
}, []);
return state;
}
/**
* The campuses the signed-in person works with: for campus-scoped staff only their own campuses
* (`scoped` true — they can't set up events for all campuses), for everyone else every campus.
* Staff dropdowns use this; the public site uses useCampuses.
*/
export function useMyCampuses() {
const all = useCampuses();
const { user } = useAuth();
const scope = all.enabled ? user?.campusScope || null : null;
return { ...all, scoped: !!scope, campuses: scope ? all.campuses.filter(c => scope.includes(c.id)) : all.campuses };
}
+2
View File
@@ -15,6 +15,8 @@ export type AuthUser = {
noticePromptPending?: boolean;
// Multi-campus: their home campus (the events page starts on it).
homeCampusId?: string | null;
// Campus-scoped staff: the campuses they're limited to (null = every campus).
campusScope?: string[] | null;
};
export type AuthResponse = AuthUser & {