import { For, Show, Suspense, createMemo, createSignal, useTransition } from "solid-js"; import { createResource } from "@/lib/create-resource"; import { ApiError } from "@/api/client"; import { getExamQuestions, getExamReviewQuestions } from "@/api/exams"; import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams"; import { getStudentAttempts, getStudentAttemptAnswers, getStudentAttemptAnswerImage } from "@/api/exams"; import { getExamReviewAttempts, getExamReviewAttemptAnswers, getExamReviewAttemptAnswerImage } from "@/api/exams"; import type { StudentAnswerSheet } from "@/api/client"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { IconCheck, IconDownload, IconX } from "@/components/ui/icons"; import { PageSpinner } from "@/components/ui/page-spinner"; import { ReplayableImage } from "@/components/ui/replayable-image"; import { DropdownSelect } from "@/components/ui/select"; import { cn } from "@/lib/cn"; import { joinAnswerSheet } from "@/lib/answer-sheet"; import { personLabel } from "@/lib/person"; import { useT } from "@/stores/preferences-context"; export function AnswerSheetView(props: { examId: string; userId: string; userLabel?: string; mode?: "grader" | "self" }) { const t = useT(); // "grader" hits the teacher, userId-scoped routes; "self" hits the self-scoped // /review routes (no userId in path). Everything below is identical either way. const mode = () => props.mode ?? "grader"; // Self-review reads 409 while the caller's latest sitting is still in // progress — a retake must submit before it can read the answer key. We // degrade to a friendly banner instead of erroring the panel. const [reviewInProgress, setReviewInProgress] = createSignal(false); // Which sitting the grader is viewing. null = the latest (grade-of-record), the default. const [selectedSeq, setSelectedSeq] = createSignal(null); // Switch sittings inside a transition so the current sheet stays on screen // while the next one loads — otherwise the `data` resource re-suspends and // the whole panel blanks to the PageSpinner on every pick. const [switching, startSwitch] = useTransition(); // Attempt list + full mark history (oldest-first, index i = seq i+1). Both grader-only, // both tolerate "student never sat" by degrading to empty. const [attempts] = createResource( () => [props.examId, props.userId] as const, async ([examId, userId]) => { if (mode() === "self") setReviewInProgress(false); try { return mode() === "self" ? await getExamReviewAttempts(examId) : await getStudentAttempts(examId, userId); } catch (err) { if (err instanceof ApiError && err.status === 404) return [] as number[]; if (mode() === "self" && err instanceof ApiError && err.status === 409) { setReviewInProgress(true); return [] as number[]; } throw err; } }, ); const latestSeq = () => { const a = attempts(); return a && a.length ? a[a.length - 1] : null; }; // Effective seq being shown, and whether it's the current (re-gradable) sitting. const activeSeq = () => selectedSeq() ?? latestSeq(); const isLatest = () => { const s = activeSeq(); return s == null || s === latestSeq(); }; // Dropdown options, newest sitting first (a student may have many). Just the // sitting label; the latest is tagged as the current one. Per-sitting stats // live in the sheet header for the selected sitting, not in the dropdown. const attemptOptions = () => [...(attempts() ?? [])].reverse().map((seq) => ({ value: seq, label: `${t("exams.attemptN", { n: seq })}${seq === latestSeq() ? ` (${t("exams.currentAttempt")})` : ""}`, })); const answerImageUrl = (questionId: string) => { const seq = activeSeq(); if (mode() === "self") return `/api/exams/${props.examId}/review/attempts/${seq}/answers/${questionId}/image`; return isLatest() || seq == null ? `/api/exams/${props.examId}/attempts/${props.userId}/answers/${questionId}/image` : `/api/exams/${props.examId}/students/${props.userId}/attempts/${seq}/answers/${questionId}/image`; }; const fetchAnswerImage = (questionId: string) => { const seq = activeSeq(); if (mode() === "self") return getExamReviewAttemptAnswerImage(props.examId, seq ?? 1, questionId); return isLatest() || seq == null ? getStudentAnswerImage(props.examId, props.userId, questionId) : getStudentAttemptAnswerImage(props.examId, props.userId, seq, questionId); }; const [data] = createResource( // Re-fetch when the grader switches attempt. Latest uses the current-attempt route // (unchanged from before); an older seq uses the per-seq history route. () => [props.examId, props.userId, activeSeq(), isLatest()] as const, async ([examId, userId, seq, latest]) => { const questions = mode() === "self" ? await getExamReviewQuestions(examId) : await getExamQuestions(examId); let sheet: StudentAnswerSheet; let hasSheet = true; try { if (mode() === "self") { if (seq == null) throw new ApiError(404, "no attempts"); sheet = await getExamReviewAttemptAnswers(examId, seq); } else { sheet = latest || seq == null ? await getStudentAnswers(examId, userId) : await getStudentAttemptAnswers(examId, userId, seq); } } catch (err) { if (err instanceof ApiError && (err.status === 404 || (mode() === "self" && err.status === 409))) { if (mode() === "self" && err instanceof ApiError && err.status === 409) setReviewInProgress(true); hasSheet = false; sheet = { exam: examId, user: { id: userId, username: "", display_name: null }, answers: [], auto_score: { earned: 0, possible: 0 }, }; } else { throw err; } } return { sheet, hasSheet, rows: joinAnswerSheet(questions.items, sheet.answers) }; }, ); // Per-sitting answer breakdown for the viewed attempt's header. `is_correct` // is only set for auto-gradable (choice) questions: right = got it, wrong = // missed it, empty = no answer given; answered text questions fall in none // (a human grades those). `pending` surfaces those so the counts stay honest. const sheetStats = createMemo(() => { const rows = data()?.rows ?? []; const answered = (a: (typeof rows)[number]["answer"]) => !!a && (a.selected != null || !!a.text || !!a.answer_image); let right = 0; let wrong = 0; let empty = 0; let pending = 0; for (const r of rows) { if (!answered(r.answer)) empty++; else if (r.answer?.is_correct === true) right++; else if (r.answer?.is_correct === false) wrong++; else pending++; } return { right, wrong, empty, pending, total: rows.length }; }); return ( // The picker stays OUTSIDE the Suspense: switching attempts re-fetches // `data`, and if the dropdown lived inside the suspending subtree it would // unmount and its portalled menu would flash unpositioned (top-left) on // every select. Only the answer sheet suspends.

{t("exams.reviewInProgress")}

1}>
{t("exams.previousAttempts")} startSwitch(() => setSelectedSeq(v))} triggerClass="w-full sm:w-auto" />
}> {(d) => (

{t("exams.pastAttemptReadOnly")}

{props.userLabel || (d().hasSheet ? personLabel(d().sheet.user) : "—")}

0} fallback={{t("exams.notStarted")}}>
{t("exams.answersRight")}: {sheetStats().right} {t("exams.answersWrong")}: {sheetStats().wrong} {t("exams.answersEmpty")}: {sheetStats().empty} 0}> {t("exams.answersPending")}: {sheetStats().pending} {t("exams.autoScore")}: {d().sheet.auto_score.earned}/{d().sheet.auto_score.possible}
{(row, idx) => (
#{idx() + 1} {row.question.points} {t("questions.points")} }> {t("questions.kind.text")} —

{row.question.text}

{t("exams.textAnswer")}

{row.answer?.text || "—"}

fetchAnswerImage(row.question.id)} src={answerImageUrl(row.question.id)} alt={t("exams.drawAnswer")} imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain" />
} >
{(choice, ci) => (
{String.fromCharCode(65 + ci())} {choice.text} ✗ {choice.id === row.question.correct && ( )}
)}
)}
)} ); }