forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

session-roll-call.tsx304 lines, 13.2 KiBHistoryRawDownload
1import { For, Show, createEffect, createMemo, createSignal } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import { deleteSessionAttendanceByUserId, getSessionAttendance, postSessionAttendance } from "@/api/sessions";
4import { getSettings } from "@/api/settings";
5import { formatApiError } from "@/api/client";
6import type { AttendanceStatus, Enrollment, PersonRef } from "@/api/client";
7import { Alert } from "@/components/ui/alert";
8import { Badge } from "@/components/ui/badge";
9import { Button } from "@/components/ui/button";
10import { EmptyState } from "@/components/ui/empty-state";
11import { ErrorAlert } from "@/components/ui/error-alert";
12import { IconCheck, IconX } from "@/components/ui/icons";
13import { ATTENDANCE_STATUSES, getAttendanceStatusMeta } from "@/lib/attendance-status";
14import { cn } from "@/lib/cn";
15import { personLabel } from "@/lib/person";
16import { useT } from "@/stores/preferences-context";
17
18/** Parallel requests while marking the rest present; the API takes one row per call. */
19const BULK_CONCURRENCY = 4;
20
21type RollCallTarget = {
22 user: PersonRef;
23 isTeacher: boolean;
24};
25
26/**
27 * Lesson roll call built for speed: one list, a tap on a status saves that
28 * row at once, and "mark the rest present" fills every unmarked row — the
29 * teacher then only touches the exceptions. Nothing is shown as present
30 * until it is actually saved: an unmarked row stays visibly unmarked.
31 */
32export function SessionRollCall(props: {
33 sessionId: string;
34 roster: Enrollment[];
35 teacher: PersonRef;
36 canMarkTeacher: boolean;
37}) {
38 const t = useT();
39 const [settings] = createResource(() => getSettings());
40 // The school's statuses in its own order, except "present" leads: it is
41 // the one a teacher taps most, so it sits first on every row.
42 const statuses = createMemo<AttendanceStatus[]>(() => {
43 const list = (settings.error ? undefined : settings.latest)?.attendance_statuses ?? ATTENDANCE_STATUSES.map((item) => item.value);
44 return list.includes("present") ? ["present", ...list.filter((status) => status !== "present")] : list;
45 });
46 const [attendance, { refetch: refetchAttendance }] = createResource(
47 () => props.sessionId,
48 async (sessionId) => (await getSessionAttendance(sessionId)).items,
49 );
50 // Saved marks live in a local signal seeded from the server list: a tap
51 // updates it optimistically instead of refetching the whole roster.
52 const [marks, setMarks] = createSignal<Record<string, AttendanceStatus>>({});
53 createEffect(() => {
54 // An errored read throws on access; the ErrorAlert below offers a retry.
55 if (attendance.error) return;
56 const rows = attendance.latest;
57 if (rows) setMarks(Object.fromEntries(rows.map((row) => [row.user.id, row.status])));
58 });
59
60 // The roster renders from props at once, but the saved marks arrive with
61 // the attendance read; a tap before then would be overwritten by it, so
62 // the status buttons wait for it.
63 const ready = () => !attendance.error && attendance.latest !== undefined;
64 const targets = createMemo<RollCallTarget[]>(() => [
65 ...props.roster.map((row) => ({ user: row.user, isTeacher: false })),
66 ...(props.canMarkTeacher && !props.roster.some((row) => row.user.id === props.teacher.id)
67 ? [{ user: props.teacher, isTeacher: true }]
68 : []),
69 ]);
70 const [saving, setSaving] = createSignal<ReadonlySet<string>>(new Set());
71 const [error, setError] = createSignal("");
72 const [onlyUnmarked, setOnlyUnmarked] = createSignal(false);
73 const [bulk, setBulk] = createSignal<{ done: number; total: number } | null>(null);
74
75 const markedCount = createMemo(() => targets().filter((target) => marks()[target.user.id] != null).length);
76 const unmarked = createMemo(() => targets().filter((target) => marks()[target.user.id] == null));
77 const counts = createMemo(() => {
78 const tally: Record<string, number> = {};
79 for (const target of targets()) {
80 const status = marks()[target.user.id];
81 if (status) tally[status] = (tally[status] ?? 0) + 1;
82 }
83 return tally;
84 });
85 const studentsLeft = createMemo(() => unmarked().filter((target) => !target.isTeacher).length);
86 const visibleTargets = createMemo(() => (onlyUnmarked() ? unmarked() : targets()));
87
88 const setBusy = (userId: string, busy: boolean) =>
89 setSaving((current) => {
90 const next = new Set(current);
91 if (busy) next.add(userId);
92 else next.delete(userId);
93 return next;
94 });
95 const setMark = (userId: string, status: AttendanceStatus | undefined) =>
96 setMarks((current) => {
97 const next = { ...current };
98 if (status) next[userId] = status;
99 else delete next[userId];
100 return next;
101 });
102
103 const mark = async (userId: string, status: AttendanceStatus) => {
104 const previous = marks()[userId];
105 if (previous === status || saving().has(userId)) return;
106 setError("");
107 setMark(userId, status);
108 setBusy(userId, true);
109 try {
110 await postSessionAttendance(props.sessionId, { user_id: userId, status });
111 } catch (err) {
112 setMark(userId, previous);
113 setError(formatApiError(err));
114 } finally {
115 setBusy(userId, false);
116 }
117 };
118
119 const clear = async (userId: string) => {
120 const previous = marks()[userId];
121 if (!previous || saving().has(userId)) return;
122 setError("");
123 setMark(userId, undefined);
124 setBusy(userId, true);
125 try {
126 await deleteSessionAttendanceByUserId(props.sessionId, userId);
127 } catch (err) {
128 setMark(userId, previous);
129 setError(formatApiError(err));
130 } finally {
131 setBusy(userId, false);
132 }
133 };
134
135 const markRestPresent = async () => {
136 // Students only: the teacher's own presence row is a separate, deliberate call.
137 const queue = unmarked().filter((target) => !target.isTeacher).map((target) => target.user.id);
138 if (queue.length === 0 || bulk()) return;
139 setError("");
140 setBulk({ done: 0, total: queue.length });
141 const failures: unknown[] = [];
142 const worker = async () => {
143 for (let userId = queue.shift(); userId; userId = queue.shift()) {
144 setMark(userId, "present");
145 setBusy(userId, true);
146 try {
147 await postSessionAttendance(props.sessionId, { user_id: userId, status: "present" });
148 } catch (err) {
149 setMark(userId, undefined);
150 failures.push(err);
151 } finally {
152 setBusy(userId, false);
153 setBulk((current) => (current ? { ...current, done: current.done + 1 } : current));
154 }
155 }
156 };
157 await Promise.all(Array.from({ length: BULK_CONCURRENCY }, worker));
158 setBulk(null);
159 if (failures.length > 0) setError(t("rollCall.bulkFailed", { count: failures.length, reason: formatApiError(failures[0]) }));
160 };
161
162 const statusLabel = (status: AttendanceStatus) => {
163 const meta = getAttendanceStatusMeta(status);
164 return meta ? t(meta.key) : status;
165 };
166
167 return (
168 <div class="space-y-3">
169 <Show when={error()}>
170 <Alert variant="destructive">{error()}</Alert>
171 </Show>
172 <Show when={attendance.error}>
173 <ErrorAlert message={formatApiError(attendance.error)} onRetry={() => void refetchAttendance()} />
174 </Show>
175 <Show
176 when={targets().length > 0}
177 fallback={<EmptyState kind="people" title={t("sessions.emptyRoster")} />}
178 >
179 <div class="sticky top-0 z-10 -mx-5 space-y-2.5 border-b border-border-hairline bg-surface-base px-5 pb-3">
180 <div class="flex items-center justify-between gap-3">
181 <p class="text-sm font-semibold text-text-strong" role="status">
182 {ready() ? t("rollCall.progress", { marked: markedCount(), total: targets().length }) : attendance.error ? "—" : t("common.loading")}
183 </p>
184 <div class="flex flex-wrap justify-end gap-1.5">
185 <For each={statuses()}>
186 {(status) => (
187 <Show when={counts()[status]}>
188 <span class={cn("rounded-full border px-2 py-0.5 text-xs font-medium", getAttendanceStatusMeta(status)?.class)}>
189 {statusLabel(status)} {counts()[status]}
190 </span>
191 </Show>
192 )}
193 </For>
194 </div>
195 </div>
196 <div class="h-1.5 overflow-hidden rounded-full bg-surface-tint" aria-hidden="true">
197 <div
198 class="h-full rounded-full bg-success transition-[width] duration-200"
199 style={{ width: `${targets().length ? (markedCount() / targets().length) * 100 : 0}%` }}
200 />
201 </div>
202 <div class="flex flex-wrap items-center gap-2">
203 <Button
204 type="button"
205 size="sm"
206 variant={studentsLeft() > 0 || bulk() ? "default" : "outline"}
207 class="h-10 rounded-lg sm:h-9 touch:h-10"
208 disabled={!ready() || bulk() != null || studentsLeft() === 0}
209 onClick={() => void markRestPresent()}
210 >
211 <IconCheck class="h-4 w-4" />
212 {bulk()
213 ? t("rollCall.marking", { done: bulk()!.done, total: bulk()!.total })
214 : studentsLeft() > 0
215 ? t("rollCall.markRestPresent")
216 : t("rollCall.studentsDone")}
217 </Button>
218 <Button
219 type="button"
220 size="sm"
221 variant="outline"
222 class="h-10 rounded-lg sm:h-9 touch:h-10"
223 aria-pressed={onlyUnmarked()}
224 onClick={() => setOnlyUnmarked((value) => !value)}
225 >
226 {t("rollCall.onlyUnmarked")}
227 </Button>
228 </div>
229 </div>
230
231 <Show
232 when={visibleTargets().length > 0}
233 fallback={<p class="py-6 text-center text-sm text-muted-foreground">{t("rollCall.allMarked")}</p>}
234 >
235 <ul class="divide-y divide-border-hairline">
236 <For each={visibleTargets()}>
237 {(target) => {
238 const current = () => marks()[target.user.id];
239 const busy = () => saving().has(target.user.id);
240 const groupLabel = () => personLabel(target.user);
241 return (
242 <li class="flex flex-col gap-2 py-2.5 sm:flex-row sm:items-center">
243 <div class="flex min-w-0 flex-1 items-center gap-2">
244 <span
245 class={cn("h-2 w-2 shrink-0 rounded-full", current() ? "bg-success" : "bg-border-line")}
246 aria-hidden="true"
247 />
248 <div class="min-w-0">
249 <p class="truncate text-sm font-medium">{groupLabel()}</p>
250 <p class="truncate text-xs text-muted-foreground">
251 {current() ? statusLabel(current()!) : t("rollCall.unmarked")}
252 </p>
253 </div>
254 <Show when={target.isTeacher}>
255 <Badge variant="secondary" class="shrink-0 rounded-full">{t("sessions.teacher")}</Badge>
256 </Show>
257 </div>
258 <div class="flex items-center gap-1.5">
259 <div role="radiogroup" aria-label={groupLabel()} class="flex min-w-0 flex-1 gap-1 sm:flex-none">
260 <For each={statuses()}>
261 {(status) => {
262 const selected = () => current() === status;
263 return (
264 <button
265 type="button"
266 role="radio"
267 aria-checked={selected()}
268 disabled={!ready() || busy() || bulk() != null}
269 class={cn(
270 "h-10 min-w-0 flex-1 truncate rounded-lg border px-1 text-xs sm:h-9 sm:px-2.5 sm:flex-none touch:h-10 font-semibold transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60",
271 selected()
272 ? getAttendanceStatusMeta(status)?.class ?? "border-primary bg-primary/10 text-primary-text"
273 : "border-border-line bg-surface-base text-muted-foreground hover:bg-muted/60 hover:text-foreground",
274 )}
275 onClick={() => void mark(target.user.id, status)}
276 >
277 {statusLabel(status)}
278 </button>
279 );
280 }}
281 </For>
282 </div>
283 <Button
284 type="button"
285 variant="ghost"
286 size="icon"
287 class={cn("h-10 w-10 shrink-0 text-muted-foreground sm:h-9 sm:w-9 touch:h-10 touch:w-10", !current() && "invisible")}
288 aria-label={`${t("rollCall.clear")}: ${groupLabel()}`}
289 disabled={busy() || !current()}
290 onClick={() => void clear(target.user.id)}
291 >
292 <IconX class="h-4 w-4" />
293 </Button>
294 </div>
295 </li>
296 );
297 }}
298 </For>
299 </ul>
300 </Show>
301 </Show>
302 </div>
303 );
304}