From e9ffc5ecc5d7a572e0895cf22c736e0ee239b2d6 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 06:16:19 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20let=20students=20rea?= =?UTF-8?q?d=20the=20answer=20key=20in=20self-review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Student self-review rendered the answer sheet but had no way to fetch the questions — GET /exams/{id}/questions is teacher-only (it exposes the `correct` index). Add a self-scoped GET /exams/{id}/review/questions returning the full QuestionResponse (with `correct`) behind the same reviewable_exam gate: draft->404, review off->403, unmarked caller->404. Revealing the key is the point — the gate proves the caller was marked. list_questions and review_questions now share question_page(); they differ only in the access wall (can_manage_course vs reviewable_exam). Browser-verified: student review renders questions + answers + drawing playback end to end. --- README.md | 1 + src/lib.rs | 2 +- src/web/exams.rs | 48 +++++++++++++++++++++++++++++++++++++++++--- tests/integration.rs | 18 +++++++++++++++++ 4 files changed, 65 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9359517..3dea46c 100644 --- a/README.md +++ b/README.md @@ -532,6 +532,7 @@ 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/questions` | student | The exam's question list **with `correct`** — the answer key the caller checks their own sheet against (same review gate) · paged | | 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) | diff --git a/src/lib.rs b/src/lib.rs index 1e0f398..9735569 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. 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 = "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 the answer key (`GET /exams/{id}/review/questions`, `correct` included) and 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/exams.rs b/src/web/exams.rs index 39509ae..205898b 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -82,6 +82,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(student_attempts)) .routes(routes!(student_attempt_answers)) .routes(routes!(student_marks_history)) + .routes(routes!(review_questions)) .routes(routes!(review_attempts)) .routes(routes!(review_attempt_answers)) // The image routes get their own HTTP body cap, like the note-file @@ -1563,8 +1564,20 @@ async fn list_questions( "only the course creator, an assigned teacher, or a manager/admin can read the question list", )); } - let questions = ExamQuestion::list_for_exam(exam.get_id(), &st.db).await?; - let images = images_by_question(exam.get_id(), &st.db).await?; + Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) +} + +/// The paged answer-key list (`correct` included) shared by the teacher +/// `list_questions` read and the student `review_questions` read — the two +/// differ only in the access wall they run first. +async fn question_page( + exam: &Exam, + limit: Option, + offset: i64, + db: &Database, +) -> Result, AppError> { + let questions = ExamQuestion::list_for_exam(exam.get_id(), db).await?; + let images = images_by_question(exam.get_id(), db).await?; let total = questions.len() as i64; let items = paginate(&questions, limit, offset) .iter() @@ -1577,7 +1590,7 @@ async fn list_questions( ) }) .collect(); - Ok(Json(Page::new(items, total, limit, offset))) + Ok(Page::new(items, total, limit, offset)) } /// Edit a question. Requires teacher+ and management rights over the exam's @@ -3014,6 +3027,35 @@ async fn review_attempts( Ok(Json(seqs)) } +/// The exam's full question list, `correct` indexes included — the answer key +/// the caller reviews their own sheet against. Same review gate as the other +/// self-review reads; revealing `correct` is the point (the gate already proves +/// the caller was marked). Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{id}/review/questions", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id"), PageParams), + responses( + (status = 200, description = "A page of the exam's questions with `correct` (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (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_questions( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let exam = reviewable_exam(&st, &user, &id).await?; + Ok(Json(question_page(&exam, limit, offset, &st.db).await?)) +} + /// 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. diff --git a/tests/integration.rs b/tests/integration.rs index e48d0f6..199384d 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -16511,6 +16511,24 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() { assert_eq!(seq1.status, StatusCode::OK, "{}", seq1.body); assert_eq!(seq1.body["answers"][0]["text"], "mitochondria"); assert_eq!(seq2.body["answers"][0]["text"], "chloroplast"); + + // The answer key: a marked student reads the questions with `correct` + // exposed (the whole point of review) — the same list the teacher sees. + let key = send( + &app, + "GET", + &format!("/exams/{exam}/review/questions"), + Some(&student), + None, + ) + .await; + assert_eq!(key.status, StatusCode::OK, "{}", key.body); + assert_eq!(key.body["items"][0]["id"], question); + assert!( + key.body["items"][0].as_object().unwrap().contains_key("correct"), + "review/questions must expose `correct`: {}", + key.body + ); } /// Own-scoped isolation: two graded students, review on. There is no `{user}`