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