diff --git a/apps/events/e2e/campus-scoped.spec.ts b/apps/events/e2e/campus-scoped.spec.ts new file mode 100644 index 0000000..952bd92 --- /dev/null +++ b/apps/events/e2e/campus-scoped.spec.ts @@ -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); + }); +}); diff --git a/apps/events/e2e/fixtures.ts b/apps/events/e2e/fixtures.ts index 6c10086..14cac2f 100644 --- a/apps/events/e2e/fixtures.ts +++ b/apps/events/e2e/fixtures.ts @@ -7,6 +7,7 @@ export type Seed = { users: Record; 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 }; diff --git a/apps/events/e2e/support/prepare-db.js b/apps/events/e2e/support/prepare-db.js index a0f93da..88f9800 100644 --- a/apps/events/e2e/support/prepare-db.js +++ b/apps/events/e2e/support/prepare-db.js @@ -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 () => { diff --git a/apps/events/frontend/src/app/dashboard/admin/page.tsx b/apps/events/frontend/src/app/dashboard/admin/page.tsx index 85867ba..f044c68 100644 --- a/apps/events/frontend/src/app/dashboard/admin/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/page.tsx @@ -121,7 +121,7 @@ export default function AdminDashboardPage() {

Welcome back{user ? `, ${user.name}` : ""} 👋

Here's what's happening with your events today.

- +
{!isAdmin && ( diff --git a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx index 6e08dfd..603ceea 100644 --- a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx @@ -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 & { password?: string } = { + const payload: Partial & { 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() { + {campusInfo.enabled && canBeScoped && ( +
+ Limit to campuses + {scope === null ?

Loading…

: ( + <> +
+ {scopeChoices.map(c => ( + + ))} +
+

+ {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."} +

+ + )} +
+ )}
setEditData(d => ({ ...d, password: e.target.value }))} /> diff --git a/apps/events/frontend/src/app/dashboard/staff/page.tsx b/apps/events/frontend/src/app/dashboard/staff/page.tsx index 1a9c7f4..ec62e3b 100644 --- a/apps/events/frontend/src/app/dashboard/staff/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/page.tsx @@ -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() {

Welcome back{user ? `, ${user.name}` : ""} 👋

Here's today's scanning activity.

+
{!canView && ( diff --git a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx index 8e7d0f9..8e93aa1 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/events/page.tsx @@ -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(0); const [pricingSubstep, setPricingSubstep] = useState(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(() => (ev?.sessions || []).map(s => keyed(toSessionDraft(s)))); const [attendance, setAttendance] = useState(() => ({ @@ -1425,6 +1440,11 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) { This event is closed — it can't be edited until it's reopened from the cashup page (admin only).
)} + {campusReadOnly && ( +
+ {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. +
+ )} {error &&
{error}
} {changedNotice && (
@@ -1496,7 +1516,7 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) { upd({ campusId: e.target.value, ...(next?.defaultLocation && isDefault ? { location: next.defaultLocation } : {}) }); }} > - + {campusInfo.scoped ? : } {campusInfo.campuses.map(c => )} {/* An archived campus stays on events that already have it. */} {ev?.campus && !campusInfo.campuses.some(c => c.id === ev.campus!.id) && } @@ -1846,8 +1866,8 @@ function EventModal({ mode, event: ev, onClose, onSuccess }: EventModalProps) { )} - @@ -1974,7 +1994,7 @@ export default function ManageEventsPage() {
setSearch(e.target.value)} /> - + diff --git a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx index 1398bf9..942d02e 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx @@ -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() {

Welcome back{user ? `, ${user.name}` : ""} 👋

Here's what's happening with your events today.

- + +
{!canView && ( diff --git a/apps/events/frontend/src/components/admin/CampusesTab.tsx b/apps/events/frontend/src/components/admin/CampusesTab.tsx index e4f2687..1835663 100644 --- a/apps/events/frontend/src/components/admin/CampusesTab.tsx +++ b/apps/events/frontend/src/components/admin/CampusesTab.tsx @@ -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 }) {

{c.name}

/campus/{c.slug} - {" · "}{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 && <> · {c.address}}

diff --git a/apps/events/frontend/src/components/reports/ReportsV2.tsx b/apps/events/frontend/src/components/reports/ReportsV2.tsx index 8cac495..459d06b 100644 --- a/apps/events/frontend/src/components/reports/ReportsV2.tsx +++ b/apps/events/frontend/src/components/reports/ReportsV2.tsx @@ -1468,6 +1468,7 @@ export default function ReportsV2({ backHref }: { backHref?: string } = {}) { everyLabel="All campuses (church-wide total)" className="mb-3" id="reports-campus" + mine /> 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); diff --git a/apps/events/frontend/src/components/shared/CampusFilter.tsx b/apps/events/frontend/src/components/shared/CampusFilter.tsx index 956643f..9ae23b1 100644 --- a/apps/events/frontend/src/components/shared/CampusFilter.tsx +++ b/apps/events/frontend/src/components/shared/CampusFilter.tsx @@ -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 (