From ca93ae9ae52f8b53217ecd8a43779bee0991d7cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 04:29:16 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=8F=A6=20choice=20identity,=20bank?= =?UTF-8?q?=20visibility,=20and=20whole-row=20save=20races?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - choices become {id, text} with stable server-minted ids; correct and exam_answer.selected name a choice id, and image rows key off it, so editing a choice list can no longer re-point an answer key, a picture or a student's recorded answer - a PATCH carrying choices no longer wipes every option picture: it drops only rows whose choice id is absent from the new list, and omitting choices re-submits the stored ids untouched - bank templates are private by default; list, read, both image routes and from-bank enforce it, and an invisible template 404s rather than 403s so it cannot be probed for existence - bank list pages in SQL, newest first, with server-side text and visibility filters and a count over the same predicate — it used to return the whole table and window it in memory - text search folds Turkish casing through one shared table used by both the Rust needle and the SurrealQL column - fix: ExamAttempt::finish whole-row-saved a stale struct, so a walk-out stamp written by the exam-room socket could be reverted; it now writes only finished_at - fix: BankQuestion::update and Subject::update had the same shape; ban it going forward with scripts/check-whole-row-saves.sh and an explicit whole-row-save-ok opt-out for rows that cannot be raced - fix: question_to_bank wrote its back-link holding only BANK_LOCK, so a save racing a question edit lost the link - ids come from the monotonic ULID generator that already existed for appointment slots — Ulid::new is not monotonic within a millisecond, so newest-first ordering was wrong for same-ms rows - source_bank splits into from_bank and banked_as; deleting a template clears both, deleting a subject clears the template's subject instead of blocking the delete - add refresh-from-bank, frozen once an attempt exists, and a one-query per-page usage count - Exam::delete no longer reads a hardcoded statement slot - proptest over QuestionSpec::try_new: a key matching a stored choice is that choice, any other key is a new option that cannot steal an identity --- Cargo.lock | 79 +- Cargo.toml | 1 + proptest-regressions/domain/exam_question.txt | 7 + scripts/check-whole-row-saves.sh | 59 + src/database.rs | 51 +- src/domain/appointment_slot.rs | 25 +- src/domain/bank_question.rs | 663 ++++++- src/domain/bank_question_image.rs | 152 +- src/domain/exam.rs | 17 +- src/domain/exam_answer.rs | 63 +- src/domain/exam_attempt.rs | 88 +- src/domain/exam_question.rs | 493 +++++- src/domain/mod.rs | 2 + src/domain/monotonic_id.rs | 47 + src/domain/question_image.rs | 140 +- src/domain/subject.rs | 60 +- src/domain/text_fold.rs | 81 + src/lib.rs | 2 +- src/web/bank_questions.rs | 447 +++-- src/web/exam_ws.rs | 4 +- src/web/exams.rs | 437 +++-- src/web/mod.rs | 44 + src/web/subjects.rs | 33 +- tests/e2e.rs | 60 +- tests/integration.rs | 1549 ++++++++++++++--- tests/persistence.rs | 6 +- 26 files changed, 3864 insertions(+), 746 deletions(-) create mode 100644 proptest-regressions/domain/exam_question.txt create mode 100755 scripts/check-whole-row-saves.sh create mode 100644 src/domain/monotonic_id.rs create mode 100644 src/domain/text_fold.rs diff --git a/Cargo.lock b/Cargo.lock index 863b09f..8235047 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -433,6 +433,21 @@ dependencies = [ "virtue", ] +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" @@ -1782,6 +1797,7 @@ dependencies = [ "futures-util", "getrandom 0.4.3", "hex", + "proptest", "quinn", "rcgen", "reqwest", @@ -2963,6 +2979,25 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec 0.8.0", + "bitflags", + "num-traits", + "rand 0.9.5", + "rand_chacha 0.9.0", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + [[package]] name = "prost" version = "0.14.4" @@ -3031,6 +3066,12 @@ dependencies = [ "psl-types", ] +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quick_cache" version = "0.6.24" @@ -3221,6 +3262,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core 0.9.5", +] + [[package]] name = "rawpointer" version = "0.2.1" @@ -3694,6 +3744,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.23" @@ -4889,6 +4951,12 @@ dependencies = [ "web-time", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicase" version = "2.9.0" @@ -5040,6 +5108,15 @@ version = "0.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1" +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -5490,7 +5567,7 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" dependencies = [ - "bit-vec", + "bit-vec 0.9.1", "time", ] diff --git a/Cargo.toml b/Cargo.toml index 2b5a369..6b03b5a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,3 +51,4 @@ reqwest = { version = "0.13", default-features = false, features = ["json", "coo tempfile = "3" tokio-tungstenite = "0.30.0" futures-util = "0.3.32" +proptest = "1.11.0" diff --git a/proptest-regressions/domain/exam_question.txt b/proptest-regressions/domain/exam_question.txt new file mode 100644 index 0000000..9baf297 --- /dev/null +++ b/proptest-regressions/domain/exam_question.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 1cbabc252057de3029f0cd3a1c557f98551848dcbaedcd44b03c331f0ed27ec5 # shrinks to stored_n = 6, submitted = [(Other(""), "a"), (Stored(0), "a")], correct = Some(Null) diff --git a/scripts/check-whole-row-saves.sh b/scripts/check-whole-row-saves.sh new file mode 100755 index 0000000..0fe52ac --- /dev/null +++ b/scripts/check-whole-row-saves.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# Ban whole-row saves: `db.update(...).content(self)` and friends. +# +# WHY: `.content(self)` REPLACES the entire stored row with the in-memory +# struct. If `self` was loaded before an `.await` (a permission check, another +# query, an HTTP/QUIC call), any concurrent PATCH that landed in between is +# silently reverted — the write succeeds, the other user's change is gone, no +# error anywhere. A grep cannot see "read before an await", so the shape itself +# is banned and the exceptions are made explicit and reviewable. +# +# FIX: write only the fields the request actually changed, e.g. +# db.query("UPDATE $id SET text = $text, points = $points") +# or hold a lock across the whole read-modify-write and opt out below. +# +# OPT OUT: put this on the line IMMEDIATELY above the call: +# // whole-row-save-ok: +# +# Usage: +# scripts/check-whole-row-saves.sh # whole tree (gate mode) +# scripts/check-whole-row-saves.sh a.rs b.rs # only these files (hook mode) +# Exit 1 if any unannotated whole-row save is found. + +cd "$(dirname "$0")/.." || exit 1 + +if [ "$#" -gt 0 ]; then + set -- "$@" +else + # shellcheck disable=SC2046 # paths in this repo have no spaces + set -- $(find src -name '*.rs' | sort) +fi +[ "$#" -eq 0 ] && exit 0 + +awk ' +FNR == 1 { prev = "" } +/\.content\(&?self[).]/ { + if (prev !~ /\/\/[ \t]*whole-row-save-ok:[ \t]*[^ \t]/) { + sub(/^[ \t]+/, "", $0) + printf "%s:%d: %s\n", FILENAME, FNR, $0 + bad++ + } +} +{ prev = $0 } +END { + if (bad) { + print "" + print "whole-row save: .content(self) replaces the ENTIRE row, so any" + print "concurrent PATCH that landed after this struct was read (i.e." + print "across any .await above) is silently reverted — no error, data" + print "just disappears. Write only the changed fields instead:" + print " db.query(\"UPDATE $id SET field = $field\")" + print "If the row genuinely cannot be raced (e.g. a write lock is held" + print "across the read and the write), opt out on the line directly above:" + print " // whole-row-save-ok: " + print "" + printf "%d unannotated whole-row save(s).\n", bad + exit 1 + } +} +' "$@" diff --git a/src/database.rs b/src/database.rs index 6e83d79..76e9a47 100644 --- a/src/database.rs +++ b/src/database.rs @@ -273,17 +273,34 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string; DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string; DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; - DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option>; - DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option; + -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices + -- gained stable ids (`array`/`int` -> `array`/`string`), + -- and IF NOT EXISTS would leave an existing database on the old types. + DEFINE FIELD OVERWRITE choices ON exam_question TYPE option>; + -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice + -- object's own fields are declared too (same shape as `settings.exam_kinds`). + DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string; + DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string; + DEFINE FIELD OVERWRITE correct ON exam_question TYPE option; DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; - DEFINE FIELD IF NOT EXISTS source_bank ON exam_question TYPE option>; + -- Provenance, one column per direction: `from_bank` is the template this + -- question was inserted from, `banked_as` the template most recently minted + -- by saving it into the bank. They replace the single `source_bank`, which + -- both directions wrote — so a question inserted from the bank read as + -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to + -- actually go on an existing database, or SCHEMAFULL keeps accepting it + -- while the struct no longer writes it. + DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option>; + DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option>; + REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question; DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record; DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record; - DEFINE FIELD IF NOT EXISTS slot ON question_image TYPE option; + -- OVERWRITE: `slot` is now the choice's id, not its position. + DEFINE FIELD OVERWRITE slot ON question_image TYPE option; DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string; DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string; DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int; @@ -292,20 +309,35 @@ const MIGRATION: &str = " DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record; - DEFINE FIELD IF NOT EXISTS subject ON bank_question TYPE record; + -- OVERWRITE, not IF NOT EXISTS: the field started life as a required + -- `record` and has to actually change type on an existing database, + -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected. + DEFINE FIELD OVERWRITE subject ON bank_question TYPE option>; DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; - DEFINE FIELD IF NOT EXISTS choices ON bank_question TYPE option>; - DEFINE FIELD IF NOT EXISTS correct ON bank_question TYPE option; + -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices + -- gained stable ids (`array`/`int` -> `array`/`string`), + -- and IF NOT EXISTS would leave an existing database on the old types. + DEFINE FIELD OVERWRITE choices ON bank_question TYPE option>; + -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice + -- object's own fields are declared too (same shape as `settings.exam_kinds`). + DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string; + DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string; + DEFINE FIELD OVERWRITE correct ON bank_question TYPE option; DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option>; + -- 'private' | 'school'. DEFAULT so a row that predates the field (or any + -- partial write) can never come out published: the answer key stays the + -- owner's until they publish it. + DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private'; DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record; - DEFINE FIELD IF NOT EXISTS slot ON bank_question_image TYPE option; + -- OVERWRITE: `slot` is now the choice's id, not its position. + DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option; DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; @@ -315,7 +347,8 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record; - DEFINE FIELD IF NOT EXISTS selected ON exam_answer TYPE option; + -- OVERWRITE: `selected` now names the picked option by id. + DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option; DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option; DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int; -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 65d31f6..5dcad37 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -9,14 +9,12 @@ //! time. Cancelling one week is then a plain row delete, and the whole series //! is still addressable through its id. -use std::sync::{LazyLock, Mutex}; - use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::{Generator, Ulid}; use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES}; use crate::database::{APPOINTMENT_SLOT_TABLE, Database}; use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment}; +use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::{MILLIS_PER_DAY, Timestamp}; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -25,23 +23,10 @@ use crate::validate::validate_optional; /// One week, the only recurrence step this backend expands. const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY; -/// Mints slot ids in write order. `Ulid::new()`'s random low bits sort -/// arbitrarily among ids minted in the same millisecond, and a recurring -/// publish writes its whole expansion inside one — which would scramble the -/// `id` tie-break of the `ORDER BY starts_at, id` listings. -static IDS: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); - -fn next_ulid() -> Ulid { - let mut ids = IDS.lock().expect("slot id generator poisoned"); - // The only error is exhausting the random bits *within* one millisecond - // (2^80 ids deep); it clears itself as the clock ticks, so retry rather - // than fall back to a random id and silently reintroduce the defect. - loop { - if let Ok(ulid) = ids.generate() { - break ulid; - } - } -} +// Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish +// writes its whole expansion inside one millisecond, which random ULID low +// bits would scramble against the `id` tie-break of the `ORDER BY starts_at, +// id` listings. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct AppointmentSlotId(RecordId); diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index ad0fad8..6493ed5 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -7,25 +7,87 @@ //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants //! because every write goes through one. +use std::collections::HashMap; + use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use ulid::Ulid; use crate::database::{BANK_QUESTION_TABLE, Database}; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ - ChoiceText, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; +use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; +use crate::domain::text_fold::{fold, fold_sql}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; +use crate::error::{AppError, ValidationError}; + +/// Who may see a template. `private` — the owner (and admins) alone; `school` — +/// every teacher. +/// +/// **The default is `private`, deliberately.** A template carries `correct`, the +/// answer key, and its images: publishing one is an explicit act, never a side +/// effect of saving a question to the bank. `#[surreal(default)]` on the field +/// means rows written before this existed decode as `private` too, so the bank +/// can't retroactively broadcast anyone's answer keys. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BankVisibility(String); + +impl Default for BankVisibility { + fn default() -> Self { + Self(Self::PRIVATE.to_string()) + } +} + +impl BankVisibility { + pub const PRIVATE: &'static str = "private"; + pub const SCHOOL: &'static str = "school"; + + pub fn try_new(value: &str) -> Result { + if value != Self::PRIVATE && value != Self::SCHOOL { + return Err(ValidationError::Invalid { + field: "visibility", + reason: "must be private or school", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Whether the template is published to the whole school. + pub fn is_school(&self) -> bool { + self.0 == Self::SCHOOL + } +} #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BankQuestionId(RecordId); +/// The whole of [`BankQuestion::usage_counts`]: **one** statement (no `;`), +/// so a page of templates costs one round trip no matter how long it is. Named +/// so a test can assert that, since a per-row `count()` is exactly the N+1 this +/// page was cleaned of once. +const USAGE_COUNTS_SQL: &str = + "SELECT from_bank, count() AS n FROM exam_question WHERE from_bank IN $ids GROUP BY from_bank"; + +/// One `GROUP BY from_bank` row of [`BankQuestion::usage_counts`]. +#[derive(SurrealValue)] +struct UsageCount { + from_bank: BankQuestionId, + n: i64, +} + impl BankQuestionId { + /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and + /// a random ULID is only millisecond-accurate — templates saved inside one + /// tick (a to-bank burst, a test loop) would come back shuffled, so the id + /// comes from [`crate::domain::monotonic_id`] instead. pub fn generate() -> Self { - Self(RecordId::new(BANK_QUESTION_TABLE, Ulid::new().to_string())) + Self(RecordId::new(BANK_QUESTION_TABLE, next_ulid().to_string())) } pub fn from_key(key: &str) -> Self { @@ -48,18 +110,33 @@ impl BankQuestionId { /// it (the only one who may edit or delete it, admins aside); `subject` is /// origin metadata only — the same-course rule is checked against the caller's /// subject when a template is copied into an exam, not here. +/// +/// `subject` is optional because it is *only* metadata: deleting a subject +/// clears it school-wide (see [`crate::domain::subject::Subject::delete`]) +/// rather than being blocked by the bank. Blocking would have been a dead end +/// — the bank is owner-or-admin editable, so a manager could not resolve their +/// own 409 — and an existence oracle, since another teacher's *private* +/// template would have raised it. #[derive(Debug, Clone, SurrealValue)] pub struct BankQuestion { id: BankQuestionId, owner: UserId, - subject: SubjectId, + /// The origin subject, or `None` once that subject was deleted. + /// `#[surreal(default)]` for the same reason `visibility` has one: rows + /// written before the field went optional still decode. + #[surreal(default)] + subject: Option, text: QuestionText, kind: QuestionKind, points: QuestionPoints, - choices: Option>, - correct: Option, + choices: Option>, + correct: Option, /// The exam question this template was saved from, if any. source_exam: Option, + /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile + /// here): rows written before the field existed decode as `private`. + #[surreal(default)] + visibility: BankVisibility, created_at: Timestamp, } @@ -72,8 +149,8 @@ impl BankQuestion { &self.owner } - pub fn get_subject(&self) -> &SubjectId { - &self.subject + pub fn get_subject(&self) -> Option<&SubjectId> { + self.subject.as_ref() } pub fn get_text(&self) -> &QuestionText { @@ -88,36 +165,33 @@ impl BankQuestion { self.points } - pub fn get_choices(&self) -> Option<&[ChoiceText]> { + pub fn get_choices(&self) -> Option<&[Choice]> { self.choices.as_deref() } - pub fn get_correct(&self) -> Option { - self.correct + pub fn get_correct(&self) -> Option<&ChoiceId> { + self.correct.as_ref() } pub fn get_source_exam(&self) -> Option<&ExamId> { self.source_exam.as_ref() } + pub fn get_visibility(&self) -> &BankVisibility { + &self.visibility + } + pub fn get_created_at(&self) -> Timestamp { self.created_at } /// The stored kind-dependent fields as the validated bundle (for - /// merge-on-update). Bypasses `try_new`: the fields were written through a - /// `QuestionSpec`, so the invariants already hold. + /// merge-on-update, and for copying into an exam). Bypasses `try_new`: the + /// fields were written through a `QuestionSpec`, so the invariants already + /// hold — and a round-trip through `try_new` would mint *new* choice ids, + /// detaching the copy's `correct` and option pictures from its choices. pub fn spec(&self) -> QuestionSpec { - // `QuestionSpec` fields are private; rebuild through `try_new`, which - // the stored values are guaranteed to satisfy. - QuestionSpec::try_new( - self.kind.clone(), - self.choices - .as_ref() - .map(|cs| cs.iter().map(|c| c.as_str().to_string()).collect()), - self.correct, - ) - .expect("stored bank question fields satisfy the spec invariants") + QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone()) } pub async fn create( @@ -158,11 +232,15 @@ impl BankQuestion { let question = BankQuestion::from_parts( BankQuestionId::generate(), owner, - subject, + // Creation always carries a validated subject; only a subject + // delete ever clears it. + Some(subject), text, points, spec, source_exam, + // Never published on creation — publishing is its own PATCH. + BankVisibility::default(), Timestamp::now(), ); let created: Option = @@ -170,62 +248,193 @@ impl BankQuestion { created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) } - /// Whether any bank template references `subject` as its origin — the gate - /// that blocks deleting a subject still used by a template. - pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM bank_question WHERE subject = $subject LIMIT 1") - .bind(("subject", subject.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - pub async fn read(id: &BankQuestionId, db: &Database) -> Result, AppError> { Ok(db.select(id.record()).await?) } - /// Every template in the bank, school-wide (no owner filter), in creation - /// order (ULID ids sort by creation). - pub async fn list(db: &Database) -> Result, AppError> { + /// One page of the bank the caller may see, **newest first** (ULID ids sort by + /// creation, so `id DESC` is newest-first) — plus the total row count under + /// the same filters, so a client can page past the window. + /// + /// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: + /// the old version read the whole table and sliced it in memory, which hid + /// every template past the client's first page. `q` is a case- and + /// diacritic-insensitive fragment of the question text (blank = no text + /// filter): needle and column both go through + /// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. + /// + /// `visible_to` is the security filter, and it is a WHERE clause like every + /// other one — never a post-filter, or `total` would count templates the + /// caller can't have and paging would return short pages of them: + /// `Some(me)` sees the school-published templates plus their own, + /// `None` (admins only) sees everything. + /// + /// `visibility` is the *user's* filter ("only mine" / "shared with the + /// school") and is ANDed on top of that gate, so it can only ever narrow: + /// `school` still hides another teacher's private rows, and `private` + /// intersected with the gate leaves exactly the caller's own drafts. It + /// joins the same `clauses` vec as the rest, so `total` honours it too — + /// a count that ignored it would break paging. + // Flat filter args, like every other `list` here — a builder struct for + // four `Option`s and a window would be more machinery than the call sites. + #[allow(clippy::too_many_arguments)] + pub async fn list( + visible_to: Option<&UserId>, + owner: Option<&UserId>, + subject: Option<&SubjectId>, + visibility: Option<&BankVisibility>, + q: Option<&str>, + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + let needle = q.map(|q| fold(q.trim())).filter(|q| !q.is_empty()); + let mut clauses = Vec::new(); + if visible_to.is_some() { + clauses.push("(visibility = 'school' OR owner = $viewer)"); + } + if visibility.is_some() { + clauses.push("visibility = $visibility"); + } + if owner.is_some() { + clauses.push("owner = $owner"); + } + if subject.is_some() { + clauses.push("subject = $subject"); + } + let text_clause = format!("{} CONTAINS $q", fold_sql("text")); + if needle.is_some() { + clauses.push(text_clause.as_str()); + } + let where_clause = if clauses.is_empty() { + "true".to_string() + } else { + clauses.join(" AND ") + }; + // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. + let window = match limit { + Some(_) => "LIMIT $limit START $offset", + None => "START $offset", + }; + // The count runs over the *same* WHERE, so `total` can never disagree + // with what paging through the list actually yields. + let mut query = db + .query(format!( + "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; + SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" + )) + .bind(("offset", offset)); + if let Some(viewer) = visible_to { + query = query.bind(("viewer", viewer.record())); + } + if let Some(visibility) = visibility { + query = query.bind(("visibility", visibility.as_str().to_string())); + } + if let Some(owner) = owner { + query = query.bind(("owner", owner.record())); + } + if let Some(subject) = subject { + query = query.bind(("subject", subject.record())); + } + if let Some(needle) = needle { + query = query.bind(("q", needle)); + } + if let Some(limit) = limit { + query = query.bind(("limit", limit)); + } + let mut result = query.await?.check()?; + let questions = result.take::>(0)?; + // `GROUP ALL` yields no row at all when nothing matched. + let total = result.take::>(1)?.first().copied().unwrap_or(0); + Ok((questions, total)) + } + + /// How many exam questions were instantiated from each of `ids` — the + /// `from_bank` side of the provenance link, tallied for a whole page in + /// **one** grouped query (a `count()` per row would be the N+1 this page + /// already had removed once). Keys are template record keys; a template + /// nobody ever used has no entry at all, so the caller reads a miss as + /// zero — and the UI can stay quiet rather than print "0". + /// + /// Counts *questions*, not distinct exams: one exam that inserted the same + /// template twice counts twice, which is what "copies made from this + /// template" means and what the divergence trap is actually about. + pub async fn usage_counts( + ids: &[&BankQuestionId], + db: &Database, + ) -> Result, AppError> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let records: Vec = ids.iter().map(|id| id.record()).collect(); let mut result = db - .query("SELECT * FROM bank_question ORDER BY id ASC") + .query(USAGE_COUNTS_SQL) + .bind(("ids", records)) .await? .check()?; - Ok(result.take::>(0)?) + Ok(result + .take::>(0)? + .into_iter() + .map(|row| (row.from_bank.key().to_string(), row.n)) + .collect()) } + /// Write the editable fields of the template. + /// + /// Field-scoped, never a whole-row content-replace save: the handler reads + /// the row, then awaits an ownership check and a subject lookup before + /// getting here, so a concurrent PATCH (or the subject-delete cascade that + /// clears `subject`) can land inside that window — a whole-row save would + /// silently revert it. Same shape, same reason as + /// [`crate::domain::exam_question::ExamQuestion::link_banked_as`]. pub async fn update( - mut self, - subject: SubjectId, + self, + subject: Option, text: QuestionText, points: QuestionPoints, spec: QuestionSpec, + visibility: BankVisibility, db: &Database, ) -> Result { - self.subject = subject; - self.text = text; - self.points = points; let (kind, choices, correct) = spec.into_parts(); - self.kind = kind; - self.choices = choices; - self.correct = correct; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + let mut result = db + .query( + "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct, + visibility = $visibility RETURN AFTER", + ) + .bind(("id", self.id.record())) + .bind(("subject", subject.map(|s| s.record()))) + .bind(("text", text)) + .bind(("points", points)) + .bind(("kind", kind)) + .bind(("choices", choices)) + .bind(("correct", correct)) + .bind(("visibility", visibility)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Delete the template and cascade-remove its bank images, so none points /// at a missing template. Bank rows have no answers. The image *blobs* are /// the web layer's to remove — it collects their names before calling this. /// - /// Exam questions saved from this template keep living: only their - /// `source_bank` provenance link is cleared, field-scoped (never a whole-row - /// save — the question isn't ours and may be edited concurrently), so the - /// bank page can't read a link to a template that no longer exists. + /// Exam questions tied to this template keep living: only their provenance + /// links are cleared, field-scoped (never a whole-row save — the question + /// isn't ours and may be edited concurrently), so nothing can read a link to + /// a template that no longer exists. *Both* directions point at a template, + /// so both are cleared: `from_bank` on the questions instantiated from it, + /// and `banked_as` on the question it was saved out of. pub async fn delete(self, db: &Database) -> Result { db.query( "DELETE bank_question_image WHERE bank_question = $b; - UPDATE exam_question SET source_bank = NONE WHERE source_bank = $b;", + UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; + UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;", ) .bind(("b", self.id.record())) .await? @@ -238,11 +447,12 @@ impl BankQuestion { fn from_parts( id: BankQuestionId, owner: UserId, - subject: SubjectId, + subject: Option, text: QuestionText, points: QuestionPoints, spec: QuestionSpec, source_exam: Option, + visibility: BankVisibility, created_at: Timestamp, ) -> BankQuestion { let (kind, choices, correct) = spec.into_parts(); @@ -256,6 +466,7 @@ impl BankQuestion { choices, correct, source_exam, + visibility, created_at, } } @@ -266,14 +477,272 @@ mod tests { use super::*; fn spec() -> QuestionSpec { + use crate::domain::exam_question::ChoiceInput; QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), - Some(vec!["yes".into(), "no".into()]), - Some(1), + Some(vec![ + ChoiceInput { id: Some("a".into()), text: "yes".into() }, + ChoiceInput { id: Some("b".into()), text: "no".into() }, + ]), + Some("b".into()), + &[], ) .unwrap() } + /// A row stored before `visibility` existed has no such key — it must decode + /// as `private`, the safe value. Asserted on the decoder itself, so no + /// schema DEFAULT can paper over it: a `school` default here would publish + /// every pre-existing template in the school at once. + #[tokio::test] + async fn a_row_without_the_field_decodes_private() { + use surrealdb::types::Value; + + let db = crate::database::init_mem().await.unwrap(); + let question = BankQuestion::create( + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("q").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + assert_eq!(question.get_visibility().as_str(), BankVisibility::PRIVATE); + + let mut stored = question.into_value(); + let Value::Object(ref mut map) = stored else { + panic!("a bank question serializes to an object"); + }; + assert!(map.remove("visibility").is_some()); + let old = BankQuestion::from_value(stored).unwrap(); + assert_eq!(old.get_visibility().as_str(), BankVisibility::PRIVATE); + assert!(!old.get_visibility().is_school()); + } + + /// The visibility gate is a WHERE clause, so `total` counts exactly what the + /// page can contain — never someone else's private templates. + #[tokio::test] + async fn list_hides_private_templates_from_others() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let other = UserId::generate(); + let private = BankQuestion::create( + owner.clone(), + SubjectId::generate(), + QuestionText::try_new("secret").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + let published = BankQuestion::create( + owner.clone(), + SubjectId::generate(), + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + let subject = published.get_subject().cloned(); + published + .update( + subject, + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(), + &db, + ) + .await + .unwrap(); + + // The stranger sees the published one alone, and `total` agrees. + let (items, total) = BankQuestion::list(Some(&other), None, None, None, None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "shared"); + // The owner sees both; an admin (`None`) too. + let (items, total) = BankQuestion::list(Some(&owner), None, None, None, None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (2, 2)); + let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (2, 2)); + // An explicit `owner=` filter can't widen the gate. + let (items, total) = + BankQuestion::list(Some(&other), Some(&owner), None, None, None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(private.get_visibility().as_str(), BankVisibility::PRIVATE); + } + + /// The `visibility` filter ANDs onto the security gate, so it narrows and + /// never widens: a stranger asking for `school` still can't see a private + /// row, and `private` means "my own drafts" for everyone but an admin. + #[tokio::test] + async fn visibility_filter_narrows_never_widens() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let other = UserId::generate(); + let mine = |text: &str| { + BankQuestion::create( + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(text).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + }; + mine("draft").await.unwrap(); + let published = mine("shared").await.unwrap(); + let subject = published.get_subject().cloned(); + published + .update( + subject, + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(), + &db, + ) + .await + .unwrap(); + let private = BankVisibility::try_new(BankVisibility::PRIVATE).unwrap(); + let school = BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(); + + // Owner: `private` = their drafts, `school` = the published one. + let (items, total) = + BankQuestion::list(Some(&owner), None, None, Some(&private), None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "draft"); + let (items, total) = + BankQuestion::list(Some(&owner), None, None, Some(&school), None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "shared"); + // A stranger's `private` is empty — never someone else's draft. + let (items, total) = + BankQuestion::list(Some(&other), None, None, Some(&private), None, None, 0, &db) + .await + .unwrap(); + assert!(items.is_empty()); + assert_eq!(total, 0); + // …and their `school` stops at the published one, gate intact. + let (items, total) = + BankQuestion::list(Some(&other), None, None, Some(&school), None, None, 0, &db) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + // Composes with the other filters: right owner, wrong visibility. + let (items, total) = BankQuestion::list( + Some(&owner), + Some(&owner), + None, + Some(&school), + Some("draft"), + None, + 0, + &db, + ) + .await + .unwrap(); + assert!(items.is_empty()); + assert_eq!(total, 0); + } + + /// The whole page's tally in one grouped statement: right number per + /// template, unused templates absent (so the UI prints nothing rather than + /// "0"), and questions authored by hand never counted. + #[tokio::test] + async fn usage_counts_tallies_a_page_in_one_statement() { + use crate::domain::exam_question::ExamQuestion; + + // One statement, so a page costs one round trip — a `;` here would mean + // the per-row N+1 crept back in. + assert!(!USAGE_COUNTS_SQL.contains(';'), "usage_counts must be one statement"); + + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let template = |text: &str| { + BankQuestion::create( + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(text).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + }; + let used_twice = template("twice").await.unwrap(); + let used_once = template("once").await.unwrap(); + let unused = template("never").await.unwrap(); + + let exam = ExamId::generate(); + let other_exam = ExamId::generate(); + async fn instantiate(exam: &ExamId, source: &BankQuestion, db: &Database) { + ExamQuestion::create_from_bank( + exam, + SubjectId::generate(), + source.get_text().clone(), + source.get_points(), + source.spec(), + source.get_id().clone(), + db, + ) + .await + .unwrap(); + } + // Two copies of the same template, in two different exams. + instantiate(&exam, &used_twice, &db).await; + instantiate(&other_exam, &used_twice, &db).await; + instantiate(&exam, &used_once, &db).await; + // A hand-authored question has no `from_bank` and must not be tallied. + ExamQuestion::create( + &exam, + SubjectId::generate(), + QuestionText::try_new("mine").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + + let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; + let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap(); + assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); + assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); + assert_eq!(counts.get(unused.get_id().key()), None, "unused stays absent"); + assert_eq!(counts.len(), 2); + + // A template outside the page is never counted into it. + let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db).await.unwrap(); + assert_eq!(narrow.len(), 1); + assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); + // An empty page asks nothing at all. + assert!(BankQuestion::usage_counts(&[], &db).await.unwrap().is_empty()); + } + + #[test] + fn visibility_rejects_anything_else() { + assert!(BankVisibility::try_new("public").is_err()); + assert!(BankVisibility::try_new("").is_err()); + assert!(BankVisibility::try_new("school").unwrap().is_school()); + } + #[tokio::test] async fn list_is_school_wide() { let db = crate::database::init_mem().await.unwrap(); @@ -290,6 +759,80 @@ mod tests { .unwrap(); } // Different owners, yet both listed. - assert_eq!(BankQuestion::list(&db).await.unwrap().len(), 2); + let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(total, 2); + } + + /// The window is SQL, not an in-memory slice, and `total` ignores it. + #[tokio::test] + async fn list_pages_newest_first_and_filters_text() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + for i in 0..5 { + BankQuestion::create( + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(&format!("question {i}")).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + } + let (page, total) = BankQuestion::list(None, None, None, None, None, Some(2), 0, &db) + .await + .unwrap(); + assert_eq!(total, 5); + assert_eq!(page.len(), 2); + // Newest first: the last-created row leads. + assert_eq!(page[0].get_text().as_str(), "question 4"); + // The tail is reachable by offset. + let (tail, _) = BankQuestion::list(None, None, None, None, None, Some(2), 4, &db) + .await + .unwrap(); + assert_eq!(tail[0].get_text().as_str(), "question 0"); + // Text filter runs in SQL, case-insensitively, and narrows `total`. + let (hits, total) = BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db) + .await + .unwrap(); + assert_eq!((hits.len(), total), (1, 1)); + // Owner filter with nobody's templates. + let (none, total) = + BankQuestion::list(None, Some(&UserId::generate()), None, None, None, None, 0, &db) + .await + .unwrap(); + assert!(none.is_empty()); + assert_eq!(total, 0); + } + + /// Turkish `İ`/`ı` must not split the search into two disjoint halves. + #[tokio::test] + async fn list_text_filter_folds_turkish_casing() { + let db = crate::database::init_mem().await.unwrap(); + BankQuestion::create( + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + for needle in ["istanbul", "İSTANBUL", "İstanbul", "ıstanbul", "ilçe", "ILCE"] { + let (hits, total) = BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db) + .await + .unwrap(); + assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); + } + let (miss, total) = BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db) + .await + .unwrap(); + assert!(miss.is_empty()); + assert_eq!(total, 0); } } diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs index 67ad865..7cc04fc 100644 --- a/src/domain/bank_question_image.rs +++ b/src/domain/bank_question_image.rs @@ -1,5 +1,6 @@ //! An image pinned to a bank question — the question's own illustration -//! (`slot = NONE`) or one choice's picture (`slot = i`, choice questions only). +//! (`slot = NONE`) or one choice's picture (`slot` = that choice's stable id, +//! choice questions only). //! A structural copy of [`crate::domain::question_image`] with the exam FK //! dropped: a bank template belongs to no exam, and its owner is reachable //! through the `bank_question` row. The row carries metadata; the bytes live @@ -14,6 +15,7 @@ use ulid::Ulid; use crate::database::{BANK_QUESTION_IMAGE_TABLE, Database}; use crate::domain::bank_question::BankQuestionId; +use crate::domain::exam_question::ChoiceId; use crate::domain::note_file::FileContentType; use crate::error::AppError; @@ -22,12 +24,15 @@ pub struct BankQuestionImageId(RecordId); impl BankQuestionImageId { /// The one id a (question, slot) pair can have: `{bid}_q` for the - /// question's own image, `{bid}_{i}` for choice `i` — uniqueness per slot - /// needs no index this way. - pub fn for_slot(question: &BankQuestionId, slot: Option) -> Self { + /// question's own image, `{bid}_{choice id}` for one option's picture — + /// uniqueness per slot needs no index this way. Keyed by the option's + /// *stable id*, so reordering the choice list moves no picture. + pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self { + // `_` is not in Crockford base32 and a ULID is never `"q"`, so + // `{qid}_{cid}` and `{qid}_q` can never collide. let suffix = match slot { - None => "q".to_string(), - Some(index) => index.to_string(), + None => "q", + Some(id) => id.as_str(), }; Self(RecordId::new( BANK_QUESTION_IMAGE_TABLE, @@ -51,8 +56,9 @@ impl BankQuestionImageId { pub struct BankQuestionImage { id: BankQuestionImageId, bank_question: BankQuestionId, - /// `NONE` = the question's illustration; `i` = the picture of choice `i`. - slot: Option, + /// `NONE` = the question's illustration; otherwise the id of the option + /// this picture belongs to. + slot: Option, /// The blob's on-disk name — a fresh ULID every upload. file: String, content_type: FileContentType, @@ -65,14 +71,14 @@ impl BankQuestionImage { /// [`Self::upsert`] — so a stored row always points at a real blob. pub fn new( question: &BankQuestionId, - slot: Option, + slot: Option<&ChoiceId>, content_type: FileContentType, size: i64, ) -> Self { Self { id: BankQuestionImageId::for_slot(question, slot), bank_question: question.clone(), - slot, + slot: slot.cloned(), file: Ulid::new().to_string(), content_type, size, @@ -83,8 +89,8 @@ impl BankQuestionImage { &self.bank_question } - pub fn get_slot(&self) -> Option { - self.slot + pub fn get_slot(&self) -> Option<&ChoiceId> { + self.slot.as_ref() } pub fn get_file(&self) -> &str { @@ -102,13 +108,14 @@ impl BankQuestionImage { /// Create or replace the slot's image row — the deterministic id makes /// this the whole "one image per slot" story. pub async fn upsert(self, db: &Database) -> Result { + // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic let written: Option = db.upsert(self.id.record()).content(self).await?; written.ok_or_else(|| AppError::Internal("failed to store bank question image".into())) } pub async fn read_slot( question: &BankQuestionId, - slot: Option, + slot: Option<&ChoiceId>, db: &Database, ) -> Result, AppError> { Ok(db @@ -128,27 +135,46 @@ impl BankQuestionImage { Ok(result.take::>(0)?) } - /// Every bank image row, school-wide — for bucketing onto a whole template - /// list in one query (the bank list is itself school-wide). - pub async fn list_all(db: &Database) -> Result, AppError> { + /// The image rows of several templates in one query — for bucketing onto a + /// listing's *page* (never the whole table: the bank spans the school). + pub async fn list_for_questions( + questions: &[&BankQuestionId], + db: &Database, + ) -> Result, AppError> { + if questions.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = questions.iter().map(|q| q.record()).collect(); let mut result = db - .query("SELECT * FROM bank_question_image") + .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") + .bind(("ids", records)) .await? .check()?; Ok(result.take::>(0)?) } - /// Drop every *choice* image of the question (the question's own - /// illustration stays), returning the removed rows so the caller can take - /// their blobs off disk. Runs when a PATCH replaces the choice list — the - /// old pictures belong to the old options. - pub async fn delete_choices_for( + /// Drop the option pictures whose choice is gone — every choice image of + /// the question whose `slot` is *not* in `keep` (the question's own + /// illustration always stays), returning the removed rows so the caller can + /// take their blobs off disk. + /// + /// This is what makes an edit non-destructive: a PATCH that reorders, + /// renames, or drops options passes the surviving choice ids as `keep`, so + /// only the pictures of genuinely removed options go. `keep = &[]` (a text + /// question, or an all-new choice list) still clears the lot. + pub async fn delete_choices_not_in( question: &BankQuestionId, + keep: &[ChoiceId], db: &Database, ) -> Result, AppError> { + let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); let mut result = db - .query("DELETE bank_question_image WHERE bank_question = $b AND slot != NONE RETURN BEFORE") + .query( + "DELETE bank_question_image \ + WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", + ) .bind(("b", question.record())) + .bind(("keep", keep)) .await? .check()?; Ok(result.take::>(0)?) @@ -163,25 +189,49 @@ impl BankQuestionImage { #[cfg(test)] mod tests { use super::*; + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; fn png() -> FileContentType { FileContentType::try_new("image/png").unwrap() } + fn choice_ids() -> Vec { + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() }) + .collect(), + ), + Some("a".into()), + &[], + ) + .unwrap() + .into_parts() + .1 + .unwrap() + .iter() + .map(|c| c.get_id().clone()) + .collect() + } + #[tokio::test] - async fn for_slot_keys_by_question_and_slot() { + async fn for_slot_keys_by_question_and_choice_id() { let question = BankQuestionId::from_key("abc"); + let ids = choice_ids(); assert_eq!( BankQuestionImageId::for_slot(&question, None).key(), "abc_q" ); assert_eq!( - BankQuestionImageId::for_slot(&question, Some(0)).key(), - "abc_0" + BankQuestionImageId::for_slot(&question, Some(&ids[0])).key(), + format!("abc_{}", ids[0].as_str()) ); - assert_eq!( - BankQuestionImageId::for_slot(&question, Some(3)).key(), - "abc_3" + // Distinct options never share a row. + assert_ne!( + BankQuestionImageId::for_slot(&question, Some(&ids[0])), + BankQuestionImageId::for_slot(&question, Some(&ids[1])) ); } @@ -207,18 +257,54 @@ mod tests { assert_eq!(rows[0].get_size(), 5); } + /// The bank half of the non-destructive edit: keeping an option keeps its + /// picture, and only a removed option's picture goes. + #[tokio::test] + async fn only_the_dropped_options_lose_their_pictures() { + let db = crate::database::init_mem().await.unwrap(); + let question = BankQuestionId::generate(); + let ids = choice_ids(); + BankQuestionImage::new(&question, None, png(), 1) + .upsert(&db) + .await + .unwrap(); + for id in &ids { + BankQuestionImage::new(&question, Some(id), png(), 1) + .upsert(&db) + .await + .unwrap(); + } + + let keep = vec![ids[0].clone(), ids[1].clone()]; + let dropped = BankQuestionImage::delete_choices_not_in(&question, &keep, &db) + .await + .unwrap(); + assert_eq!(dropped.len(), 1); + assert_eq!(dropped[0].get_slot(), Some(&ids[2])); + + let left = BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(left.len(), 3); + } + #[tokio::test] - async fn choice_wipe_spares_the_question_image() { + async fn an_empty_keep_set_clears_every_option_picture() { let db = crate::database::init_mem().await.unwrap(); let question = BankQuestionId::generate(); - for slot in [None, Some(0), Some(1)] { - BankQuestionImage::new(&question, slot, png(), 1) + let ids = choice_ids(); + BankQuestionImage::new(&question, None, png(), 1) + .upsert(&db) + .await + .unwrap(); + for id in &ids[..2] { + BankQuestionImage::new(&question, Some(id), png(), 1) .upsert(&db) .await .unwrap(); } - let dropped = BankQuestionImage::delete_choices_for(&question, &db) + let dropped = BankQuestionImage::delete_choices_not_in(&question, &[], &db) .await .unwrap(); assert_eq!(dropped.len(), 2); diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 1815faa..777dc18 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -465,6 +465,7 @@ impl Exam { self.allow_rejoin = allow_rejoin; self.allow_review = allow_review; self.draft = draft; + // whole-row-save-ok: the only caller takes EXAM_LOCK.write() before the row read (web/exams.rs:354) let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } @@ -489,15 +490,22 @@ impl Exam { DELETE question_image WHERE exam = $ex; DELETE exam_question WHERE exam = $ex; UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; - DELETE $ex RETURN BEFORE; + LET $before = (DELETE $ex RETURN BEFORE); + RETURN $before; COMMIT TRANSACTION;", ) .bind(("ex", self.id.record())) .await? .check()?; - // Statement slots count BEGIN, the child deletes and the bank - // provenance clear: the exam's own DELETE is slot 8. - let deleted: Option = result.take::>(8)?.into_iter().next(); + // The deleted row comes back through the transaction's trailing + // `RETURN`, never a hand-counted slot: the old `take(8)` turned a + // successful delete into a 404 the moment a cascade statement was + // inserted above it (it already had to be bumped once). `RETURN` is + // always the last statement before `COMMIT`, so its slot is derived + // from the statement count and every insertion above it shifts it + // along. `num_statements` counts BEGIN and COMMIT too, hence -2. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } @@ -612,3 +620,4 @@ mod tests { assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); } } + diff --git a/src/domain/exam_answer.rs b/src/domain/exam_answer.rs index 49f1f34..59b35ea 100644 --- a/src/domain/exam_answer.rs +++ b/src/domain/exam_answer.rs @@ -3,7 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::MAX_ANSWER_TEXT_LEN; use crate::database::{Database, EXAM_ANSWER_TABLE}; use crate::domain::exam::ExamId; -use crate::domain::exam_question::{ExamQuestion, ExamQuestionId}; +use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -68,7 +68,7 @@ pub struct ExamAnswer { question: ExamQuestionId, user: UserId, seq: i64, - selected: Option, + selected: Option, text: Option, updated_at: Timestamp, } @@ -95,8 +95,8 @@ impl ExamAnswer { self.seq } - pub fn get_selected(&self) -> Option { - self.selected + pub fn get_selected(&self) -> Option<&ChoiceId> { + self.selected.as_ref() } pub fn get_text(&self) -> Option<&AnswerText> { @@ -111,13 +111,13 @@ impl ExamAnswer { /// text question — correctness is the grader's call, not the machine's. pub fn is_correct(&self, question: &ExamQuestion) -> Option { let correct = question.get_correct()?; - Some(self.selected == Some(correct)) + Some(self.selected.as_ref() == Some(correct)) } /// Save (or overwrite) `user`'s answer to `question` for sitting `seq` — /// the one write path, shared by the REST handler and the WebSocket room. /// The payload must match the question's kind: a choice question takes - /// `selected` (indexing one of its choices), a text question takes `text`. + /// `selected` (the id of one of its choices), a text question takes `text`. /// The caller has already checked that the attempt is in progress. Keyed /// by `seq`, so a retake's save is a new row, not an overwrite of an /// earlier sitting's answer. @@ -125,7 +125,7 @@ impl ExamAnswer { question: &ExamQuestion, user: &UserId, seq: i64, - selected: Option, + selected: Option, text: Option, db: &Database, ) -> Result { @@ -142,14 +142,17 @@ impl ExamAnswer { let Some(selected) = selected else { return Err(invalid("selected", "required for a choice question")); }; - let count = question.get_choices().map_or(0, <[_]>::len); - if !(0..count as i64).contains(&selected) { - return Err(invalid( - "selected", - "must index one of the question's choices", - )); - } - (Some(selected), None) + // Membership, not a range: `selected` names an option by its + // stable id, so a reorder of the list can never repoint it. + let picked = question + .get_choices() + .unwrap_or_default() + .iter() + .find(|choice| choice.get_id().as_str() == selected) + .ok_or_else(|| { + invalid("selected", "must name one of the question's choices") + })?; + (Some(picked.get_id().clone()), None) } _ => { if selected.is_some() { @@ -297,13 +300,23 @@ pub fn auto_score(questions: &[ExamQuestion], answers: &[ExamAnswer]) -> (i64, i #[cfg(test)] mod tests { use super::*; - use crate::domain::exam_question::{QuestionKind, QuestionSpec}; + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; - fn choice_question(exam: &ExamId, points: i64, correct: i64) -> ExamQuestion { + /// A three-option question whose `correct` is the option at `correct`. + /// Positions are a *test* convenience only — the ids are minted, and every + /// assertion below goes through `choice_id`. + fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion { + let labels = ["a", "b", "c"]; let spec = QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), - Some(vec!["a".into(), "b".into(), "c".into()]), - Some(correct), + Some( + labels + .iter() + .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() }) + .collect(), + ), + Some(labels[correct].into()), + &[], ) .unwrap(); ExamQuestion::test_new(exam, "pick one", points, spec) @@ -311,21 +324,27 @@ mod tests { fn text_question(exam: &ExamId, points: i64) -> ExamQuestion { let spec = - QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None).unwrap(); + QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(); ExamQuestion::test_new(exam, "explain", points, spec) } - fn answer(question: &ExamQuestion, user: &UserId, selected: Option) -> ExamAnswer { + /// The minted id of the question's option at `index`. + fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId { + question.get_choices().unwrap()[index].get_id().clone() + } + + fn answer(question: &ExamQuestion, user: &UserId, selected: Option) -> ExamAnswer { + let selected = selected.map(|index| choice_id(question, index)); ExamAnswer { id: ExamAnswerId::composite(question.get_id(), user, 1), exam: question.get_exam().clone(), question: question.get_id().clone(), user: user.clone(), seq: 1, - selected, text: selected .is_none() .then(|| AnswerText::try_new("essay").unwrap()), + selected, updated_at: Timestamp::from_millis(1), } } diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 93ca3da..efe37cd 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -210,10 +210,25 @@ impl ExamAttempt { /// Stamp the submission time. The caller has already checked the deadline /// and that the attempt isn't finished. - pub async fn finish(mut self, db: &Database) -> Result { - self.finished_at = Some(Timestamp::now()); - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) + /// + /// Writes *only* `finished_at`, for the mirror image of + /// [`ExamAttempt::set_left`]'s reason: the submit path reads the attempt, + /// then awaits its deadline and already-finished checks before writing, and + /// the exam room stamps or clears `left_at` on the same row from a socket. + /// A whole-row write from the pre-read snapshot would carry its stale + /// `left_at` back over that stamp, erasing the recorded walk-out. + pub async fn finish(self, db: &Database) -> Result { + let mut result = db + .query("UPDATE $id SET finished_at = $at RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("at", Some(Timestamp::now()))) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) } /// Stamp (or clear) the walked-out marker. The exam room sets it when the @@ -316,7 +331,15 @@ mod tests { ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; use crate::domain::exam_answer::ExamAnswer; - use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec}; + use crate::domain::exam_question::{ + ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, + }; + + /// The id of the question's second option — what these tests used to write + /// as the index `1`. + fn second_choice(question: &ExamQuestion) -> String { + question.get_choices().unwrap()[1].get_id().as_str().to_string() + } use crate::domain::settings::Settings; /// An open exam with retakes allowed, plus one choice question — enough @@ -343,8 +366,12 @@ mod tests { .unwrap(); let spec = QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), - Some(vec!["5".into(), "6".into()]), - Some(1), + Some(vec![ + ChoiceInput { id: Some("a".into()), text: "5".into() }, + ChoiceInput { id: Some("b".into()), text: "6".into() }, + ]), + Some("b".into()), + &[], ) .unwrap(); let question = ExamQuestion::create( @@ -373,7 +400,7 @@ mod tests { let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); assert!(created); assert_eq!(first.get_seq(), 1); - ExamAnswer::save(&question, &user, 1, Some(1), None, &db) + ExamAnswer::save(&question, &user, 1, Some(second_choice(&question)), None, &db) .await .unwrap(); first.finish(&db).await.unwrap(); @@ -407,7 +434,7 @@ mod tests { let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); assert!(created); assert_eq!(winner.get_seq(), 2); - ExamAnswer::save(&question, &user, 2, Some(1), None, &db) + ExamAnswer::save(&question, &user, 2, Some(second_choice(&question)), None, &db) .await .unwrap(); @@ -441,6 +468,49 @@ mod tests { assert_eq!(resumed.get_seq(), 2); } + #[tokio::test] + async fn submitting_never_reverts_a_walk_out_that_raced_it() { + let db = init_mem().await.unwrap(); + let (exam, _question) = open_exam_with_question(&db, 1).await; + let user = student(); + + let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap(); + + // The REST submit path reads the attempt, then checks the deadline and + // the already-finished guard — several awaits before it writes. + let stale = ExamAttempt::read(attempt.get_id(), &db) + .await + .unwrap() + .expect("attempt exists"); + assert!(stale.get_left_at().is_none()); + + // In that gap the exam room's teardown stamps the walk-out (or a join + // clears it) — a field-scoped write to the same row. + ExamAttempt::read(attempt.get_id(), &db) + .await + .unwrap() + .expect("attempt exists") + .set_left(Some(Timestamp::now()), &db) + .await + .unwrap(); + + // The submit now writes from its stale snapshot. It owns `finished_at` + // and nothing else: carrying the snapshot's blank `left_at` back over + // the fresh stamp erases the recorded walk-out. + let finished = stale.finish(&db).await.unwrap(); + assert!(finished.get_finished_at().is_some()); + + let after = ExamAttempt::read(attempt.get_id(), &db) + .await + .unwrap() + .expect("attempt still exists"); + assert!( + after.get_left_at().is_some(), + "submitting must not revert a walk-out stamp that raced it" + ); + assert!(after.get_finished_at().is_some(), "the submission stands"); + } + #[tokio::test] async fn stamping_left_never_reverts_a_submission() { let db = init_mem().await.unwrap(); diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 345f8da..6f032aa 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -81,8 +81,7 @@ impl QuestionPoints { } } -/// One option of a choice question: non-blank, at most `MAX_CHOICE_TEXT_LEN` -/// characters. +/// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ChoiceText(String); @@ -97,27 +96,94 @@ impl ChoiceText { } } +/// An option's stable identity — a server-minted ULID, never reused, never +/// taken from client input (it becomes part of an image row's record id and of +/// a URL path, so a client-shaped value would be an injection surface). +/// +/// This id is the whole point of the choice remodel. `correct`, the per-option +/// pictures, and a student's `selected` all name an option *by id*, so +/// reordering the list or deleting an option moves none of them. They used to +/// be parallel arrays keyed by position, where any edit to the list silently +/// re-pointed the others. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ChoiceId(String); + +impl ChoiceId { + fn generate() -> Self { + Self(Ulid::new().to_string()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One option of a choice question: its identity plus its text. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct Choice { + id: ChoiceId, + text: ChoiceText, +} + +impl Choice { + pub fn get_id(&self) -> &ChoiceId { + &self.id + } + + pub fn get_text(&self) -> &ChoiceText { + &self.text + } +} + +/// One option as a client submits it. `id` is the option's *key within this +/// payload* — see [`QuestionSpec::try_new`] for how it is resolved. +#[derive(Debug, Clone)] +pub struct ChoiceInput { + pub id: Option, + pub text: String, +} + /// The kind-dependent fields of a question, validated as a unit — they only /// make sense together. `try_new` is the sole constructor, so a `QuestionSpec` /// in hand always satisfies: /// /// - `text` → no `choices`, no `correct` (the grader judges the answer), -/// - `choice` → 2–10 `choices` plus a `correct` index into them. +/// - `choice` → 2–10 `choices` plus a `correct` naming one of them. #[derive(Debug, Clone)] pub struct QuestionSpec { kind: QuestionKind, - choices: Option>, - correct: Option, + choices: Option>, + correct: Option, } impl QuestionSpec { + /// Validate the kind-dependent fields as a unit and resolve each submitted + /// option to a stable [`ChoiceId`]. + /// + /// **The identity rule, one sentence:** every submitted choice has a key — + /// its `id` if one was sent — and a key that matches one of `existing` *is* + /// that stored option (same id, so its picture survives); any other key + /// names a brand-new option, whose submitted string is used only to resolve + /// `correct` inside this payload and is never stored. + /// + /// `existing` is the question's stored choices (`&[]` on create, so every + /// option there is new and every id is minted here). `correct` names one of + /// the submitted keys. + /// + /// Why an unrecognised id mints instead of failing: `correct` has to be + /// settable on create, where nothing is stored yet, so a client must be + /// able to label an option the server has never seen. The failure mode is + /// benign and visible — a stale id degrades to "this is a new option", which + /// loses that option's picture but can never steal another option's, since + /// it matches no stored id. pub fn try_new( kind: QuestionKind, - choices: Option>, - correct: Option, + choices: Option>, + correct: Option, + existing: &[Choice], ) -> Result { let invalid = |field, reason| ValidationError::Invalid { field, reason }; - let choices = match (kind.as_str(), choices) { + let (choices, correct) = match (kind.as_str(), choices) { ("text", Some(_)) => { return Err(invalid("choices", "only choice questions take choices")); } @@ -125,28 +191,47 @@ impl QuestionSpec { if correct.is_some() { return Err(invalid( "correct", - "only choice questions take a correct index", + "only choice questions take a correct choice", )); } - None + (None, None) } (_, None) => return Err(invalid("choices", "required for a choice question")), - (_, Some(choices)) => { - if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&choices.len()) { + (_, Some(inputs)) => { + if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&inputs.len()) { return Err(invalid("choices", "must list 2 to 10 choices")); } + let mut resolved: Vec = Vec::with_capacity(inputs.len()); + // Submitted key -> the id it resolved to, so `correct` can name + // a fresh option by the label the client gave it. + let mut keys: Vec<(String, ChoiceId)> = Vec::new(); + for input in inputs { + let id = match input.id { + Some(key) => { + if keys.iter().any(|(seen, _)| *seen == key) { + return Err(invalid("choices", "duplicate choice id")); + } + let id = existing + .iter() + .find(|choice| choice.id.as_str() == key) + .map_or_else(ChoiceId::generate, |choice| choice.id.clone()); + keys.push((key, id.clone())); + id + } + None => ChoiceId::generate(), + }; + resolved.push(Choice { + id, + text: ChoiceText::try_new(&input.text)?, + }); + } let Some(correct) = correct else { return Err(invalid("correct", "required for a choice question")); }; - if !(0..choices.len() as i64).contains(&correct) { - return Err(invalid("correct", "must index one of the choices")); - } - Some( - choices - .iter() - .map(|choice| ChoiceText::try_new(choice)) - .collect::, _>>()?, - ) + let Some((_, correct)) = keys.into_iter().find(|(key, _)| *key == correct) else { + return Err(invalid("correct", "must name one of the choices")); + }; + (Some(resolved), Some(correct)) } }; Ok(Self { @@ -156,13 +241,29 @@ impl QuestionSpec { }) } + /// The stored kind-dependent fields as the validated bundle, bypassing + /// [`Self::try_new`] — the fields were written through one, so the + /// invariants already hold. For merge-on-update and for copying a question + /// between the exam and the bank. + pub(crate) fn from_stored( + kind: QuestionKind, + choices: Option>, + correct: Option, + ) -> Self { + Self { + kind, + choices, + correct, + } + } + pub fn get_kind(&self) -> &QuestionKind { &self.kind } /// The validated fields, consumed — for a writer in another module (the /// question bank) that stores the same three columns. - pub fn into_parts(self) -> (QuestionKind, Option>, Option) { + pub fn into_parts(self) -> (QuestionKind, Option>, Option) { (self.kind, self.choices, self.correct) } } @@ -180,10 +281,19 @@ pub struct ExamQuestion { text: QuestionText, kind: QuestionKind, points: QuestionPoints, - choices: Option>, - correct: Option, - /// The bank template this question was instantiated from, if any. - source_bank: Option, + choices: Option>, + correct: Option, + /// The bank template this question was created *from*, if it was inserted + /// out of the bank. Written once, at insert. + #[surreal(default)] + from_bank: Option, + /// The bank template most recently created *by saving this question* into + /// the bank, if any. Written by [`Self::link_banked_as`], repointed by every + /// repeat save. Never set by an insert-from-bank: the two directions are + /// separate columns precisely so "came from the bank" can't be misread as + /// "already saved to the bank". + #[surreal(default)] + banked_as: Option, } impl ExamQuestion { @@ -211,27 +321,26 @@ impl ExamQuestion { self.points } - pub fn get_choices(&self) -> Option<&[ChoiceText]> { + pub fn get_choices(&self) -> Option<&[Choice]> { self.choices.as_deref() } - pub fn get_correct(&self) -> Option { - self.correct + pub fn get_correct(&self) -> Option<&ChoiceId> { + self.correct.as_ref() } - pub fn get_source_bank(&self) -> Option<&BankQuestionId> { - self.source_bank.as_ref() + pub fn get_from_bank(&self) -> Option<&BankQuestionId> { + self.from_bank.as_ref() + } + + pub fn get_banked_as(&self) -> Option<&BankQuestionId> { + self.banked_as.as_ref() } /// The stored kind-dependent fields as the validated bundle (for - /// merge-on-update). Bypasses `try_new`: the fields were written through a - /// `QuestionSpec`, so the invariants already hold. + /// merge-on-update, and for copying into the bank). pub fn spec(&self) -> QuestionSpec { - QuestionSpec { - kind: self.kind.clone(), - choices: self.choices.clone(), - correct: self.correct, - } + QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone()) } pub async fn create( @@ -266,7 +375,7 @@ impl ExamQuestion { text: QuestionText, points: QuestionPoints, spec: QuestionSpec, - source_bank: Option, + from_bank: Option, db: &Database, ) -> Result { let question = ExamQuestion { @@ -278,7 +387,9 @@ impl ExamQuestion { kind: spec.kind, choices: spec.choices, correct: spec.correct, - source_bank, + from_bank, + // An insert never banks anything: only a to-bank save writes this. + banked_as: None, }; let created: Option = db.create(question.id.record()).content(question).await?; @@ -330,29 +441,35 @@ impl ExamQuestion { self.kind = spec.kind; self.choices = spec.choices; self.correct = spec.correct; + // whole-row-save-ok: callers hold EXAM_LOCK.write() across the read and this write let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } - /// Point the question at the bank template it was just saved into - /// (`POST …/questions/{qid}/to-bank`), the mirror of the `source_bank` - /// [`Self::create_from_bank`] writes on the other direction. Overwrites any - /// earlier link: repeat saves mint a new template and the newest one wins. + /// Point the question's `banked_as` at the bank template it was just saved + /// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the + /// `from_bank` [`Self::create_from_bank`] writes, and deliberately a + /// *different* column: a question inserted from the bank has not been saved + /// to it, and one field for both would make the client claim it was. + /// Overwrites any earlier link: repeat saves mint a new template and the + /// newest one wins. /// - /// Field-scoped write, unlike [`Self::update`]: the caller holds only - /// `BANK_LOCK` (which guards the bank, not `exam_question`) and awaits a - /// bank insert plus the whole blob-copy loop between reading this row and - /// linking it, so a concurrent `PATCH` of the question is entirely possible - /// in that window — a whole-row save would silently revert it. - pub async fn link_source_bank( + /// Field-scoped write, unlike [`Self::update`]: the caller awaits a bank + /// insert plus the whole blob-copy loop between reading this row and + /// linking it, so the row it holds is long stale by now — a whole-row save + /// would silently revert whatever landed in that window. (The caller takes + /// `EXAM_LOCK.read()` around this call, which is what keeps + /// [`Self::update`]'s whole-row save from clobbering the link in the other + /// direction; the lease guards the ordering, not the staleness.) + pub async fn link_banked_as( self, - source: BankQuestionId, + template: BankQuestionId, db: &Database, ) -> Result { let mut result = db - .query("UPDATE $id SET source_bank = $bank RETURN AFTER") + .query("UPDATE $id SET banked_as = $bank RETURN AFTER") .bind(("id", self.id.record())) - .bind(("bank", source.record())) + .bind(("bank", template.record())) .await? .check()?; result @@ -389,7 +506,8 @@ impl ExamQuestion { kind: spec.kind, choices: spec.choices, correct: spec.correct, - source_bank: None, + from_bank: None, + banked_as: None, } } } @@ -402,8 +520,23 @@ mod tests { QuestionKind::try_new(value).unwrap() } - fn two_choices() -> Option> { - Some(vec!["yes".into(), "no".into()]) + /// Two options keyed `a` / `b` — the client-side labels a form sends for + /// rows the server has never seen. + fn two_choices() -> Option> { + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "yes".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "no".into(), + }, + ]) + } + + fn spec(choices: Option>, correct: Option<&str>) -> Result { + QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[]) } #[tokio::test] @@ -440,40 +573,244 @@ mod tests { #[tokio::test] async fn spec_invariants_hold() { - // Text questions carry neither choices nor a correct index. - assert!(QuestionSpec::try_new(kind("text"), None, None).is_ok()); - assert!(QuestionSpec::try_new(kind("text"), two_choices(), None).is_err()); - assert!(QuestionSpec::try_new(kind("text"), None, Some(0)).is_err()); - assert!(QuestionSpec::try_new(kind("text"), two_choices(), Some(0)).is_err()); + // Text questions carry neither choices nor a correct choice. + assert!(QuestionSpec::try_new(kind("text"), None, None, &[]).is_ok()); + assert!(QuestionSpec::try_new(kind("text"), two_choices(), None, &[]).is_err()); + assert!(QuestionSpec::try_new(kind("text"), None, Some("a".into()), &[]).is_err()); // Choice questions need both. - assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(0)).is_ok()); - assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(1)).is_ok()); - assert!(QuestionSpec::try_new(kind("choice"), None, None).is_err()); - assert!(QuestionSpec::try_new(kind("choice"), None, Some(0)).is_err()); - assert!(QuestionSpec::try_new(kind("choice"), two_choices(), None).is_err()); + assert!(spec(two_choices(), Some("a")).is_ok()); + assert!(spec(two_choices(), Some("b")).is_ok()); + assert!(spec(None, None).is_err()); + assert!(spec(None, Some("a")).is_err()); + assert!(spec(two_choices(), None).is_err()); } #[tokio::test] - async fn spec_correct_must_index_a_choice() { - assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(-1)).is_err()); - assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(2)).is_err()); + async fn spec_correct_must_name_a_submitted_choice() { + assert!(spec(two_choices(), Some("c")).is_err()); + assert!(spec(two_choices(), Some("")).is_err()); + // An unlabelled option cannot be marked correct — there is nothing to + // name it by until the server's minted id comes back in the response. + let unlabelled = Some(vec![ + ChoiceInput { id: None, text: "yes".into() }, + ChoiceInput { id: None, text: "no".into() }, + ]); + assert!(spec(unlabelled, Some("a")).is_err()); + } + + #[tokio::test] + async fn spec_mints_a_distinct_id_per_choice() { + let built = spec(two_choices(), Some("b")).unwrap(); + let (_, choices, correct) = built.into_parts(); + let choices = choices.unwrap(); + // Client labels never reach storage. + assert!(choices.iter().all(|c| c.get_id().as_str().len() == 26)); + assert_ne!(choices[0].get_id(), choices[1].get_id()); + // `correct` resolved to the *second* option's minted id, by label. + assert_eq!(correct.as_ref(), Some(choices[1].get_id())); + } + + /// The heart of the remodel: an id that matches a stored option keeps that + /// option's identity, so reordering and deleting move nothing. + #[tokio::test] + async fn existing_ids_are_preserved_across_an_edit() { + let stored = spec(two_choices(), Some("a")).unwrap().into_parts().1.unwrap(); + let (first, second) = (stored[0].get_id().clone(), stored[1].get_id().clone()); + + // Resubmit reordered, renaming the first option's text, and marking the + // option that used to be second as correct. + let edited = QuestionSpec::try_new( + kind("choice"), + Some(vec![ + ChoiceInput { id: Some(second.as_str().into()), text: "no".into() }, + ChoiceInput { id: Some(first.as_str().into()), text: "YES".into() }, + ]), + Some(second.as_str().into()), + &stored, + ) + .unwrap(); + let (_, choices, correct) = edited.into_parts(); + let choices = choices.unwrap(); + assert_eq!(choices[0].get_id(), &second); + assert_eq!(choices[1].get_id(), &first); + assert_eq!(choices[1].get_text().as_str(), "YES"); + assert_eq!(correct.as_ref(), Some(&second)); + } + + #[tokio::test] + async fn spec_rejects_a_duplicate_choice_id() { + let dupes = Some(vec![ + ChoiceInput { id: Some("a".into()), text: "yes".into() }, + ChoiceInput { id: Some("a".into()), text: "no".into() }, + ]); + assert!(spec(dupes, Some("a")).is_err()); } #[tokio::test] async fn spec_choice_count_is_bounded() { - let n = |count: usize| Some(vec!["option".to_string(); count]); - assert!(QuestionSpec::try_new(kind("choice"), n(1), Some(0)).is_err()); - assert!(QuestionSpec::try_new(kind("choice"), n(2), Some(0)).is_ok()); - assert!(QuestionSpec::try_new(kind("choice"), n(10), Some(0)).is_ok()); - assert!(QuestionSpec::try_new(kind("choice"), n(11), Some(0)).is_err()); + let n = |count: usize| { + Some( + (0..count) + .map(|i| ChoiceInput { id: Some(i.to_string()), text: "option".into() }) + .collect::>(), + ) + }; + assert!(spec(n(1), Some("0")).is_err()); + assert!(spec(n(2), Some("0")).is_ok()); + assert!(spec(n(10), Some("0")).is_ok()); + assert!(spec(n(11), Some("0")).is_err()); + } + + /// Generated coverage of the §2-REVISED identity rules. The example tests + /// above each pin one hand-picked payload; these generate arbitrary stored + /// sets and arbitrary submissions over them (matching keys, stale keys, + /// `null` ids, duplicates, blank and oversized texts) and assert the rules + /// as one predicate, because every bug this remodel exists to kill lived in + /// a *relation* between a submitted option and a stored one. + mod props { + use super::*; + use proptest::prelude::*; + + /// A stored question's options, built the only way they can be: through + /// `try_new` on create, so the ids are real minted ULIDs. + fn stored_set(n: usize) -> Vec { + let inputs = (0..n) + .map(|i| ChoiceInput { id: Some(format!("s{i}")), text: format!("stored {i}") }) + .collect(); + QuestionSpec::try_new(kind("choice"), Some(inputs), Some("s0".into()), &[]) + .unwrap() + .into_parts() + .1 + .unwrap() + } + + /// How a submitted option names itself: as a stored option, as some + /// other string (a client-minted label, a stale id, junk), or not at all. + #[derive(Debug, Clone)] + enum Key { + Stored(usize), + Other(String), + Null, + } + + fn key() -> impl Strategy { + prop_oneof![ + 4 => (0usize..10).prop_map(Key::Stored), + 3 => prop_oneof![ + Just(String::new()), + Just("new:1".to_string()), + "[a-z0-9]{1,5}", + Just("01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string()), + ].prop_map(Key::Other), + 1 => Just(Key::Null), + ] + } + + fn text() -> impl Strategy { + prop_oneof![ + 6 => "[a-z ]{1,6}", + 1 => Just(String::new()), + 1 => Just(" ".to_string()), + 1 => Just("x".repeat(501)), + ] + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(400))] + + #[test] + fn a_matching_key_is_that_choice_and_nothing_else_can_be( + stored_n in 2usize..=10, + submitted in prop::collection::vec((key(), text()), 0..=12), + correct in prop::option::of(key()), + ) { + let stored = stored_set(stored_n); + let name = |k: &Key| match k { + Key::Stored(i) => Some(stored[i % stored_n].id.as_str().to_string()), + Key::Other(s) => Some(s.clone()), + Key::Null => None, + }; + let keys: Vec> = submitted.iter().map(|(k, _)| name(k)).collect(); + let texts: Vec = submitted.iter().map(|(_, t)| t.clone()).collect(); + let correct = correct.as_ref().map(|k| name(k).unwrap_or_default()); + + let inputs: Vec = keys + .iter() + .zip(&texts) + .map(|(id, text)| ChoiceInput { id: id.clone(), text: text.clone() }) + .collect(); + let built = QuestionSpec::try_new( + kind("choice"), + Some(inputs), + correct.clone(), + &stored, + ); + + // Every way a payload can be rejected, stated independently of + // the implementation's order of checks. + let bad_len = !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&submitted.len()); + let mut seen: Vec<&String> = Vec::new(); + let mut dup = false; + for k in keys.iter().flatten() { + if seen.contains(&k) { dup = true; break; } + seen.push(k); + } + let bad_text = texts.iter().any(|t| t.trim().is_empty() || t.chars().count() > MAX_CHOICE_TEXT_LEN); + // `correct` must name a *submitted key*; an option sent with + // `id: null` has no key, so it is unnameable. + let named = correct.as_ref().is_some_and(|c| keys.iter().flatten().any(|k| k == c)); + + if bad_len || dup || bad_text || !named { + prop_assert!(built.is_err()); + return Ok(()); + } + + let (_, choices, resolved) = built.unwrap().into_parts(); + let choices = choices.unwrap(); + prop_assert_eq!(choices.len(), submitted.len()); + + let stored_ids: Vec<&str> = stored.iter().map(|c| c.id.as_str()).collect(); + for (i, choice) in choices.iter().enumerate() { + // Order and text are passed through untouched. + prop_assert_eq!(choice.text.as_str(), texts[i].as_str()); + match keys[i].as_deref().and_then(|k| stored.iter().find(|c| c.id.as_str() == k)) { + // A key matching a stored choice IS that choice: same + // id, so its picture stays with it. + Some(existing) => prop_assert_eq!(&choice.id, &existing.id), + // Any other key (stale, junk, absent) is a NEW option: + // freshly minted, so it can never take over a stored + // option's identity or its picture. + None => { + prop_assert_eq!(choice.id.as_str().len(), 26); + prop_assert!(!stored_ids.contains(&choice.id.as_str())); + } + } + } + // No id is invented twice. + let mut out: Vec<&str> = choices.iter().map(|c| c.id.as_str()).collect(); + out.sort_unstable(); + let unique = out.len(); + out.dedup(); + prop_assert_eq!(out.len(), unique); + + // `correct` resolves to the option that carried that key. + let correct = correct.unwrap(); + let at = keys.iter().position(|k| k.as_ref() == Some(&correct)).unwrap(); + prop_assert_eq!(resolved.as_ref(), Some(&choices[at].id)); + } + } } #[tokio::test] async fn spec_rejects_blank_or_oversized_choices() { - let blank = Some(vec!["yes".to_string(), " ".to_string()]); - assert!(QuestionSpec::try_new(kind("choice"), blank, Some(0)).is_err()); - let oversized = Some(vec!["yes".to_string(), "x".repeat(501)]); - assert!(QuestionSpec::try_new(kind("choice"), oversized, Some(0)).is_err()); + let with = |text: String| { + Some(vec![ + ChoiceInput { id: Some("a".into()), text: "yes".into() }, + ChoiceInput { id: Some("b".into()), text }, + ]) + }; + assert!(spec(with(" ".into()), Some("a")).is_err()); + assert!(spec(with("x".repeat(501)), Some("a")).is_err()); } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index ea4d4ff..fa3eb27 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -24,6 +24,7 @@ pub mod homework_file; pub mod homework_result; pub mod homework_submission; pub mod message; +pub mod monotonic_id; pub mod note; pub mod note_file; pub mod parent_link; @@ -40,6 +41,7 @@ pub mod settings; pub mod solution; pub mod subject; pub mod term; +pub mod text_fold; pub mod timestamp; pub mod user; pub mod work_entry; diff --git a/src/domain/monotonic_id.rs b/src/domain/monotonic_id.rs new file mode 100644 index 0000000..8274ccf --- /dev/null +++ b/src/domain/monotonic_id.rs @@ -0,0 +1,47 @@ +//! Ids that sort in write order, for tables whose listings lean on `id` to +//! break ties (or to mean "newest first" outright). +//! +//! `Ulid::new()` fills the low 80 bits at random, so two ids minted in the +//! *same millisecond* sort arbitrarily against each other — millisecond- +//! accurate ordering only. That is not enough when a burst of writes lands +//! inside one tick (a recurring appointment publish expanding a series, a +//! teacher saving templates back to back, a test creating rows in a loop): +//! `ORDER BY id DESC` then scrambles them. [`next_ulid`] mints from one +//! process-wide [`Generator`], which keeps ids strictly increasing within a +//! millisecond by incrementing the random part instead of redrawing it. + +use std::sync::{LazyLock, Mutex}; + +use ulid::{Generator, Ulid}; + +static IDS: LazyLock> = LazyLock::new(|| Mutex::new(Generator::new())); + +/// The next id in write order. Process-wide: two processes writing the same +/// table still only get millisecond accuracy, which is what a distributed id +/// can promise anyway. +pub fn next_ulid() -> Ulid { + let mut ids = IDS.lock().expect("monotonic id generator poisoned"); + // The only error is exhausting the random bits *within* one millisecond + // (2^80 ids deep); it clears itself as the clock ticks, so retry rather + // than fall back to a random id and silently reintroduce the defect. + loop { + if let Ok(ulid) = ids.generate() { + break ulid; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The defect this module exists for: ids minted back to back (well inside + /// one millisecond) must still sort in mint order. + #[test] + fn ids_sort_in_mint_order_within_a_millisecond() { + let ids: Vec = (0..1000).map(|_| next_ulid().to_string()).collect(); + let mut sorted = ids.clone(); + sorted.sort(); + assert_eq!(ids, sorted); + } +} diff --git a/src/domain/question_image.rs b/src/domain/question_image.rs index 921697b..0f42e26 100644 --- a/src/domain/question_image.rs +++ b/src/domain/question_image.rs @@ -1,6 +1,6 @@ //! An image pinned to an exam question — the question's own illustration //! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture -//! (`slot = i`, choice questions only). The row carries metadata; the bytes +//! (`slot` = that choice's stable id, choice questions only). The row carries metadata; the bytes //! live on disk under [`crate::config::Config::files_path`] in a file named by //! `file` — a fresh server-generated ULID per upload, so no user input ever //! shapes a disk path and a replace never overwrites bytes in place. The row @@ -15,7 +15,7 @@ use ulid::Ulid; use crate::database::{Database, QUESTION_IMAGE_TABLE}; use crate::domain::course::CourseId; use crate::domain::exam::ExamId; -use crate::domain::exam_question::ExamQuestionId; +use crate::domain::exam_question::{ChoiceId, ExamQuestionId}; use crate::domain::note_file::FileContentType; use crate::error::AppError; @@ -24,12 +24,15 @@ pub struct QuestionImageId(RecordId); impl QuestionImageId { /// The one id a (question, slot) pair can have: `{qid}_q` for the - /// question's own image, `{qid}_{i}` for choice `i` — uniqueness per slot - /// needs no index this way. - pub fn for_slot(question: &ExamQuestionId, slot: Option) -> Self { + /// question's own image, `{qid}_{choice id}` for one option's picture — + /// uniqueness per slot needs no index this way. Keyed by the option's + /// *stable id*, so reordering the choice list moves no picture. + pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self { + // `_` is not in Crockford base32 and a ULID is never `"q"`, so + // `{qid}_{cid}` and `{qid}_q` can never collide. let suffix = match slot { - None => "q".to_string(), - Some(index) => index.to_string(), + None => "q", + Some(id) => id.as_str(), }; Self(RecordId::new( QUESTION_IMAGE_TABLE, @@ -54,8 +57,9 @@ pub struct QuestionImage { id: QuestionImageId, exam: ExamId, question: ExamQuestionId, - /// `NONE` = the question's illustration; `i` = the picture of choice `i`. - slot: Option, + /// `NONE` = the question's illustration; otherwise the id of the option + /// this picture belongs to. + slot: Option, /// The blob's on-disk name — a fresh ULID every upload. file: String, content_type: FileContentType, @@ -69,7 +73,7 @@ impl QuestionImage { pub fn new( exam: &ExamId, question: &ExamQuestionId, - slot: Option, + slot: Option<&ChoiceId>, content_type: FileContentType, size: i64, ) -> Self { @@ -77,7 +81,7 @@ impl QuestionImage { id: QuestionImageId::for_slot(question, slot), exam: exam.clone(), question: question.clone(), - slot, + slot: slot.cloned(), file: Ulid::new().to_string(), content_type, size, @@ -88,8 +92,8 @@ impl QuestionImage { &self.question } - pub fn get_slot(&self) -> Option { - self.slot + pub fn get_slot(&self) -> Option<&ChoiceId> { + self.slot.as_ref() } pub fn get_file(&self) -> &str { @@ -107,13 +111,14 @@ impl QuestionImage { /// Create or replace the slot's image row — the deterministic id makes /// this the whole "one image per slot" story. pub async fn upsert(self, db: &Database) -> Result { + // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic let written: Option = db.upsert(self.id.record()).content(self).await?; written.ok_or_else(|| AppError::Internal("failed to store question image".into())) } pub async fn read_slot( question: &ExamQuestionId, - slot: Option, + slot: Option<&ChoiceId>, db: &Database, ) -> Result, AppError> { Ok(db @@ -146,17 +151,28 @@ impl QuestionImage { Ok(result.take::>(0)?) } - /// Drop every *choice* image of the question (the question's own - /// illustration stays), returning the removed rows so the caller can take - /// their blobs off disk. Runs when a PATCH replaces the choice list — the - /// old pictures belong to the old options. - pub async fn delete_choices_for( + /// Drop the option pictures whose choice is gone — every choice image of + /// the question whose `slot` is *not* in `keep` (the question's own + /// illustration always stays), returning the removed rows so the caller can + /// take their blobs off disk. + /// + /// This is what makes an edit non-destructive: a PATCH that reorders, + /// renames, or drops options passes the surviving choice ids as `keep`, so + /// only the pictures of genuinely removed options go. `keep = &[]` (a text + /// question, or an all-new choice list) still clears the lot. + pub async fn delete_choices_not_in( question: &ExamQuestionId, + keep: &[ChoiceId], db: &Database, ) -> Result, AppError> { + let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); let mut result = db - .query("DELETE question_image WHERE question = $q AND slot != NONE RETURN BEFORE") + .query( + "DELETE question_image \ + WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", + ) .bind(("q", question.record())) + .bind(("keep", keep)) .await? .check()?; Ok(result.take::>(0)?) @@ -188,16 +204,40 @@ impl QuestionImage { #[cfg(test)] mod tests { use super::*; + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; fn png() -> FileContentType { FileContentType::try_new("image/png").unwrap() } + /// Three minted choice ids to slot pictures against. + fn choice_ids() -> Vec { + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() }) + .collect(), + ), + Some("a".into()), + &[], + ) + .unwrap() + .into_parts() + .1 + .unwrap() + .iter() + .map(|c| c.get_id().clone()) + .collect() + } + #[tokio::test] async fn upsert_replaces_per_slot() { let db = crate::database::init_mem().await.unwrap(); let exam = ExamId::generate(); let question = ExamQuestionId::generate(); + let ids = choice_ids(); let first = QuestionImage::new(&exam, &question, None, png(), 3) .upsert(&db) @@ -215,8 +255,8 @@ mod tests { assert_eq!(rows.len(), 1); assert_eq!(rows[0].get_size(), 5); - // A choice slot is its own row. - QuestionImage::new(&exam, &question, Some(0), png(), 7) + // A choice slot is its own row, keyed by the option's id. + QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7) .upsert(&db) .await .unwrap(); @@ -227,32 +267,74 @@ mod tests { .len(), 2 ); - let choice = QuestionImage::read_slot(&question, Some(0), &db) + let choice = QuestionImage::read_slot(&question, Some(&ids[0]), &db) .await .unwrap() .unwrap(); - assert_eq!(choice.get_slot(), Some(0)); + assert_eq!(choice.get_slot(), Some(&ids[0])); assert!( - QuestionImage::read_slot(&question, Some(1), &db) + QuestionImage::read_slot(&question, Some(&ids[1]), &db) .await .unwrap() .is_none() ); } + /// The behaviour the whole remodel exists for: an edit that keeps some + /// options keeps exactly their pictures, and drops only the removed one's. #[tokio::test] - async fn choice_wipe_spares_the_question_image() { + async fn only_the_dropped_options_lose_their_pictures() { let db = crate::database::init_mem().await.unwrap(); let exam = ExamId::generate(); let question = ExamQuestionId::generate(); - for slot in [None, Some(0), Some(1)] { - QuestionImage::new(&exam, &question, slot, png(), 1) + let ids = choice_ids(); + QuestionImage::new(&exam, &question, None, png(), 1) + .upsert(&db) + .await + .unwrap(); + for id in &ids { + QuestionImage::new(&exam, &question, Some(id), png(), 1) + .upsert(&db) + .await + .unwrap(); + } + + // Keep the first and last option (reordered — order is irrelevant now). + let keep = vec![ids[2].clone(), ids[0].clone()]; + let dropped = QuestionImage::delete_choices_not_in(&question, &keep, &db) + .await + .unwrap(); + assert_eq!(dropped.len(), 1); + assert_eq!(dropped[0].get_slot(), Some(&ids[1])); + + let left = QuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + // The question illustration plus the two surviving option pictures. + assert_eq!(left.len(), 3); + assert!(QuestionImage::read_slot(&question, Some(&ids[0]), &db).await.unwrap().is_some()); + assert!(QuestionImage::read_slot(&question, Some(&ids[2]), &db).await.unwrap().is_some()); + assert!(QuestionImage::read_slot(&question, None, &db).await.unwrap().is_some()); + } + + #[tokio::test] + async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() { + let db = crate::database::init_mem().await.unwrap(); + let exam = ExamId::generate(); + let question = ExamQuestionId::generate(); + let ids = choice_ids(); + QuestionImage::new(&exam, &question, None, png(), 1) + .upsert(&db) + .await + .unwrap(); + for id in &ids[..2] { + QuestionImage::new(&exam, &question, Some(id), png(), 1) .upsert(&db) .await .unwrap(); } - let dropped = QuestionImage::delete_choices_for(&question, &db) + let dropped = QuestionImage::delete_choices_not_in(&question, &[], &db) .await .unwrap(); assert_eq!(dropped.len(), 2); diff --git a/src/domain/subject.rs b/src/domain/subject.rs index 8081935..f3c8f8e 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -108,6 +108,21 @@ impl Subject { Ok(db.select(id.record()).await?) } + /// Several subjects in one query — the bulk half of a list endpoint that + /// names each row's subject (a read per row would be an N+1). + pub async fn list_by_ids(ids: &[&SubjectId], db: &Database) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(|id| id.record()).collect(); + let mut result = db + .query("SELECT * FROM subject WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + /// The course's subjects in curriculum order (ULID ids sort by creation). pub async fn list_for_course( course: &CourseId, @@ -127,14 +142,45 @@ impl Subject { description: SubjectDescription, db: &Database, ) -> Result { - self.name = name; - self.description = description; - let updated: Option = db.update(self.id.record()).content(self).await?; - updated.ok_or(AppError::NotFound) - } - + // Field-scoped: the handler holds no lock across its read and this + // write, so a whole-row save would revert a concurrent edit of the + // other field. + let mut result = db + .query("UPDATE $id SET name = $name, description = $description RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("name", name)) + .bind(("description", description)) + .await? + .check()?; + result.take::>(0)?.into_iter().next().ok_or(AppError::NotFound) + } + + /// Delete the subject and clear it off every bank template that carried it + /// as origin metadata — one transaction, so a template can't be left + /// pointing at a subject that no longer exists. + /// + /// Exam questions and homework are *not* cascaded: their `subject` is a + /// required field the web layer refuses to orphan (both still block the + /// delete with a 409). The bank's is optional metadata, and blocking on it + /// was a dead end — only the template's owner may re-tag it, so a manager + /// could never clear their own 409, and a private template raising it + /// leaked its existence. pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; + let mut result = db + .query( + "BEGIN TRANSACTION; + UPDATE bank_question SET subject = NONE WHERE subject = $sub; + LET $before = (DELETE $sub RETURN BEFORE); + RETURN $before; + COMMIT TRANSACTION;", + ) + .bind(("sub", self.id.record())) + .await? + .check()?; + // Read through the trailing `RETURN`, not a counted slot — see + // [`crate::domain::exam::Exam::delete`]. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = result.take::>(slot)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/text_fold.rs b/src/domain/text_fold.rs new file mode 100644 index 0000000..2b957b2 --- /dev/null +++ b/src/domain/text_fold.rs @@ -0,0 +1,81 @@ +//! Case- and diacritic-insensitive folding for search, shared by the needle +//! (Rust side) and the column (SurrealQL side) so the two can never disagree. +//! +//! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both +//! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307 +//! (combining dot above), so plain `string::lowercase(text) CONTAINS $q` never +//! matched `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that +//! leftover dot and maps the Turkish letters onto their ASCII base, which also +//! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`, +//! `ıgdır` ↔ `Iğdır`). + +/// Replacements applied *after* lowercasing, in order. One table, two +/// consumers ([`fold`] and [`fold_sql`]): the needle and the column are folded +/// by the same rules by construction, which is the whole point. +const REPLACEMENTS: &[(&str, &str)] = &[ + ("\u{307}", ""), // combining dot above, left behind by İ → i̇ + ("ı", "i"), + ("ş", "s"), + ("ğ", "g"), + ("ç", "c"), + ("ö", "o"), + ("ü", "u"), + ("â", "a"), + ("î", "i"), + ("û", "u"), +]; + +/// Fold a search needle (or any Rust-side string) for comparison. +pub fn fold(text: &str) -> String { + let mut folded = text.to_lowercase(); + for (from, to) in REPLACEMENTS { + folded = folded.replace(from, to); + } + folded +} + +/// The same folding as a SurrealQL expression over `column`, for use inside a +/// `WHERE`. `column` is always a literal field name we wrote — never user +/// input. +pub fn fold_sql(column: &str) -> String { + let mut expr = format!("string::lowercase({column})"); + for (from, to) in REPLACEMENTS { + expr = format!("string::replace({expr}, '{from}', '{to}')"); + } + expr +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn folds_turkish_casing_both_ways() { + assert_eq!(fold("İSTANBUL"), "istanbul"); + assert_eq!(fold("istanbul"), "istanbul"); + assert_eq!(fold("İstanbul"), "istanbul"); + assert_eq!(fold("ISTANBUL"), "istanbul"); + assert_eq!(fold("ıstanbul"), "istanbul"); + assert_eq!(fold("Iğdır"), "igdir"); + assert_eq!(fold("ÇÖZÜM"), "cozum"); + assert_eq!(fold("Şekil"), "sekil"); + } + + /// The SQL side must fold a literal exactly like the Rust side does, or the + /// needle and the column disagree again. + #[tokio::test] + async fn sql_folding_matches_rust_folding() { + let db = crate::database::init_mem().await.unwrap(); + for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] { + let mut result = db + .query(format!("RETURN {};", fold_sql("$text"))) + .bind(("text", sample.to_string())) + .await + .unwrap() + .check() + .unwrap(); + let got = result.take::>(0).unwrap().unwrap(); + assert_eq!(got, fold(sample), "sql fold disagrees for {sample}"); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index a30a928..4f9ec6e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,7 +53,7 @@ use crate::state::AppState; (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (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 = "bank", description = "The school-wide question bank: a shared library of reusable question templates. Any teacher+ reads the whole bank (`GET /bank-questions`, optional `?subject=` origin filter) and instantiates any template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Reads and instantiate are school-wide, but editing or deleting a template needs ownership (its owner, or an admin — 403 otherwise); templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and school-wide to read"), + (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (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 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"), diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index 6d5734f..8022a80 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -1,8 +1,12 @@ -//! The school-wide question bank: a shared library of reusable question -//! templates. Any teacher+ reads the whole bank and instantiates any template -//! into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, in -//! `web/exams`), but only a template's owner (admins aside) may edit or delete -//! it. A template carries the same content an exam question does — text, +//! The question bank: a library of reusable question templates. A template is +//! born `private` — visible to its owner (and admins) alone — and becomes +//! school-wide only when its owner PATCHes `visibility` to `school`, because a +//! template carries `correct`, the answer key, and saving a live exam's +//! question to the bank must not broadcast it. Teacher+ read and instantiate +//! every template they can see (`POST /exams/{id}/questions/from-bank/{bid}`, +//! in `web/exams`); a template they cannot see is a 404 on every route, never a +//! 403, since a 403 would confirm it exists. Only the owner (admins aside) may +//! edit or delete one. A template carries the same content an exam question does — text, //! points, a `choice`/`text` spec, an optional illustration, and per-option //! pictures — minus any exam tie: its `subject` is origin metadata only (the //! same-course rule is checked at instantiate time against the target exam's @@ -21,29 +25,34 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; -use crate::domain::bank_question::{BankQuestion, BankQuestionId}; +use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; -use crate::domain::exam_question::{QuestionKind, QuestionPoints, QuestionSpec, QuestionText}; +use crate::domain::exam_question::{ + Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, +}; use crate::domain::note_file::FileContentType; use crate::domain::role::Role; use crate::domain::settings::Settings; -use crate::domain::subject::SubjectId; +use crate::domain::subject::{Subject, SubjectId}; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use super::dto::person_map; use super::subjects::subject_must_exist; +use super::exams::ChoiceResponse; use super::{ - Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type, - paginate, read_upload, remove_blob, serve_inline_blob, set_or_clear, + ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type, + read_upload, remove_blob, serve_inline_blob, set_or_clear, }; /// Serializes bank writes that adopt a `subject` against a concurrent subject /// delete. Bank create/update take the reader lease across their -/// subject-exists check and the insert; the subject delete-guard takes the -/// writer lease across its `any_for_subject` check and the delete, so a -/// template can't land on a subject that vanished mid-flight — the bank twin -/// of the [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards. +/// subject-exists check and the write; the subject delete takes the writer +/// lease across the cascade that clears `subject` off every template, so a +/// template can't land on a subject that vanished mid-flight (it would outlive +/// the sweep) — the bank twin of the +/// [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards. /// Save-to-bank (`question_to_bank`) takes the same reader lease across its /// question read and insert: the source question can be re-tagged/deleted, so /// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in @@ -91,16 +100,19 @@ struct CreateBankQuestion { #[schema(example = 10)] points: i64, /// The options of a `choice` question (2–10 of them); omit for `text`. - choices: Option>, - /// Zero-based index of the right option; required for `choice`, absent - /// for `text`. - #[schema(example = 1)] - correct: Option, + /// Each carries an `id` naming it within this payload — the server mints + /// the stored ids and returns them. + choices: Option>, + /// The `id` of the right option, as sent in `choices`; required for + /// `choice`, absent for `text`. + #[schema(example = "b")] + correct: Option, } #[derive(Deserialize, ToSchema)] struct UpdateBankQuestion { - /// Re-tag the template's origin subject. Omit to keep the current one. + /// Re-tag the template's origin subject. Omit to keep the current one + /// (which is `null` if that subject has since been deleted). subject_id: Option, text: Option, points: Option, @@ -109,15 +121,22 @@ struct UpdateBankQuestion { /// when moving to `text`. kind: Option, /// Omit to keep the stored options; send `null` to drop them (text - /// questions only). Replacing or clearing the list also drops every option - /// picture — the old images belong to the old options. + /// questions only). Send each option back with the `id` it was returned + /// with to keep it — its picture rides along. Only options whose id is + /// absent from the new list lose their picture. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>)] - choices: Option>>, - /// Omit to keep; `null` to clear (text questions only). + #[schema(value_type = Option>)] + choices: Option>>, + /// The `id` of the right option. Omit to keep; `null` to clear (text + /// questions only). #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - correct: Option>, + #[schema(value_type = Option)] + correct: Option>, + /// `private` (owner + admins only) or `school` (every teacher). Publishing + /// hands the template's `correct` answer key — and its pictures — to every + /// teacher in the school, so it is only ever an explicit choice. + #[schema(example = "school")] + visibility: Option, } /// Filters for the bank list. @@ -129,6 +148,16 @@ struct BankQuestionFilter { /// Narrow to templates owned by this user (a user id, or `me` for the /// caller). Omit for every owner's templates. owner: Option, + /// Case-insensitive fragment of the question text. Blank or omitted + /// matches every template. + #[param(example = "photosynthesis")] + q: Option, + /// `private` or `school`. Narrows what the caller can already see, never + /// widens it: `private` is effectively "my drafts" (nobody else's private + /// template is ever visible), `school` is the published library. Omit for + /// both. + #[param(example = "school")] + visibility: Option, } /// A bank template as its readers see it — `correct` included (teacher+ only, @@ -140,15 +169,18 @@ pub(crate) struct BankQuestionResponse { /// The teacher who owns the template (only they, or an admin, may edit it). owner: String, /// The origin subject (metadata only — not enforced against a course). - subject: String, + /// `null` once that subject was deleted: deleting a subject clears the + /// bank's copy of it rather than being blocked by it. + subject: Option, text: String, /// `choice` or `text`. #[schema(example = "choice")] kind: String, points: i64, - choices: Option>, - /// Zero-based index of the right option (`choice` templates only). - correct: Option, + /// The options with their stable ids (`choice` templates only). + choices: Option>, + /// The id of the right option (`choice` templates only). + correct: Option, /// The template's illustration, if one was uploaded (any kind). image: Option, /// Per-option pictures, aligned with `choices` (`choice` templates only). @@ -156,59 +188,122 @@ pub(crate) struct BankQuestionResponse { /// The exam this template was saved off, if any (a direct-authored /// template has none). source_exam: Option, + /// `private` (owner + admins only) or `school` (every teacher). New + /// templates start `private`. + #[schema(example = "private")] + visibility: String, /// When the template was saved, UTC unix-milliseconds. created_at: i64, + /// The origin subject's name, resolved for display. Empty when the subject + /// is gone (deleted, so `subject` is `null` too) — and on the + /// single-template endpoints, which don't join. + #[schema(example = "Limits and continuity")] + subject_name: String, + /// The owner's display name (full name, else username). Empty when the user + /// is gone — and on the single-template endpoints, which don't join. + #[schema(example = "Ada Lovelace")] + owner_name: String, + /// How many exam questions were created from this template — the + /// divergence surface, since each of them is a detached copy that a later + /// edit here does *not* reach. `0` for an unused template, and `0` on the + /// single-template endpoints, which don't join (list-only, exactly like + /// `subject_name`/`owner_name`). + #[schema(example = 3)] + used_count: i64, } impl BankQuestionResponse { + /// The names and the usage tally are joined on by the list endpoint alone + /// (see [`Self::with_names`]); every other endpoint returns one template + /// and leaves them empty/zero. + pub(crate) fn with_names( + question: &BankQuestion, + images: &[BankQuestionImage], + subject_name: String, + owner_name: String, + used_count: i64, + ) -> Self { + Self { + subject_name, + owner_name, + used_count, + ..Self::new(question, images) + } + } + pub(crate) fn new(question: &BankQuestion, images: &[BankQuestionImage]) -> Self { Self { + subject_name: String::new(), + owner_name: String::new(), + used_count: 0, id: question.get_id().key().to_string(), owner: question.get_owner().key().to_string(), - subject: question.get_subject().key().to_string(), + subject: question.get_subject().map(|s| s.key().to_string()), text: question.get_text().as_str().to_string(), kind: question.get_kind().as_str().to_string(), points: question.get_points().as_i64(), - choices: question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), - correct: question.get_correct(), + choices: ChoiceResponse::list(question.get_choices()), + correct: question.get_correct().map(|id| id.as_str().to_string()), image: bank_image_meta(images, None), choice_images: bank_choice_image_metas(question, images), source_exam: question.get_source_exam().map(|e| e.key().to_string()), + visibility: question.get_visibility().as_str().to_string(), created_at: question.get_created_at().as_millis(), } } } +/// The template's option named by `choice_id` — a 400 for a text template or an +/// id the template doesn't have, mirroring `exams::choice_slot`. +fn bank_choice_slot(question: &BankQuestion, choice_id: &str) -> Result { + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "only choice questions take option pictures", + })); + }; + choices + .iter() + .find(|choice| choice.get_id().as_str() == choice_id) + .map(|choice| choice.get_id().clone()) + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "must name one of the choices", + })) +} + /// The template's slot out of its image rows. -fn bank_image_meta(images: &[BankQuestionImage], slot: Option) -> Option { +fn bank_image_meta(images: &[BankQuestionImage], slot: Option<&ChoiceId>) -> Option { images .iter() .find(|image| image.get_slot() == slot) .map(BankImageMeta::new) } -/// The per-choice metas, aligned index-for-index with `choices` (`None` +/// The per-choice metas, aligned position-for-position with `choices` (`None` /// entries = that option has no picture); `None` whole for text templates. +/// A response-only projection rebuilt from the current list — the pictures +/// themselves are stored against choice ids. fn bank_choice_image_metas( question: &BankQuestion, images: &[BankQuestionImage], ) -> Option>> { question.get_choices().map(|choices| { - (0..choices.len() as i64) - .map(|index| bank_image_meta(images, Some(index))) + choices + .iter() + .map(|choice| bank_image_meta(images, Some(choice.get_id()))) .collect() }) } -/// Every bank image row bucketed by template key — one query feeding a whole -/// template list (avoids an image query per row). +/// The image rows of `questions` bucketed by template key — one query feeding +/// a whole page (neither an image query per row, nor the school's every image). async fn bank_images_by_question( + questions: &[&BankQuestionId], db: &crate::database::Database, ) -> Result>, AppError> { let mut buckets: HashMap> = HashMap::new(); - for image in BankQuestionImage::list_all(db).await? { + for image in BankQuestionImage::list_for_questions(questions, db).await? { buckets .entry(image.get_bank_question().key().to_string()) .or_default() @@ -242,8 +337,23 @@ async fn question_or_404(st: &AppState, bid: &str) -> Result bool { + question.get_visibility().is_school() + || question.get_owner() == user.get_id() + || user.get_role().at_least(Role::Admin) +} + +/// Reads are gated by [`can_see`], and a mutation additionally needs ownership: +/// the caller owns the template, or is an admin. Everyone else gets a 403 — +/// but only for a template they can see; an invisible one is a 404 long before +/// this runs, so a 403 never doubles as proof the template exists. fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> { if question.get_owner() == user.get_id() || user.get_role().at_least(Role::Admin) { return Ok(()); @@ -253,10 +363,25 @@ fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> { )) } +/// The template, provided the caller may see it — the shared front half of +/// every read. A template the caller may not see is a **404, not a 403**: a +/// 403 would confirm that someone else's template exists under that id. +pub(crate) async fn visible_question( + st: &AppState, + user: &User, + bid: &str, +) -> Result { + let question = question_or_404(st, bid).await?; + if !can_see(&question, user) { + return Err(AppError::NotFound); + } + Ok(question) +} + /// The template, provided the caller may edit it — the shared front half of /// every owner-gated write (PATCH, delete, image writes). async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result { - let question = question_or_404(st, bid).await?; + let question = visible_question(st, user, bid).await?; ensure_owner(&question, user)?; Ok(question) } @@ -267,7 +392,7 @@ async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result, + slot: Option<&ChoiceId>, content_type: FileContentType, data: &[u8], ) -> Result { @@ -321,7 +446,14 @@ async fn create_question( let subject = subject_must_exist(&req.subject_id, &st.db).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; - let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; + // Nothing stored to match against on create: every option is new and every + // id is minted here. + let spec = QuestionSpec::try_new( + QuestionKind::try_new(&req.kind)?, + ChoiceBody::into_inputs(req.choices), + req.correct, + &[], + )?; let question = BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?; Ok(( @@ -330,10 +462,17 @@ async fn create_question( )) } -/// The whole bank, school-wide, in creation order — every teacher+ reads every -/// template. `?subject=` narrows to one origin subject; `?owner=` to one owner -/// (a user id, or `me` for the caller). Paged via `?limit=&offset=` (omit -/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope. +/// The bank the caller may see — their own templates plus the ones published +/// to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner +/// (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of +/// the question text; `?visibility=private|school` to one shelf — it narrows +/// what the caller may already see and never widens it, so `private` is "my +/// drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of +/// them); returns a `{items, total, limit, offset}` envelope, where `total` +/// counts every match under the same filters, not just this page. Each item +/// carries the resolved `subject_name`/`owner_name` so a client needn't look +/// them up per row, plus `used_count` — how many exam questions were copied out +/// of that template (one grouped query for the page, not one per row). #[utoipa::path( get, path = "/", @@ -342,7 +481,7 @@ async fn create_question( params(BankQuestionFilter, PageParams), responses( (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page), - (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 400, description = "Invalid limit, offset, or visibility", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), ), @@ -354,35 +493,83 @@ async fn list_questions( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let mut questions = BankQuestion::list(&st.db).await?; - if let Some(ref subject) = filter.subject { - let subject = SubjectId::from_key(subject); - questions.retain(|question| question.get_subject() == &subject); - } - if let Some(ref owner) = filter.owner { - let owner = if owner == "me" { - user.get_id().clone() - } else { - UserId::from_key(owner) - }; - questions.retain(|question| question.get_owner() == &owner); - } - let total = questions.len() as i64; - // One image query for the whole bank, bucketed by template — no per-row - // fetch on the page. - let buckets = bank_images_by_question(&st.db).await?; + let subject = filter.subject.as_deref().map(SubjectId::from_key); + let owner = filter.owner.as_deref().map(|owner| match owner { + "me" => user.get_id().clone(), + id => UserId::from_key(id), + }); + // Same newtype the PATCH validates against, so an unknown shelf is the same + // 400 ("visibility must be private or school") on both routes. + let visibility = filter + .visibility + .as_deref() + .map(BankVisibility::try_new) + .transpose()?; + // The visibility gate is one of those SQL filters, never a post-filter over + // the page: `total` counts what the caller may see, so paging can't hand + // back short pages full of holes where someone else's private templates sat. + let viewer = (!user.get_role().at_least(Role::Admin)).then(|| user.get_id().clone()); + // Filters, order, and window are all SQL — `total` comes from a count over + // the same WHERE, so a client can page past the first window. + let (questions, total) = BankQuestion::list( + viewer.as_ref(), + owner.as_ref(), + subject.as_ref(), + visibility.as_ref(), + filter.q.as_deref(), + limit, + offset, + &st.db, + ) + .await?; + + // Four bulk joins over the page alone: its images, its subjects' names, + // its owners' names, and how many exam questions each template spawned. + // A missing row renders empty, never fails the list. + let ids: Vec<&BankQuestionId> = questions.iter().map(BankQuestion::get_id).collect(); + let buckets = bank_images_by_question(&ids, &st.db).await?; + // One grouped query for the whole page — never a count per row. + let used = BankQuestion::usage_counts(&ids, &st.db).await?; + let subject_ids: Vec<&SubjectId> = questions.iter().filter_map(BankQuestion::get_subject).collect(); + let subject_names: HashMap = Subject::list_by_ids(&subject_ids, &st.db) + .await? + .iter() + .map(|subject| { + ( + subject.get_id().key().to_string(), + subject.get_name().as_str().to_string(), + ) + }) + .collect(); + let people = person_map(questions.iter().map(|q| q.get_owner().clone()), &st.db).await?; + let empty: Vec = Vec::new(); - let items = paginate(&questions, limit, offset) + let items = questions .iter() .map(|question| { let images = buckets.get(question.get_id().key()).unwrap_or(&empty); - BankQuestionResponse::new(question, images) + let subject_name = question + .get_subject() + .and_then(|subject| subject_names.get(subject.key()).cloned()) + .unwrap_or_default(); + let owner_name = people + .get(question.get_owner().key()) + .map(|person| { + person + .display_name + .clone() + .unwrap_or_else(|| person.username.clone()) + }) + .unwrap_or_default(); + let used_count = used.get(question.get_id().key()).copied().unwrap_or(0); + BankQuestionResponse::with_names(question, images, subject_name, owner_name, used_count) }) .collect(); Ok(Json(Page::new(items, total, limit, offset))) } -/// One template by id. School-wide — any teacher+ reads any template. +/// One template by id. Visible ones only: a `private` template belonging to +/// someone else is a 404, not a 403 — a 403 would confirm it exists. #[utoipa::path( get, path = "/{bid}", @@ -393,15 +580,15 @@ async fn list_questions( (status = 200, description = "The template", body = BankQuestionResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), - (status = 404, description = "No such template", body = ErrorResponse), + (status = 404, description = "No such template, or one the caller may not see", body = ErrorResponse), ), )] async fn get_question( State(st): State, - RequireTeacher(_user): RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(bid): Path, ) -> Result, AppError> { - let question = question_or_404(&st, &bid).await?; + let question = visible_question(&st, &user, &bid).await?; let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; Ok(Json(BankQuestionResponse::new(&question, &images))) } @@ -411,6 +598,12 @@ async fn get_question( /// a kind switch must bring the matching fields along. Replacing or clearing /// `choices` drops the old options' pictures. Bank templates never freeze — /// they have no exam tie. +/// +/// This is also the publish switch: `visibility: "school"` shares the template +/// with every teacher, `"private"` pulls it back. By design an **admin can +/// publish (or unpublish) another teacher's private template** — the ownership +/// gate here is the same admin-bypassing one that lets an admin edit or delete +/// any template, and it is not narrowed for this field. #[utoipa::path( patch, path = "/{bid}", @@ -437,9 +630,11 @@ async fn update_question( // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a // re-tag to a subject that's being deleted can't straddle the delete-guard. let _guard = BANK_LOCK.read().await; + // Omitted keeps the stored subject — which may already be `None`, cleared + // by that subject's delete. let subject = match req.subject_id { - Some(ref subject_id) => subject_must_exist(subject_id, &st.db).await?, - None => question.get_subject().clone(), + Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), + None => question.get_subject().cloned(), }; let text = match req.text { Some(ref text) => QuestionText::try_new(text)?, @@ -455,27 +650,37 @@ async fn update_question( Some(ref kind) => QuestionKind::try_new(kind)?, None => question.get_kind().clone(), }; - let choices_replaced = req.choices.is_some(); + // Omitting `choices` re-submits the stored options *with their ids*, so a + // text-only edit keeps every identity (and every picture) untouched. let choices = match req.choices { - Some(update) => update, - None => question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + Some(update) => ChoiceBody::into_inputs(update), + None => ChoiceBody::from_stored(question.get_choices()), }; let correct = match req.correct { Some(update) => update, - None => question.get_correct(), + None => question.get_correct().map(|id| id.as_str().to_string()), + }; + let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; + let visibility = match req.visibility { + Some(ref visibility) => BankVisibility::try_new(visibility)?, + None => question.get_visibility().clone(), }; - let spec = QuestionSpec::try_new(kind, choices, correct)?; let bid = question.get_id().clone(); - let updated = question.update(subject, text, points, spec, &st.db).await?; - // A replaced (or cleared) choice list orphans the old options' pictures — - // drop them all; the template's own illustration stays. - if choices_replaced { - for image in BankQuestionImage::delete_choices_for(&bid, &st.db).await? { - remove_blob(&st.files_path, image.get_file()).await; - } + let updated = question + .update(subject, text, points, spec, visibility, &st.db) + .await?; + // Only the options that are actually *gone* lose their pictures — an option + // that survives the edit keeps its image wherever it moved in the list. + let keep: Vec = updated + .get_choices() + .unwrap_or_default() + .iter() + .map(|choice| choice.get_id().clone()) + .collect(); + for image in BankQuestionImage::delete_choices_not_in(&bid, &keep, &st.db).await? { + remove_blob(&st.files_path, image.get_file()).await; } let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?; Ok(Json(BankQuestionResponse::new(&updated, &images))) @@ -515,7 +720,8 @@ async fn delete_question( // ---- template images -------------------------------------------------------- // A template may carry one illustration (any kind) and, on choice templates, // one picture per option — mirroring exam question images, minus the exam tie -// and the freeze. Mutations are owner-gated; reads are school-wide (teacher+). +// and the freeze. Mutations are owner-gated; reads follow the template's +// visibility (a template the caller can't see 404s, images included). /// Attach (or replace) a template's illustration. Owner only (admins aside). /// `multipart/form-data` with the image under a `file` field; the declared @@ -552,7 +758,8 @@ async fn upload_question_image( Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) } -/// A template's illustration bytes. School-wide — any teacher+ reads it. +/// A template's illustration bytes. Readable by anyone who may see the +/// template — 404 otherwise, never a 403. #[utoipa::path( get, path = "/{bid}/image", @@ -568,10 +775,10 @@ async fn upload_question_image( )] async fn get_question_image( State(st): State, - RequireTeacher(_user): RequireTeacher, + RequireTeacher(user): RequireTeacher, Path(bid): Path, ) -> Result { - let question = question_or_404(&st, &bid).await?; + let question = visible_question(&st, &user, &bid).await?; let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) .await? .ok_or(AppError::NotFound)?; @@ -612,17 +819,17 @@ async fn delete_question_image( /// drops all its option pictures. #[utoipa::path( post, - path = "/{bid}/choices/{index}/image", + path = "/{bid}/choices/{choice_id}/image", tag = "bank", security(("session_cookie" = [])), params( ("bid" = String, Path, description = "Bank question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"), ), request_body(content = UploadFileForm, content_type = "multipart/form-data"), responses( (status = 201, description = "Image stored", body = BankImageMeta), - (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text template, or an index past the choices", body = ErrorResponse), + (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text template, or an unknown choice id", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), (status = 404, description = "No such template", body = ErrorResponse), @@ -632,29 +839,18 @@ async fn delete_question_image( async fn upload_choice_image( State(st): State, RequireTeacher(user): RequireTeacher, - Path((bid, index)): Path<(String, i64)>, + Path((bid, choice_id)): Path<(String, String)>, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { let question = owned_question(&st, &user, &bid).await?; - let Some(choices) = question.get_choices() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "index", - reason: "only choice questions take option pictures", - })); - }; - if !(0..choices.len() as i64).contains(&index) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "index", - reason: "must index one of the choices", - })); - } + let slot = bank_choice_slot(&question, &choice_id)?; let limit = Settings::load(&st.db).await?.get_max_file_bytes(); let upload = read_upload(&mut multipart, limit).await?; let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; let stored = store_image( &st, question.get_id(), - Some(index), + Some(&slot), content_type, &upload.data, ) @@ -662,15 +858,16 @@ async fn upload_choice_image( Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) } -/// One option's picture bytes. School-wide — any teacher+ reads it. +/// One option's picture bytes. Readable by anyone who may see the template — +/// 404 otherwise, never a 403. #[utoipa::path( get, - path = "/{bid}/choices/{index}/image", + path = "/{bid}/choices/{choice_id}/image", tag = "bank", security(("session_cookie" = [])), params( ("bid" = String, Path, description = "Bank question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"), ), responses( (status = 200, description = "The image bytes", content_type = "image/*"), @@ -681,11 +878,12 @@ async fn upload_choice_image( )] async fn get_choice_image( State(st): State, - RequireTeacher(_user): RequireTeacher, - Path((bid, index)): Path<(String, i64)>, + RequireTeacher(user): RequireTeacher, + Path((bid, choice_id)): Path<(String, String)>, ) -> Result { - let question = question_or_404(&st, &bid).await?; - let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) + let question = visible_question(&st, &user, &bid).await?; + let slot = bank_choice_slot(&question, &choice_id)?; + let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) .await? .ok_or(AppError::NotFound)?; serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await @@ -694,12 +892,12 @@ async fn get_choice_image( /// Remove one option's picture. Owner only (admins aside). #[utoipa::path( delete, - path = "/{bid}/choices/{index}/image", + path = "/{bid}/choices/{choice_id}/image", tag = "bank", security(("session_cookie" = [])), params( ("bid" = String, Path, description = "Bank question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"), ), responses( (status = 204, description = "Deleted"), @@ -711,10 +909,11 @@ async fn get_choice_image( async fn delete_choice_image( State(st): State, RequireTeacher(user): RequireTeacher, - Path((bid, index)): Path<(String, i64)>, + Path((bid, choice_id)): Path<(String, String)>, ) -> Result { let question = owned_question(&st, &user, &bid).await?; - let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) + let slot = bank_choice_slot(&question, &choice_id)?; + let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) .await? .ok_or(AppError::NotFound)?; let image = image.delete(&st.db).await?; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 7dc5e82..3be9692 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -17,7 +17,7 @@ //! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline //! //! client → server -//! - `{"type":"answer", question_id, selected? | text?}` +//! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id) //! - `{"type":"finish"}` //! - `{"type":"ping"}` //! @@ -89,7 +89,7 @@ enum ClientMessage { Answer { question_id: String, #[serde(default)] - selected: Option, + selected: Option, #[serde(default)] text: Option, }, diff --git a/src/web/exams.rs b/src/web/exams.rs index 037cfe7..64478c4 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -23,7 +23,8 @@ use crate::domain::exam::{ use crate::domain::exam_answer::{ExamAnswer, auto_score}; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; use crate::domain::exam_question::{ - ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, + QuestionText, }; use crate::domain::exam_result::{ExamResult, Mark}; use crate::domain::note_file::FileContentType; @@ -39,9 +40,9 @@ use super::bank_questions::BankQuestionResponse; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::subjects::subject_in_course; use super::{ - CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm, - blob_path, check_not_past, image_content_type, paginate, person_map, read_upload, remove_blob, - set_or_clear, + ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, + UploadFileForm, blob_path, check_not_past, image_content_type, paginate, person_map, + read_upload, remove_blob, set_or_clear, }; /// Serializes the exam subsystem's cross-record check-then-writes, which @@ -81,6 +82,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(update_question, delete_question)) .routes(routes!(question_from_bank)) .routes(routes!(question_to_bank)) + .routes(routes!(question_refresh_from_bank)) .routes(routes!(attempt_questions)) .routes(routes!(save_answer)) .routes(routes!(attempt_answers)) @@ -1316,11 +1318,13 @@ struct CreateQuestion { #[schema(example = 10)] points: i64, /// The options of a `choice` question (2–10 of them); omit for `text`. - choices: Option>, - /// Zero-based index of the right option; required for `choice`, absent - /// for `text`. - #[schema(example = 1)] - correct: Option, + /// Each carries an `id` naming it within this payload — the server mints + /// the stored ids and returns them. + choices: Option>, + /// The `id` of the right option, as sent in `choices`; required for + /// `choice`, absent for `text`. + #[schema(example = "b")] + correct: Option, } #[derive(Deserialize, ToSchema)] @@ -1336,19 +1340,22 @@ struct UpdateQuestion { /// when moving to `text`. kind: Option, /// Omit to keep the stored options; send `null` to drop them (text - /// questions only). Replacing or clearing the list also drops every - /// option picture — the old images belong to the old options. + /// questions only). Send each option back with the `id` it was returned + /// with to keep it — its picture rides along. Only options whose id is + /// absent from the new list lose their picture, so reordering, renaming, + /// and deleting one option leave the rest untouched. #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option>)] - choices: Option>>, - /// Omit to keep; `null` to clear (text questions only). + #[schema(value_type = Option>)] + choices: Option>>, + /// The `id` of the right option. Omit to keep; `null` to clear (text + /// questions only). #[serde(default, deserialize_with = "set_or_clear")] - #[schema(value_type = Option)] - correct: Option>, + #[schema(value_type = Option)] + correct: Option>, } /// A stored question image's metadata; the bytes come from the image -/// endpoints (`GET .../image`, `GET .../choices/{index}/image`). +/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`). #[derive(Serialize, ToSchema)] struct ImageMetaResponse { /// MIME type as declared on upload (always one of the raster allowlist). @@ -1376,22 +1383,26 @@ impl ImageMetaResponse { } /// The question's slot out of its image rows. -fn image_meta(images: &[QuestionImage], slot: Option) -> Option { +fn image_meta(images: &[QuestionImage], slot: Option<&ChoiceId>) -> Option { images .iter() .find(|image| image.get_slot() == slot) .map(ImageMetaResponse::new) } -/// The per-choice metas, aligned index-for-index with `choices` (`None` +/// The per-choice metas, aligned position-for-position with `choices` (`None` /// entries = that option has no picture); `None` whole for text questions. +/// A response-only projection: the pictures are *stored* against choice ids, so +/// this alignment is rebuilt from the current list on every read and can never +/// go stale. fn choice_image_metas( question: &ExamQuestion, images: &[QuestionImage], ) -> Option>> { question.get_choices().map(|choices| { - (0..choices.len() as i64) - .map(|index| image_meta(images, Some(index))) + choices + .iter() + .map(|choice| image_meta(images, Some(choice.get_id()))) .collect() }) } @@ -1412,7 +1423,31 @@ async fn images_by_question( Ok(buckets) } -/// A question as its author sees it — including the `correct` index. Never +/// One option on the wire: its stable id and its text. Carries **no** answer +/// key — `correct` is a sibling field on the question, and only on the +/// author-facing DTO, so a student response cannot contain one by construction. +#[derive(Serialize, ToSchema)] +pub(crate) struct ChoiceResponse { + /// Send this back in a PATCH to keep the option (and its picture). + id: String, + text: String, +} + +impl ChoiceResponse { + pub(crate) fn list(choices: Option<&[Choice]>) -> Option> { + choices.map(|choices| { + choices + .iter() + .map(|choice| Self { + id: choice.get_id().as_str().to_string(), + text: choice.get_text().as_str().to_string(), + }) + .collect() + }) + } +} + +/// A question as its author sees it — including the `correct` option. Never /// serialized to students; they get [`AttemptQuestionResponse`]. #[derive(Serialize, ToSchema)] struct QuestionResponse { @@ -1425,15 +1460,21 @@ struct QuestionResponse { #[schema(example = "choice")] kind: String, points: i64, - choices: Option>, - /// Zero-based index of the right option (`choice` questions only). - correct: Option, + /// The options with their stable ids (`choice` questions only). + choices: Option>, + /// The id of the right option (`choice` questions only). + correct: Option, /// The question's illustration, if one was uploaded (any kind). image: Option, /// Per-option pictures, aligned with `choices` (`choice` questions only). choice_images: Option>>, - /// The bank template this question was instantiated from, if any. - source_bank: Option, + /// The bank template this question was created from, if it was added out of + /// the bank (`GET /bank-questions/{id}`). + from_bank: Option, + /// The bank template most recently created by saving this question into the + /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a + /// question that came *from* the bank and was never saved back. + banked_as: Option, } impl QuestionResponse { @@ -1445,13 +1486,14 @@ impl QuestionResponse { text: question.get_text().as_str().to_string(), kind: question.get_kind().as_str().to_string(), points: question.get_points().as_i64(), - choices: question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), - correct: question.get_correct(), + choices: ChoiceResponse::list(question.get_choices()), + correct: question + .get_correct() + .map(|id| id.as_str().to_string()), image: image_meta(images, None), choice_images: choice_image_metas(question, images), - source_bank: question.get_source_bank().map(|b| b.key().to_string()), + from_bank: question.get_from_bank().map(|b| b.key().to_string()), + banked_as: question.get_banked_as().map(|b| b.key().to_string()), } } } @@ -1483,6 +1525,26 @@ async fn question_of_exam( Ok(question) } +/// The question's option named by `choice_id` — a 400 for a text question or an +/// id the question doesn't have, so an option picture can only ever be +/// addressed through an option that exists. +fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result { + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "only choice questions take option pictures", + })); + }; + choices + .iter() + .find(|choice| choice.get_id().as_str() == choice_id) + .map(|choice| choice.get_id().clone()) + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "choice_id", + reason: "must name one of the choices", + })) +} + /// Add a question to an exam. Requires teacher+ and management rights over the /// exam's course. `subject_id` must name one of the course's subjects /// (`GET /courses/{id}/subjects`) — every question belongs to a subject. @@ -1528,7 +1590,14 @@ async fn create_question( let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; - let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; + // No stored choices to match against on create, so every option is new and + // every id is minted here. + let spec = QuestionSpec::try_new( + QuestionKind::try_new(&req.kind)?, + ChoiceBody::into_inputs(req.choices), + req.correct, + &[], + )?; let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; // A question is born imageless — uploads come after, against its id. Ok(( @@ -1664,27 +1733,32 @@ async fn update_question( Some(ref kind) => QuestionKind::try_new(kind)?, None => question.get_kind().clone(), }; - let choices_replaced = req.choices.is_some(); + // Omitting `choices` re-submits the stored options *with their ids*, so a + // text-only edit keeps every identity (and every picture) untouched. let choices = match req.choices { - Some(update) => update, - None => question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + Some(update) => ChoiceBody::into_inputs(update), + None => ChoiceBody::from_stored(question.get_choices()), }; let correct = match req.correct { Some(update) => update, - None => question.get_correct(), + None => question.get_correct().map(|id| id.as_str().to_string()), }; - let spec = QuestionSpec::try_new(kind, choices, correct)?; + let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; let updated = question.update(subject, text, points, spec, &st.db).await?; - // A replaced (or cleared) choice list orphans the old options' pictures — - // drop them all; the question's own illustration stays. Uploads re-attach - // against the new list. - if choices_replaced { - for image in QuestionImage::delete_choices_for(updated.get_id(), &st.db).await? { - remove_blob(&st.files_path, image.get_file()).await; - } + // Only the options that are actually *gone* lose their pictures: keyed by + // choice id, an option that survives the edit keeps its image no matter + // where it moved in the list. (This used to wipe every option picture + // whenever the request so much as carried a `choices` key.) + let keep: Vec = updated + .get_choices() + .unwrap_or_default() + .iter() + .map(|choice| choice.get_id().clone()) + .collect(); + for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? { + remove_blob(&st.files_path, image.get_file()).await; } let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; Ok(Json(QuestionResponse::new(&updated, &images))) @@ -1754,7 +1828,9 @@ struct InstantiateFromBank { } /// Instantiate a bank template into this exam as a fresh question. Requires -/// teacher+ and management rights over the exam's course. `subject_id` must +/// teacher+, management rights over the exam's course, and a template the +/// caller may see (their own, or one published to the school) — anything else +/// is a 404. `subject_id` must /// name one of the course's subjects — the template's own subject is origin /// metadata and does not carry over. The template (and its blobs) stay /// untouched; a full copy — text, points, spec, illustration, and option @@ -1774,7 +1850,7 @@ struct InstantiateFromBank { (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), - (status = 404, description = "No such exam, or no such bank template", body = ErrorResponse), + (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), ), )] @@ -1802,6 +1878,12 @@ async fn question_from_bank( let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) .await? .ok_or(AppError::NotFound)?; + // A template the caller may not see is a 404, exactly as it is on the bank's + // own routes — instantiating is a read of `correct`, and a 403 here would + // confirm that someone else's private template exists under that id. + if !super::bank_questions::can_see(&template, &user) { + return Err(AppError::NotFound); + } let question = ExamQuestion::create_from_bank( exam.get_id(), subject, @@ -1859,14 +1941,159 @@ async fn question_from_bank( )) } +/// Re-copy a bank template's *current* content over the exam question that was +/// instantiated from it — the escape hatch for the divergence a deep copy +/// creates: fixing a typo in the template does not reach the copies, so this is +/// how a copy is brought back in line, explicitly and per question. Requires +/// teacher+, management rights over the exam's course, and a template the +/// caller may still see. +/// +/// Replaces text, points, kind, choices, `correct`, the illustration, and the +/// option pictures with the template's; the question keeps its own id, its +/// exam, its `subject` (exam-course-scoped — the template's subject is +/// unrelated metadata) and its provenance links. Anything edited on the exam +/// copy since it was inserted is overwritten. +/// +/// **Choice ids come from the template**, exactly as +/// [`question_from_bank`] mints them — the copy adopts the template's ids, so +/// its option pictures key off the same slots the template's do, and a +/// re-copy after a template edit re-lands the right picture on the right +/// option. A recorded `selected` can never be stranded by that: the freeze +/// below refuses the whole route once *any* attempt exists, and an +/// `exam_answer` only exists under an attempt — so at refresh time no answer +/// points at any choice id at all. +/// +/// - No `from_bank` (never came from the bank, or its template was deleted and +/// the cascade cleared the link) → `400`; there is nothing to refresh from. +/// - Template gone or not visible to the caller → `404`, never a 403. +/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze +/// every other question mutation answers to. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/refresh-from-bank", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 200, description = "Question refreshed from its template", body = QuestionResponse), + (status = 400, description = "The question did not come from the bank", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +async fn question_refresh_from_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result, AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can edit questions", + )); + } + // Writer lease of [`EXAM_LOCK`]: the freeze gate, the read, and the + // overwrite are one unit — same reasoning as `update_question`, which this + // is a canned variant of. + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + let Some(source) = question.get_from_bank().cloned() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "question", + reason: "this question did not come from a bank template", + })); + }; + let template = BankQuestion::read(&source, &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !super::bank_questions::can_see(&template, &user) { + return Err(AppError::NotFound); + } + + // Every source blob is read up front, *before* anything is written: a + // missing one is server-side damage and must surface as a 500 with the + // question untouched, since a half-applied refresh has no old content left + // to roll back to. Bounded — at most one illustration plus ten option + // pictures, each under the school's file cap. + let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let mut incoming: Vec<(&BankQuestionImage, Vec)> = Vec::with_capacity(sources.len()); + for source in &sources { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for bank image {}: {err}", + source.get_file() + )) + })?; + incoming.push((source, bytes)); + } + + // The question's own subject stays: it is checked against the exam's + // course, and the template's is origin metadata from anywhere in school. + let subject = question.get_subject().clone(); + // `spec()` hands over the template's stored choices *with their ids* rather + // than re-minting any — the same funnel `question_from_bank` uses. + let updated = question + .update( + subject, + template.get_text().clone(), + template.get_points(), + template.spec(), + &st.db, + ) + .await?; + + // Make the pictures match the template exactly: drop every slot the + // template has no picture for (including the illustration, and every option + // that is gone after the re-copy), then write the template's over the rest. + // `store_image` upserts per slot, so a slot both sides have is replaced. + let incoming_slots: Vec> = + incoming.iter().map(|(image, _)| image.get_slot()).collect(); + for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? { + if incoming_slots.contains(&stale.get_slot()) { + continue; + } + let file = stale.get_file().to_string(); + stale.delete(&st.db).await?; + remove_blob(&st.files_path, &file).await; + } + for (source, bytes) in &incoming { + store_image( + &st, + &exam, + &updated, + source.get_slot(), + source.get_content_type().clone(), + bytes, + ) + .await?; + } + + let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?; + Ok(Json(QuestionResponse::new(&updated, &images))) +} + /// Save one of this exam's questions into the school-wide bank as a reusable /// template. Requires teacher+ and management rights over the exam's course. /// The caller becomes the template's owner; the question's subject rides along /// as origin metadata. A full copy — text, points, spec, illustration, and /// option pictures — lands under a new bank id. Provenance rides both ways: the /// origin exam is recorded on the template as `source_exam`, and the exam -/// question's `source_bank` is pointed at the new template (a repeat save is -/// allowed and repoints it at the newest one). +/// question's `banked_as` is pointed at the new template (a repeat save is +/// allowed and repoints it at the newest one). `from_bank` is left alone — it +/// records the other direction and a save never changes where a question came +/// from. #[utoipa::path( post, path = "/{id}/questions/{qid}/to-bank", @@ -1898,10 +2125,10 @@ async fn question_to_bank( )); } // Reader lease of [`BANK_LOCK`] across the question read and the insert: the - // template adopts the question's subject, and a re-tag/delete of this - // question could otherwise let that subject's delete-guard slip between the - // read and our insert (its `any_for_subject` check runs under BANK_LOCK's - // writer lease, so holding the reader lease forces it to see our new row). + // template adopts the question's subject, so without it a subject delete + // could slip between the two and leave the fresh template pointing at a + // subject its cascade had already swept (that cascade runs under BANK_LOCK's + // writer lease, so holding the reader lease orders us either side of it). let _bank_guard = super::bank_questions::BANK_LOCK.read().await; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; @@ -1964,8 +2191,20 @@ async fn question_to_bank( // template silently vanishing over a metadata write is worse than a // template with no back-link (the next save re-links it). let question_key = question.get_id().key().to_string(); + // The bank lease has done its job (the template is inserted, its subject + // pinned); hand it back *before* taking the exam one, so this handler never + // holds both — the subject delete goes EXAM_LOCK then BANK_LOCK, and taking + // them the other way round here would be a deadlock. + drop(_bank_guard); + // Reader lease of [`EXAM_LOCK`] around the back-link, the one write this + // handler makes to `exam_question`. `ExamQuestion::update` is a whole-row + // save taken under `EXAM_LOCK.write()`; without this lease the link could + // land between that handler's read and its write, and the pre-link snapshot + // would be written straight back over it — the provenance silently lost. + // Held around the link alone, never across the blob copy above. + let _exam_guard = EXAM_LOCK.read().await; if let Err(err) = question - .link_source_bank(template.get_id().clone(), &st.db) + .link_banked_as(template.get_id().clone(), &st.db) .await { tracing::warn!( @@ -2031,7 +2270,7 @@ async fn store_image( st: &AppState, exam: &Exam, question: &ExamQuestion, - slot: Option, + slot: Option<&ChoiceId>, content_type: FileContentType, data: &[u8], ) -> Result { @@ -2192,18 +2431,18 @@ async fn delete_question_image( /// drops all its option pictures — re-upload against the new list. #[utoipa::path( post, - path = "/{id}/questions/{qid}/choices/{index}/image", + path = "/{id}/questions/{qid}/choices/{choice_id}/image", tag = "exams", security(("session_cookie" = [])), params( ("id" = String, Path, description = "Exam id"), ("qid" = String, Path, description = "Question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id, as returned in the question's `choices`"), ), request_body(content = UploadFileForm, content_type = "multipart/form-data"), responses( (status = 201, description = "Image stored", body = ImageMetaResponse), - (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an index past the choices", body = ErrorResponse), + (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text question, or an unknown choice id", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), @@ -2214,7 +2453,7 @@ async fn delete_question_image( async fn upload_choice_image( State(st): State, RequireTeacher(user): RequireTeacher, - Path((id, qid, index)): Path<(String, String, i64)>, + Path((id, qid, choice_id)): Path<(String, String, String)>, mut multipart: Multipart, ) -> Result<(StatusCode, Json), AppError> { let exam = image_managed_exam(&st, &user, &id).await?; @@ -2224,40 +2463,21 @@ async fn upload_choice_image( let _guard = EXAM_LOCK.write().await; ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let Some(choices) = question.get_choices() else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "index", - reason: "only choice questions take option pictures", - })); - }; - if !(0..choices.len() as i64).contains(&index) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "index", - reason: "must index one of the choices", - })); - } - let stored = store_image( - &st, - &exam, - &question, - Some(index), - content_type, - &upload.data, - ) - .await?; + let slot = choice_slot(&question, &choice_id)?; + let stored = store_image(&st, &exam, &question, Some(&slot), content_type, &upload.data).await?; Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored)))) } /// One option's picture bytes. Same access wall as the question-image read. #[utoipa::path( get, - path = "/{id}/questions/{qid}/choices/{index}/image", + path = "/{id}/questions/{qid}/choices/{choice_id}/image", tag = "exams", security(("session_cookie" = [])), params( ("id" = String, Path, description = "Exam id"), ("qid" = String, Path, description = "Question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id"), ), responses( (status = 200, description = "The image bytes", content_type = "image/*"), @@ -2269,14 +2489,15 @@ async fn upload_choice_image( async fn get_choice_image( State(st): State, CurrentUser(user): CurrentUser, - Path((id, qid, index)): Path<(String, String, i64)>, + Path((id, qid, choice_id)): Path<(String, String, String)>, ) -> Result { let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; ensure_question_content_visible(&st, &exam, &user).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db) + let slot = choice_slot(&question, &choice_id)?; + let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) .await? .ok_or(AppError::NotFound)?; serve_image(&st, &image).await @@ -2286,13 +2507,13 @@ async fn get_choice_image( /// the exam's course; frozen once attempts exist. #[utoipa::path( delete, - path = "/{id}/questions/{qid}/choices/{index}/image", + path = "/{id}/questions/{qid}/choices/{choice_id}/image", tag = "exams", security(("session_cookie" = [])), params( ("id" = String, Path, description = "Exam id"), ("qid" = String, Path, description = "Question id"), - ("index" = i64, Path, description = "Zero-based choice index"), + ("choice_id" = String, Path, description = "Choice id"), ), responses( (status = 204, description = "Deleted"), @@ -2305,13 +2526,14 @@ async fn get_choice_image( async fn delete_choice_image( State(st): State, RequireTeacher(user): RequireTeacher, - Path((id, qid, index)): Path<(String, String, i64)>, + Path((id, qid, choice_id)): Path<(String, String, String)>, ) -> Result { let exam = image_managed_exam(&st, &user, &id).await?; let _guard = EXAM_LOCK.write().await; ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; - let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db) + let slot = choice_slot(&question, &choice_id)?; + let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) .await? .ok_or(AppError::NotFound)?; let image = image.delete(&st.db).await?; @@ -2327,8 +2549,8 @@ async fn delete_choice_image( /// A student's own saved answer, embedded in their question view. #[derive(Serialize, ToSchema)] struct AnswerStateResponse { - /// The picked option's zero-based index (`choice` questions). - selected: Option, + /// The picked option's id (`choice` questions). + selected: Option, /// The typed answer (`text` questions). text: Option, /// When this answer was last saved, UTC unix-milliseconds. @@ -2341,7 +2563,7 @@ struct AnswerStateResponse { impl AnswerStateResponse { fn new(answer: &ExamAnswer, answer_image: Option) -> Self { Self { - selected: answer.get_selected(), + selected: answer.get_selected().map(|id| id.as_str().to_string()), text: answer.get_text().map(|t| t.as_str().to_string()), updated_at: answer.get_updated_at().as_millis(), answer_image, @@ -2361,12 +2583,15 @@ struct AttemptQuestionResponse { #[schema(example = "choice")] kind: String, points: i64, - choices: Option>, + /// The options with their ids — and deliberately *not* `correct`: this DTO + /// leaks no answer key because it has no field to carry one, and + /// `ChoiceResponse` carries none either. + choices: Option>, /// The question's illustration, if any — bytes at /// `GET /exams/{id}/questions/{qid}/image`. image: Option, /// Per-option pictures aligned with `choices`, if any — bytes at - /// `GET /exams/{id}/questions/{qid}/choices/{index}/image`. + /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`. choice_images: Option>>, /// The caller's saved answer; `null` while unanswered. answer: Option, @@ -2376,8 +2601,8 @@ struct AttemptQuestionResponse { struct SaveAnswer { /// The question being answered. question_id: String, - /// The picked option's zero-based index — required for `choice` questions. - selected: Option, + /// The picked option's `id` — required for `choice` questions. + selected: Option, /// The typed answer — required for `text` questions (empty clears the draft). text: Option, } @@ -2385,7 +2610,8 @@ struct SaveAnswer { #[derive(Serialize, ToSchema)] struct AnswerSavedResponse { question: String, - selected: Option, + /// The picked option's id. + selected: Option, text: Option, /// Save instant by the server clock, UTC unix-milliseconds. updated_at: i64, @@ -2432,7 +2658,7 @@ pub(crate) async fn save_answer_checked( exam: &Exam, user: &UserId, question_id: &str, - selected: Option, + selected: Option, text: Option, db: &Database, ) -> Result { @@ -2452,7 +2678,7 @@ pub(crate) async fn save_answer_in( exam: &Exam, attempt: &ExamAttempt, question_id: &str, - selected: Option, + selected: Option, text: Option, db: &Database, ) -> Result { @@ -2580,9 +2806,7 @@ async fn attempt_questions( text: question.get_text().as_str().to_string(), kind: question.get_kind().as_str().to_string(), points: question.get_points().as_i64(), - choices: question - .get_choices() - .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + choices: ChoiceResponse::list(question.get_choices()), image: image_meta(question_images, None), choice_images: choice_image_metas(question, question_images), answer: answers.get(question.get_id().key()).map(|answer| { @@ -2643,7 +2867,7 @@ async fn save_answer( .await?; Ok(Json(AnswerSavedResponse { question: answer.get_question().key().to_string(), - selected: answer.get_selected(), + selected: answer.get_selected().map(|id| id.as_str().to_string()), text: answer.get_text().map(|t| t.as_str().to_string()), updated_at: answer.get_updated_at().as_millis(), })) @@ -2727,7 +2951,7 @@ async fn answer_sheet( .iter() .map(|answer| StudentAnswerResponse { question: answer.get_question().key().to_string(), - selected: answer.get_selected(), + selected: answer.get_selected().map(|id| id.as_str().to_string()), text: answer.get_text().map(|t| t.as_str().to_string()), updated_at: answer.get_updated_at().as_millis(), is_correct: by_question @@ -2746,7 +2970,8 @@ async fn answer_sheet( #[derive(Serialize, ToSchema)] struct StudentAnswerResponse { question: String, - selected: Option, + /// The picked option's id. + selected: Option, text: Option, /// When the answer was last saved, UTC unix-milliseconds. updated_at: i64, diff --git a/src/web/mod.rs b/src/web/mod.rs index 10633fe..b47b404 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -50,6 +50,7 @@ use utoipa::ToSchema; use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS}; use crate::database::Database; +use crate::domain::exam_question::{Choice, ChoiceInput}; use crate::domain::note_file::FileContentType; use crate::domain::parent_link::ParentLink; use crate::domain::role::Role; @@ -269,6 +270,49 @@ pub(crate) async fn read_upload( }) } +/// One option of a choice question as a client sends it — the wire form of +/// [`crate::domain::exam_question::ChoiceInput`], shared by the exam-question +/// and bank-template routes. +/// +/// `id` is the option's key within the payload: send back the `id` the server +/// returned to keep that option (and its picture) across an edit, or any fresh +/// string to introduce a new one. The server mints the stored id either way, so +/// nothing a client sends here ever reaches storage. +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub(crate) struct ChoiceBody { + #[serde(default)] + pub id: Option, + #[schema(example = "42")] + pub text: String, +} + +impl ChoiceBody { + pub(crate) fn into_input(self) -> ChoiceInput { + ChoiceInput { + id: self.id, + text: self.text, + } + } + + /// The whole submitted list, or `None` when the field was omitted/cleared. + pub(crate) fn into_inputs(choices: Option>) -> Option> { + choices.map(|list| list.into_iter().map(Self::into_input).collect()) + } + + /// The stored choices as a payload that re-submits them unchanged — how a + /// PATCH that omits `choices` keeps every option's identity. + pub(crate) fn from_stored(choices: Option<&[Choice]>) -> Option> { + choices.map(|list| { + list.iter() + .map(|choice| ChoiceInput { + id: Some(choice.get_id().as_str().to_string()), + text: choice.get_text().as_str().to_string(), + }) + .collect() + }) + } +} + /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the /// stored value); `null` or a value lands here as `Some(inner)` (clear or set). diff --git a/src/web/subjects.rs b/src/web/subjects.rs index aef4694..8d9dc8b 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -7,7 +7,6 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::bank_question::BankQuestion; use crate::domain::course::{Course, CourseId}; use crate::domain::exam_question::ExamQuestion; use crate::domain::homework::Homework; @@ -158,9 +157,15 @@ async fn update_subject( } /// Delete a subject. Requires teacher+ and management rights over its course. -/// Refused with a 409 while any exam question, homework, or bank question still -/// references it — re-tag or delete those first, so nothing is left pointing at -/// a subject that no longer exists. +/// Refused with a 409 while any exam question or homework still references it — +/// re-tag or delete those first, so nothing is left pointing at a subject that +/// no longer exists. +/// +/// Bank templates are the exception: their `subject` is optional origin +/// metadata, so the delete simply clears it on every template that carried it +/// instead of refusing. Blocking there was unresolvable (only a template's +/// owner may re-tag it, so a manager could not clear their own 409) and leaked +/// the existence of other teachers' private templates. #[utoipa::path( delete, path = "/{id}", @@ -172,7 +177,7 @@ async fn update_subject( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Exam questions, homework, or bank questions still reference this subject", body = ErrorResponse), + (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse), ), )] async fn delete_subject( @@ -207,18 +212,14 @@ async fn delete_subject( "homework still references this subject — re-tag or delete it first", )); } - // Bank templates carry this subject as origin metadata; a deleted subject - // would leave them pointing at nothing. Writer lease of [`BANK_LOCK`], the - // bank twin of the two guards above: bank create/update validate their - // subject and insert under the reader lease, so the no-templates check and - // the delete can't straddle a template that just adopted this subject. Held - // last; the order is EXAM_LOCK, then HOMEWORK_LOCK, then BANK_LOCK. + // Bank templates carry this subject as optional origin metadata, so they + // don't block: `Subject::delete` clears it off them in the delete's own + // transaction. Writer lease of [`BANK_LOCK`] all the same — bank + // create/update validate their subject and write under the reader lease, so + // without it a template could adopt this subject *after* the cascade ran + // and outlive it. Held last; the order is EXAM_LOCK, then HOMEWORK_LOCK, + // then BANK_LOCK. let _bank_guard = BANK_LOCK.write().await; - if BankQuestion::any_for_subject(subject.get_id(), &st.db).await? { - return Err(AppError::Conflict( - "bank questions still reference this subject — re-tag or delete them first", - )); - } subject.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/e2e.rs b/tests/e2e.rs index 33b90a2..1c598e9 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -508,6 +508,9 @@ struct ExamRoom { subject_id: String, exam_id: String, question_id: String, + /// The fixture question's minted choice ids, in list order — what the + /// tests below used to write as the indexes 0 and 1. + choice_ids: Vec, } async fn exam_room_fixture(window_ms: i64) -> ExamRoom { @@ -583,7 +586,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { .post(format!("{base}/exams/{exam_id}/questions")) .json( &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", - "points": 10, "choices": ["3", "4"], "correct": 1 }), + "points": 10, "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}], "correct": "b" }), ) .send() .await @@ -592,6 +595,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { .await .unwrap(); let question_id = question["id"].as_str().unwrap().to_string(); + let choice_ids = choice_ids(&question); let cookie = raw_session_cookie(&base, "veli").await; ExamRoom { base, @@ -604,9 +608,20 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { subject_id, exam_id, question_id, + choice_ids, } } +/// The minted ids of a question response's options, in list order. +fn choice_ids(question: &Value) -> Vec { + question["choices"] + .as_array() + .unwrap() + .iter() + .map(|choice| choice["id"].as_str().unwrap().to_string()) + .collect() +} + /// The student exam room over a real TCP WebSocket: connect with the session /// cookie, get the state frame, autosave an answer, survive junk input, /// finish, and watch the server close the room — with the result visible to @@ -667,7 +682,7 @@ async fn exam_room_websocket_round_trip() { // Autosave: answer -> saved ack -> a state showing the progress. ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }), ) .await; let saved = ws_frame_of_type(&mut ws, "saved").await; @@ -848,7 +863,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { // While the sitter is a student the sheet is open — save one answer. ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }), ) .await; ws_frame_of_type(&mut ws, "saved").await; @@ -859,7 +874,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { // The very next save is refused over the same socket... ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 0 }), + json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }), ) .await; let error = ws_frame_of_type(&mut ws, "error").await; @@ -871,7 +886,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { // ... and over REST — the two paths share the wall. let res = student .post(format!("{base}/exams/{exam_id}/attempt/answers")) - .json(&json!({ "question_id": question_id, "selected": 0 })) + .json(&json!({ "question_id": question_id, "selected": room.choice_ids[0] })) .send() .await .unwrap(); @@ -889,13 +904,13 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { .await .unwrap(); assert_eq!(sheet["answers"].as_array().unwrap().len(), 1); - assert_eq!(sheet["answers"][0]["selected"], 1); + assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]); // Demoted back, the same socket writes again — no reconnect required. promote(db, "veli", "student").await; ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 0 }), + json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }), ) .await; ws_frame_of_type(&mut ws, "saved").await; @@ -967,7 +982,7 @@ async fn exam_room_expires_mid_session() { // One answer lands inside the window. ws_send( &mut ws, - json!({ "type": "answer", "question_id": room.question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }), ) .await; ws_frame_of_type(&mut ws, "saved").await; @@ -987,7 +1002,7 @@ async fn exam_room_expires_mid_session() { "{}/exams/{}/attempt/answers", room.base, room.exam_id )) - .json(&json!({ "question_id": room.question_id, "selected": 0 })) + .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] })) .send() .await .unwrap(); @@ -1015,7 +1030,7 @@ async fn exam_room_expires_mid_session() { .json() .await .unwrap(); - assert_eq!(sheet["answers"][0]["selected"], 1); + assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]); assert_eq!(sheet["auto_score"]["earned"], 10); } @@ -1088,7 +1103,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() { "{}/exams/{}/attempt/answers", room.base, room.exam_id )) - .json(&json!({ "question_id": room.question_id, "selected": 1 })) + .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] })) .send() .await .unwrap(); @@ -1121,7 +1136,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() { ); ws_send( &mut ws, - json!({ "type": "answer", "question_id": room.question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }), ) .await; ws_frame_of_type(&mut ws, "saved").await; @@ -1136,7 +1151,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() { "{}/exams/{}/attempt/answers", room.base, room.exam_id )) - .json(&json!({ "question_id": room.question_id, "selected": 0 })) + .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] })) .send() .await .unwrap(); @@ -1193,7 +1208,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { .post(format!("{}/exams/{exam_id}/questions", room.base)) .json( &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", - "points": 5, "choices": ["5", "6"], "correct": 1 }), + "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }), ) .send() .await @@ -1202,6 +1217,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { .await .unwrap(); let question_id = question["id"].as_str().unwrap().to_string(); + let opts = choice_ids(&question); // Sit sitting #1 and open its room. let res = room @@ -1259,7 +1275,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { let res = room .student .post(format!("{}/exams/{exam_id}/attempt/answers", room.base)) - .json(&json!({ "question_id": question_id, "selected": 1 })) + .json(&json!({ "question_id": question_id, "selected": opts[1] })) .send() .await .unwrap(); @@ -1299,7 +1315,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() { .post(format!("{}/exams/{exam_id}/questions", room.base)) .json( &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", - "points": 5, "choices": ["5", "6"], "correct": 1 }), + "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }), ) .send() .await @@ -1308,6 +1324,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() { .await .unwrap(); let question_id = question["id"].as_str().unwrap().to_string(); + let opts = choice_ids(&question); // Sit sitting #1 and open its room. let res = room @@ -1346,7 +1363,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() { // blank sheet of sitting #2. ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }), ) .await; let error = ws_frame_of_type(&mut ws, "error").await; @@ -1432,7 +1449,7 @@ async fn exam_room_second_tab_keeps_the_student_present() { "{}/exams/{}/attempt/answers", room.base, room.exam_id )) - .json(&json!({ "question_id": room.question_id, "selected": 1 })) + .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] })) .send() .await .unwrap(); @@ -1452,7 +1469,7 @@ async fn exam_room_second_tab_keeps_the_student_present() { "{}/exams/{}/attempt/answers", room.base, room.exam_id )) - .json(&json!({ "question_id": room.question_id, "selected": 0 })) + .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] })) .send() .await .unwrap(); @@ -1486,7 +1503,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { .post(format!("{}/exams/{exam_id}/questions", room.base)) .json( &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", - "points": 5, "choices": ["5", "6"], "correct": 1 }), + "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }), ) .send() .await @@ -1495,6 +1512,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { .await .unwrap(); let question_id = question["id"].as_str().unwrap().to_string(); + let opts = choice_ids(&question); let res = room .student @@ -1515,7 +1533,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { ws_send( &mut ws, - json!({ "type": "answer", "question_id": question_id, "selected": 1 }), + json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }), ) .await; ws_frame_of_type(&mut ws, "saved").await; diff --git a/tests/integration.rs b/tests/integration.rs index 7a2e5a7..c5a45ee 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -4965,7 +4965,7 @@ async fn promotion_out_of_student_freezes_the_seat() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": "nope", "selected": 0 })), + Some(json!({ "question_id": "nope", "selected": "c0" })), ) .await; assert_eq!( @@ -6610,15 +6610,16 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { "mode": "open", "max_attempts": 2 }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let question = id_of(&question_body); // First sitting starts right away — no window to wait for — and runs // without a deadline: it can only end by submission. @@ -6644,7 +6645,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": question, "selected": 1 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -7086,7 +7087,7 @@ async fn subject_delete_blocks_while_questions_reference_it() { let tagged = create_subject(&app, &teacher, &course, "antiquity").await; let spare = create_subject(&app, &teacher, &course, "middle ages").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -7094,6 +7095,7 @@ async fn subject_delete_blocks_while_questions_reference_it() { json!({ "text": "When?", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); // Referenced: the delete is a conflict, and the subject survives. let res = send( @@ -7175,8 +7177,21 @@ async fn create_question( cookie: &str, exam: &str, subject: &str, - mut body: serde_json::Value, + body: serde_json::Value, ) -> String { + id_of(&create_question_body(app, cookie, exam, subject, body).await) +} + +/// Like [`create_question`], but hands back the whole response: choice ids are +/// minted by the server, so a test that answers a question — or pictures one of +/// its options — has to read them off the response rather than count positions. +async fn create_question_body( + app: &axum::Router, + cookie: &str, + exam: &str, + subject: &str, + mut body: serde_json::Value, +) -> serde_json::Value { body["subject_id"] = json!(subject); let res = send( app, @@ -7192,7 +7207,16 @@ async fn create_question( "create question: {}", res.body ); - id_of(&res.body) + res.body +} + +/// The minted id of the option at `index` of a question (or bank template) +/// response — what these tests used to write as a bare choice index. +fn choice_of(question: &serde_json::Value, index: usize) -> String { + question["choices"][index]["id"] + .as_str() + .unwrap_or_else(|| panic!("choice {index} of {question}")) + .to_string() } /// A course with an open sync window, one subject, and one enrolled student — @@ -7236,7 +7260,7 @@ async fn question_crud_validation_and_rbac() { Some(&teacher), Some( json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4", "5"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }), ), ) .await; @@ -7245,8 +7269,8 @@ async fn question_crud_validation_and_rbac() { assert_eq!(res.body["subject"], subject); assert_eq!(res.body["kind"], "choice"); assert_eq!(res.body["points"], 10); - assert_eq!(res.body["choices"][1], "4"); - assert_eq!(res.body["correct"], 1); + assert_eq!(res.body["choices"][1]["text"], "4"); + assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); let choice_q = id_of(&res.body); // A text question carries neither choices nor correct. @@ -7298,40 +7322,51 @@ async fn question_crud_validation_and_rbac() { ), ( "choice without choices", - json!({ "text": "x", "kind": "choice", "points": 1, "correct": 0 }), + json!({ "text": "x", "kind": "choice", "points": 1, "correct": "c0" }), ), ( "choice without correct", - json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"] }), + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }), + ), + ( + "correct names no submitted choice", + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c2" }), + ), + ( + "correct is blank", + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "" }), ), ( - "correct out of range", - json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": 2 }), + // Two options under one key: the payload can't say which one + // `correct` (or a picture) means, so it is refused outright. + "duplicate choice id in one payload", + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c0", "text": "b"}], "correct": "c0" }), ), ( - "negative correct", - json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": -1 }), + // An option with no key cannot be named by `correct`. + "correct names an unkeyed option", + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"text": "a"}, {"text": "b"}], "correct": "c0" }), ), ( "one choice", - json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a"], "correct": 0 }), + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}], "correct": "c0" }), ), ( "eleven choices", json!({ "text": "x", "kind": "choice", "points": 1, - "choices": ["a","b","c","d","e","f","g","h","i","j","k"], "correct": 0 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}, {"id": "c3", "text": "d"}, {"id": "c4", "text": "e"}, {"id": "c5", "text": "f"}, {"id": "c6", "text": "g"}, {"id": "c7", "text": "h"}, {"id": "c8", "text": "i"}, {"id": "c9", "text": "j"}, {"id": "c10", "text": "k"}], "correct": "c0" }), ), ( "blank choice", - json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", " "], "correct": 0 }), + json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": " "}], "correct": "c0" }), ), ( "text with choices", - json!({ "text": "x", "kind": "text", "points": 1, "choices": ["a", "b"] }), + json!({ "text": "x", "kind": "text", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }), ), ( "text with correct", - json!({ "text": "x", "kind": "text", "points": 1, "correct": 0 }), + json!({ "text": "x", "kind": "text", "points": 1, "correct": "c0" }), ), ] { let mut body = body; @@ -7410,7 +7445,7 @@ async fn question_crud_validation_and_rbac() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["points"], 15); - assert_eq!(res.body["correct"], 1, "kind bundle kept"); + assert_eq!(res.body["correct"], res.body["choices"][1]["id"], "kind bundle kept"); assert_eq!(res.body["subject"], subject, "subject kept by omission"); // Re-tagging stays inside the course: another of its subjects is fine, a @@ -7468,7 +7503,7 @@ async fn question_crud_validation_and_rbac() { "PATCH", &format!("/exams/{exam}/questions/{choice_q}"), Some(&teacher), - Some(json!({ "kind": "choice", "choices": ["yes", "no"], "correct": 0 })), + Some(json!({ "kind": "choice", "choices": [{"id": "c0", "text": "yes"}, {"id": "c1", "text": "no"}], "correct": "c0" })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -7546,15 +7581,16 @@ async fn questions_freeze_once_attempts_start() { let student_id = me_id(&app, &student).await; let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "algo").await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let question = id_of(&question_body); let res = send( &app, @@ -7603,15 +7639,16 @@ async fn student_question_view_hides_correct_and_embeds_answers() { let student = login(&app, "sona").await; let student_id = me_id(&app, &student).await; let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "art").await; - let choice_q = create_question( + let choice_q_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let choice_q = id_of(&choice_q_body); create_question( &app, &teacher, @@ -7641,7 +7678,7 @@ async fn student_question_view_hides_correct_and_embeds_answers() { let questions = res.body.as_array().expect("questions"); assert_eq!(questions.len(), 2); assert_eq!(questions[0]["kind"], "choice"); - assert_eq!(questions[0]["choices"][1], "4"); + assert_eq!(questions[0]["choices"][1]["text"], "4"); for question in questions { assert!( question.as_object().unwrap().get("correct").is_none(), @@ -7656,17 +7693,17 @@ async fn student_question_view_hides_correct_and_embeds_answers() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": choice_q, "selected": 0 })), + Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["question"], choice_q); - assert_eq!(res.body["selected"], 0); + assert_eq!(res.body["selected"], choice_of(&choice_q_body, 0)); let saved_at = res.body["updated_at"].as_i64().expect("updated_at"); let res = send(&app, "GET", &uri, Some(&student), None).await; let questions = res.body.as_array().expect("questions"); - assert_eq!(questions[0]["answer"]["selected"], 0); + assert_eq!(questions[0]["answer"]["selected"], choice_of(&choice_q_body, 0)); assert_eq!(questions[0]["answer"]["updated_at"], saved_at); assert!(questions[1]["answer"].is_null()); } @@ -7678,16 +7715,17 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { let student = login(&app, "arda").await; let student_id = me_id(&app, &student).await; let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "phys").await; - let choice_q = create_question( + let choice_q_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4", "5"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }), ) .await; - let text_q = create_question( + let choice_q = id_of(&choice_q_body); + let text_q_body = create_question_body( &app, &teacher, &exam, @@ -7695,6 +7733,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; + let text_q = id_of(&text_q_body); let answers_uri = format!("/exams/{exam}/attempt/answers"); // Saving needs an attempt (404 before start). @@ -7703,7 +7742,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": choice_q, "selected": 0 })), + Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), ) .await; assert_eq!(res.status, StatusCode::NOT_FOUND, "attempt first"); @@ -7723,7 +7762,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": choice_q, "selected": 0 })), + Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -7734,11 +7773,11 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": choice_q, "selected": 2 })), + Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 2) })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["selected"], 2); + assert_eq!(res.body["selected"], choice_of(&choice_q_body, 2)); assert!( res.body["updated_at"].as_i64().expect("updated_at") > first_saved_at, "a re-save moves updated_at forward" @@ -7774,20 +7813,16 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { ), ( "both fields", - json!({ "question_id": choice_q, "selected": 1, "text": "4" }), + json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1), "text": "4" }), ), ( - "selected out of range", - json!({ "question_id": choice_q, "selected": 3 }), - ), - ( - "negative selected", - json!({ "question_id": choice_q, "selected": -1 }), + "selected names no choice of this question", + json!({ "question_id": choice_q, "selected": "01NOTACHOICEOFTHISQUEST" }), ), ("nothing to save", json!({ "question_id": choice_q })), ( "selected on a text question", - json!({ "question_id": text_q, "selected": 0 }), + json!({ "question_id": text_q, "selected": choice_of(&choice_q_body, 0) }), ), ( "oversized text", @@ -7804,26 +7839,27 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": "missing", "selected": 0 })), + Some(json!({ "question_id": "missing", "selected": "c0" })), ) .await; assert_eq!(res.status, StatusCode::NOT_FOUND); let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz").await; - let foreign_q = create_question( + let foreign_q_body = create_question_body( &app, &teacher, &foreign_exam, &subject, json!({ "text": "not yours", "kind": "choice", "points": 1, - "choices": ["a", "b"], "correct": 0 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), ) .await; + let foreign_q = id_of(&foreign_q_body); let res = send( &app, "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": foreign_q, "selected": 0 })), + Some(json!({ "question_id": foreign_q, "selected": choice_of(&foreign_q_body, 0) })), ) .await; assert_eq!( @@ -7848,7 +7884,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "POST", &answers_uri, Some(&student), - Some(json!({ "question_id": choice_q, "selected": 1 })), + Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1) })), ) .await; assert_eq!( @@ -7873,7 +7909,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { "review after submit: {}", res.body ); - assert_eq!(res.body[0]["answer"]["selected"], 2); + assert_eq!(res.body[0]["answer"]["selected"], choice_of(&choice_q_body, 2)); assert_eq!(res.body[1]["answer"]["text"], "because"); } @@ -7884,15 +7920,16 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() { let student = login(&app, "cansu").await; let student_id = me_id(&app, &student).await; let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let question = id_of(&question_body); // Enrolled: start the attempt, read the questions, save an answer. let res = send( @@ -7918,7 +7955,7 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": question, "selected": 1 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -7955,7 +7992,7 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": question, "selected": 0 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })), ) .await; assert_eq!( @@ -8015,15 +8052,16 @@ async fn answer_saves_stop_at_the_deadline() { "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "quick", "kind": "choice", "points": 1, - "choices": ["a", "b"], "correct": 0 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), ) .await; + let question = id_of(&question_body); let res = send( &app, "POST", @@ -8038,7 +8076,7 @@ async fn answer_saves_stop_at_the_deadline() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": question, "selected": 0 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })), ) .await; assert_eq!( @@ -8055,7 +8093,7 @@ async fn answer_saves_stop_at_the_deadline() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&student), - Some(json!({ "question_id": question, "selected": 1 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), ) .await; assert_eq!(res.status, StatusCode::CONFLICT, "expired: {}", res.body); @@ -8070,7 +8108,7 @@ async fn answer_saves_stop_at_the_deadline() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["answers"][0]["selected"], 0); + assert_eq!(res.body["answers"][0]["selected"], choice_of(&question_body, 0)); } #[tokio::test] @@ -8081,24 +8119,26 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { let student_id = me_id(&app, &student).await; let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; - let q1 = create_question( + let q1_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; - let q2 = create_question( + let q1 = id_of(&q1_body); + let q2_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "3 + 3?", "kind": "choice", "points": 20, - "choices": ["6", "7"], "correct": 0 }), + "choices": [{"id": "c0", "text": "6"}, {"id": "c1", "text": "7"}], "correct": "c0" }), ) .await; + let q2 = id_of(&q2_body); let q3 = create_question( &app, &teacher, @@ -8123,8 +8163,8 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { .await; assert_eq!(res.status, StatusCode::CREATED); for body in [ - json!({ "question_id": q1, "selected": 1 }), // right - json!({ "question_id": q2, "selected": 1 }), // wrong + json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }), // right + json!({ "question_id": q2, "selected": choice_of(&q2_body, 1) }), // wrong json!({ "question_id": q3, "text": "entropy grows" }), ] { let res = send( @@ -8174,15 +8214,16 @@ async fn live_monitor_tracks_answer_progress() { let bora_id = me_id(&app, &bora).await; let (course, exam, subject) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await; enroll(&app, &teacher, &course, &bora_id).await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let question = id_of(&question_body); create_question( &app, &teacher, @@ -8210,7 +8251,7 @@ async fn live_monitor_tracks_answer_progress() { "POST", &format!("/exams/{exam}/attempt/answers"), Some(&ayla), - Some(json!({ "question_id": question, "selected": 1 })), + Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })), ) .await; assert_eq!(res.status, StatusCode::OK); @@ -8246,16 +8287,17 @@ async fn questions_and_answers_cascade_with_deletes() { let student = login(&app, "cem").await; let student_id = me_id(&app, &student).await; let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await; - let q1 = create_question( + let q1_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; - let q2 = create_question( + let q1 = id_of(&q1_body); + let q2_body = create_question_body( &app, &teacher, &exam, @@ -8263,6 +8305,7 @@ async fn questions_and_answers_cascade_with_deletes() { json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; + let q2 = id_of(&q2_body); let res = send( &app, "POST", @@ -8273,7 +8316,7 @@ async fn questions_and_answers_cascade_with_deletes() { .await; assert_eq!(res.status, StatusCode::CREATED); for body in [ - json!({ "question_id": q1, "selected": 1 }), + json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }), json!({ "question_id": q2, "text": "so" }), ] { let res = send( @@ -8361,15 +8404,16 @@ async fn questions_and_answers_cascade_with_deletes() { "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; - let q = create_question( + let q_body = create_question_body( &app, &teacher, &exam2, &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 }), + "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ) .await; + let q = id_of(&q_body); let res = send( &app, "POST", @@ -8384,7 +8428,7 @@ async fn questions_and_answers_cascade_with_deletes() { "POST", &format!("/exams/{exam2}/attempt/answers"), Some(&student), - Some(json!({ "question_id": q, "selected": 1 })), + Some(json!({ "question_id": q, "selected": choice_of(&q_body, 1) })), ) .await; assert_eq!(res.status, StatusCode::OK); @@ -8431,15 +8475,16 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { let course = create_course(&app, &teacher, "sets").await; let subject = create_subject(&app, &teacher, &course, "unions").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "pick", "kind": "choice", "points": 10, - "choices": ["a", "b", "c"], "correct": 2 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c2" }), ) .await; + let question = id_of(&question_body); let uri = format!("/exams/{exam}/questions/{question}"); // Shrinking the options while keeping the old `correct` would leave it @@ -8449,7 +8494,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { "PATCH", &uri, Some(&teacher), - Some(json!({ "choices": ["a", "b"] })), + Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] })), ) .await; assert_eq!( @@ -8465,11 +8510,11 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { "PATCH", &uri, Some(&teacher), - Some(json!({ "choices": ["a", "b"], "correct": 1 })), + Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c1" })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["correct"], 1); + assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); // A lone out-of-range `correct` against the kept choices is caught too. let res = send( @@ -8477,7 +8522,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { "PATCH", &uri, Some(&teacher), - Some(json!({ "correct": 5 })), + Some(json!({ "correct": "c5" })), ) .await; assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); @@ -8509,7 +8554,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { .len(), 2 ); - assert_eq!(common::items(&res.body)[0]["correct"], 1); + assert_eq!(common::items(&res.body)[0]["correct"], common::items(&res.body)[0]["choices"][1]["id"]); } #[tokio::test] @@ -8523,15 +8568,16 @@ async fn question_authoring_follows_course_management() { // A manager+ authors questions in anyone's course, like every other // course-management write. - let question = create_question( + let question_body = create_question_body( &app, &boss, &exam, &subject, json!({ "text": "pick", "kind": "choice", "points": 10, - "choices": ["a", "b"], "correct": 0 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), ) .await; + let question = id_of(&question_body); let res = send( &app, "PATCH", @@ -8560,15 +8606,16 @@ async fn concurrent_answer_saves_never_collide() { let student_id = me_id(&app, &student).await; let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "race").await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "pick", "kind": "choice", "points": 10, - "choices": ["a", "b", "c"], "correct": 0 }), + "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c0" }), ) .await; + let question = id_of(&question_body); let res = send( &app, "POST", @@ -8586,7 +8633,7 @@ async fn concurrent_answer_saves_never_collide() { let app = app.clone(); let student = student.clone(); let uri = format!("/exams/{exam}/attempt/answers"); - let body = json!({ "question_id": question, "selected": i % 3 }); + let body = json!({ "question_id": question, "selected": choice_of(&question_body, (i % 3) as usize) }); handles.push(tokio::spawn(async move { send(&app, "POST", &uri, Some(&student), Some(body)) .await @@ -10670,15 +10717,16 @@ async fn question_images_author_serve_and_cascade() { json!({ "title": "map quiz", "kind": "quiz", "mode": "open" }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "Which city is marked?", "kind": "choice", "points": 10, - "choices": ["Ankara", "İzmir"], "correct": 0 }), + "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" }), ) .await; + let question = id_of(&question_body); let essay = create_question( &app, &teacher, @@ -10715,7 +10763,7 @@ async fn question_images_author_serve_and_cascade() { let (status, _) = post_image( &app, &teacher, - &format!("/exams/{exam}/questions/{essay}/choices/0/image"), + &format!("/exams/{exam}/questions/{essay}/choices/{}/image", choice_of(&question_body, 0)), "image/png", b"x", ) @@ -10728,15 +10776,18 @@ async fn question_images_author_serve_and_cascade() { let (status, _) = post_image( &app, &teacher, - &format!("/exams/{exam}/questions/{question}/choices/2/image"), + &format!("/exams/{exam}/questions/{question}/choices/01NOTACHOICEOFTHISQUEST/image"), "image/png", b"x", ) .await; - assert_eq!(status, StatusCode::BAD_REQUEST, "slot must index a choice"); + assert_eq!(status, StatusCode::BAD_REQUEST, "slot must name a choice"); // Option picture on choice 1, and the author view carries all the metas. - let choice_image = format!("/exams/{exam}/questions/{question}/choices/1/image"); + let choice_image = format!( + "/exams/{exam}/questions/{question}/choices/{}/image", + choice_of(&question_body, 1) + ); let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await; assert_eq!(status, StatusCode::CREATED); let res = send( @@ -10874,7 +10925,7 @@ async fn student_answer_images_serve_and_cascade() { json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -10882,6 +10933,7 @@ async fn student_answer_images_serve_and_cascade() { json!({ "text": "Draw a cell.", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); let own = format!("/exams/{exam}/attempt/answers/{question}/image"); let png = b"png-drawing".as_slice(); @@ -11087,7 +11139,7 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() { json!({ "title": "sketch", "kind": "quiz", "mode": "open" }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -11095,6 +11147,7 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() { json!({ "text": "Draw a triangle.", "kind": "text", "points": 5 }), ) .await; + let question = id_of(&question_body); // Sit, then upload a drawing WITHOUT ever saving a text answer. let res = send( @@ -11161,10 +11214,13 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() { ); } -/// The authoring edits that reshape a question also groom its images: a -/// replaced `choices` list drops the option pictures (the illustration -/// stays), an explicit image DELETE removes row + blob, and deleting the -/// question sweeps the rest. +/// The authoring edits that reshape a question also groom its images — and +/// **only** the pictures of options that are actually gone. Reordering the list +/// and deleting one option leaves every surviving option's picture attached to +/// *that option*, and leaves `correct` naming the option the author marked. +/// This is the behaviour stable choice ids exist for: the images used to be +/// keyed by position, so any edit that carried a `choices` key wiped all of +/// them. #[tokio::test] async fn question_image_edits_follow_the_choices() { let (app, db) = app_and_db().await; @@ -11178,20 +11234,28 @@ async fn question_image_edits_follow_the_choices() { json!({ "title": "eras", "kind": "quiz", "mode": "open" }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, &subject, json!({ "text": "Pick the era.", "kind": "choice", "points": 5, - "choices": ["Bronze", "Iron"], "correct": 1 }), + "choices": [{"id": "c0", "text": "Stone"}, {"id": "c1", "text": "Bronze"}, + {"id": "c2", "text": "Iron"}], "correct": "c2" }), ) .await; + let question = id_of(&question_body); + let (stone, bronze, iron) = ( + choice_of(&question_body, 0), + choice_of(&question_body, 1), + choice_of(&question_body, 2), + ); let base = format!("/exams/{exam}/questions/{question}"); for (path, bytes) in [ (format!("{base}/image"), b"illustration".as_slice()), - (format!("{base}/choices/0/image"), b"bronze".as_slice()), - (format!("{base}/choices/1/image"), b"iron".as_slice()), + (format!("{base}/choices/{stone}/image"), b"stone".as_slice()), + (format!("{base}/choices/{bronze}/image"), b"bronze".as_slice()), + (format!("{base}/choices/{iron}/image"), b"iron".as_slice()), ] { let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await; assert_eq!(status, StatusCode::CREATED, "{body}"); @@ -11208,40 +11272,91 @@ async fn question_image_edits_follow_the_choices() { .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert!(res.body["image"].is_object()); - assert!(res.body["choice_images"][0].is_object()); - assert!(res.body["choice_images"][1].is_object()); + for slot in 0..3 { + assert!(res.body["choice_images"][slot].is_object()); + } + assert_eq!(res.body["correct"], iron, "the answer key must not move"); - // Replacing the choices drops the option pictures, keeps the illustration. + // The edit this whole remodel exists for: reorder the list (Iron first), + // rename one option, and drop Bronze entirely. let keys_before = image_blob_keys(&db).await; let res = send( &app, "PATCH", &base, Some(&teacher), - Some(json!({ "choices": ["Stone", "Bronze", "Iron"], "correct": 2 })), + Some(json!({ "choices": [ + {"id": iron, "text": "Iron Age"}, + {"id": stone, "text": "Stone"}, + ], "correct": iron })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); + // The surviving options kept their identities, in their new order… + assert_eq!(res.body["choices"][0]["id"], iron); + assert_eq!(res.body["choices"][0]["text"], "Iron Age"); + assert_eq!(res.body["choices"][1]["id"], stone); + // …the answer key still names the option the author marked, though it moved + // from position 2 to position 0… + assert_eq!(res.body["correct"], iron, "correct must follow its option"); + // …and each survivor kept *its own* picture, illustration included. assert!(res.body["image"].is_object(), "illustration must survive"); - assert_eq!( - res.body["choice_images"], - json!([null, null, null]), - "option pictures must not follow a replaced list" + assert!( + res.body["choice_images"][0].is_object(), + "Iron kept its picture across the reorder" + ); + assert!( + res.body["choice_images"][1].is_object(), + "Stone kept its picture across the reorder" ); + + // Exactly one blob went: the removed option's. let keys_after = image_blob_keys(&db).await; - assert_eq!(keys_after.len(), 1); - for dropped in keys_before.iter().filter(|k| !keys_after.contains(k)) { + assert_eq!( + keys_after.len(), + 3, + "illustration + two surviving option pictures" + ); + let dropped: Vec<_> = keys_before + .iter() + .filter(|k| !keys_after.contains(k)) + .collect(); + assert_eq!(dropped.len(), 1, "only the removed option's blob may go"); + for key in dropped { assert!( - !common::files_dir().join(dropped).exists(), + !common::files_dir().join(key).exists(), "dropped option blob lingers" ); } + // The remaining wipe path, now opt-in: a list of all-new options (no id + // matches a stored one) is a genuinely new set, so every option picture + // goes — and the illustration still stays. + let res = send( + &app, + "PATCH", + &base, + Some(&teacher), + Some(json!({ "choices": [{"id": "fresh-a", "text": "Iron"}, {"id": "fresh-b", "text": "Stone"}], + "correct": "fresh-a" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_ne!(res.body["choices"][0]["id"], iron, "a new option, not Iron"); + assert_eq!( + res.body["choice_images"], + json!([null, null]), + "an all-new option list keeps no pictures" + ); + assert!(res.body["image"].is_object(), "illustration must survive"); + assert_eq!(image_blob_keys(&db).await.len(), 1); + // Explicit image DELETE: 204 once, 404 after, blob gone. + let fresh = choice_of(&res.body, 0); let (status, _) = post_image( &app, &teacher, - &format!("{base}/choices/0/image"), + &format!("{base}/choices/{fresh}/image"), "image/gif", b"gif", ) @@ -11250,7 +11365,7 @@ async fn question_image_edits_follow_the_choices() { let res = send( &app, "DELETE", - &format!("{base}/choices/0/image"), + &format!("{base}/choices/{fresh}/image"), Some(&teacher), None, ) @@ -11259,7 +11374,7 @@ async fn question_image_edits_follow_the_choices() { let res = send( &app, "DELETE", - &format!("{base}/choices/0/image"), + &format!("{base}/choices/{fresh}/image"), Some(&teacher), None, ) @@ -12712,7 +12827,7 @@ async fn answer_image_round_trip_keeps_the_stroke_text_chunk_intact() { json!({ "title": "sketch quiz", "kind": "quiz", "mode": "open" }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -12720,6 +12835,7 @@ async fn answer_image_round_trip_keeps_the_stroke_text_chunk_intact() { json!({ "text": "Draw a triangle.", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); let res = send( &app, "POST", @@ -16255,7 +16371,7 @@ async fn attempt_history_preserves_each_prior_sitting() { json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -16263,6 +16379,7 @@ async fn attempt_history_preserves_each_prior_sitting() { json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); let own_image = format!("/exams/{exam}/attempt/answers/{question}/image"); // Seq 1: answer, draw, finish. @@ -16572,7 +16689,7 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() { }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -16580,6 +16697,7 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() { json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); let results_uri = format!("/exams/{exam}/results"); // Seq 1: answer, grade, finish. @@ -16695,7 +16813,7 @@ async fn self_review_is_own_scoped_between_students() { json!({ "title": "quiz", "kind": "quiz", "mode": "open", "allow_review": true }), ) .await; - let question = create_question( + let question_body = create_question_body( &app, &teacher, &exam, @@ -16703,6 +16821,7 @@ async fn self_review_is_own_scoped_between_students() { json!({ "text": "Name a consul.", "kind": "text", "points": 10 }), ) .await; + let question = id_of(&question_body); let results_uri = format!("/exams/{exam}/results"); for (who, id, text, mark) in [ @@ -16767,12 +16886,12 @@ async fn bank_question_create_get_list_and_instantiate() { "/bank-questions", Some(&teacher), Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", - "points": 10, "choices": ["3", "4", "5"], "correct": 1 })), + "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); assert_eq!(res.body["kind"], "choice"); - assert_eq!(res.body["correct"], 1); + assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); assert_eq!(res.body["subject"], subject); let bid = id_of(&res.body); @@ -16810,14 +16929,341 @@ async fn bank_question_create_get_list_and_instantiate() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); assert_eq!(res.body["exam"], exam); assert_eq!(res.body["subject"], subject); - assert_eq!(res.body["correct"], 1); - assert_eq!(res.body["choices"][1], "4"); + assert_eq!(res.body["correct"], res.body["choices"][1]["id"]); + assert_eq!(res.body["choices"][1]["text"], "4"); // The copy is independent — the template still stands. let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); } +/// The bank list pages in SQL: newest first, every row reachable by offset, +/// `total` counting the matches rather than the page, and `?q=` filtering +/// server-side. Regression for the whole-table-then-slice version, which hid +/// template #101 onward from a client asking for `limit=100`. +#[tokio::test] +async fn bank_question_list_pages_filters_and_names() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bank_p", "teacher").await; + let other = login_as(&app, &db, "bank_p2", "teacher").await; + let course = create_course(&app, &teacher, "algebra").await; + let subject = create_subject(&app, &teacher, &course, "linear").await; + let other_subject = create_subject(&app, &teacher, &course, "quadratic").await; + + // 120 templates — more than the clients' `limit=100`. + for i in 0..120 { + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": format!("template {i:03}"), + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + // A foreign owner + subject, to prove the filters actually narrow. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&other), + Some(json!({ "subject_id": other_subject, "text": "someone else's", + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + // Published, so it shows up in the first teacher's paging assertions below; + // a private one would (correctly) be invisible to them. + let foreign = id_of(&res.body); + let res = send(&app, "PATCH", &format!("/bank-questions/{foreign}"), Some(&other), Some(json!({ "visibility": "school" }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Page 1: newest first, full window, honest total. + let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await; + assert_eq!(common::items(&res.body).len(), 100); + assert_eq!(res.body["total"], 121); + assert_eq!(common::items(&res.body)[0]["text"], "someone else's"); + assert_eq!(common::items(&res.body)[1]["text"], "template 119"); + // The names are joined on, not left for the client to look up per row. + assert_eq!(common::items(&res.body)[1]["subject_name"], "linear"); + assert_eq!(common::items(&res.body)[1]["owner_name"], "bank_p"); + + // Item #101 onward is reachable — the bug was that it never was. + let res = send( + &app, + "GET", + "/bank-questions?limit=100&offset=100", + Some(&teacher), + None, + ) + .await; + assert_eq!(common::items(&res.body).len(), 21); + assert_eq!(res.body["total"], 121); + assert_eq!(common::items(&res.body)[0]["text"], "template 020"); + assert_eq!(common::items(&res.body)[20]["text"], "template 000"); + + // `?q=` filters server-side: "template 005" sits on page 2 unfiltered, but + // leads page 1 once filtered — and matches case-insensitively. + let res = send( + &app, + "GET", + "/bank-questions?limit=100&q=TEMPLATE%20005", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 1); + assert_eq!(common::items(&res.body).len(), 1); + assert_eq!(common::items(&res.body)[0]["text"], "template 005"); + // A blank `q` is no filter at all. + let res = send(&app, "GET", "/bank-questions?q=", Some(&teacher), None).await; + assert_eq!(res.body["total"], 121); + + // `owner=me` + `subject=` combine, and still page. + let res = send( + &app, + "GET", + &format!("/bank-questions?owner=me&subject={subject}&limit=100&offset=100"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 120); + assert_eq!(common::items(&res.body).len(), 20); + assert_eq!(common::items(&res.body)[0]["text"], "template 019"); + // The other teacher's `me` is their own single template. + let res = send(&app, "GET", "/bank-questions?owner=me", Some(&other), None).await; + assert_eq!(res.body["total"], 1); + assert_eq!(common::items(&res.body)[0]["owner_name"], "bank_p2"); + // Owner and subject that never co-occur → an empty page, total 0. + let res = send( + &app, + "GET", + &format!("/bank-questions?owner=me&subject={other_subject}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 0); + assert!(common::items(&res.body).is_empty()); +} + +/// `?visibility=` is a real SQL filter (so the client never has to fetch the +/// bank unpaged and window it in memory — the very bug the SQL paging fixed), +/// and it narrows the caller's view without ever widening it. +#[tokio::test] +async fn bank_question_list_filters_by_visibility() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bank_v", "teacher").await; + let other = login_as(&app, &db, "bank_v2", "teacher").await; + let course = create_course(&app, &teacher, "biology").await; + let subject = create_subject(&app, &teacher, &course, "cells").await; + let other_subject = create_subject(&app, &teacher, &course, "genes").await; + + // Mine: 3 drafts on `subject`, 2 published on `other_subject`. + let mut published = Vec::new(); + for i in 0..5 { + let on = if i < 3 { &subject } else { &other_subject }; + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": on, "text": format!("mine {i}"), + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + if i >= 3 { + published.push(id_of(&res.body)); + } + } + for bid in &published { + let res = send( + &app, + "PATCH", + &format!("/bank-questions/{bid}"), + Some(&teacher), + Some(json!({ "visibility": "school" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } + // The other teacher keeps one private template — nobody else may ever see + // it, whatever they pass in `?visibility=`. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&other), + Some(json!({ "subject_id": subject, "text": "their secret", + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // `private` = my drafts; `total` honours the filter, not the whole bank. + let res = send( + &app, + "GET", + "/bank-questions?visibility=private", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 3, "{}", res.body); + assert_eq!(common::items(&res.body).len(), 3); + assert_eq!(common::items(&res.body)[0]["text"], "mine 2"); + // `school` = the published shelf — and NOT the other teacher's private row. + let res = send( + &app, + "GET", + "/bank-questions?visibility=school", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 2, "{}", res.body); + let texts: Vec<&str> = common::items(&res.body) + .iter() + .map(|item| item["text"].as_str().unwrap()) + .collect(); + assert_eq!(texts, ["mine 4", "mine 3"]); + assert!(!texts.contains(&"their secret")); + // The stranger's `private` view is empty: the filter can't widen the gate. + let res = send( + &app, + "GET", + "/bank-questions?visibility=private", + Some(&teacher), + None, + ) + .await; + assert!( + !common::items(&res.body) + .iter() + .any(|item| item["text"] == "their secret") + ); + let res = send( + &app, + "GET", + "/bank-questions?visibility=private", + Some(&other), + None, + ) + .await; + assert_eq!(res.body["total"], 1, "{}", res.body); + assert_eq!(common::items(&res.body)[0]["text"], "their secret"); + + // Composes with `q`, `subject`, `owner`, and with paging. + let res = send( + &app, + "GET", + &format!("/bank-questions?visibility=private&subject={subject}&owner=me&q=MINE%201"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 1, "{}", res.body); + assert_eq!(common::items(&res.body)[0]["text"], "mine 1"); + // Right owner and subject, wrong shelf → nothing. + let res = send( + &app, + "GET", + &format!("/bank-questions?visibility=school&subject={subject}&owner=me"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 0, "{}", res.body); + assert!(common::items(&res.body).is_empty()); + // Paging windows the filtered set, and `total` stays the filtered total. + let res = send( + &app, + "GET", + "/bank-questions?visibility=private&limit=2&offset=2", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 3, "{}", res.body); + assert_eq!(common::items(&res.body).len(), 1); + assert_eq!(common::items(&res.body)[0]["text"], "mine 0"); + + // An unknown shelf is a 400, worded like the other param errors. + let res = send( + &app, + "GET", + "/bank-questions?visibility=public", + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .unwrap() + .contains("must be private or school"), + "{}", + res.body + ); +} + +/// The app is EN/TR, so `?q=` must fold Turkish casing: `İ` lowercases to +/// `i` + U+0307 in both Rust and SurrealQL, which used to make `istanbul` and +/// `İSTANBUL` two disjoint searches — a teacher typing lowercase got an empty +/// bank. +#[tokio::test] +async fn bank_question_search_folds_turkish_casing() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bank_tr", "teacher").await; + let course = create_course(&app, &teacher, "cografya").await; + let subject = create_subject(&app, &teacher, &course, "iller").await; + for text in ["İSTANBUL kaç ilçedir?", "istanbul boğazı nerededir?"] { + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": text, + "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + + // Lowercase needle finds the uppercase row, and every casing finds both. + for needle in ["istanbul", "%C4%B0STANBUL", "%C4%B1stanbul", "ISTANBUL"] { + let res = send( + &app, + "GET", + &format!("/bank-questions?q={needle}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 2, "needle {needle} missed: {}", res.body); + } + // Diacritics fold too, in both directions. + for needle in ["ilce", "il%C3%A7e", "bogaz", "bo%C4%9Faz"] { + let res = send( + &app, + "GET", + &format!("/bank-questions?q={needle}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.body["total"], 1, "needle {needle} missed: {}", res.body); + } + // Folding widens the match, it does not match everything. + let res = send(&app, "GET", "/bank-questions?q=ankara", Some(&teacher), None).await; + assert_eq!(res.body["total"], 0); +} + #[tokio::test] async fn bank_question_owner_gate_cross_course_and_freeze() { let (app, db) = app_and_db().await; @@ -16836,6 +17282,10 @@ async fn bank_question_owner_gate_cross_course_and_freeze() { ) .await; let bid = id_of(&res.body); + // Published, so this test is about the *owner* gate alone — the visibility + // gate (404 while private) has its own test below. + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&owner), Some(json!({ "visibility": "school" }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); // A non-owner teacher reads it, but may not edit or delete. let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&other), None).await; @@ -16888,31 +17338,236 @@ async fn bank_question_owner_gate_cross_course_and_freeze() { assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); } +/// A bank template carries `correct` — the answer key — so it is `private` +/// until its owner publishes it. Regression for the one-click answer-key +/// broadcast: saving a live exam's question to the bank used to hand the key +/// (and the pictures) to every teacher in the school, permanently and silently. +/// +/// Every read path is checked from a second teacher's seat, and each one must +/// answer **404, not 403** — a 403 confirms the template exists. #[tokio::test] -async fn exam_question_saves_to_bank() { +async fn bank_private_template_is_invisible_until_published() { let (app, db) = app_and_db().await; - let teacher = login_as(&app, &db, "s2b_t", "teacher").await; - let course = create_course(&app, &teacher, "phys").await; - let subject = create_subject(&app, &teacher, &course, "kinematics").await; - let exam = create_exam(&app, &teacher, &course, "final", "final").await; - let qid = create_question( + let owner = login_as(&app, &db, "bvis_o", "teacher").await; + let other = login_as(&app, &db, "bvis_x", "teacher").await; + let course = create_course(&app, &owner, "bio").await; + let subject = create_subject(&app, &owner, &course, "cells").await; + + // Two templates; only the second is ever published. + let res = send( &app, - &teacher, - &exam, - &subject, - json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), + "POST", + "/bank-questions", + Some(&owner), + Some(json!({ "subject_id": subject, "text": "Which organelle?", "kind": "choice", + "points": 10, "choices": [{"id": "c0", "text": "nucleus"}, {"id": "c1", "text": "ribosome"}], "correct": "c0" })), ) .await; - - let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - assert_eq!(res.body["text"], "v=?"); - assert_eq!(res.body["correct"], 0); - assert_eq!(res.body["subject"], subject); - assert_eq!(res.body["owner"], me_id(&app, &teacher).await); + // New templates are born private — nothing has to opt in to be safe. + assert_eq!(res.body["visibility"], "private"); + let secret = id_of(&res.body); + let opt = choice_of(&res.body, 0); + let res = send( + &app, + "POST", + "/bank-questions", + Some(&owner), + Some(json!({ "subject_id": subject, "text": "shared later", "kind": "text", "points": 1 })), + ) + .await; + let shared = id_of(&res.body); + + let illus = b"private-illustration".as_slice(); + let pic = b"private-choice-pic".as_slice(); + let (status, _) = + post_image(&app, &owner, &format!("/bank-questions/{secret}/image"), "image/png", illus).await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &owner, + &format!("/bank-questions/{secret}/choices/{opt}/image"), + "image/webp", + pic, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + // The other teacher's own exam, to attempt an instantiate from. + let course2 = create_course(&app, &other, "bio2").await; + let subject2 = create_subject(&app, &other, &course2, "cells2").await; + let exam2 = create_exam(&app, &other, &course2, "quiz", "final").await; + let owner_id = me_id(&app, &owner).await; + + // --- the stranger sees nothing, and is told nothing --- + let res = send(&app, "GET", "/bank-questions", Some(&other), None).await; + assert!(common::items(&res.body).is_empty()); + assert_eq!(res.body["total"], 0, "total must count only visible templates"); + let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + let (status, _, _) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{secret}/image"), + Some(&other), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + let (status, _, _) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{secret}/choices/{opt}/image"), + Some(&other), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + let res = send( + &app, + "POST", + &format!("/exams/{exam2}/questions/from-bank/{secret}"), + Some(&other), + Some(json!({ "subject_id": subject2 })), + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + // Not even by asking for the owner's templates by name. + let res = send(&app, "GET", &format!("/bank-questions?owner={owner_id}"), Some(&other), None).await; + assert_eq!(res.body["total"], 0); + + // --- the owner still has full use of their own template --- + let res = send(&app, "GET", "/bank-questions", Some(&owner), None).await; + assert_eq!(res.body["total"], 2); + let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&owner), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["correct"], res.body["choices"][0]["id"]); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{secret}/image"), + Some(&owner), + None, + Vec::new(), + ) + .await; + assert_eq!((status, bytes.as_slice()), (StatusCode::OK, illus)); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{secret}/choices/{opt}/image"), + Some(&owner), + None, + Vec::new(), + ) + .await; + assert_eq!((status, bytes.as_slice()), (StatusCode::OK, pic)); + let exam = create_exam(&app, &owner, &course, "midterm", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{secret}"), + Some(&owner), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // --- publishing one template opens exactly that one --- + let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "school" }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["visibility"], "school"); + let res = send(&app, "GET", "/bank-questions", Some(&other), None).await; + assert_eq!(res.body["total"], 1, "the private one must still be hidden"); + assert_eq!(common::items(&res.body)[0]["id"], shared); + let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam2}/questions/from-bank/{shared}"), + Some(&other), + Some(json!({ "subject_id": subject2 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + // The still-private one stays shut on every path. + let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND); + let res = send( + &app, + "POST", + &format!("/exams/{exam2}/questions/from-bank/{secret}"), + Some(&other), + Some(json!({ "subject_id": subject2 })), + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + // Unpublishing closes it again. + let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "private" }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND); + // A bogus value is a 400, not a silent publish. + let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "public" }))).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} + +/// Admins see private templates: they already read every exam's `correct` via +/// course management, and they may already delete any template. +#[tokio::test] +async fn bank_private_template_is_visible_to_admins() { + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "badm_o", "teacher").await; + let admin = login_as(&app, &db, "badm_a", "admin").await; + let course = create_course(&app, &owner, "hist").await; + let subject = create_subject(&app, &owner, &course, "ottoman").await; + let res = send( + &app, + "POST", + "/bank-questions", + Some(&owner), + Some(json!({ "subject_id": subject, "text": "when?", "kind": "text", "points": 1 })), + ) + .await; + let bid = id_of(&res.body); + + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&admin), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/bank-questions", Some(&admin), None).await; + assert_eq!(res.body["total"], 1); +} + +#[tokio::test] +async fn exam_question_saves_to_bank() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "s2b_t", "teacher").await; + let course = create_course(&app, &teacher, "phys").await; + let subject = create_subject(&app, &teacher, &course, "kinematics").await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), + ) + .await; + + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["text"], "v=?"); + assert_eq!(res.body["correct"], res.body["choices"][0]["id"]); + assert_eq!(res.body["subject"], subject); + assert_eq!(res.body["owner"], me_id(&app, &teacher).await); + // The one-click broadcast that was: the saved key stays the teacher's until + // they publish it. + assert_eq!(res.body["visibility"], "private"); let bid = id_of(&res.body); - // It now lives in the school-wide bank. + // It now lives in their bank. let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK); } @@ -16934,11 +17589,12 @@ async fn bank_instantiate_copies_images() { "/bank-questions", Some(&teacher), Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice", - "points": 10, "choices": ["Ankara", "İzmir"], "correct": 0 })), + "points": 10, "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let bid = id_of(&res.body); + let opt = choice_of(&res.body, 0); let illus = b"bank-illustration".as_slice(); let choice = b"bank-choice-pic".as_slice(); @@ -16948,7 +17604,7 @@ async fn bank_instantiate_copies_images() { let (status, _) = post_image( &app, &teacher, - &format!("/bank-questions/{bid}/choices/0/image"), + &format!("/bank-questions/{bid}/choices/{opt}/image"), "image/webp", choice, ) @@ -16985,7 +17641,7 @@ async fn bank_instantiate_copies_images() { let (status, _, bytes) = common::send_raw( &app, "GET", - &format!("/exams/{exam}/questions/{qid}/choices/0/image"), + &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"), Some(&teacher), None, Vec::new(), @@ -17016,7 +17672,7 @@ async fn bank_instantiate_copies_images() { let (status, _, bytes) = common::send_raw( &app, "GET", - &format!("/bank-questions/{bid}/choices/0/image"), + &format!("/bank-questions/{bid}/choices/{opt}/image"), Some(&teacher), None, Vec::new(), @@ -17036,14 +17692,16 @@ async fn bank_save_copies_images() { let course = create_course(&app, &teacher, "phys1").await; let subject = create_subject(&app, &teacher, &course, "kin1").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; - let qid = create_question( + let qid_body = create_question_body( &app, &teacher, &exam, &subject, - json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }), ) .await; + let qid = id_of(&qid_body); + let opt = choice_of(&qid_body, 0); let illus = b"exam-illustration".as_slice(); let choice = b"exam-choice-pic".as_slice(); @@ -17059,7 +17717,7 @@ async fn bank_save_copies_images() { let (status, _) = post_image( &app, &teacher, - &format!("/exams/{exam}/questions/{qid}/choices/0/image"), + &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"), "image/jpeg", choice, ) @@ -17078,6 +17736,7 @@ async fn bank_save_copies_images() { .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let bid = id_of(&res.body); + let opt = choice_of(&res.body, 0); // The new bank question carries both images, bytes equal. let (status, _, bytes) = common::send_raw( @@ -17094,7 +17753,7 @@ async fn bank_save_copies_images() { let (status, _, bytes) = common::send_raw( &app, "GET", - &format!("/bank-questions/{bid}/choices/0/image"), + &format!("/bank-questions/{bid}/choices/{opt}/image"), Some(&teacher), None, Vec::new(), @@ -17206,17 +17865,18 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() { "/bank-questions", Some(&teacher), Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", - "points": 10, "choices": ["a", "b"], "correct": 0 })), + "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })), ) .await; let bid = id_of(&res.body); + let opt = choice_of(&res.body, 0); let (status, _) = post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await; assert_eq!(status, StatusCode::CREATED); let (status, _) = post_image( &app, &teacher, - &format!("/bank-questions/{bid}/choices/0/image"), + &format!("/bank-questions/{bid}/choices/{opt}/image"), "image/png", b"opt", ) @@ -17307,38 +17967,72 @@ async fn bank_rejects_unknown_subject() { assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); } -/// A subject with bank templates referencing it can't be deleted (409) until -/// those templates are gone — mirrors the exam-question / homework guard. +/// Deleting a subject clears it off the bank templates that carried it as +/// origin metadata, instead of being refused. Blocking would have been a dead +/// end (only a template's owner may re-tag it, so a manager could not clear +/// their own 409) and an existence oracle for other teachers' private +/// templates — hence the cascade. #[tokio::test] -async fn subject_delete_blocked_by_bank_question() { +async fn subject_delete_clears_the_bank_templates_subject() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "bdel_t", "teacher").await; + let manager = login_as(&app, &db, "bdel_m", "manager").await; let course = create_course(&app, &teacher, "bdel_c").await; let subject = create_subject(&app, &teacher, &course, "bdel_s").await; + let other = create_subject(&app, &teacher, &course, "bdel_s2").await; + + let mut ids = Vec::new(); + for subject_id in [&subject, &other] { + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject_id, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + ids.push(id_of(&res.body)); + } + let (bid, kept) = (&ids[0], &ids[1]); + + // The manager owns none of these templates, yet the delete goes through. + let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&manager), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + // The template survives with a cleared origin; the other one is untouched. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["subject"], serde_json::Value::Null); + assert_eq!(res.body["text"], "q"); + let res = send(&app, "GET", &format!("/bank-questions/{kept}"), Some(&teacher), None).await; + assert_eq!(res.body["subject"], json!(other)); + + // The list join renders the cleared one with an empty subject name. + let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await; + let cleared = common::items(&res.body) + .iter() + .find(|q| q["id"] == *bid) + .expect("template in list") + .clone(); + assert_eq!(cleared["subject"], serde_json::Value::Null); + assert_eq!(cleared["subject_name"], ""); + + // A cleared template still edits: PATCH without `subject_id` keeps it null. let res = send( &app, - "POST", - "/bank-questions", + "PATCH", + &format!("/bank-questions/{bid}"), Some(&teacher), - Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + Some(json!({ "text": "still editable" })), ) .await; - let bid = id_of(&res.body); - - // Guarded while the template stands. - let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); - - // Drop the template — the subject frees up. - let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::NO_CONTENT); - let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["subject"], serde_json::Value::Null); + assert_eq!(res.body["text"], "still editable"); } -/// `?owner=me` (and an explicit owner id) narrows the school-wide bank to one -/// owner's templates. +/// `?owner=me` (and an explicit owner id) narrows the bank to one owner's +/// templates — on top of the visibility gate, never around it. #[tokio::test] async fn bank_owner_filter() { let (app, db) = app_and_db().await; @@ -17348,7 +18042,7 @@ async fn bank_owner_filter() { let subject = create_subject(&app, &alice, &course, "bown_s").await; for who in [&alice, &bob] { - send( + let res = send( &app, "POST", "/bank-questions", @@ -17356,6 +18050,10 @@ async fn bank_owner_filter() { Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), ) .await; + // Published, so this test is about the owner filter, not visibility. + let bid = id_of(&res.body); + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(who), Some(json!({ "visibility": "school" }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); } let alice_id = me_id(&app, &alice).await; let bob_id = me_id(&app, &bob).await; @@ -17391,10 +18089,11 @@ async fn bank_response_carries_image_metas() { "/bank-questions", Some(&teacher), Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", - "points": 10, "choices": ["a", "b"], "correct": 0 })), + "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })), ) .await; let bid = id_of(&res.body); + let opt = choice_of(&res.body, 0); // No images yet: metas are null / all-empty. assert!(res.body["image"].is_null()); @@ -17406,7 +18105,7 @@ async fn bank_response_carries_image_metas() { let (status, _) = post_image( &app, &teacher, - &format!("/bank-questions/{bid}/choices/0/image"), + &format!("/bank-questions/{bid}/choices/{opt}/image"), "image/jpeg", b"opt", ) @@ -17426,8 +18125,11 @@ async fn bank_response_carries_image_metas() { assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg"); } -/// Provenance rides both directions: instantiate records `source_bank` on the -/// new exam question; save-to-bank records `source_exam` on the new template. +/// Provenance rides both directions, one column per direction: instantiate +/// records `from_bank` on the new exam question (and leaves `banked_as` null — +/// coming *from* the bank is not being saved *to* it); save-to-bank records +/// `source_exam` on the new template and `banked_as` on the question, without +/// touching `from_bank`. #[tokio::test] async fn bank_provenance_both_directions() { let (app, db) = app_and_db().await; @@ -17435,7 +18137,7 @@ async fn bank_provenance_both_directions() { let course = create_course(&app, &teacher, "bprov_c").await; let subject = create_subject(&app, &teacher, &course, "bprov_s").await; - // Bank -> exam: source_bank is the template id. + // Bank -> exam: from_bank is the template id, banked_as stays null. let res = send( &app, "POST", @@ -17455,9 +18157,32 @@ async fn bank_provenance_both_directions() { ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - assert_eq!(res.body["source_bank"], bid); + assert_eq!(res.body["from_bank"], bid); + // The lie the split fixes: an inserted question must not read as banked. + assert!(res.body["banked_as"].is_null(), "{}", res.body); + let inserted = id_of(&res.body); - // A directly authored exam question has no source_bank. + // Saving that inserted question sets banked_as and leaves from_bank alone. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{inserted}/to-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let template = id_of(&res.body); + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + let question = common::items(&res.body) + .iter() + .find(|q| q["id"] == inserted) + .expect("question in list") + .clone(); + assert_eq!(question["from_bank"], bid, "{question}"); + assert_eq!(question["banked_as"], template, "{question}"); + + // A directly authored exam question has neither link. let qid = create_question( &app, &teacher, @@ -17497,21 +18222,21 @@ async fn to_bank_links_the_question_at_the_new_template() { .await; // Fresh question: no link yet. - let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { + let banked_as_of = |body: &serde_json::Value| -> serde_json::Value { common::items(body) .iter() .find(|q| q["id"] == qid) - .expect("question in list")["source_bank"] + .expect("question in list")["banked_as"] .clone() }; let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; - assert!(source_bank_of(&res.body).is_null()); + assert!(banked_as_of(&res.body).is_null()); let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let first = id_of(&res.body); let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; - assert_eq!(source_bank_of(&res.body), json!(first)); + assert_eq!(banked_as_of(&res.body), json!(first)); // Second save: still 201, a distinct template, and the link follows it. let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; @@ -17519,7 +18244,7 @@ async fn to_bank_links_the_question_at_the_new_template() { let second = id_of(&res.body); assert_ne!(first, second); let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; - assert_eq!(source_bank_of(&res.body), json!(second)); + assert_eq!(banked_as_of(&res.body), json!(second)); } /// The back-link is a field-scoped write. `question_to_bank` reads the question, @@ -17528,7 +18253,7 @@ async fn to_bank_links_the_question_at_the_new_template() { /// whole-row save from the stale struct would silently revert it. Driven at the /// domain level: HTTP offers no way to interleave inside the handler. #[tokio::test] -async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() { +async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { use hezarfen_backend::domain::bank_question::BankQuestionId; use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId}; @@ -17571,7 +18296,7 @@ async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); stale - .link_source_bank(BankQuestionId::from_key(&bid), &db) + .link_banked_as(BankQuestionId::from_key(&bid), &db) .await .expect("link written"); @@ -17584,19 +18309,87 @@ async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() { .clone(); assert_eq!(question["text"], "edited by someone else"); assert_eq!(question["points"], 9); - assert_eq!(question["source_bank"], bid); + assert_eq!(question["banked_as"], bid); +} + +/// A bank PATCH writes only the fields it was given: the handler reads the +/// template, then awaits an ownership check, a subject lookup and (on a choice +/// replace) an image sweep, so another write can land in that window — here the +/// exam-delete cascade clearing `source_exam`, a field the PATCH never sets. +/// A whole-row save from the stale struct would resurrect the dead exam link. +#[tokio::test] +async fn a_bank_patch_does_not_clobber_a_concurrent_write() { + use hezarfen_backend::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; + use hezarfen_backend::domain::exam_question::{ + QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + }; + + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bpatch_t", "teacher").await; + let course = create_course(&app, &teacher, "bpatch_c").await; + let subject = create_subject(&app, &teacher, &course, "bpatch_s").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "original", "kind": "text", "points": 5 }), + ) + .await; + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + assert_eq!(res.body["source_exam"], json!(exam)); + + // The handler's read, then the exam delete lands mid-window and clears the + // template's `source_exam`. + let stale = BankQuestion::read(&BankQuestionId::from_key(&bid), &db) + .await + .unwrap() + .expect("template exists"); + assert!(stale.get_source_exam().is_some()); + let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // The stale struct writes its own fields only. + let updated = stale + .update( + None, + QuestionText::try_new("edited").unwrap(), + QuestionPoints::try_new(7).unwrap(), + QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), + BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(), + &db, + ) + .await + .expect("update written"); + assert_eq!(updated.get_text().as_str(), "edited"); + assert!(updated.get_source_exam().is_none(), "the dead exam link came back"); + + // The edit landed and the cleared provenance stayed cleared. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.body["source_exam"], serde_json::Value::Null); + assert_eq!(res.body["subject"], serde_json::Value::Null); + assert_eq!(res.body["text"], "edited"); + assert_eq!(res.body["points"], 7); + assert_eq!(res.body["visibility"], "school"); } -/// Deleting a bank template clears the provenance link on every exam question -/// saved from it, instead of leaving `source_bank` pointing at a dead row. +/// Deleting a bank template clears *both* provenance links that can point at +/// it — `from_bank` on the questions instantiated from it and `banked_as` on +/// the question it was saved out of — instead of leaving either pointing at a +/// dead row. #[tokio::test] -async fn deleting_a_template_clears_the_questions_source_bank() { +async fn deleting_a_template_clears_both_question_links() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "bdang_t", "teacher").await; let course = create_course(&app, &teacher, "bdang_c").await; let subject = create_subject(&app, &teacher, &course, "bdang_s").await; let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; - let qid = create_question( + + // Question A: authored here, then saved to the bank -> banked_as = saved. + let authored = create_question( &app, &teacher, &exam, @@ -17604,28 +18397,52 @@ async fn deleting_a_template_clears_the_questions_source_bank() { json!({ "text": "plain", "kind": "text", "points": 5 }), ) .await; + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{authored}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let saved = id_of(&res.body); - let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + // Question B: instantiated from a separate template -> from_bank = origin. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "t", "kind": "text", "points": 5 })), + ) + .await; + let origin = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{origin}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); - let bid = id_of(&res.body); + let inserted = id_of(&res.body); - let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { + let link_of = |body: &serde_json::Value, qid: &str, field: &str| -> serde_json::Value { common::items(body) .iter() .find(|q| q["id"] == qid) - .expect("question in list")["source_bank"] + .expect("question in list")[field] .clone() }; let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; - assert_eq!(source_bank_of(&res.body), json!(bid)); + assert_eq!(link_of(&res.body, &authored, "banked_as"), json!(saved)); + assert_eq!(link_of(&res.body, &inserted, "from_bank"), json!(origin)); - let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + for bid in [&saved, &origin] { + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + } - // The question survives the template with no dangling link. + // Both questions survive their templates with no dangling link. let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert!(source_bank_of(&res.body).is_null(), "{}", res.body); + assert!(link_of(&res.body, &authored, "banked_as").is_null(), "{}", res.body); + assert!(link_of(&res.body, &inserted, "from_bank").is_null(), "{}", res.body); } /// The mirror: deleting the origin exam clears `source_exam` on the templates @@ -17659,3 +18476,331 @@ async fn deleting_an_exam_clears_the_templates_source_exam() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert!(res.body["source_exam"].is_null(), "{}", res.body); } + +/// `used_count` on the bank list: how many exam questions were copied out of +/// each template. It is the divergence surface made visible — every one of +/// those copies is detached, so an edit here never reaches them. Joined once +/// for the whole page (one grouped query), list-only exactly like +/// `subject_name`/`owner_name`. +#[tokio::test] +async fn bank_list_counts_the_copies_made_from_each_template() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "buse_t", "teacher").await; + let course = create_course(&app, &teacher, "buse_c").await; + let subject = create_subject(&app, &teacher, &course, "buse_s").await; + + let template = |text: &'static str| { + send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": text, "kind": "text", "points": 4 })), + ) + }; + let used = id_of(&template("reused").await.body); + let unused = id_of(&template("never used").await.body); + + // Two exams, three copies: twice out of `used` in one exam, once in the other. + let mut exams = Vec::new(); + for title in ["one", "two"] { + exams.push(create_exam(&app, &teacher, &course, title, "final").await); + } + for (exam, times) in [(&exams[0], 2), (&exams[1], 1)] { + for _ in 0..times { + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{used}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + } + // A hand-authored question in the same exam has no template and must not + // be tallied against one. + create_question( + &app, + &teacher, + &exams[0], + &subject, + json!({ "text": "mine alone", "kind": "text", "points": 1 }), + ) + .await; + + let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let counts: std::collections::HashMap = common::items(&res.body) + .iter() + .map(|item| (id_of(item), item["used_count"].as_i64().unwrap())) + .collect(); + assert_eq!(counts.get(&used).copied(), Some(3), "{}", res.body); + assert_eq!(counts.get(&unused).copied(), Some(0), "{}", res.body); + + // Deleting a copy takes it back off the tally (its `from_bank` goes with it). + let res = send( + &app, + "GET", + &format!("/exams/{}/questions", exams[1]), + Some(&teacher), + None, + ) + .await; + let qid = id_of(&common::items(&res.body)[0]); + let res = send( + &app, + "DELETE", + &format!("/exams/{}/questions/{qid}", exams[1]), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await; + let after = common::items(&res.body) + .iter() + .find(|item| id_of(item) == used) + .cloned() + .unwrap(); + assert_eq!(after["used_count"], 2, "{}", res.body); + + // List-only, like the other joined fields: the single-template GET says 0. + let res = send(&app, "GET", &format!("/bank-questions/{used}"), Some(&teacher), None).await; + assert_eq!(res.body["used_count"], 0, "{}", res.body); +} + +/// The escape hatch out of the divergence trap: re-copy a template's *current* +/// content over the exam question that was instantiated from it. +/// +/// Choice ids come from the template — the same funnel the original insert +/// used — so pictures land back on the right options and a stale option's +/// picture goes with it. A student's recorded `selected` can never be stranded +/// by that: the route dies on `ensure_questions_editable` (409) the moment any +/// attempt exists, and answers only exist under attempts. +#[tokio::test] +async fn refreshing_a_question_recopies_its_template() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bref_t", "teacher").await; + let manager = login_as(&app, &db, "bref_m", "manager").await; + let course = create_course(&app, &teacher, "bref_c").await; + let subject = create_subject(&app, &teacher, &course, "bref_s").await; + + // A template with an illustration and a picture on its first option. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "capitol of France?", "kind": "choice", + "points": 5, "choices": [{"id": "a", "text": "Paris"}, {"id": "b", "text": "Lyon"}], + "correct": "a" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + let keep_choice = choice_of(&res.body, 0); + let drop_choice = choice_of(&res.body, 1); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/image"), + "image/png", + b"old-illustration", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/choices/{drop_choice}/image"), + "image/png", + b"lyon-picture", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let qid = id_of(&res.body); + + // The exam copy drifts (a local edit), and the template is fixed and + // reshaped: the typo goes, "Lyon" is replaced by a new option (a new id), + // points change, and the illustration is replaced. + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{qid}"), + Some(&teacher), + Some(json!({ "text": "local edit that will be lost", "points": 99 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/bank-questions/{bid}"), + Some(&teacher), + Some(json!({ "text": "capital of France?", "points": 7, + "choices": [{"id": keep_choice, "text": "Paris"}, {"id": "new", "text": "Marseille"}], + "correct": keep_choice })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let fresh_choice = choice_of(&res.body, 1); + assert_ne!(fresh_choice, drop_choice, "the replaced option is a new id"); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/image"), + "image/png", + b"new-illustration", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + // A template the caller cannot see is a 404 on this route too — never a + // 403, which would confirm it exists. (A manager may manage the course but + // is not the template's owner, and the template is private.) + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + + // The refresh itself: content, points, choices (ids and all), and correct + // come back from the template; the local edit is gone. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["id"], qid, "the question keeps its id"); + assert_eq!(res.body["text"], "capital of France?"); + assert_eq!(res.body["points"], 7); + assert_eq!(res.body["subject"], subject, "the exam-side subject stays"); + assert_eq!(res.body["from_bank"], bid, "provenance survives"); + assert_eq!(choice_of(&res.body, 0), keep_choice, "template choice ids adopted"); + assert_eq!(choice_of(&res.body, 1), fresh_choice); + assert_eq!(res.body["choices"][1]["text"], "Marseille"); + assert_eq!(res.body["correct"], keep_choice); + // Pictures match the template: the new illustration landed, and the + // dropped option's picture is gone rather than orphaned on a stale slot. + assert_eq!(res.body["image"]["content_type"], "image/png", "{}", res.body); + assert!(res.body["choice_images"][0].is_null(), "{}", res.body); + assert!(res.body["choice_images"][1].is_null(), "{}", res.body); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/exams/{exam}/questions/{qid}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, b"new-illustration", "the blob was re-copied, not kept"); + // No orphan blob rows left behind by the dropped option. + assert_eq!(image_blob_keys(&db).await.len(), 1); + + // A hand-authored question has nothing to refresh from — 400, not a 404 + // that would read as "your exam is gone". + let plain = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "mine alone", "kind": "text", "points": 1 }), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{plain}/refresh-from-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // Once a student sits an exam, its questions freeze — the refresh answers + // to the same guard as every other question mutation. + let now = Timestamp::now().as_millis(); + let live = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "live", "kind": "final", "mode": "sync", + "starts_at": now - 1_000, "ends_at": now + 600_000 }), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{live}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let live_qid = id_of(&res.body); + let student = login(&app, "bref_s").await; + let student_id = me_id(&app, &student).await; + enroll(&app, &teacher, &course, &student_id).await; + let res = send(&app, "POST", &format!("/exams/{live}/attempt"), Some(&student), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{live}/questions/{live_qid}/refresh-from-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // Deleting the template clears `from_bank`, so the copy has nothing left to + // refresh from — the action stops existing rather than half-working. + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/exams/{exam}/questions"), + Some(&teacher), + None, + ) + .await; + let refreshed = common::items(&res.body) + .iter() + .find(|item| id_of(item) == qid) + .cloned() + .unwrap(); + assert!(refreshed["from_bank"].is_null(), "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{qid}/refresh-from-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} diff --git a/tests/persistence.rs b/tests/persistence.rs index c2c8faa..996eaec 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -350,12 +350,14 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() { Some(&cookie), Some( json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", - "points": 10, "choices": ["3", "4"], "correct": 1 }), + "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }), ), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let question_id = common::id_of(&res.body); + // Choice ids are minted server-side, so the answer names one off the response. + let picked = res.body["choices"][1]["id"].as_str().expect("choice id").to_string(); let res = send( &app, "POST", @@ -370,7 +372,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() { "POST", &format!("/exams/{exam_id}/attempt/answers"), Some(&student_cookie), - Some(json!({ "question_id": question_id, "selected": 1 })), + Some(json!({ "question_id": question_id, "selected": picked })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body);