diff --git a/src/components/sessions/course-sessions-panel.tsx b/src/components/sessions/course-sessions-panel.tsx index 246df04..3704a70 100644 --- a/src/components/sessions/course-sessions-panel.tsx +++ b/src/components/sessions/course-sessions-panel.tsx @@ -376,6 +376,7 @@ export function CourseSessionsPanel(props: { if (!open) setSelectedSession(null); }} title={t("sessions.rollCall")} + size="wide" description={selectedSession() ? `${selectedSession()!.topic || t("sessions.untitled")} · ${formatDateTime(selectedSession()!.starts_at, locale())}` : undefined} > diff --git a/src/components/sessions/session-roll-call.test.tsx b/src/components/sessions/session-roll-call.test.tsx index fcd9e70..af359d5 100644 --- a/src/components/sessions/session-roll-call.test.tsx +++ b/src/components/sessions/session-roll-call.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; import { SessionRollCall } from "@/components/sessions/session-roll-call"; import { PreferencesProvider } from "@/stores/preferences-context"; @@ -24,13 +24,14 @@ vi.mock("@/api/settings", () => ({ getSettings: async () => ({ attendance_statuses: ["present", "absent", "late", "excused"] }), })); -const roster = [{ - id: "enrollment-1", +const enrollment = (id: string, name: string) => ({ + id: `enrollment-${id}`, class_course: "instance-1", - user: { id: "student-1", username: "ada", display_name: "Ada Öğrenci" }, + user: { id, username: id, display_name: name }, enrolled_by: { id: "manager-1", username: "manager", display_name: null }, source: null, -}]; +}); +const roster = [enrollment("student-1", "Ada Öğrenci")]; const teacher = { id: "teacher-1", username: "teacher", display_name: "Deniz Öğretmen" }; @@ -38,35 +39,89 @@ afterEach(() => { vi.clearAllMocks(); }); -test("lets manager-level users mark the session teacher alongside enrolled students", async () => { +const mount = (props: { roster?: ReturnType[]; canMarkTeacher?: boolean } = {}) => render(() => ( - + )); +const statusButtons = (name: string) => within(screen.getByRole("radiogroup", { name })); +/** The status buttons unlock once the saved marks have loaded. */ +const ready = () => screen.findByText(/\d+ of \d+ marked|kişiden \d+ işaretlendi/); - expect(await screen.findByText("Ada Öğrenci")).toBeTruthy(); - expect(screen.getByText("Deniz Öğretmen")).toBeTruthy(); +test("lets manager-level users mark the session teacher alongside enrolled students", async () => { + mount({ canMarkTeacher: true }); - const saveButtons = screen.getAllByRole("button", { name: "Save" }); - fireEvent.click(saveButtons[1]!); + expect(await screen.findByText("Ada Öğrenci")).toBeTruthy(); + await ready(); + fireEvent.click(statusButtons("Deniz Öğretmen").getByRole("radio", { name: /Present|Var|Mevcut/ })); await waitFor(() => { - expect(postSessionAttendance).toHaveBeenCalledWith("session-1", { - user_id: "teacher-1", - status: "present", - }); + expect(postSessionAttendance).toHaveBeenCalledWith("session-1", { user_id: "teacher-1", status: "present" }); }); }); test("keeps the teacher out of roll call for users without staff-attendance rights", async () => { - render(() => ( - - - - )); + mount(); expect(await screen.findByText("Ada Öğrenci")).toBeTruthy(); expect(screen.queryByText("Deniz Öğretmen")).toBeNull(); - expect(screen.getAllByRole("button", { name: "Save" })).toHaveLength(1); + expect(screen.getAllByRole("radiogroup")).toHaveLength(1); +}); + +test("one tap saves that row, with no roster refetch", async () => { + mount(); + await ready(); + const absent = statusButtons("Ada Öğrenci").getByRole("radio", { name: /Absent|Yok|Devamsız/ }); + + fireEvent.click(absent); + + await waitFor(() => expect(postSessionAttendance).toHaveBeenCalledWith("session-1", { user_id: "student-1", status: "absent" })); + expect(absent.getAttribute("aria-checked")).toBe("true"); + expect(getSessionAttendance).toHaveBeenCalledTimes(1); +}); + +test("mark the rest present fills only the unmarked students", async () => { + getSessionAttendance.mockResolvedValueOnce({ + items: [{ + id: "a-2", + session: "session-1", + class_course: "instance-1", + user: { id: "student-2", username: "student-2", display_name: "Bora" }, + status: "absent", + marked_by: { id: "teacher-1", username: "teacher", display_name: null }, + }], + total: 1, + limit: null, + offset: 0, + } as never); + mount({ + roster: [enrollment("student-1", "Ada"), enrollment("student-2", "Bora"), enrollment("student-3", "Cem")], + canMarkTeacher: true, + }); + expect(await screen.findByText(/1 of 4 marked|4 kişiden 1/)).toBeTruthy(); + + fireEvent.click(screen.getByRole("button", { name: /Mark the rest present|Kalanları Var/ })); + + await waitFor(() => expect(postSessionAttendance).toHaveBeenCalledTimes(2)); + const marked = postSessionAttendance.mock.calls.map(([, body]) => body.user_id).sort(); + expect(marked).toEqual(["student-1", "student-3"]); + expect(await screen.findByText(/3 of 4 marked|4 kişiden 3/)).toBeTruthy(); +}); + +test("a failed save puts the row back as it was", async () => { + postSessionAttendance.mockRejectedValueOnce(new Error("offline")); + mount(); + await ready(); + const late = statusButtons("Ada Öğrenci").getByRole("radio", { name: /Late|Geç/ }); + + fireEvent.click(late); + + await waitFor(() => expect(screen.getByRole("alert")).toBeTruthy()); + expect(late.getAttribute("aria-checked")).toBe("false"); }); diff --git a/src/components/sessions/session-roll-call.tsx b/src/components/sessions/session-roll-call.tsx index 04b40fc..09417a3 100644 --- a/src/components/sessions/session-roll-call.tsx +++ b/src/components/sessions/session-roll-call.tsx @@ -1,26 +1,33 @@ 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, SessionAttendance } from "@/api/client"; -import { AttendanceStatusPicker } from "@/components/events/attendance-status-picker"; +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 { IconTrash } from "@/components/ui/icons"; -import { PaginationControls } from "@/components/ui/pagination-controls"; -import { createFlash } from "@/lib/flash"; +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"; -const PAGE_SIZE = 8; +/** 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[]; @@ -28,74 +35,130 @@ export function SessionRollCall(props: { canMarkTeacher: boolean; }) { const t = useT(); - const [attendance, { refetch }] = createResource( + const [settings] = createResource(() => getSettings()); + const statuses = createMemo( + () => settings.latest?.attendance_statuses ?? ATTENDANCE_STATUSES.map((item) => item.value), + ); + const [attendance] = createResource( () => props.sessionId, async (sessionId) => (await getSessionAttendance(sessionId)).items, ); - const rows = createMemo(() => new Map((attendance() ?? []).map((row) => [row.user.id, row]))); + // 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(() => { + 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.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 [local, setLocal] = createSignal>({}); - const [pendingUserId, setPendingUserId] = createSignal(null); + const [saving, setSaving] = createSignal>(new Set()); const [error, setError] = createSignal(""); - const [flash, setFlash] = createFlash(); - const [page, setPage] = createSignal(0); - const totalPages = createMemo(() => Math.max(1, Math.ceil(targets().length / PAGE_SIZE))); - const safePage = createMemo(() => Math.min(page(), totalPages() - 1)); - const visibleTargets = createMemo(() => { - const start = safePage() * PAGE_SIZE; - return targets().slice(start, start + PAGE_SIZE); - }); + const [onlyUnmarked, setOnlyUnmarked] = createSignal(false); + const [bulk, setBulk] = createSignal<{ done: number; total: number } | null>(null); - createEffect(() => { - if (page() >= totalPages()) setPage(totalPages() - 1); + 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 visibleTargets = createMemo(() => (onlyUnmarked() ? unmarked() : targets())); - const statusFor = (userId: string) => local()[userId] ?? rows().get(userId)?.status ?? "present"; - const save = async (userId: string) => { - if (pendingUserId()) return; + 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(""); - setPendingUserId(userId); + setMark(userId, status); + setBusy(userId, true); try { - await postSessionAttendance(props.sessionId, { user_id: userId, status: statusFor(userId) }); - await refetch(); - setFlash(t("common.saved")); + await postSessionAttendance(props.sessionId, { user_id: userId, status }); } catch (err) { + setMark(userId, previous); setError(formatApiError(err)); } finally { - setPendingUserId(null); + setBusy(userId, false); } }; const clear = async (userId: string) => { - if (pendingUserId()) return; + const previous = marks()[userId]; + if (!previous || saving().has(userId)) return; setError(""); - setPendingUserId(userId); + setMark(userId, undefined); + setBusy(userId, true); try { await deleteSessionAttendanceByUserId(props.sessionId, userId); - setLocal((current) => { - const next = { ...current }; - delete next[userId]; - return next; - }); - await refetch(); - setFlash(t("common.deleted")); } catch (err) { + setMark(userId, previous); setError(formatApiError(err)); } finally { - setPendingUserId(null); + 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 (
- - {flash()} - {error()} @@ -103,66 +166,125 @@ export function SessionRollCall(props: { when={targets().length > 0} fallback={} > - - {(target) => { - const saved = () => rows().get(target.user.id) as SessionAttendance | undefined; - const pending = () => pendingUserId() === target.user.id; - return ( -
-
-
-

{personLabel(target.user)}

- -

{target.user.username}

-
-
- - {t("sessions.teacher")} +
+
+

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

+
+ + {(status) => ( + + + {statusLabel(status)} {counts()[status]} + -
-
-
- setLocal((current) => ({ ...current, [target.user.id]: status }))} - /> -
- - - - - - {t("common.loading")} - -
-
- ); - }} - - - 1}> - + )} + +
+
+ + + 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 ( + + ); + }} + +
    + +
    +
  • + ); + }} +
    +
+
); diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index b77670c..fd855a4 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -616,6 +616,14 @@ export type MessageKey = | "common.deleted" | "common.saved" | "common.loadAll" + | "rollCall.progress" + | "rollCall.markRestPresent" + | "rollCall.marking" + | "rollCall.onlyUnmarked" + | "rollCall.allMarked" + | "rollCall.unmarked" + | "rollCall.clear" + | "rollCall.bulkFailed" | "common.skipToContent" | "form.fieldRequired" | "common.close" @@ -2759,6 +2767,14 @@ const en: Dict = { "common.deleted": "Deleted.", "common.saved": "Saved successfully.", "common.loadAll": "Load all", + "rollCall.progress": "{marked} of {total} marked", + "rollCall.markRestPresent": "Mark the rest present", + "rollCall.marking": "Saving {done} of {total}…", + "rollCall.onlyUnmarked": "Only unmarked", + "rollCall.allMarked": "Everyone is marked.", + "rollCall.unmarked": "Not marked yet", + "rollCall.clear": "Clear mark", + "rollCall.bulkFailed": "{count} rows could not be saved: {reason}", "common.skipToContent": "Skip to content", "form.fieldRequired": "This field is required.", "common.close": "Close", @@ -4904,6 +4920,14 @@ const tr: Dict = { "common.deleted": "Silindi.", "common.saved": "Başarıyla kaydedildi.", "common.loadAll": "Tümünü yükle", + "rollCall.progress": "{total} kişiden {marked} işaretlendi", + "rollCall.markRestPresent": "Kalanları Var işaretle", + "rollCall.marking": "{total} kişiden {done} kaydedildi…", + "rollCall.onlyUnmarked": "Yalnızca işaretlenmemişler", + "rollCall.allMarked": "Herkes işaretlendi.", + "rollCall.unmarked": "Henüz işaretlenmedi", + "rollCall.clear": "İşareti kaldır", + "rollCall.bulkFailed": "{count} satır kaydedilemedi: {reason}", "common.skipToContent": "İçeriğe geç", "form.fieldRequired": "Bu alan zorunlu.", "common.close": "Kapat",