From f9de6b84ee60b5131347a56131056886b3029a43 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Wed, 28 Oct 2026 01:01:08 +0200 Subject: [PATCH] Kids check-in: desk, room screen, setup and parent pages, help, e2e Co-Authored-By: Claude Opus 5.5 --- apps/events/e2e/fixtures.ts | 2 +- apps/events/e2e/kids.spec.ts | 87 +++ apps/events/e2e/support/prepare-db.js | 9 +- apps/events/frontend/package-lock.json | 4 +- apps/events/frontend/package.json | 2 +- .../app/dashboard/admin/audit-log/page.tsx | 6 + .../frontend/src/app/dashboard/admin/page.tsx | 3 + .../src/app/dashboard/staff/kids/page.tsx | 569 ++++++++++++++++++ .../app/dashboard/staff/kids/rooms/page.tsx | 97 +++ .../frontend/src/app/dashboard/staff/page.tsx | 3 +- .../app/dashboard/supervisor/kids/page.tsx | 167 +++++ .../src/app/dashboard/supervisor/page.tsx | 3 + .../src/app/dashboard/user/kids/page.tsx | 213 +++++++ .../src/components/kids/ChildForm.tsx | 67 +++ .../src/components/kids/KidsEventPicker.tsx | 67 +++ .../src/components/kids/RoomBoard.tsx | 147 +++++ .../src/components/kids/StickerPanel.tsx | 37 ++ .../src/components/layout/Sidebar.tsx | 3 +- .../events/frontend/src/content/help/kids.tsx | 154 +++++ .../frontend/src/content/help/privacy.tsx | 6 +- .../frontend/src/content/help/registry.ts | 21 + apps/events/frontend/src/lib/kids.ts | 127 ++++ 22 files changed, 1784 insertions(+), 10 deletions(-) create mode 100644 apps/events/e2e/kids.spec.ts create mode 100644 apps/events/frontend/src/app/dashboard/staff/kids/page.tsx create mode 100644 apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx create mode 100644 apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx create mode 100644 apps/events/frontend/src/app/dashboard/user/kids/page.tsx create mode 100644 apps/events/frontend/src/components/kids/ChildForm.tsx create mode 100644 apps/events/frontend/src/components/kids/KidsEventPicker.tsx create mode 100644 apps/events/frontend/src/components/kids/RoomBoard.tsx create mode 100644 apps/events/frontend/src/components/kids/StickerPanel.tsx create mode 100644 apps/events/frontend/src/content/help/kids.tsx create mode 100644 apps/events/frontend/src/lib/kids.ts diff --git a/apps/events/e2e/fixtures.ts b/apps/events/e2e/fixtures.ts index 14cac2f..e80f22d 100644 --- a/apps/events/e2e/fixtures.ts +++ b/apps/events/e2e/fixtures.ts @@ -5,7 +5,7 @@ import path from "path"; export type Role = "admin" | "supervisor" | "staff" | "user"; export type Seed = { users: Record; - events: { free: string; paid: string; course: string; dropIn: string; conference: string }; + events: { free: string; paid: string; course: string; dropIn: string; conference: string; kids: string }; campuses: Record<"north" | "south", { id: string; slug: string }>; northTicketQr: string; course: { sessions: { id: string; label: string }[]; ticketId: string; qrCode: string }; diff --git a/apps/events/e2e/kids.spec.ts b/apps/events/e2e/kids.spec.ts new file mode 100644 index 0000000..ec6b9ba --- /dev/null +++ b/apps/events/e2e/kids.spec.ts @@ -0,0 +1,87 @@ +import { test, expect, seed, loginAs } from "./fixtures"; + +// Kids check-in (1.45.0): a supervisor sets it up, a parent adds a child, the desk checks the child +// in (pickup code + sticker panel), the parent sees the code, and a wrong code is refused before +// the real one checks the child out. "E2E Kids Church" is seeded hidden and on today. +test.describe.serial("kids check-in", () => { + test("a supervisor sets up the kids ticket, a room and switches it on", async ({ page }) => { + await loginAs(page, "supervisor"); + await page.goto("/dashboard/supervisor/kids"); + await page.getByRole("combobox").first().selectOption(seed().events.kids); + await page.getByRole("button", { name: /Add a free "Kids check-in" ticket/ }).click(); + await expect(page.getByLabel("Kids ticket")).not.toHaveValue(""); + await page.getByRole("button", { name: /Add "Kids rooms"/ }).click(); + await page.getByLabel("Room name").last().fill("Little Lambs"); + await page.getByLabel("Youngest age").last().fill("0"); + await page.getByLabel("Oldest age").last().fill("5"); + await page.getByLabel("Children per leader").last().fill("4"); + await page.getByRole("button", { name: "Add", exact: true }).click(); + await expect(page.getByLabel("Room name").first()).toHaveValue("Little Lambs"); + await page.getByRole("button", { name: "Switch on" }).click(); + await expect(page.getByText("Kids check-in is on")).toBeVisible(); + }); + + test("a parent adds their family and a child", async ({ page }) => { + await loginAs(page, "user"); + await page.goto("/dashboard/user/kids"); + await page.getByRole("button", { name: "Add family" }).click(); + await page.getByRole("button", { name: "Add a child" }).click(); + await page.getByLabel("First name *").fill("Lulu"); + const dob = new Date(); + dob.setFullYear(dob.getFullYear() - 3); + await page.getByLabel("Date of birth").fill(dob.toISOString().slice(0, 10)); + await page.getByLabel("Allergies").fill("Peanuts"); + await page.getByRole("button", { name: "Add child" }).click(); + await expect(page.getByText("Allergies: Peanuts")).toBeVisible(); + await expect(page.getByAltText("Family QR code")).toBeVisible(); + }); + + test("the desk checks the child in, the parent sees the code, and only the right code checks out", async ({ page, browser }) => { + await loginAs(page, "staff"); + await page.goto("/dashboard/staff/kids"); + await page.getByLabel("Event").selectOption(seed().events.kids); + await page.getByLabel("Find a family").fill("Lulu"); + await page.getByRole("button", { name: "Search" }).click(); + await page.getByRole("button", { name: /Lulu/ }).click(); + // The room is suggested from her age. + await expect(page.getByLabel("Room for Lulu")).toHaveValue(/.+/); + await page.getByRole("button", { name: "Check in", exact: true }).last().click(); + + const code = (await page.getByTestId("desk-code").textContent())!.trim(); + expect(code).toMatch(/^[A-HJ-NP-Z2-9]{4}$/); + const sticker = page.getByTestId("sticker"); + await expect(sticker).toContainText("Lulu"); + await expect(sticker).toContainText("Little Lambs"); + await expect(sticker).toContainText("ALLERGY: PEANUTS"); + + // The parent's phone shows the same code. + const parent = await browser.newPage(); + await parent.addInitScript(() => localStorage.setItem("hope_events_cookie_consent", "declined")); + await loginAs(parent, "user"); + await parent.goto("/dashboard/user/kids"); + await expect(parent.getByTestId("pickup-code")).toHaveText(code); + await parent.close(); + + // A wrong code is refused. + await page.getByRole("button", { name: "Check out" }).first().click(); + const wrong = code === "ZZZZ" ? "YYYY" : "ZZZZ"; + await page.getByLabel("Pickup code").fill(wrong); + await page.getByRole("button", { name: "Find" }).click(); + await expect(page.getByRole("alert").filter({ hasText: "doesn't match any child" })).toBeVisible(); + + // The real one checks her out. + await page.getByLabel("Pickup code").fill(code.toLowerCase()); + await page.getByRole("button", { name: "Find" }).click(); + await expect(page.getByText("Lulu", { exact: false }).first()).toBeVisible(); + await page.getByRole("button", { name: "Check out" }).last().click(); + await expect(page.getByRole("status")).toContainText("Collected: Lulu"); + }); + + test("the room screen shows the wrong-code alert", async ({ page }) => { + await loginAs(page, "staff"); + await page.goto("/dashboard/staff/kids/rooms"); + await expect(page.getByRole("alert").filter({ hasText: "Wrong pickup code" }).first()).toBeVisible(); + await page.getByRole("button", { name: "Dealt with" }).first().click(); + await expect(page.getByRole("status")).toContainText("Alert cleared"); + }); +}); diff --git a/apps/events/e2e/support/prepare-db.js b/apps/events/e2e/support/prepare-db.js index 88f9800..8671d7b 100644 --- a/apps/events/e2e/support/prepare-db.js +++ b/apps/events/e2e/support/prepare-db.js @@ -81,6 +81,13 @@ async function seed(url) { eventOptions: { create: [{ name: 'Entry', price: 0, isMainTicket: true }] }, }, }); + // Kids check-in (kids.spec.ts): on today, hidden so it doesn't change the public lists. + const kids = await prisma.event.create({ + data: { + title: 'E2E Kids Church', description: 'Kids check-in 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, + }, + }); const paid = await prisma.event.create({ data: { campusId: south.id, @@ -174,7 +181,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 }, + events: { free: free.id, paid: paid.id, course: course.id, dropIn: dropIn.id, conference: conference.id, kids: kids.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 }, diff --git a/apps/events/frontend/package-lock.json b/apps/events/frontend/package-lock.json index ddbdb1a..21bd712 100644 --- a/apps/events/frontend/package-lock.json +++ b/apps/events/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events-frontend", - "version": "1.44.0", + "version": "1.45.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events-frontend", - "version": "1.44.0", + "version": "1.45.0", "dependencies": { "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", diff --git a/apps/events/frontend/package.json b/apps/events/frontend/package.json index 71429fc..4e57544 100644 --- a/apps/events/frontend/package.json +++ b/apps/events/frontend/package.json @@ -1,6 +1,6 @@ { "name": "hope-events-frontend", - "version": "1.44.0", + "version": "1.45.0", "private": true, "scripts": { "dev": "next dev --turbopack", diff --git a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx index f2c7164..85bb2cd 100644 --- a/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/audit-log/page.tsx @@ -103,6 +103,12 @@ const ACTION_LABELS: Record = { campus_archived: "Campus archived/restored", campus_deleted: "Campus deleted", event_campus_changed: "Event moved to another campus", + user_campus_scope_changed: "Staff member limited to campuses", + kids_settings_updated: "Kids check-in settings changed", + kids_checkout_override: "Child checked out without the pickup code", + kids_wrong_code: "Wrong pickup code entered", + kids_custody_notes_changed: "Child's custody notes changed", + kids_offline_sync: "Offline kids desk synced", }; interface AuditLogEntry { diff --git a/apps/events/frontend/src/app/dashboard/admin/page.tsx b/apps/events/frontend/src/app/dashboard/admin/page.tsx index f044c68..92abeb0 100644 --- a/apps/events/frontend/src/app/dashboard/admin/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/page.tsx @@ -9,6 +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, } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; @@ -30,6 +31,8 @@ const QUICK_ACTIONS = [ { href: "/dashboard/supervisor/at-the-door", label: "At the door", description: "Walk-ins, payments, ticket printing", icon: DoorOpen }, { href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet }, { 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/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 }, diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx new file mode 100644 index 0000000..609ebf2 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/staff/kids/page.tsx @@ -0,0 +1,569 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import Link from "next/link"; +import { useAuth } from "@/hooks/useAuth"; +import { apiFetch, ApiError } from "@/lib/api"; +import { errorMessage } from "@/lib/utils"; +import { useVisiblePolling } from "@/hooks/useVisiblePolling"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { Baby, CloudOff, LogIn, LogOut, QrCode, RefreshCw, Search, UserPlus, Users } from "lucide-react"; +import { BackLink } from "@/components/shared/BackLink"; +import { QRScanner } from "@/components/qr/QRScanner"; +import { KidsEventPicker } from "@/components/kids/KidsEventPicker"; +import { RoomBoard } from "@/components/kids/RoomBoard"; +import { StickerPanel } from "@/components/kids/StickerPanel"; +import { ChildForm, type ChildInput } from "@/components/kids/ChildForm"; +import { + FAMILY_QR_PREFIX, QR_PREFIX, deviceId, loadOffline, offlineCheckIn, saveOffline, stickerAlert, suggestRoom, + type CheckInResult, type KidsBoard, type KidsFamily, type OfflineState, +} from "@/lib/kids"; + +type Tab = "in" | "out" | "rooms"; +type Msg = { type: "ok" | "err"; text: string } | null; +type CodeLookup = { + code: string | null; found: boolean; + family?: { name: string; parents: { userId: string; name: string; phone: string | null }[]; adults: { id: string; name: string; relationship: string | null }[] } | null; + children: { id: string; name: string; room: { id: string; name: string } | null; checkedOutAt: string | null; collectedBy: string | null }[]; +}; + +const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; +const tabCls = (on: boolean) => `px-4 py-2 rounded-lg text-sm font-medium inline-flex items-center gap-1.5 ${on ? "bg-brand-600 text-white" : "bg-white border text-gray-700"}`; + +/** The kids check-in desk: find the family, check children in (pickup code + sticker panel), check them out by code. */ +export default function KidsDeskPage() { + const { token, user } = useAuth(); + const isSupervisor = user?.role === "admin" || user?.role === "supervisor"; + const [eventId, setEventId] = useState(""); + const [sessionId, setSessionId] = useState(""); + const [tab, setTab] = useState("in"); + const [board, setBoard] = useState(null); + const [boardError, setBoardError] = useState(null); + const [msg, setMsg] = useDismissingState(null, 9000); + const [busy, setBusy] = useState(false); + + // Offline + const [offline, setOffline] = useState(null); + const [working, setWorking] = useState<"online" | "offline">("online"); + + // Check in + const [q, setQ] = useState(""); + const [results, setResults] = useState(null); + const [family, setFamily] = useState(null); + const [picked, setPicked] = useState>({}); // childId → roomId + const [sendTo, setSendTo] = useState(""); + const [result, setResult] = useState(null); + const [scanning, setScanning] = useState(false); + const [newFamily, setNewFamily] = useState<{ name: string; parentName: string; phone: string; email: string } | null>(null); + const [addingChild, setAddingChild] = useState(false); + + // Check out + const [code, setCode] = useState(""); + const [lookup, setLookup] = useState(null); + const [outPicked, setOutPicked] = useState>({}); + const [collectedBy, setCollectedBy] = useState(""); + const [wrongCode, setWrongCode] = useState(null); + + const qs = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""; + + const loadBoard = useCallback(async (log = false) => { + if (!token || !eventId || working === "offline") return; + try { + const data = await apiFetch(`/api/kids/events/${eventId}/board${qs}${log ? `${qs ? "&" : "?"}log=1` : ""}`, { authToken: token }); + setBoard(data); + setBoardError(null); + } catch (e) { + setBoard(null); + setBoardError(errorMessage(e) || "Could not load the desk"); + } + }, [token, eventId, qs, working]); + + useEffect(() => { + setBoard(null); + setFamily(null); + setResult(null); + setOffline(eventId ? loadOffline(eventId) : null); + loadBoard(true); + }, [eventId, sessionId]); // eslint-disable-line react-hooks/exhaustive-deps + useVisiblePolling(() => { loadBoard(); }, 10000, !!token && !!eventId && working === "online"); + + // Go offline by itself when the browser loses its connection (if an offline list is ready). + useEffect(() => { + const down = () => { if (loadOffline(eventId)) setWorking("offline"); }; + window.addEventListener("offline", down); + return () => window.removeEventListener("offline", down); + }, [eventId]); + + const rooms = useMemo(() => (working === "offline" ? offline?.snapshot.rooms : board?.rooms) || [], [working, offline, board]); + const inNow = useMemo(() => { + const m = new Map(); // childId → room name + const list = working === "offline" ? offline?.snapshot.checkIns : board?.checkIns; + for (const c of list || []) if (!c.checkedOutAt && c.childId) m.set(c.childId, rooms.find(r => r.id === c.roomId)?.name || ""); + if (working === "offline") for (const c of offline?.checkIns || []) if (!offline!.checkOuts.some(o => o.clientId === c.clientId)) m.set(c.childId, c.roomName); + return m; + }, [working, offline, board, rooms]); + + const fail = (e: unknown, fallback: string) => { + // A dropped connection with an offline list ready: switch over instead of failing. + if (!(e instanceof ApiError) && loadOffline(eventId)) { + setWorking("offline"); + setOffline(loadOffline(eventId)); + setMsg({ type: "err", text: "No connection — switched to the offline list. Try that again." }); + return; + } + setMsg({ type: "err", text: errorMessage(e) || fallback }); + }; + + // ─── Families ─────────────────────────────────────────────────────────────── + + const chooseFamily = (f: KidsFamily) => { + setFamily(f); + setResults(null); + setResult(null); + setSendTo(""); + setAddingChild(false); + const extra: Record = {}; + const next: Record = {}; + for (const c of f.children) { + if (inNow.has(c.id)) continue; + const room = suggestRoom(rooms, c.age, extra); + if (room) { next[c.id] = room.id; extra[room.id] = (extra[room.id] || 0) + 1; } + } + setPicked(next); + }; + + const search = async (e?: React.FormEvent) => { + e?.preventDefault(); + const term = q.trim(); + if (term.length < 2) return; + if (working === "offline") { + const t = term.toLowerCase(), digits = term.replace(/\D/g, ""); + setResults((offline?.snapshot.families || []).filter(f => + f.name.toLowerCase().includes(t) + || f.children.some(c => c.name.toLowerCase().includes(t)) + || f.parents.some(p => p.name.toLowerCase().includes(t) || (digits.length >= 6 && (p.phone || "").replace(/\D/g, "").slice(-9).includes(digits.slice(-9))))).slice(0, 20)); + return; + } + try { + setResults(await apiFetch(`/api/kids/events/${eventId}/families?q=${encodeURIComponent(term)}`, { authToken: token })); + } catch (err) { + fail(err, "Search failed"); + } + }; + + const onScan = async (text: string) => { + setScanning(false); + const t = text.trim(); + if (t.toUpperCase().startsWith(QR_PREFIX)) { + setTab("out"); + setCode(t.slice(QR_PREFIX.length)); + lookUpCode(t.slice(QR_PREFIX.length)); + return; + } + if (!t.toUpperCase().startsWith(FAMILY_QR_PREFIX)) { setMsg({ type: "err", text: "That isn't a family or pickup QR code." }); return; } + if (working === "offline") { setMsg({ type: "err", text: "Family QR codes need a connection — search by name or phone instead." }); return; } + try { + chooseFamily(await apiFetch(`/api/kids/events/${eventId}/families/qr/${encodeURIComponent(t.slice(FAMILY_QR_PREFIX.length))}`, { authToken: token })); + } catch (err) { + fail(err, "Family not found"); + } + }; + + const createFamily = async (child: ChildInput) => { + if (!newFamily) return; + setBusy(true); + try { + const f = await apiFetch(`/api/kids/events/${eventId}/families`, { + method: "POST", authToken: token, + body: { name: newFamily.name, parent: { name: newFamily.parentName, phone: newFamily.phone, email: newFamily.email }, children: [child] }, + }); + setNewFamily(null); + chooseFamily(f); + setMsg({ type: "ok", text: `${f.name} added.` }); + } catch (err) { + fail(err, "Could not add the family"); + } finally { + setBusy(false); + } + }; + + const addChild = async (child: ChildInput) => { + if (!family) return; + setBusy(true); + try { + await apiFetch(`/api/kids/events/${eventId}/families/${family.id}/children`, { method: "POST", authToken: token, body: child }); + chooseFamily(await apiFetch(`/api/kids/events/${eventId}/families/${family.id}`, { authToken: token })); + setMsg({ type: "ok", text: `${child.firstName} added.` }); + } catch (err) { + fail(err, "Could not add the child"); + } finally { + setBusy(false); + } + }; + + // ─── Check in ─────────────────────────────────────────────────────────────── + + const doCheckIn = async () => { + if (!family) return; + const children = Object.entries(picked).filter(([, roomId]) => roomId).map(([childId, roomId]) => ({ childId, roomId })); + if (!children.length) { setMsg({ type: "err", text: "Tick the children to check in." }); return; } + if (working === "offline" && offline) { + try { + const picks = children.map(p => ({ child: family.children.find(c => c.id === p.childId)!, room: rooms.find(r => r.id === p.roomId)! })); + const out = offlineCheckIn(offline, family, picks); + setOffline(out.state); + saveOffline(eventId, out.state); + setResult({ + code: out.code, qr: QR_PREFIX + out.code, occasion: offline.snapshot.occasion, family: { id: family.id, name: family.name }, + checkIns: picks.map(p => ({ id: p.child.id, name: p.child.name, firstName: p.child.firstName, room: { id: p.room.id, name: p.room.name }, already: false, sticker: stickerAlert(p.child.allergies, p.child.hasMedical) })), + }); + setMsg({ type: "ok", text: "Checked in on this device — tell the parent the code (no message is sent while offline)." }); + } catch (err) { + setMsg({ type: "err", text: errorMessage(err) || "Could not check in offline" }); + } + return; + } + setBusy(true); + try { + const r = await apiFetch(`/api/kids/events/${eventId}/check-in`, { + method: "POST", authToken: token, body: { familyId: family.id, sessionId: sessionId || undefined, children, sendToAdultId: sendTo || undefined }, + }); + setResult(r); + loadBoard(); + } catch (err) { + fail(err, "Check-in failed"); + } finally { + setBusy(false); + } + }; + + // ─── Check out ────────────────────────────────────────────────────────────── + + const offlineLookup = (raw: string): CodeLookup => { + const c = raw.trim().toUpperCase().replace(/[\s-]/g, ""); + const mine = (offline?.checkIns || []).filter(x => x.code === c); + const fam = offline?.snapshot.families.find(f => f.id === mine[0]?.familyId); + return { + code: c, found: mine.length > 0, + family: fam ? { name: fam.name, parents: fam.parents, adults: fam.adults } : null, + children: mine.map(x => { + const o = offline!.checkOuts.find(k => k.clientId === x.clientId); + return { id: x.clientId, name: x.name, room: { id: x.roomId, name: x.roomName }, checkedOutAt: o?.at || null, collectedBy: o?.collectedBy || null }; + }), + }; + }; + + const lookUpCode = async (raw = code) => { + setWrongCode(null); + setLookup(null); + if (!raw.trim()) return; + let l: CodeLookup; + if (working === "offline") { + l = offlineLookup(raw); + if (!l.found) { + setWrongCode(offline?.snapshot.checkIns.some(c => c.code === raw.trim().toUpperCase()) + ? "This code was given out before going offline. Check these children out on a connected device, or use \"Without code\" there." + : "That code doesn't match any child checked in on this device."); + return; + } + } else { + try { + l = await apiFetch(`/api/kids/events/${eventId}/code/${encodeURIComponent(raw.trim())}${qs}`, { authToken: token }); + } catch (err) { + fail(err, "Lookup failed"); + return; + } + if (!l.found) { + // Record the wrong code (alerts the rooms) through the check-out call. + try { + await apiFetch(`/api/kids/events/${eventId}/check-out`, { method: "POST", authToken: token, body: { code: raw, collectedBy: "", sessionId: sessionId || undefined } }); + } catch (err) { + setWrongCode(errorMessage(err) || "Wrong code"); + } + loadBoard(); + return; + } + } + setLookup(l); + setOutPicked(Object.fromEntries(l.children.filter(c => !c.checkedOutAt).map(c => [c.id, true]))); + setCollectedBy(l.family?.parents[0]?.name || ""); + }; + + const doCheckOut = async () => { + if (!lookup) return; + const ids = Object.entries(outPicked).filter(([, on]) => on).map(([id]) => id); + if (!ids.length) { setMsg({ type: "err", text: "Tick the children being collected." }); return; } + if (!collectedBy.trim()) { setMsg({ type: "err", text: "Enter who is collecting." }); return; } + if (working === "offline" && offline) { + const at = new Date().toISOString(); + const next = { ...offline, checkOuts: [...offline.checkOuts, ...ids.map(clientId => ({ clientId, collectedBy, at }))] }; + setOffline(next); + saveOffline(eventId, next); + setMsg({ type: "ok", text: `Checked out on this device: ${lookup.children.filter(c => ids.includes(c.id)).map(c => c.name).join(", ")}.` }); + setLookup(null); + setCode(""); + return; + } + setBusy(true); + try { + const r = await apiFetch<{ checkedOut: { name: string }[] }>(`/api/kids/events/${eventId}/check-out`, { + method: "POST", authToken: token, body: { code: lookup.code, checkInIds: ids, collectedBy, sessionId: sessionId || undefined }, + }); + setMsg({ type: "ok", text: `Collected: ${r.checkedOut.map(c => c.name).join(", ")}.` }); + setLookup(null); + setCode(""); + loadBoard(); + } catch (err) { + fail(err, "Check-out failed"); + } finally { + setBusy(false); + } + }; + + // ─── Offline list ─────────────────────────────────────────────────────────── + + const getReady = async () => { + setBusy(true); + try { + const snapshot = await apiFetch(`/api/kids/events/${eventId}/offline?deviceId=${encodeURIComponent(deviceId())}${sessionId ? `&sessionId=${encodeURIComponent(sessionId)}` : ""}`, { authToken: token }); + const prev = loadOffline(eventId); + const sameOccasion = prev?.snapshot.occasion === snapshot.occasion; + const state: OfflineState = { + snapshot, + familyCodes: sameOccasion ? prev!.familyCodes : {}, + checkIns: sameOccasion ? prev!.checkIns : [], + checkOuts: sameOccasion ? prev!.checkOuts : [], + }; + saveOffline(eventId, state); + setOffline(state); + setMsg({ type: "ok", text: `Offline list ready: ${snapshot.families.length} families, ${snapshot.codes.length} pickup codes for this device.` }); + } catch (err) { + fail(err, "Could not download the offline list"); + } finally { + setBusy(false); + } + }; + + const sync = async () => { + if (!offline) return; + setBusy(true); + try { + const r = await apiFetch<{ checkedIn: number; checkedOut: number; conflicts: { clientId: string | null; message: string }[] }>(`/api/kids/events/${eventId}/sync`, { + method: "POST", authToken: token, + body: { deviceId: deviceId(), occasion: offline.snapshot.occasion, checkIns: offline.checkIns, checkOuts: offline.checkOuts }, + }); + const next: OfflineState = { ...offline, checkIns: [], checkOuts: [] }; + saveOffline(eventId, next); + setOffline(next); + setWorking("online"); + setMsg({ + type: r.conflicts.length ? "err" : "ok", + text: `Synced: ${r.checkedIn} checked in, ${r.checkedOut} checked out.${r.conflicts.length ? ` Check: ${r.conflicts.map(c => c.message).join(" ")}` : ""}`, + }); + loadBoard(); + } catch (err) { + setMsg({ type: "err", text: errorMessage(err) || "Sync failed — still offline? Your check-ins are kept on this device." }); + } finally { + setBusy(false); + } + }; + + const queued = (offline?.checkIns.length || 0) + (offline?.checkOuts.length || 0); + const ready = working === "offline" ? !!offline : !!board; + + return ( +
+
+
+
+
+ +

Kids check-in

+

{board?.sessionLabel ? `${board.sessionLabel} · ` : ""}Check children in and out with pickup codes

+
+
+ Room screen +
+ + { setEventId(id); setSessionId(sid); }} /> + + {eventId && ( +
+ + {working === "offline" ? ( + <> + Working offline + {queued} change{queued === 1 ? "" : "s"} waiting to sync · {Math.max(0, (offline?.snapshot.codes.length || 0) - Object.keys(offline?.familyCodes || {}).length)} codes left + + + ) : ( + <> + {offline ? `Offline list from ${new Date(offline.snapshot.downloadedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}` : "Wi-Fi unreliable? Download the list first."} + {queued > 0 && } + + {offline && } + + )} +
+ )} + + {boardError && working === "online" &&
{boardError}
} + {msg &&
{msg.text}
} + + {ready && ( + <> +
+ + + {working === "online" && } +
+ + {(tab === "in" || tab === "out") && ( +
+ + {scanning &&
} +
+ )} + + {tab === "in" && ( + result ? ( +
+ ({ id: c.id, firstName: c.firstName, room: c.room?.name || null, sticker: c.sticker, already: c.already }))} /> + +
+ ) : ( +
+
+
+ setQ(e.target.value)} aria-label="Find a family" /> + +
+ {results && ( +
    + {results.map(f => ( +
  • + +
  • + ))} + {!results.length &&
  • No family found.
  • } +
+ )} + {working === "online" && !newFamily && ( + + )} + {newFamily && ( +
+
New family
+ setNewFamily({ ...newFamily, parentName: e.target.value })} /> +
+ setNewFamily({ ...newFamily, phone: e.target.value })} /> + setNewFamily({ ...newFamily, email: e.target.value })} /> +
+ setNewFamily({ ...newFamily, name: e.target.value })} /> +
First child:
+ setNewFamily(null)} saveLabel="Add family" /> +
+ )} +
+ + {family && ( +
+

{family.name}

+
{family.parents.map(p => `${p.name}${p.phone ? ` · ${p.phone}` : ""}`).join(" — ")}
+
    + {family.children.map(c => { + const inRoom = inNow.get(c.id); + return ( +
  • + + {inRoom !== undefined ? In — {inRoom} : picked[c.id] ? ( + + ) : null} +
  • + ); + })} +
+ {working === "online" && (addingChild ? ( +
setAddingChild(false)} saveLabel="Add child" />
+ ) : ( + + ))} + {working === "online" && family.adults.some(a => a.phone) && ( + + )} + +
+ )} +
+ ) + )} + + {tab === "out" && ( +
+
{ e.preventDefault(); lookUpCode(); }} className="flex gap-2"> + setCode(e.target.value)} maxLength={10} aria-label="Pickup code" /> + +
+ {wrongCode &&
{wrongCode}
} + {lookup && ( +
+ {lookup.family && ( +
+
{lookup.family.name}
+
Parents: {lookup.family.parents.map(p => p.name).join(", ") || "—"}
+ {lookup.family.adults.length > 0 &&
May also collect: {lookup.family.adults.map(a => `${a.name}${a.relationship ? ` (${a.relationship})` : ""}`).join(", ")}
} +
+ )} +
    + {lookup.children.map(c => { + const custody = board?.checkIns.find(b => b.id === c.id)?.custodyNotes; + return ( +
  • + + {custody &&
    Custody: {custody}
    } +
  • + ); + })} +
+ + +
+ )} +
+ )} + + {tab === "rooms" && board && working === "online" && ( + loadBoard()} onMessage={setMsg} /> + )} + + )} +
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx new file mode 100644 index 0000000..454cf3c --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/staff/kids/rooms/page.tsx @@ -0,0 +1,97 @@ +"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 { useVisiblePolling } from "@/hooks/useVisiblePolling"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { Users } from "lucide-react"; +import { BackLink } from "@/components/shared/BackLink"; +import { KidsEventPicker } from "@/components/kids/KidsEventPicker"; +import { RoomBoard, RoomStatusBadges } from "@/components/kids/RoomBoard"; +import type { KidsBoard } from "@/lib/kids"; + +const ROOM_KEY = "hope_events_kids_room"; + +/** A kids room's screen: the children in it, allergies and custody notes, "I'm on duty", alerts. */ +export default function KidsRoomsPage() { + const { token, user } = useAuth(); + const [eventId, setEventId] = useState(""); + const [sessionId, setSessionId] = useState(""); + const [roomId, setRoomId] = useState(""); + const [board, setBoard] = useState(null); + const [error, setError] = useState(null); + const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); + + useEffect(() => { try { setRoomId(localStorage.getItem(ROOM_KEY) || ""); } catch { /* ignore */ } }, []); + + const qs = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""; + const load = useCallback(async (log = false) => { + if (!token || !eventId) return; + try { + setBoard(await apiFetch(`/api/kids/events/${eventId}/board${qs}${log ? `${qs ? "&" : "?"}log=1` : ""}`, { authToken: token })); + setError(null); + } catch (e) { + setBoard(null); + setError(errorMessage(e) || "Could not load the rooms"); + } + }, [token, eventId, qs]); + + useEffect(() => { load(true); }, [load]); + useVisiblePolling(() => { load(); }, 5000, !!token && !!eventId); + + const pickRoom = (id: string) => { + setRoomId(id); + try { localStorage.setItem(ROOM_KEY, id); } catch { /* ignore */ } + }; + const room = board?.rooms.find(r => r.id === roomId) || null; + const onDuty = !!room && !!user && room.leaderIds.includes(user.id); + const duty = async (on: boolean) => { + try { + await apiFetch(`/api/kids/events/${eventId}/duty`, { method: "POST", authToken: token, body: { roomId, on, sessionId: sessionId || undefined } }); + load(); + } catch (e) { + setMsg({ type: "err", text: errorMessage(e) || "Could not change duty" }); + } + }; + + return ( +
+
+
+
+ +

Kids rooms

+

{board?.sessionLabel ? `${board.sessionLabel} · ` : ""}Who is in each room right now

+
+
+ +
+ { setEventId(id); setSessionId(sid); }} /> + {board && ( + + )} +
+ + {room && ( +
+ + +
+ )} + + {error &&
{error}
} + {msg &&
{msg.text}
} + {board &&
load()} onMessage={setMsg} />
} +
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/staff/page.tsx b/apps/events/frontend/src/app/dashboard/staff/page.tsx index ec62e3b..f87f4a0 100644 --- a/apps/events/frontend/src/app/dashboard/staff/page.tsx +++ b/apps/events/frontend/src/app/dashboard/staff/page.tsx @@ -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 } from "lucide-react"; +import { QrCode, Ticket, Activity, UserCheck, Clock, Users, ClipboardCheck, Baby } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; import type { DashboardStats, RecentScan, ScanStats } from "@/types"; @@ -16,6 +16,7 @@ const QUICK_ACTIONS = [ { href: "/dashboard/staff/ticket-scanning", label: "Scan tickets", description: "Use your device camera to validate tickets", icon: QrCode }, { 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/supervisor/attendance", label: "Attendance", description: "Who came to each session of an event", icon: ClipboardCheck }, ] as const; diff --git a/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx new file mode 100644 index 0000000..1632e67 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/supervisor/kids/page.tsx @@ -0,0 +1,167 @@ +"use client"; + +import React, { useCallback, useEffect, useState } from "react"; +import Link from "next/link"; +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 { Baby, Plus, Trash2 } from "lucide-react"; +import { BackLink } from "@/components/shared/BackLink"; + +type Room = { id: string; name: string; capacity: number | null; minAge: number | null; maxAge: number | null; ratio: number | null; order: number }; +type Settings = { + event: { id: string; title: string; scheduleType: string; kidsCheckIn: boolean; kidsOptionId: string | null; kidsRoomSetId: string | null }; + options: { id: string; name: string; price: number }[]; + sets: { id: string; name: string; groups: Room[] }[]; +}; +type SetupEvent = { id: string; title: string; startDate: string; kidsCheckIn: boolean }; + +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 num = (v: string) => (v.trim() === "" ? null : Number(v)); + +/** Supervisor → Kids check-in setup: switch it on for an event, choose the kids ticket and the rooms. */ +export default function KidsSetupPage() { + const { token } = useAuth(); + const [events, setEvents] = useState([]); + const [eventId, setEventId] = useState(""); + const [s, setS] = useState(null); + const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null); + const [busy, setBusy] = useState(false); + const [draft, setDraft] = useState>({}); + const [newRoom, setNewRoom] = useState({ name: "", minAge: "", maxAge: "", capacity: "", ratio: "" }); + + useEffect(() => { + if (!token) return; + apiFetch("/api/kids/setup-events", { authToken: token }).then(setEvents).catch(e => setMsg({ type: "err", text: errorMessage(e) || "Could not load events" })); + }, [token, setMsg]); + + const load = useCallback(async () => { + if (!token || !eventId) return; + try { + const data = await apiFetch(`/api/kids/events/${eventId}/settings`, { authToken: token }); + setS(data); + const set = data.sets.find(x => x.id === data.event.kidsRoomSetId); + setDraft(Object.fromEntries((set?.groups || []).map(g => [g.id, { name: g.name, minAge: g.minAge?.toString() ?? "", maxAge: g.maxAge?.toString() ?? "", capacity: g.capacity?.toString() ?? "", ratio: g.ratio?.toString() ?? "" }]))); + } catch (e) { + setMsg({ type: "err", text: errorMessage(e) || "Could not load the settings" }); + } + }, [token, eventId, setMsg]); + useEffect(() => { setS(null); load(); }, [load]); + + const run = async (fn: () => Promise, ok: string) => { + setBusy(true); + try { + await fn(); + setMsg({ type: "ok", text: ok }); + await load(); + return true; + } catch (e) { + setMsg({ type: "err", text: errorMessage(e) || "Something went wrong" }); + return false; + } finally { + setBusy(false); + } + }; + const save = (body: Record, ok = "Saved.") => run(() => apiFetch(`/api/kids/events/${eventId}/settings`, { method: "PUT", authToken: token, body }), ok); + + const rooms = s?.sets.find(x => x.id === s.event.kidsRoomSetId)?.groups || []; + const roomBody = (d: { name: string; minAge: string; maxAge: string; capacity: string; ratio: string }) => ({ name: d.name, minAge: num(d.minAge), maxAge: num(d.maxAge), capacity: num(d.capacity), ratio: num(d.ratio) }); + const addRoom = () => s?.event.kidsRoomSetId && run( + () => apiFetch(`/api/allocations/sets/${s.event.kidsRoomSetId}/groups`, { method: "POST", authToken: token, body: roomBody(newRoom) }), + "Room added.", + ).then(ok => { if (ok) setNewRoom({ name: "", minAge: "", maxAge: "", capacity: "", ratio: "" }); }); + const saveRoom = (id: string) => run(() => apiFetch(`/api/allocations/groups/${id}`, { method: "PUT", authToken: token, body: roomBody(draft[id]) }), "Room saved."); + const deleteRoom = (r: Room) => confirm(`Delete ${r.name}? Children checked in to it now will need a new room.`) && run(() => apiFetch(`/api/allocations/groups/${r.id}`, { method: "DELETE", authToken: token }), "Room deleted."); + + const roomRow = (d: { name: string; minAge: string; maxAge: string; capacity: string; ratio: string }, set: (v: typeof d) => void) => ( + <> + set({ ...d, name: e.target.value })} placeholder="Toddlers" /> + set({ ...d, minAge: e.target.value })} placeholder="from" /> + set({ ...d, maxAge: e.target.value })} placeholder="to" /> + set({ ...d, capacity: e.target.value })} placeholder="—" /> + set({ ...d, ratio: e.target.value })} placeholder="—" /> + + ); + + return ( +
+
+
+
+ +

Kids check-in setup

+

Switch kids check-in on for an event and set up its rooms

+
+
+ + + + {msg &&
{msg.text}
} + + {s && ( +
+
+

1. Kids ticket

+

Each child gets a free place on this ticket the first time they're checked in, so they appear on the attendance register and reports. Parents don't buy it.

+
+ + {!s.event.kidsOptionId && } +
+
+ +
+

2. Rooms

+
+ + {!s.event.kidsRoomSetId && } +
+ {s.event.kidsRoomSetId && ( +
+
+ RoomAge fromAge toCapacityPer leader + {rooms.map(r => draft[r.id] && ( + + {roomRow(draft[r.id], v => setDraft(d => ({ ...d, [r.id]: v })))} + + + + + + ))} + {roomRow(newRoom, setNewRoom)} + +
+

Ages are whole years (both included). The desk suggests the room with the narrowest age range that fits and isn't full. "Per leader" is the ratio: the room screen warns when there are more children than the leaders on duty can look after.

+
+ )} +
+ +
+
+

3. Switch on

+

{s.event.kidsCheckIn ? "Kids check-in is on — staff use Staff → Kids check-in." : "Staff can check children in once this is on."}

+
+ + {s.event.kidsCheckIn && Open the desk} +
+
+ )} +
+ ); +} diff --git a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx index 942d02e..291dd8b 100644 --- a/apps/events/frontend/src/app/dashboard/supervisor/page.tsx +++ b/apps/events/frontend/src/app/dashboard/supervisor/page.tsx @@ -9,6 +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, } from "lucide-react"; import { StatCard, StatCardRow } from "@/components/shared/StatCard"; import { QuickActionTile, QuickActionGrid } from "@/components/shared/QuickActionTile"; @@ -27,6 +28,8 @@ const QUICK_ACTIONS = [ { href: "/dashboard/supervisor/events", label: "Manage events", description: "Create, edit, and update ticket types", icon: Calendar }, { href: "/dashboard/supervisor/payments", label: "Payments & donations", description: "Manual payments and assignment", icon: Wallet }, { 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/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 }, diff --git a/apps/events/frontend/src/app/dashboard/user/kids/page.tsx b/apps/events/frontend/src/app/dashboard/user/kids/page.tsx new file mode 100644 index 0000000..5583bf5 --- /dev/null +++ b/apps/events/frontend/src/app/dashboard/user/kids/page.tsx @@ -0,0 +1,213 @@ +"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 { useVisiblePolling } from "@/hooks/useVisiblePolling"; +import { useDismissingState } from "@/hooks/useDismissingState"; +import { Baby, BellRing, Pencil, Plus, QrCode, Trash2, UserCheck } from "lucide-react"; +import { BackLink } from "@/components/shared/BackLink"; +import { QrImage } from "@/components/shared/QrImage"; +import { ChildForm, type ChildInput } from "@/components/kids/ChildForm"; +import { FAMILY_QR_PREFIX, type KidsAdult, type KidsChild, type KidsFamily } from "@/lib/kids"; + +type ActiveCode = { code: string; qr: string; event: { id: string; title: string }; children: { name: string; room: string | null; checkedInAt: string }[] }; +type Mine = { family: KidsFamily | null; qrToken: string | null; codes: ActiveCode[]; pages: { id: string; message: string; createdAt: string }[] }; +type Msg = { type: "ok" | "err"; text: string } | null; + +const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; + +/** My account → Kids: the family's children, authorised adults, family QR and live pickup codes. */ +export default function MyKidsPage() { + const { token, user } = useAuth(); + const [data, setData] = useState(null); + const [msg, setMsg] = useDismissingState(null); + const [busy, setBusy] = useState(false); + const [editing, setEditing] = useState(null); + const [adultForm, setAdultForm] = useState<{ id?: string; name: string; phone: string; relationship: string } | null>(null); + const [familyName, setFamilyName] = useState(""); + + const load = useCallback(async () => { + if (!token) return; + try { + setData(await apiFetch("/api/kids/me", { authToken: token })); + } catch (e) { + setMsg({ type: "err", text: errorMessage(e) || "Could not load your family" }); + } + }, [token, setMsg]); + + useEffect(() => { load(); }, [load]); + // Codes and pages change while children are checked in. + useVisiblePolling(() => { if (data?.codes.length) load(); }, 15000, !!token); + + const call = async (fn: () => Promise, ok: string) => { + setBusy(true); + try { + await fn(); + setMsg({ type: "ok", text: ok }); + await load(); + return true; + } catch (e) { + setMsg({ type: "err", text: errorMessage(e) || "Something went wrong" }); + return false; + } finally { + setBusy(false); + } + }; + + const startFamily = () => call(() => apiFetch("/api/kids/me", { method: "POST", authToken: token, body: { name: familyName || `${user?.name?.split(" ").slice(-1)[0] || "My"} family` } }), "Family added — now add your children."); + const saveChild = (child: KidsChild | null, input: ChildInput) => call( + () => apiFetch(child ? `/api/kids/me/children/${child.id}` : "/api/kids/me/children", { method: child ? "PUT" : "POST", authToken: token, body: input }), + child ? "Saved." : "Child added.", + ).then(ok => { if (ok) setEditing(null); }); + const removeChild = (child: KidsChild) => { + if (!confirm(`Remove ${child.firstName}? Their details are deleted.`)) return; + call(() => apiFetch(`/api/kids/me/children/${child.id}`, { method: "DELETE", authToken: token }), "Removed."); + }; + const saveAdult = () => adultForm && call( + () => apiFetch(adultForm.id ? `/api/kids/me/adults/${adultForm.id}` : "/api/kids/me/adults", { method: adultForm.id ? "PUT" : "POST", authToken: token, body: adultForm }), + "Saved.", + ).then(ok => { if (ok) setAdultForm(null); }); + const removeAdult = (a: KidsAdult) => { + if (!confirm(`Remove ${a.name} from your authorised adults?`)) return; + call(() => apiFetch(`/api/kids/me/adults/${a.id}`, { method: "DELETE", authToken: token }), "Removed."); + }; + const share = async (c: ActiveCode) => { + const text = `Pickup code for ${c.children.map(k => k.name.split(" ")[0]).join(", ")} at ${c.event.title}: ${c.code}`; + try { + if (navigator.share) await navigator.share({ text }); + else { await navigator.clipboard.writeText(text); setMsg({ type: "ok", text: "Copied — paste it into a message to whoever is collecting." }); } + } catch { /* cancelled */ } + }; + + const family = data?.family; + return ( +
+
+
+
+ +

Kids

+

Your children for kids check-in, and their pickup codes

+
+
+ {msg &&
{msg.text}
} + + {data?.pages.map(p => ( +
+ +
{p.message}
{new Date(p.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
+
+ ))} + + {data?.codes.map(c => ( +
+
Checked in · {c.event.title}
+
+ +
+
Pickup code
+
{c.code}
+
    {c.children.map(k =>
  • {k.name}{k.room ? ` — ${k.room}` : ""}
  • )}
+
+
+

Show this code or QR to collect your children. Anyone you give the code to can collect them.

+ +
+ ))} + + {data && !family && ( +
+

Add your family

+

Add your children once, and the kids desk can check them in quickly every time — scan your family QR code or give your phone number.

+
+ setFamilyName(e.target.value)} /> + +
+
+ )} + + {family && ( + <> +
+
+

{family.name}

+ Parents: {family.parents.map(p => p.name).join(", ")} +
+
+ {family.children.map(c => ( +
+ {editing === c.id ? ( + saveChild(c, v)} onCancel={() => setEditing(null)} /> + ) : ( +
+
+
{c.name}{c.age != null && · {c.age} yrs}
+
+ {c.allergies && Allergies: {c.allergies}} + {c.hasMedical && Medical notes ✓} + {c.hasCustody && Custody notes ✓} + {!c.allergies && !c.hasMedical && !c.dateOfBirth && Add a date of birth so the right room is suggested} +
+
+
+ + +
+
+ )} +
+ ))} + {editing === "new" ? ( +
saveChild(null, v)} onCancel={() => setEditing(null)} saveLabel="Add child" />
+ ) : ( + + )} +
+
+ +
+

Authorised adults

+

People who may collect your children (grandparents, friends). They don't need an account — the room leader sees this list, and the desk can send them the pickup code.

+
    + {family.adults.map(a => ( +
  • + {a.name}{a.relationship ? ` (${a.relationship})` : ""}{a.phone ? ` · ${a.phone}` : ""} + + + + +
  • + ))} + {!family.adults.length &&
  • Nobody yet.
  • } +
+ {adultForm ? ( +
+ setAdultForm({ ...adultForm, name: e.target.value })} /> + setAdultForm({ ...adultForm, phone: e.target.value })} /> + setAdultForm({ ...adultForm, relationship: e.target.value })} /> +
+ + +
+
+ ) : ( + + )} +
+ + {data?.qrToken && ( +
+ +
+
Family QR code
+ Show this at the kids desk to find your family quickly. It only finds your family — it doesn't collect children; that needs the pickup code. +
+
+ )} + + )} +
+ ); +} diff --git a/apps/events/frontend/src/components/kids/ChildForm.tsx b/apps/events/frontend/src/components/kids/ChildForm.tsx new file mode 100644 index 0000000..55f1912 --- /dev/null +++ b/apps/events/frontend/src/components/kids/ChildForm.tsx @@ -0,0 +1,67 @@ +"use client"; + +import React, { useState } from "react"; +import type { KidsChild } from "@/lib/kids"; + +export type ChildInput = { + firstName: string; lastName: string; dateOfBirth: string; gender: string; + allergies: string; medicalNotes: string; custodyNotes?: string; +}; + +const inputCls = "w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500"; + +export function childToInput(c?: KidsChild | null): ChildInput { + return { + firstName: c?.firstName || "", lastName: c?.lastName || "", + dateOfBirth: c?.dateOfBirth ? c.dateOfBirth.slice(0, 10) : "", gender: c?.gender || "", + allergies: c?.allergies || "", medicalNotes: c?.medicalNotes || "", custodyNotes: c?.custodyNotes || "", + }; +} + +type Props = { + initial?: KidsChild | null; + /** Show the custody notes box (parents, supervisors and admins). */ + custody: boolean; + busy?: boolean; + onSave: (input: ChildInput) => void; + onCancel?: () => void; + saveLabel?: string; +}; + +/** Add or change a child: name, date of birth, allergies, medical and (optionally) custody notes. */ +export function ChildForm({ initial, custody, busy, onSave, onCancel, saveLabel = "Save" }: Props) { + const [v, setV] = useState(() => childToInput(initial)); + const set = (k: keyof ChildInput) => (e: React.ChangeEvent) => setV(prev => ({ ...prev, [k]: e.target.value })); + return ( +
{ + e.preventDefault(); + const out = { ...v }; + if (!custody) delete out.custodyNotes; + onSave(out); + }} + > +
+ + + + +
+ +