forge
Explore
Log in

Don't you dare go Hollow

Let students review their own graded exam

Browse files at this commit

4db4ff2309a443ae8096f42f5a9fe062701d28f2Ahmet Kaan GümüşParent: 43e9f86
  • feat
    • let students review their own graded exam
Show full message
✨ feat(exams): let students review their own graded exam

Add a per-exam teacher toggle `allow_review` (default false, opt-in,
mirrors `allow_rejoin`) and three student self-review endpoints:

  GET /exams/{id}/review/attempts
  GET /exams/{id}/review/attempts/{seq}/answers
  GET /exams/{id}/review/attempts/{seq}/answers/{qid}/image

All are CurrentUser-scoped (no {user} param, so a student only ever
sees their own data) and gated by reviewable_exam(): 404 on missing or
draft exam, 403 when allow_review is off, 404 until an ExamResult row
exists for that student (proves the teacher marked them). Readers are
the same ones the teacher history endpoints use.

Schema: DEFINE FIELD allow_review DEFAULT false + a separate backfill
query flipping legacy NONE rows to false — no existing exam auto-exposes
answer sheets. Podman-verified: 9 legacy rows migrated null->false.
README.mdmodified+9 -2
@@ -497,11 +497,11 @@ their existing shapes: the student exam-room reads
497 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |497 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |
498 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |498 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |
499 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |499 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
500-| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |500+| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, allow_review?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |
501 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |501 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged |
502 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged |502 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged |
503 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |503 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
504-| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) |504+| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `allow_review`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) |
505 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |505 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) |
506 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |506 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |
507 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |507 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
@@ -532,6 +532,9 @@ their existing shapes: the student exam-room reads
532 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |532 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) |
533 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |533 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) |
534 | GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first — the latest seq is the grade-of-record (course manager) |534 | GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first — the latest seq is the grade-of-record (course manager) |
535+| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending — only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise) |
536+| GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) |
537+| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) |
535 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |538 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |
536 | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |539 | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current |
537 | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) |540 | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) |
@@ -986,6 +989,10 @@ Two per-exam policy knobs ride along, both **live-editable** at any point:
986 never kills a running attempt, it only blocks future starts.989 never kills a running attempt, it only blocks future starts.
987 - `allow_rejoin` (default `true`) — whether a student who *left the exam room*990 - `allow_rejoin` (default `true`) — whether a student who *left the exam room*
988 may come back in and keep answering (see the exam-room section).991 may come back in and keep answering (see the exam-room section).
992+- `allow_review` (default `false`) — opt-in door to the student self-review
993+ reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A
994+ student may review only when this is on **and** the teacher has marked them
995+ (an `ExamResult` row exists); own-scoped, so no student reads another's sheet.
989 996
990 A student **sits** an exam through attempts (sitting 1, 2, … — each row id is997 A student **sits** an exam through attempts (sitting 1, 2, … — each row id is
991 the composite `exam_user[_seq]` key, so a sitting exists at most once by998 the composite `exam_user[_seq]` key, so a sitting exists at most once by
src/database.rsmodified+4 -0
@@ -252,6 +252,7 @@ const MIGRATION: &str = "
252 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;252 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
253 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;253 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
254 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;254 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
255+ DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false;
255 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;256 DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
256 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;257 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
257 258
@@ -458,6 +459,9 @@ const BACKFILL: &str = "
458 -- was live for its course, so it stays published.459 -- was live for its course, so it stays published.
459 UPDATE exam SET draft = false WHERE draft = NONE;460 UPDATE exam SET draft = false WHERE draft = NONE;
460 461
462+ -- Exams predate the review toggle (2026-07-24): default it closed (opt-in).
463+ UPDATE exam SET allow_review = false WHERE allow_review = NONE;
464+
461 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};465 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
462 466
463 -- Questions written before subjects existed (2026-07-17) are destroyed, not467 -- Questions written before subjects existed (2026-07-17) are destroyed, not
src/domain/exam.rsmodified+11 -0
@@ -274,6 +274,7 @@ pub struct Exam {
274 // migration (limit 1, rejoin open), so reads never see them missing.274 // migration (limit 1, rejoin open), so reads never see them missing.
275 max_attempts: ExamAttemptLimit,275 max_attempts: ExamAttemptLimit,
276 allow_rejoin: bool,276 allow_rejoin: bool,
277+ allow_review: bool,
277 // Work-in-progress marker: a draft is visible only to its course's278 // Work-in-progress marker: a draft is visible only to its course's
278 // managers, cannot be sat, and cannot be graded. Rows predating the279 // managers, cannot be sat, and cannot be graded. Rows predating the
279 // column are backfilled published (`false`).280 // column are backfilled published (`false`).
@@ -331,6 +332,12 @@ impl Exam {
331 self.allow_rejoin332 self.allow_rejoin
332 }333 }
333 334
335+ /// Whether students may review their graded attempt once results are out.
336+ /// The teacher can flip this live.
337+ pub fn get_allow_review(&self) -> bool {
338+ self.allow_review
339+ }
340+
334 /// Whether the exam is still being prepared — hidden from students, not341 /// Whether the exam is still being prepared — hidden from students, not
335 /// sittable, not gradable, until published.342 /// sittable, not gradable, until published.
336 pub fn is_draft(&self) -> bool {343 pub fn is_draft(&self) -> bool {
@@ -366,6 +373,7 @@ impl Exam {
366 schedule: ExamSchedule,373 schedule: ExamSchedule,
367 max_attempts: ExamAttemptLimit,374 max_attempts: ExamAttemptLimit,
368 allow_rejoin: bool,375 allow_rejoin: bool,
376+ allow_review: bool,
369 draft: bool,377 draft: bool,
370 db: &Database,378 db: &Database,
371 ) -> Result<Exam, AppError> {379 ) -> Result<Exam, AppError> {
@@ -382,6 +390,7 @@ impl Exam {
382 duration_ms: schedule.duration_ms,390 duration_ms: schedule.duration_ms,
383 max_attempts,391 max_attempts,
384 allow_rejoin,392 allow_rejoin,
393+ allow_review,
385 draft,394 draft,
386 };395 };
387 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;396 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
@@ -441,6 +450,7 @@ impl Exam {
441 schedule: ExamSchedule,450 schedule: ExamSchedule,
442 max_attempts: ExamAttemptLimit,451 max_attempts: ExamAttemptLimit,
443 allow_rejoin: bool,452 allow_rejoin: bool,
453+ allow_review: bool,
444 draft: bool,454 draft: bool,
445 db: &Database,455 db: &Database,
446 ) -> Result<Exam, AppError> {456 ) -> Result<Exam, AppError> {
@@ -453,6 +463,7 @@ impl Exam {
453 self.duration_ms = schedule.duration_ms;463 self.duration_ms = schedule.duration_ms;
454 self.max_attempts = max_attempts;464 self.max_attempts = max_attempts;
455 self.allow_rejoin = allow_rejoin;465 self.allow_rejoin = allow_rejoin;
466+ self.allow_review = allow_review;
456 self.draft = draft;467 self.draft = draft;
457 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;468 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;
458 updated.ok_or(AppError::NotFound)469 updated.ok_or(AppError::NotFound)
src/domain/exam_attempt.rsmodified+1 -0
@@ -336,6 +336,7 @@ mod tests {
336 ExamAttemptLimit::try_new(max_attempts).unwrap(),336 ExamAttemptLimit::try_new(max_attempts).unwrap(),
337 true,337 true,
338 false,338 false,
339+ false,
339 db,340 db,
340 )341 )
341 .await342 .await
src/lib.rsmodified+1 -1
@@ -54,7 +54,7 @@ use crate::state::AppState;
54 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),54 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
55 (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),55 (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),
56 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),56 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
57- (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),57+ (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),
58 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),58 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
59 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Read: any authenticated user; edit: manager+"),59 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Read: any authenticated user; edit: manager+"),
60 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),60 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
src/web/courses.rsmodified+4 -0
@@ -140,6 +140,9 @@ struct CreateExamInCourse {
140 /// Whether a student who left the exam room may come back in and keep140 /// Whether a student who left the exam room may come back in and keep
141 /// answering. Defaults to `true`; editable live while the exam runs.141 /// answering. Defaults to `true`; editable live while the exam runs.
142 allow_rejoin: Option<bool>,142 allow_rejoin: Option<bool>,
143+ /// Whether students may review their graded attempt once results are out.
144+ /// Defaults to `false`; editable live.
145+ allow_review: Option<bool>,
143 /// Save as a work-in-progress draft: visible only to the course's146 /// Save as a work-in-progress draft: visible only to the course's
144 /// managers, not sittable, not gradable, until published via147 /// managers, not sittable, not gradable, until published via
145 /// `PATCH /exams/{id}` with `draft: false`. Defaults to `false`.148 /// `PATCH /exams/{id}` with `draft: false`. Defaults to `false`.
@@ -834,6 +837,7 @@ async fn create_exam_in_course(
834 schedule,837 schedule,
835 max_attempts,838 max_attempts,
836 req.allow_rejoin.unwrap_or(true),839 req.allow_rejoin.unwrap_or(true),
840+ req.allow_review.unwrap_or(false),
837 req.draft.unwrap_or(false),841 req.draft.unwrap_or(false),
838 &st.db,842 &st.db,
839 )843 )
src/web/dto.rsmodified+4 -0
@@ -341,6 +341,9 @@ pub struct ExamResponse {
341 /// Whether a student who left the exam room may come back in and keep341 /// Whether a student who left the exam room may come back in and keep
342 /// answering. Teachers can flip this live.342 /// answering. Teachers can flip this live.
343 pub allow_rejoin: bool,343 pub allow_rejoin: bool,
344+ /// Whether students may review their graded attempt once results are out.
345+ /// Teachers can flip this live.
346+ pub allow_review: bool,
344 /// Still being prepared: visible only to the course's managers, not347 /// Still being prepared: visible only to the course's managers, not
345 /// sittable, not gradable. Publish by `PATCH`ing `draft: false`.348 /// sittable, not gradable. Publish by `PATCH`ing `draft: false`.
346 pub draft: bool,349 pub draft: bool,
@@ -361,6 +364,7 @@ impl ExamResponse {
361 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),364 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),
362 max_attempts: exam.get_max_attempts().as_i64(),365 max_attempts: exam.get_max_attempts().as_i64(),
363 allow_rejoin: exam.get_allow_rejoin(),366 allow_rejoin: exam.get_allow_rejoin(),
367+ allow_review: exam.get_allow_review(),
364 draft: exam.is_draft(),368 draft: exam.is_draft(),
365 }369 }
366 }370 }
src/web/exams.rsmodified+127 -0
@@ -82,6 +82,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
82 .routes(routes!(student_attempts))82 .routes(routes!(student_attempts))
83 .routes(routes!(student_attempt_answers))83 .routes(routes!(student_attempt_answers))
84 .routes(routes!(student_marks_history))84 .routes(routes!(student_marks_history))
85+ .routes(routes!(review_attempts))
86+ .routes(routes!(review_attempt_answers))
85 // The image routes get their own HTTP body cap, like the note-file87 // The image routes get their own HTTP body cap, like the note-file
86 // ones: the server-wide hard ceiling plus multipart framing headroom.88 // ones: the server-wide hard ceiling plus multipart framing headroom.
87 .merge(89 .merge(
@@ -103,6 +105,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
103 ))105 ))
104 .routes(routes!(get_student_answer_image))106 .routes(routes!(get_student_answer_image))
105 .routes(routes!(student_attempt_answer_image))107 .routes(routes!(student_attempt_answer_image))
108+ .routes(routes!(review_attempt_answer_image))
106 .layer(DefaultBodyLimit::max(109 .layer(DefaultBodyLimit::max(
107 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,110 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
108 )),111 )),
@@ -148,6 +151,9 @@ struct UpdateExam {
148 /// Whether students who left the exam room may come back in. Omit to151 /// Whether students who left the exam room may come back in. Omit to
149 /// keep. Editable live — the teacher's door handle for the running room.152 /// keep. Editable live — the teacher's door handle for the running room.
150 allow_rejoin: Option<bool>,153 allow_rejoin: Option<bool>,
154+ /// Whether students may review their graded attempt once results are out.
155+ /// Omit to keep. Editable live.
156+ allow_review: Option<bool>,
151 /// `false` publishes a draft (students can now see and sit it); `true`157 /// `false` publishes a draft (students can now see and sit it); `true`
152 /// pulls a published exam back into hiding — allowed only while nobody158 /// pulls a published exam back into hiding — allowed only while nobody
153 /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.159 /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.
@@ -402,6 +408,7 @@ async fn update_exam(
402 None => exam.get_max_attempts(),408 None => exam.get_max_attempts(),
403 };409 };
404 let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());410 let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
411+ let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review());
405 let draft = req.draft.unwrap_or_else(|| exam.is_draft());412 let draft = req.draft.unwrap_or_else(|| exam.is_draft());
406 413
407 // Switching sync <-> async <-> open (or back to unscheduled) would414 // Switching sync <-> async <-> open (or back to unscheduled) would
@@ -440,6 +447,7 @@ async fn update_exam(
440 schedule,447 schedule,
441 max_attempts,448 max_attempts,
442 allow_rejoin,449 allow_rejoin,
450+ allow_review,
443 draft,451 draft,
444 &st.db,452 &st.db,
445 )453 )
@@ -2948,3 +2956,122 @@ async fn student_marks_history(
2948 .collect(),2956 .collect(),
2949 ))2957 ))
2950 }2958 }
2959+
2960+// ---- student self-review ----------------------------------------------------
2961+// The mirror of the teacher history reads above, but own-scoped: no `{user}`
2962+// path param, so the target is always the caller — a student can never reach
2963+// another student's sheet. Opens only once the teacher enables review AND has
2964+// marked this student (an ExamResult row proves it).
2965+
2966+/// The exam plus the per-student review gate the three self-review reads share.
2967+/// 404 if the exam is missing or still a draft, 403 if review is off for it, and
2968+/// 404 until the caller has a mark on it (nothing to review yet).
2969+async fn reviewable_exam(st: &AppState, user: &User, id: &str) -> Result<Exam, AppError> {
2970+ let exam = Exam::read(&ExamId::from_key(id), &st.db)
2971+ .await?
2972+ .ok_or(AppError::NotFound)?;
2973+ if exam.is_draft() {
2974+ return Err(AppError::NotFound);
2975+ }
2976+ if !exam.get_allow_review() {
2977+ return Err(AppError::Forbidden("review not enabled for this exam"));
2978+ }
2979+ ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db)
2980+ .await?
2981+ .ok_or(AppError::NotFound)?;
2982+ Ok(exam)
2983+}
2984+
2985+/// The caller's own sitting numbers at an exam — every seq that carries answers
2986+/// or a mark, ascending. Own-scoped review view; opens once the teacher enables
2987+/// review and has marked the caller.
2988+#[utoipa::path(
2989+ get,
2990+ path = "/{id}/review/attempts",
2991+ tag = "exams",
2992+ security(("session_cookie" = [])),
2993+ params(("id" = String, Path, description = "Exam id")),
2994+ responses(
2995+ (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]),
2996+ (status = 401, description = "Not authenticated", body = ErrorResponse),
2997+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
2998+ (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse),
2999+ ),
3000+)]
3001+async fn review_attempts(
3002+ State(st): State<AppState>,
3003+ CurrentUser(user): CurrentUser,
3004+ Path(id): Path<String>,
3005+) -> Result<Json<Vec<i64>>, AppError> {
3006+ let exam = reviewable_exam(&st, &user, &id).await?;
3007+ let target = user.get_id().clone();
3008+ let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?;
3009+ for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? {
3010+ seqs.push(result.get_seq());
3011+ }
3012+ seqs.sort_unstable();
3013+ seqs.dedup();
3014+ Ok(Json(seqs))
3015+}
3016+
3017+/// One of the caller's own sittings, judged — the `seq`th attempt's answers,
3018+/// drawing refs, correctness flags, and auto-score suggestion. Own-scoped
3019+/// review view.
3020+#[utoipa::path(
3021+ get,
3022+ path = "/{id}/review/attempts/{seq}/answers",
3023+ tag = "exams",
3024+ security(("session_cookie" = [])),
3025+ params(
3026+ ("id" = String, Path, description = "Exam id"),
3027+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
3028+ ),
3029+ responses(
3030+ (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse),
3031+ (status = 401, description = "Not authenticated", body = ErrorResponse),
3032+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
3033+ (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse),
3034+ ),
3035+)]
3036+async fn review_attempt_answers(
3037+ State(st): State<AppState>,
3038+ CurrentUser(user): CurrentUser,
3039+ Path((id, seq)): Path<(String, i64)>,
3040+) -> Result<Json<AttemptAnswersResponse>, AppError> {
3041+ let exam = reviewable_exam(&st, &user, &id).await?;
3042+ Ok(Json(
3043+ answer_sheet(&exam, user.get_id(), seq, &st.db).await?,
3044+ ))
3045+}
3046+
3047+/// The caller's own drawn-answer bytes for one of their sittings — the
3048+/// seq-scoped, own-scoped mirror of the grader's drawing read.
3049+#[utoipa::path(
3050+ get,
3051+ path = "/{id}/review/attempts/{seq}/answers/{qid}/image",
3052+ tag = "exams",
3053+ security(("session_cookie" = [])),
3054+ params(
3055+ ("id" = String, Path, description = "Exam id"),
3056+ ("seq" = i64, Path, description = "Sitting number (1, 2, …)"),
3057+ ("qid" = String, Path, description = "Question id"),
3058+ ),
3059+ responses(
3060+ (status = 200, description = "The caller's drawing bytes", content_type = "image/*"),
3061+ (status = 401, description = "Not authenticated", body = ErrorResponse),
3062+ (status = 403, description = "Review not enabled for this exam", body = ErrorResponse),
3063+ (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse),
3064+ ),
3065+)]
3066+async fn review_attempt_answer_image(
3067+ State(st): State<AppState>,
3068+ CurrentUser(user): CurrentUser,
3069+ Path((id, seq, qid)): Path<(String, i64, String)>,
3070+) -> Result<Response, AppError> {
3071+ let exam = reviewable_exam(&st, &user, &id).await?;
3072+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
3073+ let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db)
3074+ .await?
3075+ .ok_or(AppError::NotFound)?;
3076+ super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
3077+}
tests/integration.rsmodified+291 -0
@@ -16300,3 +16300,294 @@ async fn attempt_history_endpoints_are_teacher_walled() {
16300 assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}");16300 assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}");
16301 }16301 }
16302 }16302 }
16303+
16304+// --- student self-review (own-scoped, allow_review + a mark gate it) ---------
16305+
16306+/// Sit, answer, teacher grades — but with `allow_review` left at its default
16307+/// (false), the student's own review read is refused: 403, "review not enabled".
16308+#[tokio::test]
16309+async fn self_review_is_forbidden_until_the_teacher_enables_it() {
16310+ let (app, db) = app_and_db().await;
16311+ let teacher = login_as(&app, &db, "rev_off_t", "teacher").await;
16312+ let student = login(&app, "rev_off_s").await;
16313+ let student_id = me_id(&app, &student).await;
16314+
16315+ let course = create_course(&app, &teacher, "physics").await;
16316+ enroll(&app, &teacher, &course, &student_id).await;
16317+ let exam = scheduled_exam(
16318+ &app,
16319+ &teacher,
16320+ &course,
16321+ json!({ "title": "kinematics", "kind": "quiz", "mode": "open" }),
16322+ )
16323+ .await;
16324+
16325+ send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;
16326+ let res = send(
16327+ &app,
16328+ "POST",
16329+ &format!("/exams/{exam}/results"),
16330+ Some(&teacher),
16331+ Some(json!({ "mark": 55, "user_id": student_id })),
16332+ )
16333+ .await;
16334+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16335+
16336+ let res = send(
16337+ &app,
16338+ "GET",
16339+ &format!("/exams/{exam}/review/attempts"),
16340+ Some(&student),
16341+ None,
16342+ )
16343+ .await;
16344+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
16345+}
16346+
16347+/// `allow_review` on, but the student has no mark yet — nothing to review, so
16348+/// the gate 404s rather than leaking an empty (or in-progress) sheet.
16349+#[tokio::test]
16350+async fn self_review_is_not_found_until_a_mark_exists() {
16351+ let (app, db) = app_and_db().await;
16352+ let teacher = login_as(&app, &db, "rev_ungraded_t", "teacher").await;
16353+ let student = login(&app, "rev_ungraded_s").await;
16354+ let student_id = me_id(&app, &student).await;
16355+
16356+ let course = create_course(&app, &teacher, "chemistry").await;
16357+ enroll(&app, &teacher, &course, &student_id).await;
16358+ let exam = scheduled_exam(
16359+ &app,
16360+ &teacher,
16361+ &course,
16362+ json!({ "title": "moles", "kind": "quiz", "mode": "open", "allow_review": true }),
16363+ )
16364+ .await;
16365+
16366+ // Sat, but never graded — no ExamResult row.
16367+ send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;
16368+
16369+ let res = send(
16370+ &app,
16371+ "GET",
16372+ &format!("/exams/{exam}/review/attempts"),
16373+ Some(&student),
16374+ None,
16375+ )
16376+ .await;
16377+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
16378+}
16379+
16380+/// A draft exam is invisible to students even with review on and a mark in hand:
16381+/// the draft check comes first, so every self-review read is a flat 404.
16382+#[tokio::test]
16383+async fn self_review_of_a_draft_exam_is_not_found() {
16384+ let (app, db) = app_and_db().await;
16385+ let teacher = login_as(&app, &db, "rev_draft_t", "teacher").await;
16386+ let student = login(&app, "rev_draft_s").await;
16387+ let student_id = me_id(&app, &student).await;
16388+
16389+ let course = create_course(&app, &teacher, "geography").await;
16390+ enroll(&app, &teacher, &course, &student_id).await;
16391+ let exam = scheduled_exam(
16392+ &app,
16393+ &teacher,
16394+ &course,
16395+ json!({
16396+ "title": "maps", "kind": "quiz", "mode": "open",
16397+ "allow_review": true, "draft": true,
16398+ }),
16399+ )
16400+ .await;
16401+
16402+ for uri in [
16403+ format!("/exams/{exam}/review/attempts"),
16404+ format!("/exams/{exam}/review/attempts/1/answers"),
16405+ ] {
16406+ let res = send(&app, "GET", &uri, Some(&student), None).await;
16407+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{uri}: {}", res.body);
16408+ }
16409+}
16410+
16411+/// The happy path across retakes: review on, both sittings graded, and the
16412+/// student reads their own seqs `[1, 2]` plus each sitting's own answer text —
16413+/// seq 1 was not overwritten by the retake.
16414+#[tokio::test]
16415+async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16416+ let (app, db) = app_and_db().await;
16417+ let teacher = login_as(&app, &db, "rev_ok_t", "teacher").await;
16418+ let student = login(&app, "rev_ok_s").await;
16419+ let student_id = me_id(&app, &student).await;
16420+
16421+ let course = create_course(&app, &teacher, "biology").await;
16422+ let subject = create_subject(&app, &teacher, &course, "cells").await;
16423+ enroll(&app, &teacher, &course, &student_id).await;
16424+ let exam = scheduled_exam(
16425+ &app,
16426+ &teacher,
16427+ &course,
16428+ json!({
16429+ "title": "cell quiz", "kind": "quiz", "mode": "open",
16430+ "max_attempts": 2, "allow_review": true,
16431+ }),
16432+ )
16433+ .await;
16434+ let question = create_question(
16435+ &app,
16436+ &teacher,
16437+ &exam,
16438+ &subject,
16439+ json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }),
16440+ )
16441+ .await;
16442+ let results_uri = format!("/exams/{exam}/results");
16443+
16444+ // Seq 1: answer, grade, finish.
16445+ send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;
16446+ send(
16447+ &app,
16448+ "POST",
16449+ &format!("/exams/{exam}/attempt/answers"),
16450+ Some(&student),
16451+ Some(json!({ "question_id": question, "text": "mitochondria" })),
16452+ )
16453+ .await;
16454+ send(
16455+ &app,
16456+ "POST",
16457+ &results_uri,
16458+ Some(&teacher),
16459+ Some(json!({ "mark": 40, "user_id": student_id })),
16460+ )
16461+ .await;
16462+ send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await;
16463+ // Seq 2: retake, answer differently, grade.
16464+ send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await;
16465+ send(
16466+ &app,
16467+ "POST",
16468+ &format!("/exams/{exam}/attempt/answers"),
16469+ Some(&student),
16470+ Some(json!({ "question_id": question, "text": "chloroplast" })),
16471+ )
16472+ .await;
16473+ send(
16474+ &app,
16475+ "POST",
16476+ &results_uri,
16477+ Some(&teacher),
16478+ Some(json!({ "mark": 90, "user_id": student_id })),
16479+ )
16480+ .await;
16481+
16482+ // Own seqs, ascending.
16483+ let res = send(
16484+ &app,
16485+ "GET",
16486+ &format!("/exams/{exam}/review/attempts"),
16487+ Some(&student),
16488+ None,
16489+ )
16490+ .await;
16491+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16492+ assert_eq!(res.body, json!([1, 2]));
16493+
16494+ // Each sitting keeps its own answer text.
16495+ let seq1 = send(
16496+ &app,
16497+ "GET",
16498+ &format!("/exams/{exam}/review/attempts/1/answers"),
16499+ Some(&student),
16500+ None,
16501+ )
16502+ .await;
16503+ let seq2 = send(
16504+ &app,
16505+ "GET",
16506+ &format!("/exams/{exam}/review/attempts/2/answers"),
16507+ Some(&student),
16508+ None,
16509+ )
16510+ .await;
16511+ assert_eq!(seq1.status, StatusCode::OK, "{}", seq1.body);
16512+ assert_eq!(seq1.body["answers"][0]["text"], "mitochondria");
16513+ assert_eq!(seq2.body["answers"][0]["text"], "chloroplast");
16514+}
16515+
16516+/// Own-scoped isolation: two graded students, review on. There is no `{user}`
16517+/// path param, so student A's token resolves to A — A sees A's own seqs and
16518+/// answer text, never B's, even though both are graded on the same exam.
16519+#[tokio::test]
16520+async fn self_review_is_own_scoped_between_students() {
16521+ let (app, db) = app_and_db().await;
16522+ let teacher = login_as(&app, &db, "rev_iso_t", "teacher").await;
16523+ let alice = login(&app, "rev_iso_a").await;
16524+ let alice_id = me_id(&app, &alice).await;
16525+ let bob = login(&app, "rev_iso_b").await;
16526+ let bob_id = me_id(&app, &bob).await;
16527+
16528+ let course = create_course(&app, &teacher, "history").await;
16529+ let subject = create_subject(&app, &teacher, &course, "rome").await;
16530+ enroll(&app, &teacher, &course, &alice_id).await;
16531+ enroll(&app, &teacher, &course, &bob_id).await;
16532+ let exam = scheduled_exam(
16533+ &app,
16534+ &teacher,
16535+ &course,
16536+ json!({ "title": "quiz", "kind": "quiz", "mode": "open", "allow_review": true }),
16537+ )
16538+ .await;
16539+ let question = create_question(
16540+ &app,
16541+ &teacher,
16542+ &exam,
16543+ &subject,
16544+ json!({ "text": "Name a consul.", "kind": "text", "points": 10 }),
16545+ )
16546+ .await;
16547+ let results_uri = format!("/exams/{exam}/results");
16548+
16549+ for (who, id, text, mark) in [
16550+ (&alice, &alice_id, "cicero", 70),
16551+ (&bob, &bob_id, "cato", 30),
16552+ ] {
16553+ send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(who), None).await;
16554+ send(
16555+ &app,
16556+ "POST",
16557+ &format!("/exams/{exam}/attempt/answers"),
16558+ Some(who),
16559+ Some(json!({ "question_id": question, "text": text })),
16560+ )
16561+ .await;
16562+ send(
16563+ &app,
16564+ "POST",
16565+ &results_uri,
16566+ Some(&teacher),
16567+ Some(json!({ "mark": mark, "user_id": id })),
16568+ )
16569+ .await;
16570+ }
16571+
16572+ // Alice's token sees only Alice's data — one seq, her own answer.
16573+ let res = send(
16574+ &app,
16575+ "GET",
16576+ &format!("/exams/{exam}/review/attempts"),
16577+ Some(&alice),
16578+ None,
16579+ )
16580+ .await;
16581+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16582+ assert_eq!(res.body, json!([1]));
16583+ let sheet = send(
16584+ &app,
16585+ "GET",
16586+ &format!("/exams/{exam}/review/attempts/1/answers"),
16587+ Some(&alice),
16588+ None,
16589+ )
16590+ .await;
16591+ assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer");
16592+ assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer");
16593+}