From 4db4ff2309a443ae8096f42f5a9fe062701d28f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 24 Jul 2026 05:44:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20let=20students=20rev?= =?UTF-8?q?iew=20their=20own=20graded=20exam?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.md | 11 +- src/database.rs | 4 + src/domain/exam.rs | 11 ++ src/domain/exam_attempt.rs | 1 + src/lib.rs | 2 +- src/web/courses.rs | 4 + src/web/dto.rs | 4 + src/web/exams.rs | 127 ++++++++++++++++ tests/integration.rs | 291 +++++++++++++++++++++++++++++++++++++ 9 files changed, 452 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d536b23..9359517 100644 --- a/README.md +++ b/README.md @@ -497,11 +497,11 @@ their existing shapes: the student exam-room reads | 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+ | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | -| 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 | +| 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 | | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, assigned teacher, or manager+; drafts appear to course managers only) · paged | | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) | -| 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) | +| 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) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question + answer images (course manager) | | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) | | 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 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's answer sheet: `is_correct` flags + suggested `auto_score` (course manager) | | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) | | 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) | +| 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) | +| 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) | +| GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | | 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") | | 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 | | 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: never kills a running attempt, it only blocks future starts. - `allow_rejoin` (default `true`) — whether a student who *left the exam room* may come back in and keep answering (see the exam-room section). +- `allow_review` (default `false`) — opt-in door to the student self-review + reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A + student may review only when this is on **and** the teacher has marked them + (an `ExamResult` row exists); own-scoped, so no student reads another's sheet. A student **sits** an exam through attempts (sitting 1, 2, … — each row id is the composite `exam_user[_seq]` key, so a sitting exists at most once by diff --git a/src/database.rs b/src/database.rs index 8fa522d..481018c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -252,6 +252,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option; DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1; DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true; + DEFINE FIELD IF NOT EXISTS allow_review ON exam TYPE bool DEFAULT false; DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false; DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; @@ -458,6 +459,9 @@ const BACKFILL: &str = " -- was live for its course, so it stays published. UPDATE exam SET draft = false WHERE draft = NONE; + -- Exams predate the review toggle (2026-07-24): default it closed (opt-in). + UPDATE exam SET allow_review = false WHERE allow_review = NONE; + UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; -- Questions written before subjects existed (2026-07-17) are destroyed, not diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 6029c3e..437f9b7 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -274,6 +274,7 @@ pub struct Exam { // migration (limit 1, rejoin open), so reads never see them missing. max_attempts: ExamAttemptLimit, allow_rejoin: bool, + allow_review: bool, // Work-in-progress marker: a draft is visible only to its course's // managers, cannot be sat, and cannot be graded. Rows predating the // column are backfilled published (`false`). @@ -331,6 +332,12 @@ impl Exam { self.allow_rejoin } + /// Whether students may review their graded attempt once results are out. + /// The teacher can flip this live. + pub fn get_allow_review(&self) -> bool { + self.allow_review + } + /// Whether the exam is still being prepared — hidden from students, not /// sittable, not gradable, until published. pub fn is_draft(&self) -> bool { @@ -366,6 +373,7 @@ impl Exam { schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, + allow_review: bool, draft: bool, db: &Database, ) -> Result { @@ -382,6 +390,7 @@ impl Exam { duration_ms: schedule.duration_ms, max_attempts, allow_rejoin, + allow_review, draft, }; let created: Option = db.create(exam.id.record()).content(exam).await?; @@ -441,6 +450,7 @@ impl Exam { schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, + allow_review: bool, draft: bool, db: &Database, ) -> Result { @@ -453,6 +463,7 @@ impl Exam { self.duration_ms = schedule.duration_ms; self.max_attempts = max_attempts; self.allow_rejoin = allow_rejoin; + self.allow_review = allow_review; self.draft = draft; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index be62bb5..93ca3da 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -336,6 +336,7 @@ mod tests { ExamAttemptLimit::try_new(max_attempts).unwrap(), true, false, + false, db, ) .await diff --git a/src/lib.rs b/src/lib.rs index 1824f85..1e0f398 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,7 +54,7 @@ use crate::state::AppState; (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"), (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)"), (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"), - (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"), + (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"), (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"), (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+"), (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"), diff --git a/src/web/courses.rs b/src/web/courses.rs index e06d29c..fc5cb6b 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -140,6 +140,9 @@ struct CreateExamInCourse { /// Whether a student who left the exam room may come back in and keep /// answering. Defaults to `true`; editable live while the exam runs. allow_rejoin: Option, + /// Whether students may review their graded attempt once results are out. + /// Defaults to `false`; editable live. + allow_review: Option, /// Save as a work-in-progress draft: visible only to the course's /// managers, not sittable, not gradable, until published via /// `PATCH /exams/{id}` with `draft: false`. Defaults to `false`. @@ -834,6 +837,7 @@ async fn create_exam_in_course( schedule, max_attempts, req.allow_rejoin.unwrap_or(true), + req.allow_review.unwrap_or(false), req.draft.unwrap_or(false), &st.db, ) diff --git a/src/web/dto.rs b/src/web/dto.rs index 641e475..f1f4d5c 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -341,6 +341,9 @@ pub struct ExamResponse { /// Whether a student who left the exam room may come back in and keep /// answering. Teachers can flip this live. pub allow_rejoin: bool, + /// Whether students may review their graded attempt once results are out. + /// Teachers can flip this live. + pub allow_review: bool, /// Still being prepared: visible only to the course's managers, not /// sittable, not gradable. Publish by `PATCH`ing `draft: false`. pub draft: bool, @@ -361,6 +364,7 @@ impl ExamResponse { duration_ms: exam.get_duration_ms().map(|d| d.as_millis()), max_attempts: exam.get_max_attempts().as_i64(), allow_rejoin: exam.get_allow_rejoin(), + allow_review: exam.get_allow_review(), draft: exam.is_draft(), } } diff --git a/src/web/exams.rs b/src/web/exams.rs index 2d41286..39509ae 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -82,6 +82,8 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(student_attempts)) .routes(routes!(student_attempt_answers)) .routes(routes!(student_marks_history)) + .routes(routes!(review_attempts)) + .routes(routes!(review_attempt_answers)) // The image routes get their own HTTP body cap, like the note-file // ones: the server-wide hard ceiling plus multipart framing headroom. .merge( @@ -103,6 +105,7 @@ pub fn routes() -> OpenApiRouter { )) .routes(routes!(get_student_answer_image)) .routes(routes!(student_attempt_answer_image)) + .routes(routes!(review_attempt_answer_image)) .layer(DefaultBodyLimit::max( MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, )), @@ -148,6 +151,9 @@ struct UpdateExam { /// Whether students who left the exam room may come back in. Omit to /// keep. Editable live — the teacher's door handle for the running room. allow_rejoin: Option, + /// Whether students may review their graded attempt once results are out. + /// Omit to keep. Editable live. + allow_review: Option, /// `false` publishes a draft (students can now see and sit it); `true` /// pulls a published exam back into hiding — allowed only while nobody /// has attempted it and nothing is graded (`409` otherwise). Omit to keep. @@ -402,6 +408,7 @@ async fn update_exam( None => exam.get_max_attempts(), }; let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin()); + let allow_review = req.allow_review.unwrap_or_else(|| exam.get_allow_review()); let draft = req.draft.unwrap_or_else(|| exam.is_draft()); // Switching sync <-> async <-> open (or back to unscheduled) would @@ -440,6 +447,7 @@ async fn update_exam( schedule, max_attempts, allow_rejoin, + allow_review, draft, &st.db, ) @@ -2948,3 +2956,122 @@ async fn student_marks_history( .collect(), )) } + +// ---- student self-review ---------------------------------------------------- +// The mirror of the teacher history reads above, but own-scoped: no `{user}` +// path param, so the target is always the caller — a student can never reach +// another student's sheet. Opens only once the teacher enables review AND has +// marked this student (an ExamResult row proves it). + +/// The exam plus the per-student review gate the three self-review reads share. +/// 404 if the exam is missing or still a draft, 403 if review is off for it, and +/// 404 until the caller has a mark on it (nothing to review yet). +async fn reviewable_exam(st: &AppState, user: &User, id: &str) -> Result { + let exam = Exam::read(&ExamId::from_key(id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if exam.is_draft() { + return Err(AppError::NotFound); + } + if !exam.get_allow_review() { + return Err(AppError::Forbidden("review not enabled for this exam")); + } + ExamResult::read_for_user(exam.get_id(), user.get_id(), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(exam) +} + +/// The caller's own sitting numbers at an exam — every seq that carries answers +/// or a mark, ascending. Own-scoped review view; opens once the teacher enables +/// review and has marked the caller. +#[utoipa::path( + get, + path = "/{id}/review/attempts", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The caller's own sitting numbers, ascending", body = [i64]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +async fn review_attempts( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let exam = reviewable_exam(&st, &user, &id).await?; + let target = user.get_id().clone(); + let mut seqs = ExamAnswer::list_seqs_for_user(exam.get_id(), &target, &st.db).await?; + for result in ExamResult::list_all_for_exam_user(exam.get_id(), &target, &st.db).await? { + seqs.push(result.get_seq()); + } + seqs.sort_unstable(); + seqs.dedup(); + Ok(Json(seqs)) +} + +/// One of the caller's own sittings, judged — the `seq`th attempt's answers, +/// drawing refs, correctness flags, and auto-score suggestion. Own-scoped +/// review view. +#[utoipa::path( + get, + path = "/{id}/review/attempts/{seq}/answers", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ), + responses( + (status = 200, description = "That sitting's answers, judged", body = AttemptAnswersResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "Exam not found, still a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +async fn review_attempt_answers( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, seq)): Path<(String, i64)>, +) -> Result, AppError> { + let exam = reviewable_exam(&st, &user, &id).await?; + Ok(Json( + answer_sheet(&exam, user.get_id(), seq, &st.db).await?, + )) +} + +/// The caller's own drawn-answer bytes for one of their sittings — the +/// seq-scoped, own-scoped mirror of the grader's drawing read. +#[utoipa::path( + get, + path = "/{id}/review/attempts/{seq}/answers/{qid}/image", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("seq" = i64, Path, description = "Sitting number (1, 2, …)"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "The caller's drawing bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Review not enabled for this exam", body = ErrorResponse), + (status = 404, description = "No such exam/question/drawing, a draft, or the caller has no mark on it", body = ErrorResponse), + ), +)] +async fn review_attempt_answer_image( + State(st): State, + CurrentUser(user): CurrentUser, + Path((id, seq, qid)): Path<(String, i64, String)>, +) -> Result { + let exam = reviewable_exam(&st, &user, &id).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let image = AnswerImage::read(question.get_id(), user.get_id(), seq, &st.db) + .await? + .ok_or(AppError::NotFound)?; + super::serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} diff --git a/tests/integration.rs b/tests/integration.rs index 7de1c0a..e48d0f6 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -16300,3 +16300,294 @@ async fn attempt_history_endpoints_are_teacher_walled() { assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}"); } } + +// --- student self-review (own-scoped, allow_review + a mark gate it) --------- + +/// Sit, answer, teacher grades — but with `allow_review` left at its default +/// (false), the student's own review read is refused: 403, "review not enabled". +#[tokio::test] +async fn self_review_is_forbidden_until_the_teacher_enables_it() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_off_t", "teacher").await; + let student = login(&app, "rev_off_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "physics").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "kinematics", "kind": "quiz", "mode": "open" }), + ) + .await; + + send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": 55, "user_id": student_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} + +/// `allow_review` on, but the student has no mark yet — nothing to review, so +/// the gate 404s rather than leaking an empty (or in-progress) sheet. +#[tokio::test] +async fn self_review_is_not_found_until_a_mark_exists() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_ungraded_t", "teacher").await; + let student = login(&app, "rev_ungraded_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "chemistry").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "moles", "kind": "quiz", "mode": "open", "allow_review": true }), + ) + .await; + + // Sat, but never graded — no ExamResult row. + send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; + + let res = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// A draft exam is invisible to students even with review on and a mark in hand: +/// the draft check comes first, so every self-review read is a flat 404. +#[tokio::test] +async fn self_review_of_a_draft_exam_is_not_found() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_draft_t", "teacher").await; + let student = login(&app, "rev_draft_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "geography").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ + "title": "maps", "kind": "quiz", "mode": "open", + "allow_review": true, "draft": true, + }), + ) + .await; + + for uri in [ + format!("/exams/{exam}/review/attempts"), + format!("/exams/{exam}/review/attempts/1/answers"), + ] { + let res = send(&app, "GET", &uri, Some(&student), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{uri}: {}", res.body); + } +} + +/// The happy path across retakes: review on, both sittings graded, and the +/// student reads their own seqs `[1, 2]` plus each sitting's own answer text — +/// seq 1 was not overwritten by the retake. +#[tokio::test] +async fn self_review_returns_own_seqs_and_per_sitting_answers() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_ok_t", "teacher").await; + let student = login(&app, "rev_ok_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "biology").await; + let subject = create_subject(&app, &teacher, &course, "cells").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ + "title": "cell quiz", "kind": "quiz", "mode": "open", + "max_attempts": 2, "allow_review": true, + }), + ) + .await; + let question = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }), + ) + .await; + let results_uri = format!("/exams/{exam}/results"); + + // Seq 1: answer, grade, finish. + send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "text": "mitochondria" })), + ) + .await; + send( + &app, + "POST", + &results_uri, + Some(&teacher), + Some(json!({ "mark": 40, "user_id": student_id })), + ) + .await; + send(&app, "POST", &format!("/exams/{exam}/attempt/finish"), Some(&student), None).await; + // Seq 2: retake, answer differently, grade. + send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(&student), + Some(json!({ "question_id": question, "text": "chloroplast" })), + ) + .await; + send( + &app, + "POST", + &results_uri, + Some(&teacher), + Some(json!({ "mark": 90, "user_id": student_id })), + ) + .await; + + // Own seqs, ascending. + let res = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body, json!([1, 2])); + + // Each sitting keeps its own answer text. + let seq1 = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts/1/answers"), + Some(&student), + None, + ) + .await; + let seq2 = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts/2/answers"), + Some(&student), + None, + ) + .await; + assert_eq!(seq1.status, StatusCode::OK, "{}", seq1.body); + assert_eq!(seq1.body["answers"][0]["text"], "mitochondria"); + assert_eq!(seq2.body["answers"][0]["text"], "chloroplast"); +} + +/// Own-scoped isolation: two graded students, review on. There is no `{user}` +/// path param, so student A's token resolves to A — A sees A's own seqs and +/// answer text, never B's, even though both are graded on the same exam. +#[tokio::test] +async fn self_review_is_own_scoped_between_students() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rev_iso_t", "teacher").await; + let alice = login(&app, "rev_iso_a").await; + let alice_id = me_id(&app, &alice).await; + let bob = login(&app, "rev_iso_b").await; + let bob_id = me_id(&app, &bob).await; + + let course = create_course(&app, &teacher, "history").await; + let subject = create_subject(&app, &teacher, &course, "rome").await; + enroll(&app, &teacher, &course, &alice_id).await; + enroll(&app, &teacher, &course, &bob_id).await; + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "quiz", "kind": "quiz", "mode": "open", "allow_review": true }), + ) + .await; + let question = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "Name a consul.", "kind": "text", "points": 10 }), + ) + .await; + let results_uri = format!("/exams/{exam}/results"); + + for (who, id, text, mark) in [ + (&alice, &alice_id, "cicero", 70), + (&bob, &bob_id, "cato", 30), + ] { + send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(who), None).await; + send( + &app, + "POST", + &format!("/exams/{exam}/attempt/answers"), + Some(who), + Some(json!({ "question_id": question, "text": text })), + ) + .await; + send( + &app, + "POST", + &results_uri, + Some(&teacher), + Some(json!({ "mark": mark, "user_id": id })), + ) + .await; + } + + // Alice's token sees only Alice's data — one seq, her own answer. + let res = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts"), + Some(&alice), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body, json!([1])); + let sheet = send( + &app, + "GET", + &format!("/exams/{exam}/review/attempts/1/answers"), + Some(&alice), + None, + ) + .await; + assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer"); + assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer"); +}