forge
Explore
Log in

Don't you dare go Hollow

View a student's previous exam attempts

Browse files at this commit

f7005deada68bfcd901e9c50273a3b759e20d2ebAhmet Kaan GümüşParent: f0738f4
  • feat
    • view a student's previous exam attempts
Show full message
✨ feat(exams): view a student's previous exam attempts

The backend now keeps every sitting's answers, drawings, and mark instead
of wiping on retake. Surface that in the grader's answer sheet: fetch the
student's attempt list + mark history and, when there is more than one
sitting, show an attempt picker (each tab labelled with its mark, the
latest tagged current). Selecting an older sitting loads its answers and
drawings read-only — grading still targets the current attempt.

Four new read-only API wrappers hit the history endpoints; prior-attempt
views reuse the existing answer-sheet + drawing-replay components.
src/api/__tests__/exams/exam-results.test.tsmodified+46 -0
@@ -5,6 +5,7 @@ import { postExamResult } from "../../exams";
5 import { deleteExamResultByUserId } from "../../exams";5 import { deleteExamResultByUserId } from "../../exams";
6 import { getExamStatistics } from "../../exams";6 import { getExamStatistics } from "../../exams";
7 import { getStudentAnswers, getStudentAnswerImage } from "../../exams";7 import { getStudentAnswers, getStudentAnswerImage } from "../../exams";
8+import { getStudentAttempts, getStudentAttemptAnswers, getStudentAttemptAnswerImage, getStudentMarksHistory } from "../../exams";
8 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";9 import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch";
9 10
10 describe("exams API - results", () => {11 describe("exams API - results", () => {
@@ -95,4 +96,49 @@ describe("exams API - results", () => {
95 const [url] = lastFetchCall();96 const [url] = lastFetchCall();
96 expect(url).toBe("/api/exams/ex1/attempts/u1/answers/q1/image");97 expect(url).toBe("/api/exams/ex1/attempts/u1/answers/q1/image");
97 });98 });
99+
100+ it("getStudentAttempts calls /exams/:id/students/:userId/attempts", async () => {
101+ mockFetchSuccess([1, 2]);
102+
103+ const result = await getStudentAttempts("ex1", "u1");
104+ expect(result).toEqual([1, 2]);
105+
106+ const [url, init] = lastFetchCall();
107+ expect(url).toBe("/api/exams/ex1/students/u1/attempts");
108+ expect(init?.method).toBe("GET");
109+ });
110+
111+ it("getStudentAttemptAnswers calls the per-seq answers route", async () => {
112+ const mockAnswers = { exam: "ex1", answers: [] };
113+ mockFetchSuccess(mockAnswers);
114+
115+ const result = await getStudentAttemptAnswers("ex1", "u1", 2);
116+ expect(result).toEqual(mockAnswers);
117+
118+ const [url, init] = lastFetchCall();
119+ expect(url).toBe("/api/exams/ex1/students/u1/attempts/2/answers");
120+ expect(init?.method).toBe("GET");
121+ });
122+
123+ it("getStudentAttemptAnswerImage calls the per-seq answer-image route", async () => {
124+ mockFetchBlob(new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }));
125+
126+ const result = await getStudentAttemptAnswerImage("ex1", "u1", 2, "q1");
127+ expect(result).toBeInstanceOf(Blob);
128+
129+ const [url] = lastFetchCall();
130+ expect(url).toBe("/api/exams/ex1/students/u1/attempts/2/answers/q1/image");
131+ });
132+
133+ it("getStudentMarksHistory calls /exams/:id/students/:userId/marks", async () => {
134+ const mockMarks = [{ id: "r1", mark: 60 }, { id: "r2", mark: 80 }];
135+ mockFetchSuccess(mockMarks);
136+
137+ const result = await getStudentMarksHistory("ex1", "u1");
138+ expect(result).toEqual(mockMarks);
139+
140+ const [url, init] = lastFetchCall();
141+ expect(url).toBe("/api/exams/ex1/students/u1/marks");
142+ expect(init?.method).toBe("GET");
143+ });
98 });144 });
src/api/exams/getStudentAttemptAnswerImage.tsadded+12 -0
@@ -0,0 +1,12 @@
1+import { blobClient } from "../client";
2+
3+/** Grader view of a specific past sitting's answer image (mirrors getStudentAnswerImage, scoped to a seq). */
4+export async function getStudentAttemptAnswerImage(
5+ examId: string,
6+ userId: string,
7+ seq: number,
8+ questionId: string,
9+ signal?: AbortSignal,
10+): Promise<Blob> {
11+ return blobClient(`/exams/${examId}/students/${userId}/attempts/${seq}/answers/${questionId}/image`, signal);
12+}
src/api/exams/getStudentAttemptAnswers.tsadded+15 -0
@@ -0,0 +1,15 @@
1+import { client } from "@/api/client";
2+import type { StudentAnswerSheet } from "@/api/client";
3+
4+/** Grader view of a specific past sitting's answer sheet (same shape as the current attempt). */
5+export async function getStudentAttemptAnswers(
6+ examId: string,
7+ userId: string,
8+ seq: number,
9+ signal?: AbortSignal,
10+): Promise<StudentAnswerSheet> {
11+ return client<StudentAnswerSheet>(
12+ `/exams/${encodeURIComponent(examId)}/students/${encodeURIComponent(userId)}/attempts/${seq}/answers`,
13+ { signal },
14+ );
15+}
src/api/exams/getStudentAttempts.tsadded+6 -0
@@ -0,0 +1,6 @@
1+import { client } from "@/api/client";
2+
3+/** Sitting seqs a student has for this exam, ascending (e.g. [1, 2]). Grader-only. */
4+export async function getStudentAttempts(examId: string, userId: string, signal?: AbortSignal): Promise<number[]> {
5+ return client<number[]>(`/exams/${encodeURIComponent(examId)}/students/${encodeURIComponent(userId)}/attempts`, { signal });
6+}
src/api/exams/getStudentMarksHistory.tsadded+11 -0
@@ -0,0 +1,11 @@
1+import { client } from "../client";
2+import type { ExamResult } from "../client";
3+
4+/** Full mark history for a student, oldest-first — index 0 = seq 1 (marks carry no seq). Grader-only. */
5+export async function getStudentMarksHistory(
6+ examId: string,
7+ userId: string,
8+ signal?: AbortSignal,
9+): Promise<ExamResult[]> {
10+ return client<ExamResult[]>(`/exams/${encodeURIComponent(examId)}/students/${encodeURIComponent(userId)}/marks`, { signal });
11+}
src/api/exams/index.tsmodified+4 -0
@@ -27,3 +27,7 @@ export * from "./postExamAttemptAnswerImage";
27 export * from "./deleteExamAttemptAnswerImage";27 export * from "./deleteExamAttemptAnswerImage";
28 export * from "./getExamAnswerImageBlob";28 export * from "./getExamAnswerImageBlob";
29 export * from "./getStudentAnswerImage";29 export * from "./getStudentAnswerImage";
30+export * from "./getStudentAttempts";
31+export * from "./getStudentAttemptAnswers";
32+export * from "./getStudentAttemptAnswerImage";
33+export * from "./getStudentMarksHistory";
src/components/exams/answer-sheet-view.tsxmodified+92 -6
@@ -1,7 +1,8 @@
1-import { For, Show, Suspense, createResource } from "solid-js";1+import { For, Show, Suspense, createResource, createSignal } from "solid-js";
2 import { ApiError } from "@/api/client";2 import { ApiError } from "@/api/client";
3 import { getExamQuestions } from "@/api/exams";3 import { getExamQuestions } from "@/api/exams";
4 import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams";4 import { getStudentAnswers, getStudentAnswerImage } from "@/api/exams";
5+import { getStudentAttempts, getStudentAttemptAnswers, getStudentAttemptAnswerImage, getStudentMarksHistory } from "@/api/exams";
5 import type { StudentAnswerSheet } from "@/api/client";6 import type { StudentAnswerSheet } from "@/api/client";
6 import { Badge } from "@/components/ui/badge";7 import { Badge } from "@/components/ui/badge";
7 import { Button } from "@/components/ui/button";8 import { Button } from "@/components/ui/button";
@@ -15,13 +16,71 @@ import { useT } from "@/stores/preferences-context";
15 16
16 export function AnswerSheetView(props: { examId: string; userId: string }) {17 export function AnswerSheetView(props: { examId: string; userId: string }) {
17 const t = useT();18 const t = useT();
18- const [data] = createResource(19+
20+ // Which sitting the grader is viewing. null = the latest (grade-of-record), the default.
21+ const [selectedSeq, setSelectedSeq] = createSignal<number | null>(null);
22+
23+ // Attempt list + full mark history (oldest-first, index i = seq i+1). Both grader-only,
24+ // both tolerate "student never sat" by degrading to empty.
25+ const [attempts] = createResource(
26+ () => [props.examId, props.userId] as const,
27+ async ([examId, userId]) => {
28+ try {
29+ return await getStudentAttempts(examId, userId);
30+ } catch (err) {
31+ if (err instanceof ApiError && err.status === 404) return [] as number[];
32+ throw err;
33+ }
34+ },
35+ );
36+ const [marks] = createResource(
19 () => [props.examId, props.userId] as const,37 () => [props.examId, props.userId] as const,
20 async ([examId, userId]) => {38 async ([examId, userId]) => {
39+ try {
40+ return await getStudentMarksHistory(examId, userId);
41+ } catch (err) {
42+ if (err instanceof ApiError && err.status === 404) return [];
43+ throw err;
44+ }
45+ },
46+ );
47+
48+ const latestSeq = () => {
49+ const a = attempts();
50+ return a && a.length ? a[a.length - 1] : null;
51+ };
52+ // Effective seq being shown, and whether it's the current (re-gradable) sitting.
53+ const activeSeq = () => selectedSeq() ?? latestSeq();
54+ const isLatest = () => {
55+ const s = activeSeq();
56+ return s == null || s === latestSeq();
57+ };
58+ const markForSeq = (seq: number) => marks()?.[seq - 1]?.mark ?? null;
59+
60+ const answerImageUrl = (questionId: string) => {
61+ const seq = activeSeq();
62+ return isLatest() || seq == null
63+ ? `/api/exams/${props.examId}/attempts/${props.userId}/answers/${questionId}/image`
64+ : `/api/exams/${props.examId}/students/${props.userId}/attempts/${seq}/answers/${questionId}/image`;
65+ };
66+ const fetchAnswerImage = (questionId: string) => {
67+ const seq = activeSeq();
68+ return isLatest() || seq == null
69+ ? getStudentAnswerImage(props.examId, props.userId, questionId)
70+ : getStudentAttemptAnswerImage(props.examId, props.userId, seq, questionId);
71+ };
72+
73+ const [data] = createResource(
74+ // Re-fetch when the grader switches attempt. Latest uses the current-attempt route
75+ // (unchanged from before); an older seq uses the per-seq history route.
76+ () => [props.examId, props.userId, activeSeq(), isLatest()] as const,
77+ async ([examId, userId, seq, latest]) => {
21 const questions = await getExamQuestions(examId);78 const questions = await getExamQuestions(examId);
22 let sheet: StudentAnswerSheet;79 let sheet: StudentAnswerSheet;
23 try {80 try {
24- sheet = await getStudentAnswers(examId, userId);81+ sheet = latest || seq == null
82+ ? await getStudentAnswers(examId, userId)
83+ : await getStudentAttemptAnswers(examId, userId, seq);
25 } catch (err) {84 } catch (err) {
26 if (err instanceof ApiError && err.status === 404) {85 if (err instanceof ApiError && err.status === 404) {
27 sheet = {86 sheet = {
@@ -40,9 +99,36 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
40 99
41 return (100 return (
42 <Suspense fallback={<PageSpinner />}>101 <Suspense fallback={<PageSpinner />}>
102+ <Show when={(attempts() ?? []).length > 1}>
103+ <div class="flex flex-wrap items-center gap-2">
104+ <span class="text-xs font-medium text-muted-foreground">{t("exams.previousAttempts")}</span>
105+ <For each={attempts()}>
106+ {(seq) => (
107+ <Button
108+ type="button"
109+ size="sm"
110+ variant={activeSeq() === seq ? "secondary" : "outline"}
111+ class="h-8 rounded-lg"
112+ onClick={() => setSelectedSeq(seq)}
113+ >
114+ {t("exams.attemptN", { n: seq })}
115+ <Show when={markForSeq(seq) != null}>
116+ <Badge variant="outline" class="ml-1.5 tabular-nums text-[10px]">{markForSeq(seq)}</Badge>
117+ </Show>
118+ <Show when={seq === latestSeq()}>
119+ <span class="ml-1 text-[10px] text-muted-foreground">({t("exams.currentAttempt")})</span>
120+ </Show>
121+ </Button>
122+ )}
123+ </For>
124+ </div>
125+ </Show>
43 <Show when={data()}>126 <Show when={data()}>
44 {(d) => (127 {(d) => (
45 <div class="space-y-4">128 <div class="space-y-4">
129+ <Show when={!isLatest()}>
130+ <p class="rounded-md border border-dashed bg-muted/20 px-3 py-2 text-xs text-muted-foreground">{t("exams.pastAttemptReadOnly")}</p>
131+ </Show>
46 <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-4 py-3">132 <div class="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 px-4 py-3">
47 <p class="text-sm font-medium">{personLabelWithId(d().sheet.user)}</p>133 <p class="text-sm font-medium">{personLabelWithId(d().sheet.user)}</p>
48 <Show when={d().sheet.answers.length > 0} fallback={<Badge variant="outline">{t("exams.notStarted")}</Badge>}>134 <Show when={d().sheet.answers.length > 0} fallback={<Badge variant="outline">{t("exams.notStarted")}</Badge>}>
@@ -86,12 +172,12 @@ export function AnswerSheetView(props: { examId: string; userId: string }) {
86 <Show when={row.answer?.answer_image}>172 <Show when={row.answer?.answer_image}>
87 <div class="mt-3 space-y-2">173 <div class="mt-3 space-y-2">
88 <ReplayableImage174 <ReplayableImage
89- fetchBlob={() => getStudentAnswerImage(d().sheet.exam, d().sheet.user.id, row.question.id)}175+ fetchBlob={() => fetchAnswerImage(row.question.id)}
90- src={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`}176+ src={answerImageUrl(row.question.id)}
91 alt={t("exams.drawAnswer")}177 alt={t("exams.drawAnswer")}
92 imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain"178 imgClass="h-64 w-full max-w-2xl rounded-md border bg-background object-contain"
93 />179 />
94- <a href={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`} download={`answer-${idx() + 1}.png`}>180+ <a href={answerImageUrl(row.question.id)} download={`answer-${idx() + 1}.png`}>
95 <Button type="button" size="sm" variant="outline" class="rounded-lg">181 <Button type="button" size="sm" variant="outline" class="rounded-lg">
96 <IconDownload class="h-4 w-4" />182 <IconDownload class="h-4 w-4" />
97 {t("notes.downloadFile")}183 {t("notes.downloadFile")}
src/i18n/messages.tsmodified+12 -0
@@ -664,6 +664,10 @@ export type MessageKey =
664 | "exams.isCorrect"664 | "exams.isCorrect"
665 | "exams.textAnswer"665 | "exams.textAnswer"
666 | "exams.drawAnswer"666 | "exams.drawAnswer"
667+ | "exams.previousAttempts"
668+ | "exams.attemptN"
669+ | "exams.currentAttempt"
670+ | "exams.pastAttemptReadOnly"
667 | "exams.uploadAnswerImage"671 | "exams.uploadAnswerImage"
668 | "exams.playDrawing"672 | "exams.playDrawing"
669 | "exams.showImage"673 | "exams.showImage"
@@ -1490,6 +1494,10 @@ const en: Dict = {
1490 "exams.isCorrect": "Correct",1494 "exams.isCorrect": "Correct",
1491 "exams.textAnswer": "Text answer",1495 "exams.textAnswer": "Text answer",
1492 "exams.drawAnswer": "Draw answer",1496 "exams.drawAnswer": "Draw answer",
1497+ "exams.previousAttempts": "Previous attempts",
1498+ "exams.attemptN": "Attempt {n}",
1499+ "exams.currentAttempt": "current",
1500+ "exams.pastAttemptReadOnly": "Viewing a previous attempt — read-only. Grading applies to the current attempt.",
1493 "exams.uploadAnswerImage": "Upload image",1501 "exams.uploadAnswerImage": "Upload image",
1494 "exams.playDrawing": "Play drawing",1502 "exams.playDrawing": "Play drawing",
1495 "exams.showImage": "Show image",1503 "exams.showImage": "Show image",
@@ -2310,6 +2318,10 @@ const tr: Dict = {
2310 "exams.isCorrect": "Doğru",2318 "exams.isCorrect": "Doğru",
2311 "exams.textAnswer": "Metin cevap",2319 "exams.textAnswer": "Metin cevap",
2312 "exams.drawAnswer": "Cevabı çiz",2320 "exams.drawAnswer": "Cevabı çiz",
2321+ "exams.previousAttempts": "Önceki denemeler",
2322+ "exams.attemptN": "{n}. deneme",
2323+ "exams.currentAttempt": "güncel",
2324+ "exams.pastAttemptReadOnly": "Önceki bir deneme görüntüleniyor — salt okunur. Puanlama güncel denemeye uygulanır.",
2313 "exams.uploadAnswerImage": "Görsel yükle",2325 "exams.uploadAnswerImage": "Görsel yükle",
2314 "exams.playDrawing": "Çizimi oynat",2326 "exams.playDrawing": "Çizimi oynat",
2315 "exams.showImage": "Görseli göster",2327 "exams.showImage": "Görseli göster",