"use client"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { useAuth } from "@/hooks/useAuth"; import { useRouter } from "next/navigation"; import { DndContext, DragEndEvent, PointerSensor, TouchSensor, useDraggable, useDroppable, useSensor, useSensors } from "@dnd-kit/core"; import { apiFetch, fetchManagedEvents } from "@/lib/api"; import { useDismissingState } from "@/hooks/useDismissingState"; import { BedDouble, Plus, Wand2, Printer, Trash2, Pencil, Eraser } from "lucide-react"; import { errorMessage } from "@/lib/utils"; import type { Event } from "@/types"; import { BackLink } from "@/components/shared/BackLink"; import { EventPicker } from "@/components/shared/EventPicker"; type Group = { id: string; name: string; capacity: number | null; gender: "male" | "female" | null; leaderUserId: string | null; leader?: { id: string; name: string } | null }; type AllocSet = { id: string; name: string; showOnTicket: boolean; groups: Group[]; assignments: { attendeeId: string; groupId: string }[] }; type Person = { id: string; name: string; gender: string | null; dateOfBirth: string | null; registrationId: string; bookedBy: string }; // GET /api/allocations/sets/:id/lists — medical/emergency only when ?medical=true and consent was given. type ListMember = { groupId: string; id: string; name: string; gender: string | null; dateOfBirth: string | null; phone: string | null; parentName: string | null; parentPhone: string | null; bookedBy: string; bookedByPhone: string | null; medical?: Record | null; emergency?: Record | null; }; type SetLists = { set: { id: string; name: string }; event: { id: string; title: string; startDate: string }; groups: { id: string; name: string; capacity: number | null; gender: string | null; leader: string | null; members: ListMember[] }[]; }; type Board = { event: { id: string; title: string; startDate: string; collectGender: boolean; requiresParentalConsent: boolean }; sets: AllocSet[]; attendees: Person[]; leaders: { id: string; name: string }[]; unnamedPlaces: number }; const UNASSIGNED = "unassigned"; const esc = (s: unknown) => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]!)); const genderLabel = (g: string | null) => (g === "male" ? "Male" : g === "female" ? "Female" : ""); const ageOn = (dob: string | null, on: string) => { if (!dob) return null; const d = new Date(dob), e = new Date(on); let age = e.getFullYear() - d.getFullYear(); if (e.getMonth() < d.getMonth() || (e.getMonth() === d.getMonth() && e.getDate() < d.getDate())) age -= 1; return age; }; function PersonChip({ person, eventStart }: { person: Person; eventStart: string }) { const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: person.id }); const age = ageOn(person.dateOfBirth, eventStart); return (
{person.name} {[genderLabel(person.gender), age != null ? `${age}` : "", person.bookedBy ? `· ${person.bookedBy}` : ""].filter(Boolean).map(s => ` ${s}`).join("")}
); } function Column({ id, title, subtitle, full, children, actions }: { id: string; title: string; subtitle?: string; full?: boolean; children: React.ReactNode; actions?: React.ReactNode }) { const { setNodeRef, isOver } = useDroppable({ id }); return (
{title}
{subtitle &&
{subtitle}
}
{actions}
{children}
); } export default function AllocationsPage() { const { user, loading, token } = useAuth(); const router = useRouter(); const canView = useMemo(() => user?.role === "admin" || user?.role === "supervisor", [user]); useEffect(() => { if (!loading && !user) router.replace("/login"); }, [user, loading, router]); const [events, setEvents] = useState([]); const [eventId, setEventId] = useState(""); const [board, setBoard] = useState(null); const [setId, setSetId] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useDismissingState(null); const [info, setInfo] = useDismissingState(null); const [groupForm, setGroupForm] = useState<{ id?: string; name: string; capacity: string; gender: string; leaderUserId: string } | null>(null); const [newSetName, setNewSetName] = useState(""); const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), useSensor(TouchSensor, { activationConstraint: { delay: 150, tolerance: 5 } })); useEffect(() => { if (!token || !canView) return; fetchManagedEvents(token, { past: true }) .then(evs => { const upcoming = (evs || []).filter(e => new Date(e.endDate).getTime() > Date.now() - 7 * 864e5) .sort((a, b) => new Date(a.startDate).getTime() - new Date(b.startDate).getTime()); setEvents(upcoming); if (upcoming.length) setEventId(id => id || upcoming[0].id); }) .catch(e => setError(e?.message || "Failed to load events")); }, [token, canView, setError]); const load = useCallback(async () => { if (!token || !eventId) return; try { const b = await apiFetch(`/api/allocations/event/${encodeURIComponent(eventId)}`, { authToken: token }); setBoard(b); setSetId(id => (b.sets.some(s => s.id === id) ? id : b.sets[0]?.id || "")); } catch (e) { setError(errorMessage(e) || "Failed to load allocations"); } }, [token, eventId, setError]); useEffect(() => { load(); }, [load]); const current = board?.sets.find(s => s.id === setId) || null; const groupOf = useMemo(() => new Map((current?.assignments || []).map(a => [a.attendeeId, a.groupId])), [current]); const membersOf = (groupId: string) => (board?.attendees || []).filter(p => groupOf.get(p.id) === groupId); const unassigned = (board?.attendees || []).filter(p => !groupOf.has(p.id)); const call = async (path: string, method: string, body?: unknown): Promise => apiFetch(path, { method, authToken: token!, ...(body !== undefined ? { body } : {}) }); const onDragEnd = async (e: DragEndEvent) => { if (!current || !e.over) return; const attendeeId = String(e.active.id); const target = String(e.over.id); const groupId = target === UNASSIGNED ? null : target; if ((groupOf.get(attendeeId) || null) === groupId) return; // Optimistic move; reload on failure. setBoard(b => b && ({ ...b, sets: b.sets.map(s => s.id !== current.id ? s : { ...s, assignments: [...s.assignments.filter(a => a.attendeeId !== attendeeId), ...(groupId ? [{ attendeeId, groupId }] : [])], }), })); try { await call(`/api/allocations/sets/${current.id}/assignments`, "PUT", { attendeeId, groupId }); } catch (err) { setError(errorMessage(err) || "Couldn't move them"); load(); } }; const run = async (fn: () => Promise) => { setBusy(true); try { const msg = await fn(); if (msg) setInfo(msg); await load(); } catch (e) { setError(errorMessage(e) || "Something went wrong"); } finally { setBusy(false); } }; const addSet = () => run(async () => { const s = await call<{ id: string }>("/api/allocations/sets", "POST", { eventId, name: newSetName || "Rooms" }); setNewSetName(""); setSetId(s.id); }); const saveGroup = () => groupForm && current && run(async () => { const body = { name: groupForm.name, capacity: groupForm.capacity || null, gender: groupForm.gender || null, leaderUserId: groupForm.leaderUserId || null }; if (groupForm.id) await call(`/api/allocations/groups/${groupForm.id}`, "PUT", body); else await call(`/api/allocations/sets/${current.id}/groups`, "POST", body); setGroupForm(null); }); const printLists = async (master: boolean, medical: boolean) => { if (!current || !board) return; try { const data = await apiFetch(`/api/allocations/sets/${current.id}/lists${medical ? "?medical=true" : ""}`, { authToken: token! }); const w = window.open("", "_blank"); if (!w) return; const row = (m: ListMember) => `${esc(m.name)}${esc(genderLabel(m.gender))}${esc(ageOn(m.dateOfBirth, board.event.startDate) ?? "")}` + `${esc(m.phone || m.parentPhone || m.bookedByPhone || "")}${esc(m.parentName || m.bookedBy || "")}` + (medical ? `${esc(m.medical ? Object.values(m.medical).filter(Boolean).join("; ") : "")}${esc(m.emergency ? Object.values(m.emergency).filter(Boolean).join(", ") : "")}` : "") + ``; const head = `NameGenderAgePhoneParent / booked by${medical ? "MedicalEmergency contact" : ""}`; let body = ""; if (master) { const all = data.groups.flatMap((g) => g.members.map((m) => ({ ...m, group: g.name }))).sort((a, b) => a.name.localeCompare(b.name)); body = `

${esc(data.event.title)} — ${esc(data.set.name)} (master list)

${head.slice(4)}${all.map((m) => row(m).replace("", ``)).join("")}
${esc(data.set.name)}
${esc(m.group)}
`; } else { body = data.groups.map((g) => `

${esc(data.event.title)} — ${esc(g.name)}

` + `

${esc(data.set.name)}${g.leader ? ` · Leader: ${esc(g.leader)}` : ""} · ${g.members.length}${g.capacity ? ` / ${g.capacity}` : ""} people

` + `${head}${g.members.map(row).join("")}
`).join(""); } w.document.write(`${esc(data.set.name)}${body}`); w.document.close(); } catch (e) { setError(errorMessage(e) || "Couldn't load the lists"); } }; return (

Rooms & groups

Put attendees into rooms, small groups, teams or buses

{!canView &&
You need supervisor access to manage allocations.
} {error &&
{error}
} {info &&
{info}
} {canView && (
{ setEventId(id); setSetId(""); }} />
{board && (
{board.sets.map(s => ( ))} setNewSetName(e.target.value)} onKeyDown={e => { if (e.key === "Enter") addSet(); }} />
)}
{board && board.attendees.length === 0 && (
No named attendees yet. Allocation works per person, so it needs names — turn on "Named attendees" for the event{board.event.collectGender ? "" : " (and \"Ask each person's gender\" if rooms are split by gender)"}.
)} {board && board.unnamedPlaces > 0 && (

{board.unnamedPlaces} place(s) have no name yet, so they can't be placed until the person booking adds names.

)} {current && board && ( <>
{board.event.requiresParentalConsent && ( )}
{groupForm ? (
setGroupForm({ ...groupForm, name: e.target.value })} placeholder="Cabin 1" autoFocus />
setGroupForm({ ...groupForm, capacity: e.target.value })} placeholder="No limit" />
) : ( )}
{unassigned.map(p => )}
{current.groups.length === 0 &&

Add groups (rooms, cabins, buses…) to start placing people.

} {current.groups.map(g => { const members = membersOf(g.id); const full = g.capacity != null && members.length >= g.capacity; const subtitle = [`${members.length}${g.capacity ? ` / ${g.capacity}` : ""}${full ? " · full" : ""}`, g.gender ? (g.gender === "male" ? "males" : "females") : "", g.leader ? `leader ${g.leader.name}` : ""].filter(Boolean).join(" · "); return (
}> {members.map(p => )} ); })}
)} {board && board.sets.length === 0 && board.attendees.length > 0 && (

Start by adding a set, e.g. "Rooms", "Small groups" or "Buses". An event can have several.

)}
)} ); }