forge
Explore
Log in

Don't you dare go Hollow

🔄 extract shared exam status logic, add max_attempts, unify colors

Browse files at this commit

bae952564a99658d069fb5467bad055e352f997fBurak BoduroğluParent: 2e966a9
  • refactor
    • 🔄 extract shared exam status logic, add max_attempts, unify colors
Show full message
refactor: 🔄 extract shared exam status logic, add max_attempts, unify colors
- new src/lib/exam-status.ts: examDisplayStatus, examStatusTone, isSittableExam,
  ExamAttemptSummary, ExamDisplayStatus (adds no_attempts_left)
- exams-page / exam-card / exam-detail-page / dashboard: use shared helpers
- dashboard + exams-page: poll attempt statuses with max_attempts tracking
- detail page: replace draft metric card with max_attempts
- live-monitor: badge uses schedule-status colors (dot + semantic border)
- i18n: attempt.noAttemptsLeft (EN/TR)
src/components/exams/exam-card.tsxmodified+8 -8
@@ -5,6 +5,7 @@ import { Badge } from "@/components/ui/badge";
5 import { ExamLink } from "@/components/exams/exam-link";5 import { ExamLink } from "@/components/exams/exam-link";
6 import { cn } from "@/lib/cn";6 import { cn } from "@/lib/cn";
7 import { examKindLabel } from "@/lib/exam-labels";7 import { examKindLabel } from "@/lib/exam-labels";
8+import { examDisplayStatus, examStatusTone } from "@/lib/exam-status";
8 import { examWeight } from "@/lib/exam-weight";9 import { examWeight } from "@/lib/exam-weight";
9 import { examDurationMs, formatDateTime, formatDurationMinutes } from "@/lib/format";10 import { examDurationMs, formatDateTime, formatDurationMinutes } from "@/lib/format";
10 import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status";11 import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status";
@@ -22,17 +23,16 @@ export function ExamCard(props: { exam: Exam; courseTitle?: string; now?: number
22 };23 };
23 24
24 const status = () => {25 const status = () => {
25- if (props.exam.mode !== "sync" && props.exam.mode !== "async" && props.exam.mode !== "open") return "unscheduled";26+ return examDisplayStatus(props.exam, props.now ?? Date.now());
26- if (props.exam.mode === "open") return "active";
27- const current = props.now ?? Date.now();
28- if (props.exam.ends_at != null && props.exam.ends_at < current) return "finished";
29- if (props.exam.starts_at != null && props.exam.starts_at > current) return "upcoming";
30- return "active";
31 };27 };
32 28
33 const statusLabel = () => {29 const statusLabel = () => {
34 const s = status();30 const s = status();
31+ if (s === "draft") return t("exams.draft");
35 if (s === "unscheduled") return t("exams.unscheduled");32 if (s === "unscheduled") return t("exams.unscheduled");
33+ if (s === "submitted") return t("attempt.submitted");
34+ if (s === "expired") return t("attempt.expired");
35+ if (s === "no_attempts_left") return t("attempt.noAttemptsLeft");
36 if (s === "finished") return t("exams.finished");36 if (s === "finished") return t("exams.finished");
37 if (s === "upcoming") return t("exams.upcoming");37 if (s === "upcoming") return t("exams.upcoming");
38 return t("exams.active");38 return t("exams.active");
@@ -51,8 +51,8 @@ export function ExamCard(props: { exam: Exam; courseTitle?: string; now?: number
51 {props.exam.title}51 {props.exam.title}
52 </h3>52 </h3>
53 </div>53 </div>
54- <Badge variant="outline" class={cn("shrink-0 rounded-sm capitalize", scheduleStatusClass(status()))}>54+ <Badge variant="outline" class={cn("shrink-0 rounded-sm capitalize", scheduleStatusClass(examStatusTone(status())))}>
55- <span class={cn("mr-1.5 inline-block h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(status()))} />55+ <span class={cn("mr-1.5 inline-block h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(examStatusTone(status())))} />
56 {statusLabel()}56 {statusLabel()}
57 </Badge>57 </Badge>
58 </div>58 </div>
src/i18n/messages.tsmodified+3 -0
@@ -372,6 +372,7 @@ export type MessageKey =
372 | "attempt.submittedInfo"372 | "attempt.submittedInfo"
373 | "attempt.expired"373 | "attempt.expired"
374 | "attempt.expiredInfo"374 | "attempt.expiredInfo"
375+ | "attempt.noAttemptsLeft"
375 | "attempt.closed"376 | "attempt.closed"
376 | "attempt.inProgress"377 | "attempt.inProgress"
377 | "attempt.absent"378 | "attempt.absent"
@@ -983,6 +984,7 @@ const en: Dict = {
983 "attempt.submittedInfo": "You have already submitted this exam. It cannot be reopened.",984 "attempt.submittedInfo": "You have already submitted this exam. It cannot be reopened.",
984 "attempt.expired": "Expired",985 "attempt.expired": "Expired",
985 "attempt.expiredInfo": "The time for this exam has expired. It cannot be reopened.",986 "attempt.expiredInfo": "The time for this exam has expired. It cannot be reopened.",
987+ "attempt.noAttemptsLeft": "No attempts left",
986 "attempt.closed": "This attempt is closed. Answers are read-only.",988 "attempt.closed": "This attempt is closed. Answers are read-only.",
987 "attempt.inProgress": "In progress",989 "attempt.inProgress": "In progress",
988 "attempt.absent": "No-show",990 "attempt.absent": "No-show",
@@ -1604,6 +1606,7 @@ const tr: Dict = {
1604 "attempt.submittedInfo": "Bu sınavı zaten teslim ettin. Yeniden açılamaz.",1606 "attempt.submittedInfo": "Bu sınavı zaten teslim ettin. Yeniden açılamaz.",
1605 "attempt.expired": "Süresi doldu",1607 "attempt.expired": "Süresi doldu",
1606 "attempt.expiredInfo": "Bu sınavın süresi doldu. Yeniden açılamaz.",1608 "attempt.expiredInfo": "Bu sınavın süresi doldu. Yeniden açılamaz.",
1609+ "attempt.noAttemptsLeft": "Deneme hakkı bitti",
1607 "attempt.closed": "Bu oturum kapalı. Cevaplar salt okunur.",1610 "attempt.closed": "Bu oturum kapalı. Cevaplar salt okunur.",
1608 "attempt.inProgress": "Devam ediyor",1611 "attempt.inProgress": "Devam ediyor",
1609 "attempt.absent": "Katılmadı",1612 "attempt.absent": "Katılmadı",
src/lib/exam-status.tsadded+30 -0
@@ -0,0 +1,30 @@
1+import type { AttemptStatus, Exam } from "@/api/types";
2+
3+export type ExamAttemptSummary = {
4+ status: AttemptStatus | "not_started";
5+ attempts_used: number;
6+ max_attempts: number;
7+};
8+
9+export type ExamDisplayStatus = "draft" | "unscheduled" | "upcoming" | "active" | "finished" | "submitted" | "expired" | "no_attempts_left";
10+
11+export function isSittableExam(exam: Exam): boolean {
12+ return exam.mode === "sync" || exam.mode === "async" || exam.mode === "open";
13+}
14+
15+export function examDisplayStatus(exam: Exam, now: number, attempt?: ExamAttemptSummary | null): ExamDisplayStatus {
16+ if (attempt?.status === "submitted" || attempt?.status === "expired") return attempt.status;
17+ if (attempt && attempt.max_attempts > 0 && attempt.attempts_used >= attempt.max_attempts) return "no_attempts_left";
18+ if (exam.draft) return "draft";
19+ if (!isSittableExam(exam)) return "unscheduled";
20+ if (exam.mode === "open") return "active";
21+ if (exam.ends_at != null && exam.ends_at < now) return "finished";
22+ if (exam.starts_at != null && exam.starts_at > now) return "upcoming";
23+ return "active";
24+}
25+
26+export function examStatusTone(status: ExamDisplayStatus): string {
27+ if (status === "submitted") return "submitted";
28+ if (status === "expired" || status === "no_attempts_left") return "finished";
29+ return status;
30+}
src/pages/dashboard-page.tsxmodified+31 -8
@@ -1,7 +1,8 @@
1-import { For, Show, createEffect, createMemo, createResource, createSignal, type Component } from "solid-js";1+import { For, Show, createEffect, createMemo, createResource, createSignal, onCleanup, type Component } from "solid-js";
2 import { Link } from "@tanstack/solid-router";2 import { Link } from "@tanstack/solid-router";
3 import { formatApiError } from "@/api/client";3 import { formatApiError } from "@/api/client";
4 import { getCourses } from "@/api/getCourses";4 import { getCourses } from "@/api/getCourses";
5+import { getExamAttempt } from "@/api/getExamAttempt";
5 import { getEvents } from "@/api/getEvents";6 import { getEvents } from "@/api/getEvents";
6 import { getExams } from "@/api/getExams";7 import { getExams } from "@/api/getExams";
7 import { getMyCourses } from "@/api/getMyCourses";8 import { getMyCourses } from "@/api/getMyCourses";
@@ -29,6 +30,7 @@ import type { MessageKey } from "@/i18n/messages";
29 import { cn } from "@/lib/cn";30 import { cn } from "@/lib/cn";
30 import { createNow } from "@/lib/create-now";31 import { createNow } from "@/lib/create-now";
31 import { examKindLabel } from "@/lib/exam-labels";32 import { examKindLabel } from "@/lib/exam-labels";
33+import { examDisplayStatus, isSittableExam, type ExamAttemptSummary } from "@/lib/exam-status";
32 import { formatDateTime } from "@/lib/format";34 import { formatDateTime } from "@/lib/format";
33 import { hasMinRole } from "@/lib/roles";35 import { hasMinRole } from "@/lib/roles";
34 import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status";36 import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status";
@@ -68,17 +70,17 @@ const ROLE_KEY: Record<Role, MessageKey> = {
68 admin: "role.admin",70 admin: "role.admin",
69 };71 };
70 72
71-function examWindow(exam: Exam, now: number): AttentionKind | "upcoming" | "past" | "unscheduled" {73+function examWindow(exam: Exam, now: number, attempt?: ExamAttemptSummary | null): AttentionKind | "upcoming" | "past" | "unscheduled" {
72- if (exam.mode === "open") return "active";74+ const status = examDisplayStatus(exam, now, attempt);
73- if (exam.mode !== "sync" && exam.mode !== "async") return "unscheduled";75+ if (status === "active") return "active";
74- if (exam.ends_at != null && exam.ends_at < now) return "past";76+ if (status !== "upcoming") return status === "unscheduled" ? "unscheduled" : "past";
75 if (exam.starts_at != null && exam.starts_at > now) {77 if (exam.starts_at != null && exam.starts_at > now) {
76 const delta = exam.starts_at - now;78 const delta = exam.starts_at - now;
77 if (delta <= 24 * 60 * 60 * 1000) return "today";79 if (delta <= 24 * 60 * 60 * 1000) return "today";
78 if (delta <= WEEK_MS) return "soon";80 if (delta <= WEEK_MS) return "soon";
79 return "upcoming";81 return "upcoming";
80 }82 }
81- return "active";83+ return "upcoming";
82 }84 }
83 85
84 function eventWindow(event: Event, now: number): AttentionKind | "upcoming" | "past" | "unscheduled" {86 function eventWindow(event: Event, now: number): AttentionKind | "upcoming" | "past" | "unscheduled" {
@@ -114,6 +116,7 @@ function DashboardContent() {
114 const [draggingPortal, setDraggingPortal] = createSignal<string | null>(null);116 const [draggingPortal, setDraggingPortal] = createSignal<string | null>(null);
115 const [dragOverPortal, setDragOverPortal] = createSignal<string | null>(null);117 const [dragOverPortal, setDragOverPortal] = createSignal<string | null>(null);
116 const [editingPortalOrder, setEditingPortalOrder] = createSignal(false);118 const [editingPortalOrder, setEditingPortalOrder] = createSignal(false);
119+ const [attemptStatuses, setAttemptStatuses] = createSignal<Record<string, ExamAttemptSummary>>({});
117 120
118 const [courses] = createResource(121 const [courses] = createResource(
119 () => (role() !== "student" ? true : null),122 () => (role() !== "student" ? true : null),
@@ -173,6 +176,26 @@ function DashboardContent() {
173 return all;176 return all;
174 });177 });
175 178
179+ createEffect(() => {
180+ if (role() !== "student") return;
181+ const exams = visibleExams();
182+ const refresh = () => {
183+ for (const exam of exams) {
184+ if (!isSittableExam(exam)) continue;
185+ const current = attemptStatuses()[exam.id];
186+ if (current?.status === "submitted" || current?.status === "expired") continue;
187+ if (current && current.max_attempts > 0 && current.attempts_used >= current.max_attempts) continue;
188+ if (current != null && current.status !== "in_progress") continue;
189+ void getExamAttempt(exam.id)
190+ .then((attempt) => setAttemptStatuses((prev) => ({ ...prev, [exam.id]: { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } })))
191+ .catch(() => setAttemptStatuses((prev) => ({ ...prev, [exam.id]: { status: "not_started", attempts_used: 0, max_attempts: exam.max_attempts } })));
192+ }
193+ };
194+ refresh();
195+ const interval = window.setInterval(refresh, 5000);
196+ onCleanup(() => window.clearInterval(interval));
197+ });
198+
176 const countCoursesByKind = (kind: Course["kind"]) => scopedCourses().filter((course) => course.kind === kind).length;199 const countCoursesByKind = (kind: Course["kind"]) => scopedCourses().filter((course) => course.kind === kind).length;
177 const courseCount = createMemo(() => countCoursesByKind("course"));200 const courseCount = createMemo(() => countCoursesByKind("course"));
178 const studyCount = createMemo(() => countCoursesByKind("study"));201 const studyCount = createMemo(() => countCoursesByKind("study"));
@@ -297,7 +320,7 @@ function DashboardContent() {
297 const items: AttentionItem[] = [];320 const items: AttentionItem[] = [];
298 321
299 for (const exam of visibleExams()) {322 for (const exam of visibleExams()) {
300- const status = examWindow(exam, n);323+ const status = examWindow(exam, n, attemptStatuses()[exam.id]);
301 if (status === "active" || status === "today" || status === "soon") {324 if (status === "active" || status === "today" || status === "soon") {
302 items.push({325 items.push({
303 id: exam.id,326 id: exam.id,
@@ -342,7 +365,7 @@ function DashboardContent() {
342 365
343 for (const exam of visibleExams()) {366 for (const exam of visibleExams()) {
344 if (exam.starts_at != null && exam.starts_at > n && exam.starts_at <= n + WEEK_MS) {367 if (exam.starts_at != null && exam.starts_at > n && exam.starts_at <= n + WEEK_MS) {
345- const w = examWindow(exam, n);368+ const w = examWindow(exam, n, attemptStatuses()[exam.id]);
346 if (w === "upcoming" || w === "soon" || w === "today") {369 if (w === "upcoming" || w === "soon" || w === "today") {
347 items.push({370 items.push({
348 id: exam.id,371 id: exam.id,
src/pages/exam-detail-page.tsxmodified+18 -13
@@ -14,7 +14,7 @@ import { getSettings } from "@/api/getSettings";
14 import { patchExamById } from "@/api/patchExamById";14 import { patchExamById } from "@/api/patchExamById";
15 import { postExamResult } from "@/api/postExamResult";15 import { postExamResult } from "@/api/postExamResult";
16 import { ApiError, formatApiError } from "@/api/client";16 import { ApiError, formatApiError } from "@/api/client";
17-import type { AttemptStatus, ExamResult } from "@/api/types";17+import type { ExamResult } from "@/api/types";
18 import { ExamForm } from "@/components/exams/exam-form";18 import { ExamForm } from "@/components/exams/exam-form";
19 import { ExamQuestionsPanel } from "@/components/exams/exam-questions-panel";19 import { ExamQuestionsPanel } from "@/components/exams/exam-questions-panel";
20 import { AnswerSheetView } from "@/components/exams/answer-sheet-view";20 import { AnswerSheetView } from "@/components/exams/answer-sheet-view";
@@ -35,6 +35,7 @@ import { TableRowActions } from "@/components/ui/table-row-actions";
35 import { hasMinRole } from "@/lib/roles";35 import { hasMinRole } from "@/lib/roles";
36 import { createNow } from "@/lib/create-now";36 import { createNow } from "@/lib/create-now";
37 import { examKindLabel } from "@/lib/exam-labels";37 import { examKindLabel } from "@/lib/exam-labels";
38+import { examDisplayStatus, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status";
38 import { examWeight } from "@/lib/exam-weight";39 import { examWeight } from "@/lib/exam-weight";
39 import { examDurationMs, formatDateTime, formatDurationMinutes } from "@/lib/format";40 import { examDurationMs, formatDateTime, formatDurationMinutes } from "@/lib/format";
40 import { personId, personLabel, personLabelWithId } from "@/lib/person";41 import { personId, personLabel, personLabelWithId } from "@/lib/person";
@@ -92,7 +93,10 @@ function ExamDetailContent() {
92 questions: false,93 questions: false,
93 results: false,94 results: false,
94 });95 });
95- const isSittable = () => exam()?.mode === "sync" || exam()?.mode === "async" || exam()?.mode === "open";96+ const isSittable = () => {
97+ const e = exam();
98+ return e ? isSittableExam(e) : false;
99+ };
96 const isScheduled = () => isSittable();100 const isScheduled = () => isSittable();
97 101
98 const [ownResult] = createResource(102 const [ownResult] = createResource(
@@ -157,16 +161,17 @@ function ExamDetailContent() {
157 };161 };
158 const isFinished = () => examStatus().finished;162 const isFinished = () => examStatus().finished;
159 const isUpcoming = () => examStatus().upcoming;163 const isUpcoming = () => examStatus().upcoming;
160- const ownAttemptStatus = (): AttemptStatus | null => ownAttempt()?.status ?? null;164+ const ownAttemptSummary = (): ExamAttemptSummary | null => {
161- const detailStatus = () => {165+ const attempt = ownAttempt();
162- const own = ownAttemptStatus();166+ return attempt ? { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } : null;
163- if (own === "submitted" || own === "expired") return own;
164- return !isScheduled() ? "unscheduled" : isFinished() ? "finished" : isUpcoming() ? "upcoming" : "active";
165 };167 };
168+ const noAttemptsLeft = () => detailStatus() === "no_attempts_left";
169+ const detailStatus = (): ExamDisplayStatus => exam() ? examDisplayStatus(exam()!, now(), ownAttemptSummary()) : "unscheduled";
166 const detailStatusLabel = () => {170 const detailStatusLabel = () => {
167 const status = detailStatus();171 const status = detailStatus();
168 if (status === "submitted") return t("attempt.submitted");172 if (status === "submitted") return t("attempt.submitted");
169 if (status === "expired") return t("attempt.expired");173 if (status === "expired") return t("attempt.expired");
174+ if (status === "no_attempts_left") return t("attempt.noAttemptsLeft");
170 if (status === "unscheduled") return t("exams.unscheduled");175 if (status === "unscheduled") return t("exams.unscheduled");
171 if (status === "finished") return t("exams.finished");176 if (status === "finished") return t("exams.finished");
172 if (status === "upcoming") return t("exams.upcoming");177 if (status === "upcoming") return t("exams.upcoming");
@@ -301,7 +306,7 @@ function ExamDetailContent() {
301 </Link>306 </Link>
302 <Show when={isStudent() && !isDraft() && isSittable()}>307 <Show when={isStudent() && !isDraft() && isSittable()}>
303 <Show when={!isUpcoming() && !isFinished()}>308 <Show when={!isUpcoming() && !isFinished()}>
304- <Show when={ownAttempt()?.status === "submitted" || ownAttempt()?.status === "expired"}309+ <Show when={ownAttempt()?.status === "submitted" || ownAttempt()?.status === "expired" || noAttemptsLeft()}
305 fallback={310 fallback={
306 <Link to="/exam-room/$id" params={{ id: id() }}>311 <Link to="/exam-room/$id" params={{ id: id() }}>
307 <Button size="sm" class="flex-1 rounded-sm sm:flex-none">312 <Button size="sm" class="flex-1 rounded-sm sm:flex-none">
@@ -312,7 +317,7 @@ function ExamDetailContent() {
312 }317 }
313 >318 >
314 <Badge variant="secondary" class="flex-1 rounded-sm px-3 py-2 text-center sm:flex-none">319 <Badge variant="secondary" class="flex-1 rounded-sm px-3 py-2 text-center sm:flex-none">
315- {ownAttempt()?.status === "submitted" ? t("attempt.submitted") : t("attempt.expired")}320+ {ownAttempt()?.status === "submitted" ? t("attempt.submitted") : ownAttempt()?.status === "expired" ? t("attempt.expired") : t("attempt.noAttemptsLeft")}
316 </Badge>321 </Badge>
317 </Show>322 </Show>
318 </Show>323 </Show>
@@ -347,10 +352,10 @@ function ExamDetailContent() {
347 variant="outline"352 variant="outline"
348 class={cn(353 class={cn(
349 "mt-2 w-fit rounded-sm capitalize",354 "mt-2 w-fit rounded-sm capitalize",
350- scheduleStatusClass(detailStatus() === "expired" ? "finished" : detailStatus()),355+ scheduleStatusClass(examStatusTone(detailStatus())),
351 )}356 )}
352 >357 >
353- <span class={cn("mr-1.5 inline-block h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(detailStatus() === "expired" ? "finished" : detailStatus()))} />358+ <span class={cn("mr-1.5 inline-block h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(examStatusTone(detailStatus())))} />
354 {detailStatusLabel()}359 {detailStatusLabel()}
355 </Badge>360 </Badge>
356 </div>361 </div>
@@ -366,8 +371,8 @@ function ExamDetailContent() {
366 <p class="mt-1 font-medium">{examModeLabel(ex().mode)}</p>371 <p class="mt-1 font-medium">{examModeLabel(ex().mode)}</p>
367 </div>372 </div>
368 <div class="detail-metric-card">373 <div class="detail-metric-card">
369- <p class="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("exams.draft")}</p>374+ <p class="text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{t("exams.maxAttempts")}</p>
370- <p class="mt-1 font-medium">{ex().draft ? t("exams.draft") : "—"}</p>375+ <p class="mono mt-1 font-medium tabular-nums">{ex().max_attempts}</p>
371 </div>376 </div>
372 </div>377 </div>
373 </div>378 </div>
src/pages/exams-page.tsxmodified+17 -28
@@ -8,7 +8,7 @@ import { getMyCourses } from "@/api/getMyCourses";
8 import { patchExamById } from "@/api/patchExamById";8 import { patchExamById } from "@/api/patchExamById";
9 import { postCourseExam } from "@/api/postCourseExam";9 import { postCourseExam } from "@/api/postCourseExam";
10 import { formatApiError } from "@/api/client";10 import { formatApiError } from "@/api/client";
11-import type { AttemptStatus, Course, Exam } from "@/api/types";11+import type { Course, Exam } from "@/api/types";
12 import { ExamForm, type ExamFormValues } from "@/components/exams/exam-form";12 import { ExamForm, type ExamFormValues } from "@/components/exams/exam-form";
13 import { RouteGuard } from "@/components/layout/route-guard";13 import { RouteGuard } from "@/components/layout/route-guard";
14 import { PageHeader } from "@/components/layout/page-header";14 import { PageHeader } from "@/components/layout/page-header";
@@ -22,6 +22,7 @@ import { SidePanel } from "@/components/ui/side-panel";
22 import { TableRowActions } from "@/components/ui/table-row-actions";22 import { TableRowActions } from "@/components/ui/table-row-actions";
23 import { createNow } from "@/lib/create-now";23 import { createNow } from "@/lib/create-now";
24 import { examKindLabel } from "@/lib/exam-labels";24 import { examKindLabel } from "@/lib/exam-labels";
25+import { examDisplayStatus, examStatusTone, isSittableExam, type ExamAttemptSummary, type ExamDisplayStatus } from "@/lib/exam-status";
25 import { createFlash } from "@/lib/flash";26 import { createFlash } from "@/lib/flash";
26 import { formatDateTime } from "@/lib/format";27 import { formatDateTime } from "@/lib/format";
27 import { hasMinRole } from "@/lib/roles";28 import { hasMinRole } from "@/lib/roles";
@@ -32,8 +33,7 @@ import { usePreferences, useT } from "@/stores/preferences-context";
32 33
33 const EXAM_PAGE_SIZE = 12;34 const EXAM_PAGE_SIZE = 12;
34 35
35-type ExamStatus = "draft" | "unscheduled" | "upcoming" | "active" | "finished" | "submitted" | "expired";36+type ExamRow = Exam & { displayStatus: ExamDisplayStatus };
36-type ExamRow = Exam & { displayStatus: ExamStatus };
37 37
38 export default function ExamsPage() {38 export default function ExamsPage() {
39 return (39 return (
@@ -49,13 +49,13 @@ function ExamsContent() {
49 const t = useT();49 const t = useT();
50 const { locale } = usePreferences();50 const { locale } = usePreferences();
51 const now = createNow();51 const now = createNow();
52- const [statusFilter, setStatusFilter] = createSignal<ExamStatus | "all">("all");52+ const [statusFilter, setStatusFilter] = createSignal<ExamDisplayStatus | "all">("all");
53 const [courseFilter, setCourseFilter] = createSignal("all");53 const [courseFilter, setCourseFilter] = createSignal("all");
54 const [showMoreFilters, setShowMoreFilters] = createSignal(false);54 const [showMoreFilters, setShowMoreFilters] = createSignal(false);
55 const [createOpen, setCreateOpen] = createSignal(false);55 const [createOpen, setCreateOpen] = createSignal(false);
56 const [selectedCourseId, setSelectedCourseId] = createSignal("");56 const [selectedCourseId, setSelectedCourseId] = createSignal("");
57 const [editingExam, setEditingExam] = createSignal<Exam | null>(null);57 const [editingExam, setEditingExam] = createSignal<Exam | null>(null);
58- const [attemptStatuses, setAttemptStatuses] = createSignal<Record<string, AttemptStatus | "not_started">>({});58+ const [attemptStatuses, setAttemptStatuses] = createSignal<Record<string, ExamAttemptSummary>>({});
59 const [flash, setFlash] = createFlash();59 const [flash, setFlash] = createFlash();
60 60
61 const [courses] = createResource(61 const [courses] = createResource(
@@ -78,18 +78,7 @@ function ExamsContent() {
78 const courseById = createMemo(() => new Map(visibleCourses().map((course) => [course.id, course])));78 const courseById = createMemo(() => new Map(visibleCourses().map((course) => [course.id, course])));
79 const courseTitle = (courseId: string) => courseById().get(courseId)?.title ?? courseId;79 const courseTitle = (courseId: string) => courseById().get(courseId)?.title ?? courseId;
80 80
81- const isSittable = (exam: Exam) => exam.mode === "sync" || exam.mode === "async" || exam.mode === "open";81+ const examStatus = (exam: Exam) => examDisplayStatus(exam, now(), attemptStatuses()[exam.id]);
82- const examStatus = (exam: Exam): ExamStatus => {
83- const own = attemptStatuses()[exam.id];
84- if (own === "submitted" || own === "expired") return own;
85- if (exam.draft) return "draft";
86- if (!isSittable(exam)) return "unscheduled";
87- if (exam.mode === "open") return "active";
88- const current = now();
89- if (exam.ends_at != null && exam.ends_at < current) return "finished";
90- if (exam.starts_at != null && exam.starts_at > current) return "upcoming";
91- return "active";
92- };
93 82
94 const filterExams = (items: Exam[]) => {83 const filterExams = (items: Exam[]) => {
95 const allowed = isStudent() ? new Set(visibleCourses().map((course) => course.id)) : null;84 const allowed = isStudent() ? new Set(visibleCourses().map((course) => course.id)) : null;
@@ -120,17 +109,16 @@ function ExamsContent() {
120 setSelectedCourseId(manageableCourses()[0]?.id ?? "");109 setSelectedCourseId(manageableCourses()[0]?.id ?? "");
121 });110 });
122 111
123- const statusLabel = (status: ExamStatus) => {112+ const statusLabel = (status: ExamDisplayStatus) => {
124 if (status === "submitted") return t("attempt.submitted");113 if (status === "submitted") return t("attempt.submitted");
125 if (status === "expired") return t("attempt.expired");114 if (status === "expired") return t("attempt.expired");
115+ if (status === "no_attempts_left") return t("attempt.noAttemptsLeft");
126 if (status === "draft") return t("exams.draft");116 if (status === "draft") return t("exams.draft");
127 if (status === "unscheduled") return t("exams.unscheduled");117 if (status === "unscheduled") return t("exams.unscheduled");
128 if (status === "finished") return t("exams.finished");118 if (status === "finished") return t("exams.finished");
129 if (status === "upcoming") return t("exams.upcoming");119 if (status === "upcoming") return t("exams.upcoming");
130 return t("exams.active");120 return t("exams.active");
131 };121 };
132- const statusTone = (status: ExamStatus) => status === "expired" ? "finished" : status;
133-
134 const rows = (): ExamRow[] => filterExams(list() ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }));122 const rows = (): ExamRow[] => filterExams(list() ?? []).map((exam) => ({ ...exam, displayStatus: examStatus(exam) }));
135 createEffect(() => {123 createEffect(() => {
136 if (!isStudent()) return;124 if (!isStudent()) return;
@@ -139,16 +127,17 @@ function ExamsContent() {
139 const allowed = new Set(visibleCourses().map((course) => course.id));127 const allowed = new Set(visibleCourses().map((course) => course.id));
140 const refresh = () => {128 const refresh = () => {
141 for (const exam of exams) {129 for (const exam of exams) {
142- if (!allowed.has(exam.course) || !isSittable(exam)) continue;130+ if (!allowed.has(exam.course) || !isSittableExam(exam)) continue;
143 const current = attemptStatuses()[exam.id];131 const current = attemptStatuses()[exam.id];
144- if (current === "submitted" || current === "expired") continue;132+ if (current?.status === "submitted" || current?.status === "expired") continue;
145- if (current != null && current !== "in_progress") continue;133+ if (current && current.max_attempts > 0 && current.attempts_used >= current.max_attempts) continue;
134+ if (current != null && current.status !== "in_progress") continue;
146 void getExamAttempt(exam.id)135 void getExamAttempt(exam.id)
147 .then((attempt) => {136 .then((attempt) => {
148- setAttemptStatuses((prev) => ({ ...prev, [exam.id]: attempt.status }));137+ setAttemptStatuses((prev) => ({ ...prev, [exam.id]: { status: attempt.status, attempts_used: attempt.attempts_used, max_attempts: attempt.max_attempts } }));
149 })138 })
150 .catch(() => {139 .catch(() => {
151- setAttemptStatuses((prev) => ({ ...prev, [exam.id]: "not_started" }));140+ setAttemptStatuses((prev) => ({ ...prev, [exam.id]: { status: "not_started", attempts_used: 0, max_attempts: exam.max_attempts } }));
152 });141 });
153 }142 }
154 };143 };
@@ -188,8 +177,8 @@ function ExamsContent() {
188 cell: (cell) => {177 cell: (cell) => {
189 const status = cell.row.original.displayStatus;178 const status = cell.row.original.displayStatus;
190 return (179 return (
191- <Badge variant="outline" class={cn("w-28 justify-center rounded-sm", scheduleStatusClass(statusTone(status)))}>180+ <Badge variant="outline" class={cn("w-28 justify-center rounded-sm", scheduleStatusClass(examStatusTone(status)))}>
192- <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(statusTone(status)))} />181+ <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(examStatusTone(status)))} />
193 {statusLabel(status)}182 {statusLabel(status)}
194 </Badge>183 </Badge>
195 );184 );
@@ -282,7 +271,7 @@ function ExamsContent() {
282 empty={t("exams.empty")}271 empty={t("exams.empty")}
283 filters={272 filters={
284 <>273 <>
285- <Select class="h-9 w-full rounded-sm sm:w-40" value={statusFilter()} onChange={(event) => setStatusFilter(event.currentTarget.value as ExamStatus | "all")}>274+ <Select class="h-9 w-full rounded-sm sm:w-40" value={statusFilter()} onChange={(event) => setStatusFilter(event.currentTarget.value as ExamDisplayStatus | "all")}>
286 <option value="all">{t("common.all")}</option>275 <option value="all">{t("common.all")}</option>
287 <option value="submitted">{t("attempt.submitted")}</option>276 <option value="submitted">{t("attempt.submitted")}</option>
288 <option value="expired">{t("attempt.expired")}</option>277 <option value="expired">{t("attempt.expired")}</option>
src/pages/live-monitor-page.tsxmodified+12 -6
@@ -17,8 +17,10 @@ import { IconChevronLeft } from "@/components/ui/icons";
17 import { PageSpinner } from "@/components/ui/page-spinner";17 import { PageSpinner } from "@/components/ui/page-spinner";
18 import { usePreferences, useT } from "@/stores/preferences-context";18 import { usePreferences, useT } from "@/stores/preferences-context";
19 import { createNow } from "@/lib/create-now";19 import { createNow } from "@/lib/create-now";
20+import { cn } from "@/lib/cn";
20 import { attemptLabel } from "@/lib/exam-labels";21 import { attemptLabel } from "@/lib/exam-labels";
21 import { formatDateTime } from "@/lib/format";22 import { formatDateTime } from "@/lib/format";
23+import { scheduleStatusClass, scheduleStatusDotClass } from "@/lib/schedule-status";
22 24
23 const PAGE_SIZE = 10;25 const PAGE_SIZE = 10;
24 26
@@ -43,6 +45,13 @@ function labelFromStatus(status: string, t: (key: MessageKey) => string): string
43 return k ? t(k) : status;45 return k ? t(k) : status;
44 }46 }
45 47
48+function statusTone(status: string): string {
49+ if (status === "in_progress") return "active";
50+ if (status === "submitted") return "submitted";
51+ if (status === "expired" || status === "absent") return "finished";
52+ return "unscheduled";
53+}
54+
46 function progressPercent(entry: LiveRosterEntry, questionCount: number): number {55 function progressPercent(entry: LiveRosterEntry, questionCount: number): number {
47 if (questionCount <= 0) return 0;56 if (questionCount <= 0) return 0;
48 return Math.round(((entry.answered ?? 0) / questionCount) * 100);57 return Math.round(((entry.answered ?? 0) / questionCount) * 100);
@@ -227,13 +236,10 @@ function LiveMonitorContent() {
227 meta: { headerClass: "text-center", cellClass: "text-center" },236 meta: { headerClass: "text-center", cellClass: "text-center" },
228 cell: (cell) => (237 cell: (cell) => (
229 <Badge238 <Badge
230- class="rounded-full"239+ variant="outline"
231- variant={240+ class={cn("rounded-full", scheduleStatusClass(statusTone(cell.row.original.status)))}
232- cell.row.original.status === "in_progress" ? "default" :
233- cell.row.original.status === "submitted" ? "secondary" :
234- "outline"
235- }
236 >241 >
242+ <span class={cn("mr-1.5 h-1.5 w-1.5 rounded-full", scheduleStatusDotClass(statusTone(cell.row.original.status)))} />
237 {labelFromStatus(cell.row.original.status, t)}243 {labelFromStatus(cell.row.original.status, t)}
238 </Badge>244 </Badge>
239 ),245 ),