Archived
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:
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user