Kids check-in: desk, room screen, setup and parent pages, help, e2e
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,7 @@ import path from "path";
|
||||
export type Role = "admin" | "supervisor" | "staff" | "user";
|
||||
export type Seed = {
|
||||
users: Record<Role, { id: string; name: string; email: string; token: string }>;
|
||||
events: { free: string; paid: string; course: string; dropIn: string; conference: string };
|
||||
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 };
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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 },
|
||||
|
||||
Generated
+2
-2
@@ -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",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "hope-events-frontend",
|
||||
"version": "1.44.0",
|
||||
"version": "1.45.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
|
||||
@@ -103,6 +103,12 @@ const ACTION_LABELS: Record<string, string> = {
|
||||
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 {
|
||||
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<Tab>("in");
|
||||
const [board, setBoard] = useState<KidsBoard | null>(null);
|
||||
const [boardError, setBoardError] = useState<string | null>(null);
|
||||
const [msg, setMsg] = useDismissingState<Msg>(null, 9000);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
// Offline
|
||||
const [offline, setOffline] = useState<OfflineState | null>(null);
|
||||
const [working, setWorking] = useState<"online" | "offline">("online");
|
||||
|
||||
// Check in
|
||||
const [q, setQ] = useState("");
|
||||
const [results, setResults] = useState<KidsFamily[] | null>(null);
|
||||
const [family, setFamily] = useState<KidsFamily | null>(null);
|
||||
const [picked, setPicked] = useState<Record<string, string>>({}); // childId → roomId
|
||||
const [sendTo, setSendTo] = useState("");
|
||||
const [result, setResult] = useState<CheckInResult | null>(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<CodeLookup | null>(null);
|
||||
const [outPicked, setOutPicked] = useState<Record<string, boolean>>({});
|
||||
const [collectedBy, setCollectedBy] = useState("");
|
||||
const [wrongCode, setWrongCode] = useState<string | null>(null);
|
||||
|
||||
const qs = sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : "";
|
||||
|
||||
const loadBoard = useCallback(async (log = false) => {
|
||||
if (!token || !eventId || working === "offline") return;
|
||||
try {
|
||||
const data = await apiFetch<KidsBoard>(`/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<string, string>(); // 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<string, number> = {};
|
||||
const next: Record<string, string> = {};
|
||||
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<KidsFamily[]>(`/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<KidsFamily>(`/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<KidsFamily>(`/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<KidsFamily>(`/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<CheckInResult>(`/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<CodeLookup>(`/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<OfflineState["snapshot"]>(`/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 (
|
||||
<div className="max-w-5xl mx-auto w-full p-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3 mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><Baby className="w-5 h-5 text-brand-600" /></div>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Kids check-in</h1>
|
||||
<p className="text-sm text-gray-500">{board?.sessionLabel ? `${board.sessionLabel} · ` : ""}Check children in and out with pickup codes</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/dashboard/staff/kids/rooms" className="text-sm px-3 py-2 rounded-lg border inline-flex items-center gap-1.5"><Users className="w-4 h-4" /> Room screen</Link>
|
||||
</div>
|
||||
|
||||
<KidsEventPicker token={token} eventId={eventId} sessionId={sessionId} onChange={(id, sid) => { setEventId(id); setSessionId(sid); }} />
|
||||
|
||||
{eventId && (
|
||||
<div className={`mt-3 p-3 rounded-lg border text-sm flex flex-wrap items-center gap-2 ${working === "offline" ? "bg-amber-50 border-amber-300" : "bg-gray-50"}`}>
|
||||
<CloudOff className="w-4 h-4 text-gray-500" />
|
||||
{working === "offline" ? (
|
||||
<>
|
||||
<span className="font-medium text-amber-900">Working offline</span>
|
||||
<span className="text-amber-800">{queued} change{queued === 1 ? "" : "s"} waiting to sync · {Math.max(0, (offline?.snapshot.codes.length || 0) - Object.keys(offline?.familyCodes || {}).length)} codes left</span>
|
||||
<button disabled={busy} onClick={sync} className="ml-auto px-3 py-1.5 rounded-lg bg-amber-600 text-white inline-flex items-center gap-1"><RefreshCw className="w-3.5 h-3.5" /> Back online — sync</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-gray-700">{offline ? `Offline list from ${new Date(offline.snapshot.downloadedAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}` : "Wi-Fi unreliable? Download the list first."}</span>
|
||||
{queued > 0 && <button disabled={busy} onClick={sync} className="px-3 py-1.5 rounded-lg bg-amber-600 text-white">Sync {queued} offline change{queued === 1 ? "" : "s"}</button>}
|
||||
<button disabled={busy} onClick={getReady} className="ml-auto px-3 py-1.5 rounded-lg border bg-white">{offline ? "Refresh offline list" : "Get ready for offline"}</button>
|
||||
{offline && <button onClick={() => setWorking("offline")} className="px-3 py-1.5 rounded-lg border bg-white">Work offline</button>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{boardError && working === "online" && <div className="mt-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{boardError}</div>}
|
||||
{msg && <div role="status" className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
|
||||
|
||||
{ready && (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-2 my-4">
|
||||
<button className={tabCls(tab === "in")} onClick={() => setTab("in")}><LogIn className="w-4 h-4" /> Check in</button>
|
||||
<button className={tabCls(tab === "out")} onClick={() => setTab("out")}><LogOut className="w-4 h-4" /> Check out</button>
|
||||
{working === "online" && <button className={tabCls(tab === "rooms")} onClick={() => setTab("rooms")}><Users className="w-4 h-4" /> Who's in ({board?.checkIns.filter(c => !c.checkedOutAt).length || 0})</button>}
|
||||
</div>
|
||||
|
||||
{(tab === "in" || tab === "out") && (
|
||||
<div className="mb-4">
|
||||
<button onClick={() => setScanning(s => !s)} className="text-sm px-3 py-2 rounded-lg border inline-flex items-center gap-1.5 bg-white"><QrCode className="w-4 h-4" /> {scanning ? "Stop scanning" : tab === "in" ? "Scan family QR" : "Scan pickup QR"}</button>
|
||||
{scanning && <div className="mt-2 max-w-sm"><QRScanner onResult={onScan} /></div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tab === "in" && (
|
||||
result ? (
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<StickerPanel code={result.code} offline={working === "offline"} kids={result.checkIns.map(c => ({ id: c.id, firstName: c.firstName, room: c.room?.name || null, sticker: c.sticker, already: c.already }))} />
|
||||
<button onClick={() => { setResult(null); setFamily(null); setQ(""); }} className="mt-4 px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium">Next family</button>
|
||||
</section>
|
||||
) : (
|
||||
<div className="grid lg:grid-cols-2 gap-4">
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<form onSubmit={search} className="flex gap-2">
|
||||
<input className={inputCls} placeholder="Parent or child name, or phone number" value={q} onChange={e => setQ(e.target.value)} aria-label="Find a family" />
|
||||
<button className="px-3 py-2 rounded-lg border" aria-label="Search"><Search className="w-4 h-4" /></button>
|
||||
</form>
|
||||
{results && (
|
||||
<ul className="mt-3 divide-y">
|
||||
{results.map(f => (
|
||||
<li key={f.id}>
|
||||
<button onClick={() => chooseFamily(f)} className="w-full text-left py-2 hover:bg-gray-50 px-1 rounded">
|
||||
<div className="font-medium">{f.name}</div>
|
||||
<div className="text-xs text-gray-500">{f.parents.map(p => p.name).join(", ")} · {f.children.map(c => c.firstName).join(", ") || "no children yet"}</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{!results.length && <li className="py-2 text-sm text-gray-500">No family found.</li>}
|
||||
</ul>
|
||||
)}
|
||||
{working === "online" && !newFamily && (
|
||||
<button onClick={() => setNewFamily({ name: "", parentName: "", phone: "", email: "" })} className="mt-3 text-sm inline-flex items-center gap-1 text-brand-700"><UserPlus className="w-4 h-4" /> New family</button>
|
||||
)}
|
||||
{newFamily && (
|
||||
<div className="mt-3 border-t pt-3 space-y-2">
|
||||
<div className="font-medium text-sm">New family</div>
|
||||
<input className={inputCls} placeholder="Parent's name *" value={newFamily.parentName} onChange={e => setNewFamily({ ...newFamily, parentName: e.target.value })} />
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input className={inputCls} placeholder="Phone" value={newFamily.phone} onChange={e => setNewFamily({ ...newFamily, phone: e.target.value })} />
|
||||
<input className={inputCls} placeholder="Email" value={newFamily.email} onChange={e => setNewFamily({ ...newFamily, email: e.target.value })} />
|
||||
</div>
|
||||
<input className={inputCls} placeholder="Family name (e.g. Smith family)" value={newFamily.name} onChange={e => setNewFamily({ ...newFamily, name: e.target.value })} />
|
||||
<div className="text-xs text-gray-500">First child:</div>
|
||||
<ChildForm custody={isSupervisor} busy={busy} onSave={createFamily} onCancel={() => setNewFamily(null)} saveLabel="Add family" />
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{family && (
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<h2 className="font-semibold">{family.name}</h2>
|
||||
<div className="text-xs text-gray-500 mb-3">{family.parents.map(p => `${p.name}${p.phone ? ` · ${p.phone}` : ""}`).join(" — ")}</div>
|
||||
<ul className="space-y-2">
|
||||
{family.children.map(c => {
|
||||
const inRoom = inNow.get(c.id);
|
||||
return (
|
||||
<li key={c.id} className="border rounded-lg p-2 flex flex-wrap items-center gap-2">
|
||||
<label className="flex items-center gap-2 flex-1 min-w-[10rem]">
|
||||
<input type="checkbox" disabled={inRoom !== undefined} checked={!!picked[c.id]} onChange={e => setPicked(p => ({ ...p, [c.id]: e.target.checked ? (suggestRoom(rooms, c.age)?.id || "") : "" }))} />
|
||||
<span>
|
||||
<span className="font-medium">{c.name}</span>{c.age != null && <span className="text-sm text-gray-500"> · {c.age}</span>}
|
||||
{c.allergies && <span className="block text-xs text-red-700">Allergies: {c.allergies}</span>}
|
||||
{c.hasCustody && <span className="block text-xs text-red-900">Custody notes — see room screen</span>}
|
||||
</span>
|
||||
</label>
|
||||
{inRoom !== undefined ? <span className="text-xs px-2 py-1 rounded-full bg-green-50 text-green-700">In — {inRoom}</span> : picked[c.id] ? (
|
||||
<select aria-label={`Room for ${c.firstName}`} className="border rounded-lg px-2 py-1 text-sm" value={picked[c.id]} onChange={e => setPicked(p => ({ ...p, [c.id]: e.target.value }))}>
|
||||
{rooms.map(r => <option key={r.id} value={r.id}>{r.name}{r.full ? " (full)" : ""}</option>)}
|
||||
</select>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{working === "online" && (addingChild ? (
|
||||
<div className="mt-3 border-t pt-3"><ChildForm custody={isSupervisor} busy={busy} onSave={addChild} onCancel={() => setAddingChild(false)} saveLabel="Add child" /></div>
|
||||
) : (
|
||||
<button onClick={() => setAddingChild(true)} className="mt-2 text-sm text-brand-700">+ Add a child</button>
|
||||
))}
|
||||
{working === "online" && family.adults.some(a => a.phone) && (
|
||||
<label className="block text-sm mt-3"><span className="block text-xs text-gray-500 mb-1">Also send the code to</span>
|
||||
<select className={inputCls} value={sendTo} onChange={e => setSendTo(e.target.value)}>
|
||||
<option value="">Nobody else</option>
|
||||
{family.adults.filter(a => a.phone).map(a => <option key={a.id} value={a.id}>{a.name}{a.relationship ? ` (${a.relationship})` : ""}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<button disabled={busy || !Object.values(picked).some(Boolean)} onClick={doCheckIn} className="mt-4 w-full px-4 py-3 rounded-lg bg-brand-600 text-white font-semibold disabled:opacity-50">Check in</button>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{tab === "out" && (
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm max-w-xl">
|
||||
<form onSubmit={e => { e.preventDefault(); lookUpCode(); }} className="flex gap-2">
|
||||
<input className={`${inputCls} text-2xl font-mono tracking-widest uppercase`} placeholder="Pickup code" value={code} onChange={e => setCode(e.target.value)} maxLength={10} aria-label="Pickup code" />
|
||||
<button className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium">Find</button>
|
||||
</form>
|
||||
{wrongCode && <div role="alert" className="mt-3 p-3 rounded-lg border-2 border-red-500 bg-red-50 text-red-900 text-sm font-medium">{wrongCode}</div>}
|
||||
{lookup && (
|
||||
<div className="mt-4">
|
||||
{lookup.family && (
|
||||
<div className="text-sm mb-3">
|
||||
<div className="font-semibold">{lookup.family.name}</div>
|
||||
<div className="text-xs text-gray-600">Parents: {lookup.family.parents.map(p => p.name).join(", ") || "—"}</div>
|
||||
{lookup.family.adults.length > 0 && <div className="text-xs text-gray-600">May also collect: {lookup.family.adults.map(a => `${a.name}${a.relationship ? ` (${a.relationship})` : ""}`).join(", ")}</div>}
|
||||
</div>
|
||||
)}
|
||||
<ul className="space-y-1 mb-3">
|
||||
{lookup.children.map(c => {
|
||||
const custody = board?.checkIns.find(b => b.id === c.id)?.custodyNotes;
|
||||
return (
|
||||
<li key={c.id} className="text-sm">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" disabled={!!c.checkedOutAt} checked={!!outPicked[c.id]} onChange={e => setOutPicked(p => ({ ...p, [c.id]: e.target.checked }))} />
|
||||
<span className="font-medium">{c.name}</span> <span className="text-gray-500">{c.room?.name}</span>
|
||||
{c.checkedOutAt && <span className="text-xs text-gray-500">collected by {c.collectedBy || "—"}</span>}
|
||||
</label>
|
||||
{custody && <div className="ml-6 mt-1 text-xs text-red-900 bg-red-50 rounded px-2 py-1">Custody: {custody}</div>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<label className="block text-sm"><span className="block text-xs text-gray-500 mb-1">Collected by</span>
|
||||
<input className={inputCls} list="kids-collectors" value={collectedBy} onChange={e => setCollectedBy(e.target.value)} />
|
||||
<datalist id="kids-collectors">
|
||||
{lookup.family?.parents.map(p => <option key={p.userId} value={p.name} />)}
|
||||
{lookup.family?.adults.map(a => <option key={a.id} value={a.name} />)}
|
||||
</datalist>
|
||||
</label>
|
||||
<button disabled={busy} onClick={doCheckOut} className="mt-3 w-full px-4 py-3 rounded-lg bg-brand-600 text-white font-semibold disabled:opacity-50">Check out</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{tab === "rooms" && board && working === "online" && (
|
||||
<RoomBoard board={board} token={token} roomId="" onChanged={() => loadBoard()} onMessage={setMsg} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<KidsBoard | null>(null);
|
||||
const [error, setError] = useState<string | null>(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<KidsBoard>(`/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 (
|
||||
<div className="max-w-5xl mx-auto w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><Users className="w-5 h-5 text-brand-600" /></div>
|
||||
<div>
|
||||
<BackLink href="/dashboard/staff/kids" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Kids rooms</h1>
|
||||
<p className="text-sm text-gray-500">{board?.sessionLabel ? `${board.sessionLabel} · ` : ""}Who is in each room right now</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 items-end">
|
||||
<KidsEventPicker token={token} eventId={eventId} sessionId={sessionId} onChange={(id, sid) => { setEventId(id); setSessionId(sid); }} />
|
||||
{board && (
|
||||
<label className="text-sm">
|
||||
<span className="block text-xs text-gray-500 mb-1">Room</span>
|
||||
<select className="border rounded-lg px-3 py-2 text-sm" value={room ? roomId : ""} onChange={e => pickRoom(e.target.value)}>
|
||||
<option value="">All rooms</option>
|
||||
{board.rooms.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{room && (
|
||||
<div className="mt-3 p-3 rounded-lg border bg-white flex flex-wrap items-center gap-3">
|
||||
<RoomStatusBadges room={room} />
|
||||
<button onClick={() => duty(!onDuty)} className={`ml-auto px-4 py-2 rounded-lg text-sm font-medium ${onDuty ? "border" : "bg-brand-600 text-white"}`}>
|
||||
{onDuty ? "I'm going off duty" : "I'm on duty in this room"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div className="mt-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||||
{msg && <div role="status" className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
|
||||
{board && <div className="mt-4"><RoomBoard board={board} token={token} roomId={room ? roomId : ""} onChanged={() => load()} onMessage={setMsg} /></div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<SetupEvent[]>([]);
|
||||
const [eventId, setEventId] = useState("");
|
||||
const [s, setS] = useState<Settings | null>(null);
|
||||
const [msg, setMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [draft, setDraft] = useState<Record<string, { name: string; minAge: string; maxAge: string; capacity: string; ratio: string }>>({});
|
||||
const [newRoom, setNewRoom] = useState({ name: "", minAge: "", maxAge: "", capacity: "", ratio: "" });
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
apiFetch<SetupEvent[]>("/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<Settings>(`/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<unknown>, 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<string, unknown>, 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) => (
|
||||
<>
|
||||
<input aria-label="Room name" className={inputCls} value={d.name} onChange={e => set({ ...d, name: e.target.value })} placeholder="Toddlers" />
|
||||
<input aria-label="Youngest age" className={inputCls} inputMode="numeric" value={d.minAge} onChange={e => set({ ...d, minAge: e.target.value })} placeholder="from" />
|
||||
<input aria-label="Oldest age" className={inputCls} inputMode="numeric" value={d.maxAge} onChange={e => set({ ...d, maxAge: e.target.value })} placeholder="to" />
|
||||
<input aria-label="Capacity" className={inputCls} inputMode="numeric" value={d.capacity} onChange={e => set({ ...d, capacity: e.target.value })} placeholder="—" />
|
||||
<input aria-label="Children per leader" className={inputCls} inputMode="numeric" value={d.ratio} onChange={e => set({ ...d, ratio: e.target.value })} placeholder="—" />
|
||||
</>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><Baby className="w-5 h-5 text-brand-600" /></div>
|
||||
<div>
|
||||
<BackLink href="/dashboard" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Kids check-in setup</h1>
|
||||
<p className="text-sm text-gray-500">Switch kids check-in on for an event and set up its rooms</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="text-sm block max-w-md">
|
||||
<span className="block text-xs text-gray-500 mb-1">Event</span>
|
||||
<select className="w-full border rounded-lg px-3 py-2 text-sm" value={eventId} onChange={e => setEventId(e.target.value)}>
|
||||
<option value="">Choose an event…</option>
|
||||
{events.map(e => <option key={e.id} value={e.id}>{e.title} · {formatDate(new Date(e.startDate))}{e.kidsCheckIn ? " · kids check-in on" : ""}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{msg && <div role="status" className={`mt-3 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
|
||||
|
||||
{s && (
|
||||
<div className="space-y-4 mt-4">
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm space-y-3">
|
||||
<h2 className="font-semibold">1. Kids ticket</h2>
|
||||
<p className="text-sm text-gray-600">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.</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<select className="border rounded-lg px-3 py-2 text-sm" value={s.event.kidsOptionId || ""} onChange={e => save({ optionId: e.target.value || null })} aria-label="Kids ticket">
|
||||
<option value="">Choose…</option>
|
||||
{s.options.map(o => <option key={o.id} value={o.id}>{o.name}{o.price ? ` (R${o.price})` : " (free)"}</option>)}
|
||||
</select>
|
||||
{!s.event.kidsOptionId && <button disabled={busy} onClick={() => save({ optionId: "new" }, "Added a free \"Kids check-in\" ticket.")} className="px-3 py-2 rounded-lg border text-sm">Add a free "Kids check-in" ticket</button>}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm space-y-3">
|
||||
<h2 className="font-semibold">2. Rooms</h2>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<select className="border rounded-lg px-3 py-2 text-sm" value={s.event.kidsRoomSetId || ""} onChange={e => save({ roomSetId: e.target.value || null })} aria-label="Rooms set">
|
||||
<option value="">Choose…</option>
|
||||
{s.sets.map(x => <option key={x.id} value={x.id}>{x.name} ({x.groups.length} rooms)</option>)}
|
||||
</select>
|
||||
{!s.event.kidsRoomSetId && <button disabled={busy} onClick={() => save({ roomSetId: "new" }, "Added \"Kids rooms\" — now add the rooms.")} className="px-3 py-2 rounded-lg border text-sm">Add "Kids rooms"</button>}
|
||||
</div>
|
||||
{s.event.kidsRoomSetId && (
|
||||
<div className="overflow-x-auto">
|
||||
<div className="grid grid-cols-[2fr_repeat(4,minmax(4rem,1fr))_auto] gap-2 items-center min-w-[36rem] text-xs text-gray-500">
|
||||
<span>Room</span><span>Age from</span><span>Age to</span><span>Capacity</span><span>Per leader</span><span />
|
||||
{rooms.map(r => draft[r.id] && (
|
||||
<React.Fragment key={r.id}>
|
||||
{roomRow(draft[r.id], v => setDraft(d => ({ ...d, [r.id]: v })))}
|
||||
<span className="flex gap-1">
|
||||
<button disabled={busy} onClick={() => saveRoom(r.id)} className="px-2 py-1.5 rounded-lg border text-sm text-gray-800">Save</button>
|
||||
<button disabled={busy} aria-label={`Delete ${r.name}`} onClick={() => deleteRoom(r)} className="p-1.5 rounded-lg border"><Trash2 className="w-4 h-4" /></button>
|
||||
</span>
|
||||
</React.Fragment>
|
||||
))}
|
||||
{roomRow(newRoom, setNewRoom)}
|
||||
<button disabled={busy || !newRoom.name.trim()} onClick={addRoom} className="px-2 py-1.5 rounded-lg bg-brand-600 text-white text-sm inline-flex items-center gap-1 disabled:opacity-50"><Plus className="w-4 h-4" /> Add</button>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2">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.</p>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm flex flex-wrap items-center gap-3">
|
||||
<div className="flex-1 min-w-[14rem]">
|
||||
<h2 className="font-semibold">3. Switch on</h2>
|
||||
<p className="text-sm text-gray-600">{s.event.kidsCheckIn ? "Kids check-in is on — staff use Staff → Kids check-in." : "Staff can check children in once this is on."}</p>
|
||||
</div>
|
||||
<button disabled={busy} onClick={() => save({ enabled: !s.event.kidsCheckIn }, s.event.kidsCheckIn ? "Kids check-in switched off." : "Kids check-in switched on.")} className={`px-4 py-2 rounded-lg text-sm font-medium ${s.event.kidsCheckIn ? "border" : "bg-brand-600 text-white"}`}>
|
||||
{s.event.kidsCheckIn ? "Switch off" : "Switch on"}
|
||||
</button>
|
||||
{s.event.kidsCheckIn && <Link href="/dashboard/staff/kids" className="px-4 py-2 rounded-lg border text-sm">Open the desk</Link>}
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 },
|
||||
|
||||
@@ -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<Mine | null>(null);
|
||||
const [msg, setMsg] = useDismissingState<Msg>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [editing, setEditing] = useState<string | "new" | null>(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<Mine>("/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<unknown>, 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 (
|
||||
<div className="max-w-3xl mx-auto w-full p-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0"><Baby className="w-5 h-5 text-brand-600" /></div>
|
||||
<div>
|
||||
<BackLink href="/dashboard/user" />
|
||||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Kids</h1>
|
||||
<p className="text-sm text-gray-500">Your children for kids check-in, and their pickup codes</p>
|
||||
</div>
|
||||
</div>
|
||||
{msg && <div className={`mb-4 p-3 rounded-lg text-sm ${msg.type === "ok" ? "bg-green-50 text-green-800 border border-green-200" : "bg-red-50 text-red-800 border border-red-200"}`}>{msg.text}</div>}
|
||||
|
||||
{data?.pages.map(p => (
|
||||
<div key={p.id} className="mb-4 p-4 rounded-xl border-2 border-amber-400 bg-amber-50 flex gap-3 items-start">
|
||||
<BellRing className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
|
||||
<div><div className="font-semibold text-amber-900">{p.message}</div><div className="text-xs text-amber-700">{new Date(p.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</div></div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{data?.codes.map(c => (
|
||||
<section key={c.event.id + c.code} className="mb-4 border-2 border-brand-500 rounded-xl p-4 bg-white shadow-sm">
|
||||
<div className="text-xs uppercase tracking-wide text-brand-700 font-semibold">Checked in · {c.event.title}</div>
|
||||
<div className="flex flex-wrap items-center gap-4 mt-2">
|
||||
<QrImage value={c.qr} size={160} className="w-32 h-32" alt={`Pickup QR code ${c.code}`} />
|
||||
<div>
|
||||
<div className="text-xs text-gray-500">Pickup code</div>
|
||||
<div className="text-5xl font-black tracking-[0.2em] font-mono" data-testid="pickup-code">{c.code}</div>
|
||||
<ul className="mt-2 text-sm text-gray-700">{c.children.map(k => <li key={k.name}>{k.name}{k.room ? ` — ${k.room}` : ""}</li>)}</ul>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-3">Show this code or QR to collect your children. Anyone you give the code to can collect them.</p>
|
||||
<button onClick={() => share(c)} className="mt-2 text-sm px-3 py-1.5 rounded-lg border">Send the code to someone else</button>
|
||||
</section>
|
||||
))}
|
||||
|
||||
{data && !family && (
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<h2 className="font-semibold mb-1">Add your family</h2>
|
||||
<p className="text-sm text-gray-600 mb-3">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.</p>
|
||||
<div className="flex gap-2">
|
||||
<input className={inputCls} placeholder={`${user?.name?.split(" ").slice(-1)[0] || "Smith"} family`} value={familyName} onChange={e => setFamilyName(e.target.value)} />
|
||||
<button disabled={busy} onClick={startFamily} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium whitespace-nowrap disabled:opacity-50">Add family</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{family && (
|
||||
<>
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm mb-4">
|
||||
<div className="flex items-center justify-between gap-2 mb-3">
|
||||
<h2 className="font-semibold">{family.name}</h2>
|
||||
<span className="text-xs text-gray-500">Parents: {family.parents.map(p => p.name).join(", ")}</span>
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{family.children.map(c => (
|
||||
<div key={c.id} className="border rounded-lg p-3">
|
||||
{editing === c.id ? (
|
||||
<ChildForm initial={c} custody busy={busy} onSave={v => saveChild(c, v)} onCancel={() => setEditing(null)} />
|
||||
) : (
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-medium">{c.name}{c.age != null && <span className="text-sm text-gray-500 font-normal"> · {c.age} yrs</span>}</div>
|
||||
<div className="text-xs text-gray-600 space-x-2">
|
||||
{c.allergies && <span className="text-red-700">Allergies: {c.allergies}</span>}
|
||||
{c.hasMedical && <span>Medical notes ✓</span>}
|
||||
{c.hasCustody && <span>Custody notes ✓</span>}
|
||||
{!c.allergies && !c.hasMedical && !c.dateOfBirth && <span className="text-amber-700">Add a date of birth so the right room is suggested</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
<button aria-label={`Edit ${c.firstName}`} onClick={() => setEditing(c.id)} className="p-1.5 rounded hover:bg-gray-100"><Pencil className="w-4 h-4" /></button>
|
||||
<button aria-label={`Remove ${c.firstName}`} onClick={() => removeChild(c)} className="p-1.5 rounded hover:bg-gray-100"><Trash2 className="w-4 h-4" /></button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{editing === "new" ? (
|
||||
<div className="border rounded-lg p-3"><ChildForm custody busy={busy} onSave={v => saveChild(null, v)} onCancel={() => setEditing(null)} saveLabel="Add child" /></div>
|
||||
) : (
|
||||
<button onClick={() => setEditing("new")} className="inline-flex items-center gap-1 text-sm px-3 py-2 rounded-lg border"><Plus className="w-4 h-4" /> Add a child</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm mb-4">
|
||||
<h2 className="font-semibold flex items-center gap-2"><UserCheck className="w-4 h-4" /> Authorised adults</h2>
|
||||
<p className="text-sm text-gray-600 mb-3">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.</p>
|
||||
<ul className="space-y-2 mb-3">
|
||||
{family.adults.map(a => (
|
||||
<li key={a.id} className="flex items-center justify-between border rounded-lg px-3 py-2 text-sm">
|
||||
<span>{a.name}{a.relationship ? ` (${a.relationship})` : ""}{a.phone ? ` · ${a.phone}` : ""}</span>
|
||||
<span className="flex gap-1">
|
||||
<button aria-label={`Edit ${a.name}`} onClick={() => setAdultForm({ id: a.id, name: a.name, phone: a.phone || "", relationship: a.relationship || "" })} className="p-1.5 rounded hover:bg-gray-100"><Pencil className="w-4 h-4" /></button>
|
||||
<button aria-label={`Remove ${a.name}`} onClick={() => removeAdult(a)} className="p-1.5 rounded hover:bg-gray-100"><Trash2 className="w-4 h-4" /></button>
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
{!family.adults.length && <li className="text-sm text-gray-500">Nobody yet.</li>}
|
||||
</ul>
|
||||
{adultForm ? (
|
||||
<div className="grid sm:grid-cols-3 gap-2">
|
||||
<input className={inputCls} placeholder="Name" value={adultForm.name} onChange={e => setAdultForm({ ...adultForm, name: e.target.value })} />
|
||||
<input className={inputCls} placeholder="Phone" value={adultForm.phone} onChange={e => setAdultForm({ ...adultForm, phone: e.target.value })} />
|
||||
<input className={inputCls} placeholder="Relationship (e.g. Gran)" value={adultForm.relationship} onChange={e => setAdultForm({ ...adultForm, relationship: e.target.value })} />
|
||||
<div className="sm:col-span-3 flex gap-2">
|
||||
<button disabled={busy} onClick={saveAdult} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">Save</button>
|
||||
<button onClick={() => setAdultForm(null)} className="px-4 py-2 rounded-lg border text-sm">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => setAdultForm({ name: "", phone: "", relationship: "" })} className="inline-flex items-center gap-1 text-sm px-3 py-2 rounded-lg border"><Plus className="w-4 h-4" /> Add an adult</button>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{data?.qrToken && (
|
||||
<section className="border rounded-xl p-4 bg-white shadow-sm flex flex-wrap items-center gap-4">
|
||||
<QrImage value={FAMILY_QR_PREFIX + data.qrToken} size={160} className="w-32 h-32" alt="Family QR code" />
|
||||
<div className="text-sm text-gray-700 max-w-sm">
|
||||
<div className="font-semibold flex items-center gap-2"><QrCode className="w-4 h-4" /> Family QR code</div>
|
||||
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.
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<ChildInput>(() => childToInput(initial));
|
||||
const set = (k: keyof ChildInput) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => setV(prev => ({ ...prev, [k]: e.target.value }));
|
||||
return (
|
||||
<form
|
||||
className="space-y-3"
|
||||
onSubmit={e => {
|
||||
e.preventDefault();
|
||||
const out = { ...v };
|
||||
if (!custody) delete out.custodyNotes;
|
||||
onSave(out);
|
||||
}}
|
||||
>
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
<label className="text-sm"><span className="block text-xs text-gray-500 mb-1">First name *</span><input className={inputCls} value={v.firstName} onChange={set("firstName")} required maxLength={60} /></label>
|
||||
<label className="text-sm"><span className="block text-xs text-gray-500 mb-1">Surname</span><input className={inputCls} value={v.lastName} onChange={set("lastName")} maxLength={60} /></label>
|
||||
<label className="text-sm"><span className="block text-xs text-gray-500 mb-1">Date of birth</span><input type="date" className={inputCls} value={v.dateOfBirth} onChange={set("dateOfBirth")} max={new Date().toISOString().slice(0, 10)} /></label>
|
||||
<label className="text-sm"><span className="block text-xs text-gray-500 mb-1">Gender</span>
|
||||
<select className={inputCls} value={v.gender} onChange={set("gender")}>
|
||||
<option value="">—</option><option value="female">Girl</option><option value="male">Boy</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<label className="block text-sm"><span className="block text-xs text-gray-500 mb-1">Allergies</span><input className={inputCls} value={v.allergies} onChange={set("allergies")} maxLength={300} placeholder="e.g. Peanuts, bee stings" /></label>
|
||||
<label className="block text-sm"><span className="block text-xs text-gray-500 mb-1">Medical notes</span><textarea className={inputCls} rows={2} value={v.medicalNotes} onChange={set("medicalNotes")} maxLength={1000} placeholder="Conditions, medicine, what leaders should know" /></label>
|
||||
{custody && (
|
||||
<label className="block text-sm"><span className="block text-xs text-gray-500 mb-1">Custody notes (room leaders only)</span><textarea className={inputCls} rows={2} value={v.custodyNotes} onChange={set("custodyNotes")} maxLength={1000} placeholder='e.g. "Do not release to …"' /></label>
|
||||
)}
|
||||
<p className="text-xs text-gray-500">Allergies, medical and custody notes are stored encrypted and only shown to kids-ministry staff. They are never sent in messages.</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" disabled={busy} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">{busy ? "Saving…" : saveLabel}</button>
|
||||
{onCancel && <button type="button" onClick={onCancel} className="px-4 py-2 rounded-lg border text-sm">Cancel</button>}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { formatDate } from "@/lib/date";
|
||||
import type { KidsEvent } from "@/lib/kids";
|
||||
|
||||
type Props = {
|
||||
token: string | null;
|
||||
eventId: string;
|
||||
sessionId: string;
|
||||
onChange: (eventId: string, sessionId: string) => void;
|
||||
};
|
||||
|
||||
const STORAGE = "hope_events_kids_event";
|
||||
|
||||
/** Picks the kids event (and session) the desk or room screen works on; remembers the choice. */
|
||||
export function KidsEventPicker({ token, eventId, sessionId, onChange }: Props) {
|
||||
const [events, setEvents] = useState<KidsEvent[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return;
|
||||
apiFetch<KidsEvent[]>("/api/kids/events", { authToken: token })
|
||||
.then(list => {
|
||||
setEvents(list);
|
||||
if (eventId || !list.length) return;
|
||||
let remembered = "";
|
||||
try { remembered = localStorage.getItem(STORAGE) || ""; } catch { /* ignore */ }
|
||||
const now = Date.now();
|
||||
const current = list.find(e => e.id === remembered) || list.find(e => new Date(e.endDate).getTime() >= now) || list[0];
|
||||
onChange(current.id, "");
|
||||
})
|
||||
.catch(e => setError(e?.message || "Could not load events"));
|
||||
}, [token]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const event = events?.find(e => e.id === eventId);
|
||||
const pick = (id: string, sid = "") => {
|
||||
try { localStorage.setItem(STORAGE, id); } catch { /* ignore */ }
|
||||
onChange(id, sid);
|
||||
};
|
||||
|
||||
if (error) return <div className="p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>;
|
||||
if (events && !events.length) {
|
||||
return <div className="p-3 border rounded bg-amber-50 text-amber-800 text-sm">No events have kids check-in switched on. A supervisor sets it up under Supervisor → Kids check-in setup.</div>;
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2 items-end">
|
||||
<label className="text-sm">
|
||||
<span className="block text-xs text-gray-500 mb-1">Event</span>
|
||||
<select className="border rounded-lg px-3 py-2 text-sm min-w-[14rem]" value={eventId} onChange={e => pick(e.target.value)}>
|
||||
{!eventId && <option value="">Choose an event…</option>}
|
||||
{events?.map(e => <option key={e.id} value={e.id}>{e.title} · {formatDate(new Date(e.startDate))}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
{event?.scheduleType === "sessions" && (
|
||||
<label className="text-sm">
|
||||
<span className="block text-xs text-gray-500 mb-1">Session</span>
|
||||
<select className="border rounded-lg px-3 py-2 text-sm" value={sessionId} onChange={e => pick(event.id, e.target.value)}>
|
||||
<option value="">Today's session</option>
|
||||
{event.sessions.map((s, i) => <option key={s.id} value={s.id}>{s.label || `Session ${i + 1}`} · {formatDate(new Date(s.startsAt))}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { errorMessage } from "@/lib/utils";
|
||||
import { AlertTriangle, BellRing, HeartPulse, LogOut, ShieldAlert, Users } from "lucide-react";
|
||||
import { ageRange, type KidsBoard, type KidsCheckIn, type KidsRoom } from "@/lib/kids";
|
||||
|
||||
type Props = {
|
||||
board: KidsBoard;
|
||||
token: string | null;
|
||||
/** Only this room ('' = every room). */
|
||||
roomId: string;
|
||||
onChanged: () => void;
|
||||
onMessage: (m: { type: "ok" | "err"; text: string }) => void;
|
||||
};
|
||||
|
||||
const time = (iso: string) => new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
|
||||
export function RoomStatusBadges({ room }: { room: KidsRoom }) {
|
||||
return (
|
||||
<span className="inline-flex flex-wrap gap-1 text-xs">
|
||||
<span className="px-2 py-0.5 rounded-full bg-gray-100 text-gray-700">{room.children}{room.capacity ? ` / ${room.capacity}` : ""} in</span>
|
||||
<span className={`px-2 py-0.5 rounded-full ${room.overRatio ? "bg-red-100 text-red-800" : "bg-gray-100 text-gray-700"}`}>
|
||||
{room.leaders} leader{room.leaders === 1 ? "" : "s"}{room.ratio ? ` (needs ${room.leadersNeeded})` : ""}
|
||||
</span>
|
||||
{room.full && <span className="px-2 py-0.5 rounded-full bg-amber-100 text-amber-800">Full</span>}
|
||||
{room.overRatio && <span className="px-2 py-0.5 rounded-full bg-red-100 text-red-800">Over ratio</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Live cards of the children in the rooms, with paging, moving and checking out without the code. */
|
||||
export function RoomBoard({ board, token, roomId, onChanged, onMessage }: Props) {
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const rooms = board.rooms.filter(r => !roomId || r.id === roomId);
|
||||
const alerts = board.alerts.filter(a => !a.resolvedAt && a.kind === "wrong_code" && (!roomId || !a.roomId || a.roomId === roomId));
|
||||
|
||||
const act = async (id: string, fn: () => Promise<unknown>, ok: string) => {
|
||||
setBusy(id);
|
||||
try {
|
||||
await fn();
|
||||
onMessage({ type: "ok", text: ok });
|
||||
onChanged();
|
||||
} catch (e) {
|
||||
onMessage({ type: "err", text: errorMessage(e) || "Something went wrong" });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const page = (c: KidsCheckIn) => {
|
||||
const extra = prompt(`Message the parents of ${c.firstName}? They'll be asked to come to the room. Add a note (optional):`, "");
|
||||
if (extra === null) return;
|
||||
act(c.id, () => apiFetch(`/api/kids/check-ins/${c.id}/page`, { method: "POST", authToken: token, body: { message: extra } }), `Message sent to ${c.firstName}'s parents.`);
|
||||
};
|
||||
const override = (c: KidsCheckIn) => {
|
||||
const who = prompt(`Who is collecting ${c.firstName}?`, c.family?.parents[0]?.name || "");
|
||||
if (!who) return;
|
||||
const reason = prompt("Why without the pickup code? (recorded in the audit log)", "");
|
||||
if (!reason) return;
|
||||
act(c.id, () => apiFetch(`/api/kids/check-ins/${c.id}/override`, { method: "POST", authToken: token, body: { collectedBy: who, reason } }), `${c.firstName} checked out.`);
|
||||
};
|
||||
const move = (c: KidsCheckIn, to: string) => act(c.id, () => apiFetch(`/api/kids/check-ins/${c.id}/room`, { method: "PUT", authToken: token, body: { roomId: to } }), `${c.firstName} moved.`);
|
||||
const resolve = (id: string) => act(id, () => apiFetch(`/api/kids/alerts/${id}/resolve`, { method: "POST", authToken: token }), "Alert cleared.");
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{alerts.map(a => (
|
||||
<div key={a.id} role="alert" className="p-3 rounded-xl border-2 border-red-500 bg-red-50 flex items-start justify-between gap-3">
|
||||
<div className="flex gap-2"><ShieldAlert className="w-5 h-5 text-red-600 shrink-0" />
|
||||
<div><div className="font-semibold text-red-900">{a.message}</div><div className="text-xs text-red-700">{time(a.at)}{a.by ? ` · ${a.by}` : ""} — check who is collecting before handing over any child.</div></div>
|
||||
</div>
|
||||
<button disabled={busy === a.id} onClick={() => resolve(a.id)} className="text-sm px-3 py-1 rounded-lg border border-red-300 bg-white">Dealt with</button>
|
||||
</div>
|
||||
))}
|
||||
{rooms.map(r => {
|
||||
const inRoom = board.checkIns.filter(c => c.roomId === r.id && !c.checkedOutAt);
|
||||
const out = board.checkIns.filter(c => c.roomId === r.id && c.checkedOutAt);
|
||||
return (
|
||||
<section key={r.id} className="border rounded-xl p-4 bg-white shadow-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 mb-3">
|
||||
<h2 className="font-semibold text-lg">{r.name} <span className="text-sm font-normal text-gray-500">{ageRange(r)}</span></h2>
|
||||
<RoomStatusBadges room={r} />
|
||||
</div>
|
||||
{r.leaderNames.length > 0 && <div className="text-xs text-gray-500 mb-2 flex items-center gap-1"><Users className="w-3.5 h-3.5" /> On duty: {r.leaderNames.join(", ")}</div>}
|
||||
{inRoom.length === 0 && <p className="text-sm text-gray-500">No children in this room.</p>}
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
{inRoom.map(c => (
|
||||
<div key={c.id} className={`border rounded-lg p-3 ${c.custodyNotes ? "border-red-400" : c.allergies || c.medicalNotes ? "border-amber-400" : ""}`} data-testid="kids-card">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<div className="font-semibold">{c.name}{c.age != null && <span className="text-sm font-normal text-gray-500"> · {c.age}</span>}</div>
|
||||
<div className="text-xs text-gray-500">In {time(c.checkedInAt)} · code <span className="font-mono font-semibold text-gray-800">{c.code}</span>{c.offline ? " · offline" : ""}</div>
|
||||
</div>
|
||||
</div>
|
||||
{c.allergies && <div className="mt-1 text-sm text-red-800 flex gap-1"><AlertTriangle className="w-4 h-4 shrink-0" /> Allergies: {c.allergies}</div>}
|
||||
{c.medicalNotes && <div className="mt-1 text-sm text-amber-800 flex gap-1"><HeartPulse className="w-4 h-4 shrink-0" /> {c.medicalNotes}</div>}
|
||||
{c.custodyNotes && <div className="mt-1 text-sm text-red-900 bg-red-50 rounded px-2 py-1 flex gap-1"><ShieldAlert className="w-4 h-4 shrink-0" /> {c.custodyNotes}</div>}
|
||||
{c.family && (
|
||||
<div className="mt-2 text-xs text-gray-600">
|
||||
{c.family.parents.map(p => <div key={p.userId}>{p.name}{p.phone ? ` · ${p.phone}` : ""}</div>)}
|
||||
{c.family.adults.length > 0 && <div>May also collect: {c.family.adults.map(a => `${a.name}${a.relationship ? ` (${a.relationship})` : ""}`).join(", ")}</div>}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<button disabled={busy === c.id} onClick={() => page(c)} className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded-lg border"><BellRing className="w-3.5 h-3.5" /> Call parent</button>
|
||||
<select aria-label={`Move ${c.firstName}`} value="" onChange={e => e.target.value && move(c, e.target.value)} className="text-xs border rounded-lg px-2 py-1">
|
||||
<option value="">Move to…</option>
|
||||
{board.rooms.filter(o => o.id !== r.id).map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</select>
|
||||
<button disabled={busy === c.id} onClick={() => override(c)} className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded-lg border text-gray-600"><LogOut className="w-3.5 h-3.5" /> Without code</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{out.length > 0 && (
|
||||
<details className="mt-3 text-sm">
|
||||
<summary className="cursor-pointer text-gray-500">Collected ({out.length})</summary>
|
||||
<ul className="mt-1 space-y-0.5 text-xs text-gray-600">
|
||||
{out.map(c => <li key={c.id}>{c.name} — {time(c.checkedOutAt!)} by {c.collectedBy || "—"}{c.override ? " (without code)" : ""}</li>)}
|
||||
</ul>
|
||||
</details>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
{!roomId && board.checkIns.some(c => !c.roomId && !c.checkedOutAt) && (
|
||||
<section className="border border-amber-300 rounded-xl p-4 bg-amber-50">
|
||||
<h2 className="font-semibold mb-2">No room</h2>
|
||||
<p className="text-xs text-amber-800 mb-2">Their room was deleted — choose a new one.</p>
|
||||
<ul className="space-y-1 text-sm">
|
||||
{board.checkIns.filter(c => !c.roomId && !c.checkedOutAt).map(c => (
|
||||
<li key={c.id} className="flex items-center gap-2">
|
||||
<span>{c.name}</span>
|
||||
<select aria-label={`Move ${c.firstName}`} value="" onChange={e => e.target.value && move(c, e.target.value)} className="text-xs border rounded-lg px-2 py-1 bg-white">
|
||||
<option value="">Move to…</option>
|
||||
{board.rooms.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||
</select>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import React from "react";
|
||||
|
||||
type Props = {
|
||||
code: string;
|
||||
/** Checked in on an offline desk: nothing was sent to the parents. */
|
||||
offline?: boolean;
|
||||
kids: { id: string; firstName: string; room: string | null; sticker: string; already?: boolean }[];
|
||||
};
|
||||
|
||||
/**
|
||||
* "Write on the sticker": what volunteers copy onto a blank name sticker for each child — first
|
||||
* name, room, pickup code and a short allergy/medical alert — in print big enough to copy at a
|
||||
* glance. Nothing is printed; the full details stay on screen.
|
||||
*/
|
||||
export function StickerPanel({ code, kids, offline = false }: Props) {
|
||||
return (
|
||||
<div>
|
||||
<div className="text-center mb-3">
|
||||
<div className="text-xs uppercase tracking-wide text-gray-500">Pickup code</div>
|
||||
<div className="text-6xl font-black font-mono tracking-[0.25em]" data-testid="desk-code">{code}</div>
|
||||
<div className="text-xs text-gray-500">{offline ? "Offline: nothing was sent — tell the parent the code." : "Sent to the parents. Tell them too, in case the message is slow."}</div>
|
||||
</div>
|
||||
<div className="text-xs uppercase tracking-wide text-gray-500 mb-2">Write on the sticker</div>
|
||||
<div className="grid sm:grid-cols-2 gap-3">
|
||||
{kids.map(c => (
|
||||
<div key={c.id} className="border-2 border-dashed border-gray-400 rounded-xl p-4 bg-white" data-testid="sticker">
|
||||
<div className="text-3xl font-bold leading-tight">{c.firstName}</div>
|
||||
<div className="text-lg text-gray-700">{c.room || "—"}</div>
|
||||
<div className="mt-1 text-2xl font-mono font-bold tracking-widest">{code}</div>
|
||||
{c.sticker && <div className="mt-1 text-lg font-bold text-red-700">{c.sticker}</div>}
|
||||
{c.already && <div className="mt-1 text-xs text-gray-500">Was already checked in.</div>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import React, { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, Lock, type LucideIcon } from "lucide-react";
|
||||
import { Calendar, User, LayoutDashboard, ShieldCheck, Globe, Menu, Lock, Baby, type LucideIcon } from "lucide-react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { RoleBadge, type Role } from "@/components/shared/RoleBadge";
|
||||
import { UserAvatar } from "@/components/shared/UserAvatar";
|
||||
@@ -12,6 +12,7 @@ import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
|
||||
const navLinks: { href: string; label: string; icon: LucideIcon; roles?: string[] }[] = [
|
||||
{ href: "/dashboard/user", label: "My Events", icon: Calendar, roles: ["user", "staff", "supervisor", "admin"] },
|
||||
{ href: "/dashboard/user/profile", label: "Profile & Security", icon: User, roles: ["user", "staff", "supervisor", "admin"] },
|
||||
{ href: "/dashboard/user/kids", label: "Kids", icon: Baby, roles: ["user", "staff", "supervisor", "admin"] },
|
||||
{ href: "/dashboard/user/privacy", label: "Privacy", icon: Lock, roles: ["user", "staff", "supervisor", "admin"] },
|
||||
{ href: "/dashboard/staff", label: "Staff", icon: LayoutDashboard, roles: ["staff"] },
|
||||
{ href: "/dashboard/supervisor", label: "Supervisor", icon: LayoutDashboard, roles: ["supervisor"] },
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import React from "react";
|
||||
import { Baby, BellRing, CloudOff, KeyRound, LogIn, LogOut, PenLine, QrCode, Settings, ShieldAlert, ShieldCheck, Users } from "lucide-react";
|
||||
import { GuideItem } from "@/components/shared/GuideItem";
|
||||
import type { HelpContent } from "./types";
|
||||
|
||||
/** Help content for /dashboard/staff/kids (the kids check-in desk). */
|
||||
export const kidsDeskHelpContent: HelpContent = {
|
||||
title: "Kids check-in desk",
|
||||
subtitle: "Check children in and out with pickup codes — no printer needed.",
|
||||
tabs: [
|
||||
{
|
||||
key: "in",
|
||||
label: "Checking in",
|
||||
icon: LogIn,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>Pick the event (and session) at the top. Find the family by a parent's or child's name or phone number, or tap "Scan family QR" and scan the code on the parent's phone (My account → Kids). New here? Tap "New family" and add the parent and their first child.</p>
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Users} title="Ticking children and rooms" tone="brand">
|
||||
Tick the children being dropped off. Each one gets a room suggested from their age — the room with the narrowest age range that isn't full. Change it if you need to. Children already in show "In — room".
|
||||
</GuideItem>
|
||||
<GuideItem icon={KeyRound} title="The pickup code" tone="green">
|
||||
Checking in gives the family a 4-character pickup code for today (or this session), shared by all the children checked in together. It's sent to the parents by WhatsApp or email and shows on their phone. You can also send it to one of the family's authorised adults. Anyone with the code can collect the children.
|
||||
</GuideItem>
|
||||
<GuideItem icon={PenLine} title="Write on the sticker" tone="amber">
|
||||
Nothing is printed. The screen shows, in large letters, what to copy onto a blank name sticker for each child: first name, room, the pickup code and a short alert like ALLERGY: PEANUTS or MEDICAL. The full details stay on the room screen.
|
||||
</GuideItem>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "out",
|
||||
label: "Checking out",
|
||||
icon: LogOut,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>On "Check out", type the code or scan the QR on the parent's phone. You'll see the family, the children on that code (with any custody notes) and who may collect them. Untick any child staying behind, choose or type who is collecting, and tap Check out.</p>
|
||||
<GuideItem icon={ShieldAlert} title="A wrong code" tone="rose">
|
||||
A code that doesn't match anyone is refused, recorded in the audit log and shown as a red alert on the room screens — check the person carefully before handing over any child.
|
||||
</GuideItem>
|
||||
<GuideItem icon={ShieldCheck} title="Without the code" tone="gray">
|
||||
Phone dead or code lost? On "Who's in" (or the room screen), tap "Without code" on the child. You must say who is collecting and why; it's recorded in the audit log.
|
||||
</GuideItem>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "offline",
|
||||
label: "Offline",
|
||||
icon: CloudOff,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>Before the service, while the Wi-Fi works, tap "Get ready for offline". The desk downloads the families and 20 pickup codes kept for this device. If the connection drops, the desk switches to the offline list (or tap "Work offline").</p>
|
||||
<ul className="list-disc pl-5 space-y-1">
|
||||
<li>Offline, no messages are sent — tell the parent their code.</li>
|
||||
<li>Offline, you can only check out children checked in on <strong>this</strong> device.</li>
|
||||
<li>New families and family QR codes need a connection; search by name or phone instead.</li>
|
||||
<li>Back online, tap "Sync". If a family got a different code from another desk meanwhile, you'll be told which code to give them.</li>
|
||||
</ul>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
quickLinks: [{ label: "Room screen", description: "Children in each room, allergies and alerts", href: "/dashboard/staff/kids/rooms", icon: Users }],
|
||||
};
|
||||
|
||||
/** Help content for /dashboard/staff/kids/rooms. */
|
||||
export const kidsRoomsHelpContent: HelpContent = {
|
||||
title: "Kids rooms",
|
||||
subtitle: "Who is in your room, what to watch for, and calling a parent.",
|
||||
tabs: [
|
||||
{
|
||||
key: "room",
|
||||
label: "Your room",
|
||||
icon: Users,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>Choose the event and your room (the screen remembers it). Each child's card shows their pickup code, allergies (red), medical notes (amber) and custody notes — for example "Do not release to …" — with the parents' names and the adults allowed to collect. The screen refreshes every few seconds.</p>
|
||||
<GuideItem icon={Baby} title="I'm on duty" tone="brand">
|
||||
Tap "I'm on duty in this room" when you start, and "I'm going off duty" when you leave. With a ratio set (e.g. 5 children per leader), the room shows "Over ratio" when there are more children than the leaders on duty can look after.
|
||||
</GuideItem>
|
||||
<GuideItem icon={BellRing} title="Call parent" tone="amber">
|
||||
Sends the parents a WhatsApp (or email) asking them to come to the room, and shows it on their Kids page. Medical details are never put in the message.
|
||||
</GuideItem>
|
||||
<GuideItem icon={ShieldAlert} title="Alerts" tone="rose">
|
||||
When someone at the desk enters a wrong pickup code, a red alert appears at the top. Tap "Dealt with" once you've checked.
|
||||
</GuideItem>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** Help content for /dashboard/supervisor/kids. */
|
||||
export const kidsSetupHelpContent: HelpContent = {
|
||||
title: "Kids check-in setup",
|
||||
subtitle: "Switch kids check-in on for an event and set up its rooms.",
|
||||
tabs: [
|
||||
{
|
||||
key: "setup",
|
||||
label: "Setting up",
|
||||
icon: Settings,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>For weekly kids church, use one event with a session per Sunday — families and children are kept between sessions, so parents only add their children once.</p>
|
||||
<ol className="list-decimal pl-5 space-y-1">
|
||||
<li><strong>Kids ticket:</strong> a main ticket covering the whole event. Each child gets a free place on it the first time they're checked in, so they show on the attendance register and reports. "Add a free Kids check-in ticket" makes one.</li>
|
||||
<li><strong>Rooms:</strong> an allocation set; each group is a room with an age range, a capacity and how many children one leader may look after.</li>
|
||||
<li><strong>Switch on.</strong> Staff then use Staff → Kids check-in.</li>
|
||||
</ol>
|
||||
<GuideItem icon={ShieldCheck} title="Children's information" tone="rose">
|
||||
Allergies, medical and custody notes are stored encrypted, shown only to staff at the desk and in the rooms (opening those screens is written to the access log) and never sent in messages. Only parents, supervisors and admins can change custody notes. A child's profile is deleted after 6 months without a check-in (Admin → Privacy → Retention).
|
||||
</GuideItem>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
/** Help content for /dashboard/user/kids. */
|
||||
export const userKidsHelpContent: HelpContent = {
|
||||
title: "Kids",
|
||||
subtitle: "Your children for kids check-in, and their pickup codes.",
|
||||
tabs: [
|
||||
{
|
||||
key: "family",
|
||||
label: "Your family",
|
||||
icon: Baby,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>Add your children once — with their date of birth (so the right room is suggested), allergies and anything leaders should know. Custody notes (e.g. someone who may not collect them) are only shown to the room leaders.</p>
|
||||
<GuideItem icon={Users} title="Authorised adults" tone="brand">
|
||||
List the people who may collect your children, such as grandparents. They don't need an account. The room leader sees the list, and the desk can send them the pickup code.
|
||||
</GuideItem>
|
||||
<GuideItem icon={QrCode} title="Family QR code" tone="gray">
|
||||
Show it at the kids desk to find your family quickly. It can't be used to collect children.
|
||||
</GuideItem>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: "codes",
|
||||
label: "Pickup codes",
|
||||
icon: KeyRound,
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<p>When your children are checked in, their pickup code shows at the top of this page with a QR code, and is sent to you. Show it to collect them. Anyone you give the code to can collect them — use "Send the code to someone else". If a leader asks you to come to the room, it shows here too.</p>
|
||||
<p className="text-xs text-gray-500">A child's details are deleted after 6 months without a check-in. You can remove them at any time.</p>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -33,7 +33,7 @@ export const userPrivacyHelpContent: HelpContent = {
|
||||
content: (
|
||||
<div className="space-y-4">
|
||||
<GuideItem icon={Download} title="Download my data" tone="brand">
|
||||
The PDF is easy to read; the JSON file is the complete copy. Both include your registrations, the people you registered, form answers, payments, tickets and check-ins.
|
||||
The PDF is easy to read; the JSON file is the complete copy. Both include your registrations, the people you registered, form answers, payments, tickets and check-ins, and your family and children for kids check-in.
|
||||
</GuideItem>
|
||||
<GuideItem icon={PencilLine} title="Correct my data" tone="green">
|
||||
Change your name, email and phone in Profile & Security. For anything else, send a correction request — we answer by email within 30 days.
|
||||
@@ -62,7 +62,7 @@ export const adminPrivacyHelpContent: HelpContent = {
|
||||
A checklist with a score: Information Officer set, notice published, operators described, retention reviewed and running, requests answered on time, breaches reported, unsubscribe and WhatsApp STOP working, backups, two-factor login. Each open item links to where you fix it.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Timer} title="Retention" tone="amber">
|
||||
How long each kind of personal information is kept. Every night at 03:30 the retention job deletes or anonymises what's older: inactive accounts (after a warning 30 days before — logging in keeps the account), event form answers, login history, payer details from payment notifications, and old audit/access records. The privacy notice's retention section follows these settings ({"{retention}"}). Review and save them, even if you keep the defaults.
|
||||
How long each kind of personal information is kept. Every night at 03:30 the retention job deletes or anonymises what's older: inactive accounts (after a warning 30 days before — logging in keeps the account), event form answers, children at kids check-in (after 6 months without a check-in), login history, payer details from payment notifications, and old audit/access records. The privacy notice's retention section follows these settings ({"{retention}"}). Review and save them, even if you keep the defaults.
|
||||
</GuideItem>
|
||||
<GuideItem icon={AlertTriangle} title="Breaches" tone="rose">
|
||||
Record any security compromise. POPIA requires telling the Information Regulator and the people affected as soon as reasonably possible; each entry has a draft for both, and you record when you told them. Readiness flags any not reported to the Regulator within 3 days.
|
||||
@@ -101,7 +101,7 @@ export const adminPrivacyHelpContent: HelpContent = {
|
||||
Proof of consent: every news opt-in and opt-out (and how — sign-up, unsubscribe link, STOP reply…), every privacy notice acceptance, and every parental consent answer.
|
||||
</GuideItem>
|
||||
<GuideItem icon={Eye} title="Access log" tone="violet">
|
||||
Who downloaded, emailed or opened personal information in bulk — reports, attendance registers, certificates, group lists, form answers, consent and medical lists, backups — and every "view as" session.
|
||||
Who downloaded, emailed or opened personal information in bulk — reports, attendance registers, certificates, group lists, form answers, consent and medical lists, the kids check-in desk and room screens, backups — and every "view as" session.
|
||||
</GuideItem>
|
||||
</div>
|
||||
),
|
||||
|
||||
@@ -34,6 +34,7 @@ import { supervisorWhatsappAttendeesHelpContent } from "./supervisor-whatsapp-at
|
||||
import { staffEventTicketsHelpContent } from "./staff-event-tickets";
|
||||
import { staffTicketScanningHelpContent } from "./staff-ticket-scanning";
|
||||
import { userFormsHelpContent } from "./user-forms";
|
||||
import { kidsDeskHelpContent, kidsRoomsHelpContent, kidsSetupHelpContent, userKidsHelpContent } from "./kids";
|
||||
|
||||
type HelpRegistryEntry = {
|
||||
/** Unique, stable identifier for this guide. */
|
||||
@@ -160,6 +161,26 @@ const REGISTRY: HelpRegistryEntry[] = [
|
||||
matches: pathname => pathname === "/dashboard/supervisor/allocations",
|
||||
content: supervisorAllocationsHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "staff-kids-rooms",
|
||||
matches: pathname => pathname === "/dashboard/staff/kids/rooms",
|
||||
content: kidsRoomsHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "staff-kids",
|
||||
matches: pathname => pathname === "/dashboard/staff/kids",
|
||||
content: kidsDeskHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "supervisor-kids",
|
||||
matches: pathname => pathname === "/dashboard/supervisor/kids",
|
||||
content: kidsSetupHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "user-kids",
|
||||
matches: pathname => pathname === "/dashboard/user/kids",
|
||||
content: userKidsHelpContent,
|
||||
},
|
||||
{
|
||||
slug: "staff-my-groups",
|
||||
matches: pathname => pathname === "/dashboard/staff/my-groups",
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// Kids check-in (1.45.0): shared types and the offline desk's local copy.
|
||||
|
||||
export type KidsChild = {
|
||||
id: string; firstName: string; lastName: string; name: string; dateOfBirth: string | null; age: number | null;
|
||||
gender: string | null; allergies: string; hasMedical: boolean; hasCustody: boolean;
|
||||
medicalNotes?: string; custodyNotes?: string; lastCheckInAt: string | null;
|
||||
};
|
||||
export type KidsParent = { userId: string; name: string; phone: string | null; email: string | null };
|
||||
export type KidsAdult = { id: string; name: string; phone: string | null; relationship: string | null };
|
||||
export type KidsFamily = { id: string; name: string; parents: KidsParent[]; children: KidsChild[]; adults: KidsAdult[] };
|
||||
|
||||
export type KidsRoom = {
|
||||
id: string; name: string; minAge: number | null; maxAge: number | null; capacity: number | null; ratio: number | null; order: number;
|
||||
leaderNames: string[]; leaderIds: string[]; children: number; leaders: number; leadersNeeded: number; full: boolean; overRatio: boolean;
|
||||
};
|
||||
export type KidsCheckIn = {
|
||||
id: string; childId: string | null; name: string; firstName: string; age: number | null; roomId: string | null; code: string;
|
||||
checkedInAt: string; checkedInBy: string | null; checkedOutAt: string | null; checkedOutBy: string | null; collectedBy: string | null;
|
||||
override: boolean; offline: boolean; allergies: string; medicalNotes: string; custodyNotes: string; sticker: string;
|
||||
family: { id: string; name: string; parents: KidsParent[]; adults: KidsAdult[] } | null;
|
||||
};
|
||||
export type KidsAlert = { id: string; kind: "wrong_code" | "page_parent" | "override"; roomId: string | null; checkInId: string | null; message: string; by: string | null; at: string; resolvedAt: string | null };
|
||||
export type KidsBoard = {
|
||||
event: { id: string; title: string; scheduleType: string };
|
||||
occasion: string; sessionId: string | null; sessionLabel: string | null;
|
||||
rooms: KidsRoom[]; checkIns: KidsCheckIn[]; alerts: KidsAlert[];
|
||||
};
|
||||
export type KidsEvent = {
|
||||
id: string; title: string; startDate: string; endDate: string; scheduleType: string; campusId: string | null;
|
||||
sessions: { id: string; label: string | null; startsAt: string; endsAt: string }[];
|
||||
};
|
||||
export type CheckInResult = {
|
||||
code: string; qr: string; occasion: string; family: { id: string; name: string };
|
||||
checkIns: { id: string; name: string; firstName: string; room: { id: string; name: string } | null; already: boolean; sticker: string }[];
|
||||
};
|
||||
|
||||
export const QR_PREFIX = "KIDS-";
|
||||
export const FAMILY_QR_PREFIX = "FAMILY-";
|
||||
|
||||
/** "2–4 yrs", "4+ yrs", "up to 3 yrs", "" */
|
||||
export function ageRange(r: { minAge: number | null; maxAge: number | null }) {
|
||||
if (r.minAge != null && r.maxAge != null) return `${r.minAge}–${r.maxAge} yrs`;
|
||||
if (r.minAge != null) return `${r.minAge}+ yrs`;
|
||||
if (r.maxAge != null) return `up to ${r.maxAge} yrs`;
|
||||
return "";
|
||||
}
|
||||
|
||||
/** The same choice as the backend's suggestRoom: narrowest fitting room that isn't full. */
|
||||
export function suggestRoom(rooms: KidsRoom[], age: number | null, extra: Record<string, number> = {}) {
|
||||
const fits = rooms.filter(r =>
|
||||
(age == null || ((r.minAge == null || age >= r.minAge) && (r.maxAge == null || age <= r.maxAge)))
|
||||
&& !(r.capacity && r.children + (extra[r.id] || 0) >= r.capacity));
|
||||
const span = (r: KidsRoom) => (r.maxAge ?? 25) - (r.minAge ?? 0);
|
||||
return [...fits].sort((a, b) => (age == null ? 0 : span(a) - span(b)) || a.order - b.order)[0] || rooms[0] || null;
|
||||
}
|
||||
|
||||
export function stickerAlert(allergies: string, medical: boolean) {
|
||||
const parts: string[] = [];
|
||||
const a = (allergies || "").trim();
|
||||
if (a) parts.push(`ALLERGY: ${a.toUpperCase().slice(0, 24)}${a.length > 24 ? "…" : ""}`);
|
||||
if (medical) parts.push("MEDICAL");
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
// ─── Offline desk ─────────────────────────────────────────────────────────────
|
||||
|
||||
export type OfflineSnapshot = {
|
||||
occasion: string; sessionId: string | null; sessionLabel: string | null;
|
||||
event: { id: string; title: string; scheduleType: string };
|
||||
rooms: KidsRoom[]; checkIns: KidsCheckIn[]; families: KidsFamily[]; codes: string[]; downloadedAt: string;
|
||||
};
|
||||
export type OfflineCheckIn = { clientId: string; familyId: string; childId: string; roomId: string; code: string; at: string; name: string; roomName: string };
|
||||
export type OfflineCheckOut = { clientId: string; collectedBy: string; at: string };
|
||||
export type OfflineState = {
|
||||
snapshot: OfflineSnapshot;
|
||||
// Codes handed out offline, per family (one code per family per occasion).
|
||||
familyCodes: Record<string, string>;
|
||||
checkIns: OfflineCheckIn[];
|
||||
checkOuts: OfflineCheckOut[];
|
||||
};
|
||||
|
||||
const key = (eventId: string) => `hope_events_kids_offline_${eventId}`;
|
||||
|
||||
export function deviceId(): string {
|
||||
const k = "hope_events_kids_device";
|
||||
try {
|
||||
let id = localStorage.getItem(k);
|
||||
if (!id) {
|
||||
id = `kd-${crypto.randomUUID()}`;
|
||||
localStorage.setItem(k, id);
|
||||
}
|
||||
return id;
|
||||
} catch {
|
||||
return "kd-unknown";
|
||||
}
|
||||
}
|
||||
|
||||
export function loadOffline(eventId: string): OfflineState | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(key(eventId));
|
||||
return raw ? (JSON.parse(raw) as OfflineState) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveOffline(eventId: string, state: OfflineState | null) {
|
||||
try {
|
||||
if (state) localStorage.setItem(key(eventId), JSON.stringify(state));
|
||||
else localStorage.removeItem(key(eventId));
|
||||
} catch {
|
||||
// Storage full or blocked: the desk keeps working online.
|
||||
}
|
||||
}
|
||||
|
||||
/** Check children in on the offline copy. Returns the code, or throws when the device has no codes left. */
|
||||
export function offlineCheckIn(state: OfflineState, family: KidsFamily, picks: { child: KidsChild; room: KidsRoom }[]): { state: OfflineState; code: string } {
|
||||
const used = new Set(Object.values(state.familyCodes));
|
||||
const code = state.familyCodes[family.id] || state.snapshot.codes.find(c => !used.has(c));
|
||||
if (!code) throw new Error("This device has no offline pickup codes left. Go back online to get more.");
|
||||
const at = new Date().toISOString();
|
||||
const already = new Set(state.checkIns.filter(c => !state.checkOuts.some(o => o.clientId === c.clientId)).map(c => c.childId));
|
||||
const fresh = picks.filter(p => !already.has(p.child.id)).map(p => ({
|
||||
clientId: `kc-${crypto.randomUUID()}`, familyId: family.id, childId: p.child.id, roomId: p.room.id, code, at, name: p.child.name, roomName: p.room.name,
|
||||
}));
|
||||
return { code, state: { ...state, familyCodes: { ...state.familyCodes, [family.id]: code }, checkIns: [...state.checkIns, ...fresh] } };
|
||||
}
|
||||
Reference in New Issue
Block a user