import { For, Show, createEffect, createMemo, createSignal } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { deleteSessionAttendanceByUserId, getSessionAttendance, postSessionAttendance } from "@/api/sessions"; import { getSettings } from "@/api/settings"; import { formatApiError } from "@/api/client"; import type { AttendanceStatus, Enrollment, PersonRef } from "@/api/client"; import { Alert } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { EmptyState } from "@/components/ui/empty-state"; import { ErrorAlert } from "@/components/ui/error-alert"; import { IconCheck, IconX } from "@/components/ui/icons"; import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status"; import { cn } from "@/lib/cn"; import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; /** Parallel requests while marking the rest present; the API takes one row per call. */ const BULK_CONCURRENCY = 4; type RollCallTarget = { user: PersonRef; isTeacher: boolean; }; /** * Lesson roll call built for speed: one list, a tap on a status saves that * row at once, and "mark the rest present" fills every unmarked row — the * teacher then only touches the exceptions. Nothing is shown as present * until it is actually saved: an unmarked row stays visibly unmarked. */ export function SessionRollCall(props: { sessionId: string; roster: Enrollment[]; teacher: PersonRef; canMarkTeacher: boolean; }) { const t = useT(); const [settings] = createResource(() => getSettings()); // The school's statuses in its own order, except "present" leads: it is // the one a teacher taps most, so it sits first on every row. const statuses = createMemo(() => { const list = (settings.error ? undefined : settings.latest)?.attendance_statuses ?? ATTENDANCE_STATUSES.map((item) => item.value); return list.includes("present") ? ["present", ...list.filter((status) => status !== "present")] : list; }); const [attendance, { refetch: refetchAttendance }] = createResource( () => props.sessionId, async (sessionId) => (await getSessionAttendance(sessionId)).items, ); // Saved marks live in a local signal seeded from the server list: a tap // updates it optimistically instead of refetching the whole roster. const [marks, setMarks] = createSignal>({}); createEffect(() => { // An errored read throws on access; the ErrorAlert below offers a retry. if (attendance.error) return; const rows = attendance.latest; if (rows) setMarks(Object.fromEntries(rows.map((row) => [row.user.id, row.status]))); }); // The roster renders from props at once, but the saved marks arrive with // the attendance read; a tap before then would be overwritten by it, so // the status buttons wait for it. const ready = () => !attendance.error && attendance.latest !== undefined; const targets = createMemo(() => [ ...props.roster.map((row) => ({ user: row.user, isTeacher: false })), ...(props.canMarkTeacher && !props.roster.some((row) => row.user.id === props.teacher.id) ? [{ user: props.teacher, isTeacher: true }] : []), ]); const [saving, setSaving] = createSignal>(new Set()); const [error, setError] = createSignal(""); const [onlyUnmarked, setOnlyUnmarked] = createSignal(false); const [bulk, setBulk] = createSignal<{ done: number; total: number } | null>(null); const markedCount = createMemo(() => targets().filter((target) => marks()[target.user.id] != null).length); const unmarked = createMemo(() => targets().filter((target) => marks()[target.user.id] == null)); const counts = createMemo(() => { const tally: Record = {}; for (const target of targets()) { const status = marks()[target.user.id]; if (status) tally[status] = (tally[status] ?? 0) + 1; } return tally; }); const studentsLeft = createMemo(() => unmarked().filter((target) => !target.isTeacher).length); const visibleTargets = createMemo(() => (onlyUnmarked() ? unmarked() : targets())); const setBusy = (userId: string, busy: boolean) => setSaving((current) => { const next = new Set(current); if (busy) next.add(userId); else next.delete(userId); return next; }); const setMark = (userId: string, status: AttendanceStatus | undefined) => setMarks((current) => { const next = { ...current }; if (status) next[userId] = status; else delete next[userId]; return next; }); const mark = async (userId: string, status: AttendanceStatus) => { const previous = marks()[userId]; if (previous === status || saving().has(userId)) return; setError(""); setMark(userId, status); setBusy(userId, true); try { await postSessionAttendance(props.sessionId, { user_id: userId, status }); } catch (err) { setMark(userId, previous); setError(formatApiError(err)); } finally { setBusy(userId, false); } }; const clear = async (userId: string) => { const previous = marks()[userId]; if (!previous || saving().has(userId)) return; setError(""); setMark(userId, undefined); setBusy(userId, true); try { await deleteSessionAttendanceByUserId(props.sessionId, userId); } catch (err) { setMark(userId, previous); setError(formatApiError(err)); } finally { setBusy(userId, false); } }; const markRestPresent = async () => { // Students only: the teacher's own presence row is a separate, deliberate call. const queue = unmarked().filter((target) => !target.isTeacher).map((target) => target.user.id); if (queue.length === 0 || bulk()) return; setError(""); setBulk({ done: 0, total: queue.length }); const failures: unknown[] = []; const worker = async () => { for (let userId = queue.shift(); userId; userId = queue.shift()) { setMark(userId, "present"); setBusy(userId, true); try { await postSessionAttendance(props.sessionId, { user_id: userId, status: "present" }); } catch (err) { setMark(userId, undefined); failures.push(err); } finally { setBusy(userId, false); setBulk((current) => (current ? { ...current, done: current.done + 1 } : current)); } } }; await Promise.all(Array.from({ length: BULK_CONCURRENCY }, worker)); setBulk(null); if (failures.length > 0) setError(t("rollCall.bulkFailed", { count: failures.length, reason: formatApiError(failures[0]) })); }; const statusLabel = (status: AttendanceStatus) => { const meta = getAttendanceStatusMeta(status); return meta ? t(meta.key) : status; }; return (
{error()} void refetchAttendance()} /> 0} fallback={} >

{ready() ? t("rollCall.progress", { marked: markedCount(), total: targets().length }) : attendance.error ? "—" : t("common.loading")}

{(status) => ( {statusLabel(status)} {counts()[status]} )}
0} fallback={

{t("rollCall.allMarked")}

} >
    {(target) => { const current = () => marks()[target.user.id]; const busy = () => saving().has(target.user.id); const groupLabel = () => personLabel(target.user); return (
  • {(status) => { const selected = () => current() === status; return ( ); }}
  • ); }}
); }