forge
Explore
Log in

Don't you dare go Hollow

🏦 choice identity, bank visibility, and whole-row save races

Browse files at this commit

ca93ae9ae52f8b53217ecd8a43779bee0991d7cfAhmet Kaan GümüşParent: ebbd813
  • fix
    • 🏦 choice identity, bank visibility, and whole-row save races
Show full message
fix: 🏦 choice identity, bank visibility, and whole-row save races

- 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

26 changed files +3864 -746

Cargo.lockmodified+78 -1
@@ -433,6 +433,21 @@ dependencies = [
433 "virtue",433 "virtue",
434 ]434 ]
435 435
436+[[package]]
437+name = "bit-set"
438+version = "0.8.0"
439+source = "registry+https://github.com/rust-lang/crates.io-index"
440+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
441+dependencies = [
442+ "bit-vec 0.8.0",
443+]
444+
445+[[package]]
446+name = "bit-vec"
447+version = "0.8.0"
448+source = "registry+https://github.com/rust-lang/crates.io-index"
449+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
450+
436 [[package]]451 [[package]]
437 name = "bit-vec"452 name = "bit-vec"
438 version = "0.9.1"453 version = "0.9.1"
@@ -1782,6 +1797,7 @@ dependencies = [
1782 "futures-util",1797 "futures-util",
1783 "getrandom 0.4.3",1798 "getrandom 0.4.3",
1784 "hex",1799 "hex",
1800+ "proptest",
1785 "quinn",1801 "quinn",
1786 "rcgen",1802 "rcgen",
1787 "reqwest",1803 "reqwest",
@@ -2963,6 +2979,25 @@ dependencies = [
2963 "unicode-ident",2979 "unicode-ident",
2964 ]2980 ]
2965 2981
2982+[[package]]
2983+name = "proptest"
2984+version = "1.11.0"
2985+source = "registry+https://github.com/rust-lang/crates.io-index"
2986+checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
2987+dependencies = [
2988+ "bit-set",
2989+ "bit-vec 0.8.0",
2990+ "bitflags",
2991+ "num-traits",
2992+ "rand 0.9.5",
2993+ "rand_chacha 0.9.0",
2994+ "rand_xorshift",
2995+ "regex-syntax",
2996+ "rusty-fork",
2997+ "tempfile",
2998+ "unarray",
2999+]
3000+
2966 [[package]]3001 [[package]]
2967 name = "prost"3002 name = "prost"
2968 version = "0.14.4"3003 version = "0.14.4"
@@ -3031,6 +3066,12 @@ dependencies = [
3031 "psl-types",3066 "psl-types",
3032 ]3067 ]
3033 3068
3069+[[package]]
3070+name = "quick-error"
3071+version = "1.2.3"
3072+source = "registry+https://github.com/rust-lang/crates.io-index"
3073+checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"
3074+
3034 [[package]]3075 [[package]]
3035 name = "quick_cache"3076 name = "quick_cache"
3036 version = "0.6.24"3077 version = "0.6.24"
@@ -3221,6 +3262,15 @@ dependencies = [
3221 "rand_core 0.10.1",3262 "rand_core 0.10.1",
3222 ]3263 ]
3223 3264
3265+[[package]]
3266+name = "rand_xorshift"
3267+version = "0.4.0"
3268+source = "registry+https://github.com/rust-lang/crates.io-index"
3269+checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a"
3270+dependencies = [
3271+ "rand_core 0.9.5",
3272+]
3273+
3224 [[package]]3274 [[package]]
3225 name = "rawpointer"3275 name = "rawpointer"
3226 version = "0.2.1"3276 version = "0.2.1"
@@ -3694,6 +3744,18 @@ version = "1.0.23"
3694 source = "registry+https://github.com/rust-lang/crates.io-index"3744 source = "registry+https://github.com/rust-lang/crates.io-index"
3695 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"3745 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
3696 3746
3747+[[package]]
3748+name = "rusty-fork"
3749+version = "0.3.1"
3750+source = "registry+https://github.com/rust-lang/crates.io-index"
3751+checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2"
3752+dependencies = [
3753+ "fnv",
3754+ "quick-error",
3755+ "tempfile",
3756+ "wait-timeout",
3757+]
3758+
3697 [[package]]3759 [[package]]
3698 name = "ryu"3760 name = "ryu"
3699 version = "1.0.23"3761 version = "1.0.23"
@@ -4889,6 +4951,12 @@ dependencies = [
4889 "web-time",4951 "web-time",
4890 ]4952 ]
4891 4953
4954+[[package]]
4955+name = "unarray"
4956+version = "0.1.4"
4957+source = "registry+https://github.com/rust-lang/crates.io-index"
4958+checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
4959+
4892 [[package]]4960 [[package]]
4893 name = "unicase"4961 name = "unicase"
4894 version = "2.9.0"4962 version = "2.9.0"
@@ -5040,6 +5108,15 @@ version = "0.0.18"
5040 source = "registry+https://github.com/rust-lang/crates.io-index"5108 source = "registry+https://github.com/rust-lang/crates.io-index"
5041 checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1"5109 checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1"
5042 5110
5111+[[package]]
5112+name = "wait-timeout"
5113+version = "0.2.1"
5114+source = "registry+https://github.com/rust-lang/crates.io-index"
5115+checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
5116+dependencies = [
5117+ "libc",
5118+]
5119+
5043 [[package]]5120 [[package]]
5044 name = "walkdir"5121 name = "walkdir"
5045 version = "2.5.0"5122 version = "2.5.0"
@@ -5490,7 +5567,7 @@ version = "0.6.0"
5490 source = "registry+https://github.com/rust-lang/crates.io-index"5567 source = "registry+https://github.com/rust-lang/crates.io-index"
5491 checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"5568 checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
5492 dependencies = [5569 dependencies = [
5493- "bit-vec",5570+ "bit-vec 0.9.1",
5494 "time",5571 "time",
5495 ]5572 ]
5496 5573
Cargo.tomlmodified+1 -0
@@ -51,3 +51,4 @@ reqwest = { version = "0.13", default-features = false, features = ["json", "coo
51 tempfile = "3"51 tempfile = "3"
52 tokio-tungstenite = "0.30.0"52 tokio-tungstenite = "0.30.0"
53 futures-util = "0.3.32"53 futures-util = "0.3.32"
54+proptest = "1.11.0"
proptest-regressions/domain/exam_question.txtadded+7 -0
@@ -0,0 +1,7 @@
1+# Seeds for failure cases proptest has generated in the past. It is
2+# automatically read and these particular cases re-run before any
3+# novel cases are generated.
4+#
5+# It is recommended to check this file in to source control so that
6+# everyone who runs the test benefits from these saved cases.
7+cc 1cbabc252057de3029f0cd3a1c557f98551848dcbaedcd44b03c331f0ed27ec5 # shrinks to stored_n = 6, submitted = [(Other(""), "a"), (Stored(0), "a")], correct = Some(Null)
scripts/check-whole-row-saves.shadded+59 -0
@@ -0,0 +1,59 @@
1+#!/bin/sh
2+# Ban whole-row saves: `db.update(...).content(self)` and friends.
3+#
4+# WHY: `.content(self)` REPLACES the entire stored row with the in-memory
5+# struct. If `self` was loaded before an `.await` (a permission check, another
6+# query, an HTTP/QUIC call), any concurrent PATCH that landed in between is
7+# silently reverted — the write succeeds, the other user's change is gone, no
8+# error anywhere. A grep cannot see "read before an await", so the shape itself
9+# is banned and the exceptions are made explicit and reviewable.
10+#
11+# FIX: write only the fields the request actually changed, e.g.
12+# db.query("UPDATE $id SET text = $text, points = $points")
13+# or hold a lock across the whole read-modify-write and opt out below.
14+#
15+# OPT OUT: put this on the line IMMEDIATELY above the call:
16+# // whole-row-save-ok: <why this row cannot be raced>
17+#
18+# Usage:
19+# scripts/check-whole-row-saves.sh # whole tree (gate mode)
20+# scripts/check-whole-row-saves.sh a.rs b.rs # only these files (hook mode)
21+# Exit 1 if any unannotated whole-row save is found.
22+
23+cd "$(dirname "$0")/.." || exit 1
24+
25+if [ "$#" -gt 0 ]; then
26+ set -- "$@"
27+else
28+ # shellcheck disable=SC2046 # paths in this repo have no spaces
29+ set -- $(find src -name '*.rs' | sort)
30+fi
31+[ "$#" -eq 0 ] && exit 0
32+
33+awk '
34+FNR == 1 { prev = "" }
35+/\.content\(&?self[).]/ {
36+ if (prev !~ /\/\/[ \t]*whole-row-save-ok:[ \t]*[^ \t]/) {
37+ sub(/^[ \t]+/, "", $0)
38+ printf "%s:%d: %s\n", FILENAME, FNR, $0
39+ bad++
40+ }
41+}
42+{ prev = $0 }
43+END {
44+ if (bad) {
45+ print ""
46+ print "whole-row save: .content(self) replaces the ENTIRE row, so any"
47+ print "concurrent PATCH that landed after this struct was read (i.e."
48+ print "across any .await above) is silently reverted — no error, data"
49+ print "just disappears. Write only the changed fields instead:"
50+ print " db.query(\"UPDATE $id SET field = $field\")"
51+ print "If the row genuinely cannot be raced (e.g. a write lock is held"
52+ print "across the read and the write), opt out on the line directly above:"
53+ print " // whole-row-save-ok: <why this row cannot be raced>"
54+ print ""
55+ printf "%d unannotated whole-row save(s).\n", bad
56+ exit 1
57+ }
58+}
59+' "$@"
src/database.rsmodified+42 -9
@@ -273,17 +273,34 @@ const MIGRATION: &str = "
273 DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;273 DEFINE FIELD IF NOT EXISTS text ON exam_question TYPE string;
274 DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;274 DEFINE FIELD IF NOT EXISTS kind ON exam_question TYPE string;
275 DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;275 DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int;
276- DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>;276+ -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
277- DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>;277+ -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
278+ -- and IF NOT EXISTS would leave an existing database on the old types.
279+ DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<object>>;
280+ -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
281+ -- object's own fields are declared too (same shape as `settings.exam_kinds`).
282+ DEFINE FIELD OVERWRITE choices.*.id ON exam_question TYPE string;
283+ DEFINE FIELD OVERWRITE choices.*.text ON exam_question TYPE string;
284+ DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<string>;
278 DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;285 DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>;
279- DEFINE FIELD IF NOT EXISTS source_bank ON exam_question TYPE option<record<bank_question>>;286+ -- Provenance, one column per direction: `from_bank` is the template this
287+ -- question was inserted from, `banked_as` the template most recently minted
288+ -- by saving it into the bank. They replace the single `source_bank`, which
289+ -- both directions wrote — so a question inserted from the bank read as
290+ -- already-saved. OVERWRITE (not IF NOT EXISTS): the old column has to
291+ -- actually go on an existing database, or SCHEMAFULL keeps accepting it
292+ -- while the struct no longer writes it.
293+ DEFINE FIELD OVERWRITE from_bank ON exam_question TYPE option<record<bank_question>>;
294+ DEFINE FIELD OVERWRITE banked_as ON exam_question TYPE option<record<bank_question>>;
295+ REMOVE FIELD IF EXISTS source_bank ON TABLE exam_question;
280 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;296 DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam;
281 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;297 DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject;
282 298
283 DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;299 DEFINE TABLE IF NOT EXISTS question_image SCHEMAFULL;
284 DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;300 DEFINE FIELD IF NOT EXISTS exam ON question_image TYPE record<exam>;
285 DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;301 DEFINE FIELD IF NOT EXISTS question ON question_image TYPE record<exam_question>;
286- DEFINE FIELD IF NOT EXISTS slot ON question_image TYPE option<int>;302+ -- OVERWRITE: `slot` is now the choice's id, not its position.
303+ DEFINE FIELD OVERWRITE slot ON question_image TYPE option<string>;
287 DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;304 DEFINE FIELD IF NOT EXISTS file ON question_image TYPE string;
288 DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;305 DEFINE FIELD IF NOT EXISTS content_type ON question_image TYPE string;
289 DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;306 DEFINE FIELD IF NOT EXISTS size ON question_image TYPE int;
@@ -292,20 +309,35 @@ const MIGRATION: &str = "
292 309
293 DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;310 DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL;
294 DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;311 DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>;
295- DEFINE FIELD IF NOT EXISTS subject ON bank_question TYPE record<subject>;312+ -- OVERWRITE, not IF NOT EXISTS: the field started life as a required
313+ -- `record<subject>` and has to actually change type on an existing database,
314+ -- otherwise the subject-delete cascade (`SET subject = NONE`) is rejected.
315+ DEFINE FIELD OVERWRITE subject ON bank_question TYPE option<record<subject>>;
296 DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;316 DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string;
297 DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;317 DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string;
298 DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;318 DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int;
299- DEFINE FIELD IF NOT EXISTS choices ON bank_question TYPE option<array<string>>;319+ -- OVERWRITE, not IF NOT EXISTS: these columns changed type when choices
300- DEFINE FIELD IF NOT EXISTS correct ON bank_question TYPE option<int>;320+ -- gained stable ids (`array<string>`/`int` -> `array<object>`/`string`),
321+ -- and IF NOT EXISTS would leave an existing database on the old types.
322+ DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<object>>;
323+ -- SCHEMAFULL rejects any nested key it wasn't told about, so the choice
324+ -- object's own fields are declared too (same shape as `settings.exam_kinds`).
325+ DEFINE FIELD OVERWRITE choices.*.id ON bank_question TYPE string;
326+ DEFINE FIELD OVERWRITE choices.*.text ON bank_question TYPE string;
327+ DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<string>;
301 DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;328 DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>;
329+ -- 'private' | 'school'. DEFAULT so a row that predates the field (or any
330+ -- partial write) can never come out published: the answer key stays the
331+ -- owner's until they publish it.
332+ DEFINE FIELD IF NOT EXISTS visibility ON bank_question TYPE string DEFAULT 'private';
302 DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;333 DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY;
303 DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;334 DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner;
304 DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;335 DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject;
305 336
306 DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;337 DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL;
307 DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;338 DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>;
308- DEFINE FIELD IF NOT EXISTS slot ON bank_question_image TYPE option<int>;339+ -- OVERWRITE: `slot` is now the choice's id, not its position.
340+ DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<string>;
309 DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;341 DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string;
310 DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;342 DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string;
311 DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;343 DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int;
@@ -315,7 +347,8 @@ const MIGRATION: &str = "
315 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;347 DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>;
316 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;348 DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>;
317 DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;349 DEFINE FIELD IF NOT EXISTS user ON exam_answer TYPE record<user>;
318- DEFINE FIELD IF NOT EXISTS selected ON exam_answer TYPE option<int>;350+ -- OVERWRITE: `selected` now names the picked option by id.
351+ DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<string>;
319 DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;352 DEFINE FIELD IF NOT EXISTS text ON exam_answer TYPE option<string>;
320 DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;353 DEFINE FIELD IF NOT EXISTS updated_at ON exam_answer TYPE int;
321 -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring354 -- `seq` numbers the sitting an answer belongs to (1, 2, …), mirroring
src/domain/appointment_slot.rsmodified+5 -20
@@ -9,14 +9,12 @@
9 //! time. Cancelling one week is then a plain row delete, and the whole series9 //! time. Cancelling one week is then a plain row delete, and the whole series
10 //! is still addressable through its id.10 //! is still addressable through its id.
11 11
12-use std::sync::{LazyLock, Mutex};
13-
14 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};12 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
15-use ulid::{Generator, Ulid};
16 13
17 use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES};14 use crate::constant::{MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES};
18 use crate::database::{APPOINTMENT_SLOT_TABLE, Database};15 use crate::database::{APPOINTMENT_SLOT_TABLE, Database};
19 use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment};16 use crate::domain::appointment::{APPOINTMENT_LOCK, Appointment};
17+use crate::domain::monotonic_id::next_ulid;
20 use crate::domain::timestamp::{MILLIS_PER_DAY, Timestamp};18 use crate::domain::timestamp::{MILLIS_PER_DAY, Timestamp};
21 use crate::domain::user::UserId;19 use crate::domain::user::UserId;
22 use crate::error::{AppError, ValidationError};20 use crate::error::{AppError, ValidationError};
@@ -25,23 +23,10 @@ use crate::validate::validate_optional;
25 /// One week, the only recurrence step this backend expands.23 /// One week, the only recurrence step this backend expands.
26 const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;24 const MILLIS_PER_WEEK: i64 = 7 * MILLIS_PER_DAY;
27 25
28-/// Mints slot ids in write order. `Ulid::new()`'s random low bits sort26+// Slot ids come from [`crate::domain::monotonic_id`]: a recurring publish
29-/// arbitrarily among ids minted in the same millisecond, and a recurring27+// writes its whole expansion inside one millisecond, which random ULID low
30-/// publish writes its whole expansion inside one — which would scramble the28+// bits would scramble against the `id` tie-break of the `ORDER BY starts_at,
31-/// `id` tie-break of the `ORDER BY starts_at, id` listings.29+// id` listings.
32-static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
33-
34-fn next_ulid() -> Ulid {
35- let mut ids = IDS.lock().expect("slot id generator poisoned");
36- // The only error is exhausting the random bits *within* one millisecond
37- // (2^80 ids deep); it clears itself as the clock ticks, so retry rather
38- // than fall back to a random id and silently reintroduce the defect.
39- loop {
40- if let Ok(ulid) = ids.generate() {
41- break ulid;
42- }
43- }
44-}
45 30
46 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]31 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
47 pub struct AppointmentSlotId(RecordId);32 pub struct AppointmentSlotId(RecordId);
src/domain/bank_question.rsmodified+603 -60
@@ -7,25 +7,87 @@
7 //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants7 //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants
8 //! because every write goes through one.8 //! because every write goes through one.
9 9
10+use std::collections::HashMap;
11+
10 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};12 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
11-use ulid::Ulid;
12 13
13 use crate::database::{BANK_QUESTION_TABLE, Database};14 use crate::database::{BANK_QUESTION_TABLE, Database};
14 use crate::domain::exam::ExamId;15 use crate::domain::exam::ExamId;
15 use crate::domain::exam_question::{16 use crate::domain::exam_question::{
16- ChoiceText, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,17+ Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
17 };18 };
19+use crate::domain::monotonic_id::next_ulid;
18 use crate::domain::subject::SubjectId;20 use crate::domain::subject::SubjectId;
21+use crate::domain::text_fold::{fold, fold_sql};
19 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::UserId;23 use crate::domain::user::UserId;
21-use crate::error::AppError;24+use crate::error::{AppError, ValidationError};
25+
26+/// Who may see a template. `private` — the owner (and admins) alone; `school` —
27+/// every teacher.
28+///
29+/// **The default is `private`, deliberately.** A template carries `correct`, the
30+/// answer key, and its images: publishing one is an explicit act, never a side
31+/// effect of saving a question to the bank. `#[surreal(default)]` on the field
32+/// means rows written before this existed decode as `private` too, so the bank
33+/// can't retroactively broadcast anyone's answer keys.
34+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
35+pub struct BankVisibility(String);
36+
37+impl Default for BankVisibility {
38+ fn default() -> Self {
39+ Self(Self::PRIVATE.to_string())
40+ }
41+}
42+
43+impl BankVisibility {
44+ pub const PRIVATE: &'static str = "private";
45+ pub const SCHOOL: &'static str = "school";
46+
47+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
48+ if value != Self::PRIVATE && value != Self::SCHOOL {
49+ return Err(ValidationError::Invalid {
50+ field: "visibility",
51+ reason: "must be private or school",
52+ });
53+ }
54+ Ok(Self(value.to_string()))
55+ }
56+
57+ pub fn as_str(&self) -> &str {
58+ &self.0
59+ }
60+
61+ /// Whether the template is published to the whole school.
62+ pub fn is_school(&self) -> bool {
63+ self.0 == Self::SCHOOL
64+ }
65+}
22 66
23 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]67 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
24 pub struct BankQuestionId(RecordId);68 pub struct BankQuestionId(RecordId);
25 69
70+/// The whole of [`BankQuestion::usage_counts`]: **one** statement (no `;`),
71+/// so a page of templates costs one round trip no matter how long it is. Named
72+/// so a test can assert that, since a per-row `count()` is exactly the N+1 this
73+/// page was cleaned of once.
74+const USAGE_COUNTS_SQL: &str =
75+ "SELECT from_bank, count() AS n FROM exam_question WHERE from_bank IN $ids GROUP BY from_bank";
76+
77+/// One `GROUP BY from_bank` row of [`BankQuestion::usage_counts`].
78+#[derive(SurrealValue)]
79+struct UsageCount {
80+ from_bank: BankQuestionId,
81+ n: i64,
82+}
83+
26 impl BankQuestionId {84 impl BankQuestionId {
85+ /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and
86+ /// a random ULID is only millisecond-accurate — templates saved inside one
87+ /// tick (a to-bank burst, a test loop) would come back shuffled, so the id
88+ /// comes from [`crate::domain::monotonic_id`] instead.
27 pub fn generate() -> Self {89 pub fn generate() -> Self {
28- Self(RecordId::new(BANK_QUESTION_TABLE, Ulid::new().to_string()))90+ Self(RecordId::new(BANK_QUESTION_TABLE, next_ulid().to_string()))
29 }91 }
30 92
31 pub fn from_key(key: &str) -> Self {93 pub fn from_key(key: &str) -> Self {
@@ -48,18 +110,33 @@ impl BankQuestionId {
48 /// it (the only one who may edit or delete it, admins aside); `subject` is110 /// it (the only one who may edit or delete it, admins aside); `subject` is
49 /// origin metadata only — the same-course rule is checked against the caller's111 /// origin metadata only — the same-course rule is checked against the caller's
50 /// subject when a template is copied into an exam, not here.112 /// subject when a template is copied into an exam, not here.
113+///
114+/// `subject` is optional because it is *only* metadata: deleting a subject
115+/// clears it school-wide (see [`crate::domain::subject::Subject::delete`])
116+/// rather than being blocked by the bank. Blocking would have been a dead end
117+/// — the bank is owner-or-admin editable, so a manager could not resolve their
118+/// own 409 — and an existence oracle, since another teacher's *private*
119+/// template would have raised it.
51 #[derive(Debug, Clone, SurrealValue)]120 #[derive(Debug, Clone, SurrealValue)]
52 pub struct BankQuestion {121 pub struct BankQuestion {
53 id: BankQuestionId,122 id: BankQuestionId,
54 owner: UserId,123 owner: UserId,
55- subject: SubjectId,124+ /// The origin subject, or `None` once that subject was deleted.
125+ /// `#[surreal(default)]` for the same reason `visibility` has one: rows
126+ /// written before the field went optional still decode.
127+ #[surreal(default)]
128+ subject: Option<SubjectId>,
56 text: QuestionText,129 text: QuestionText,
57 kind: QuestionKind,130 kind: QuestionKind,
58 points: QuestionPoints,131 points: QuestionPoints,
59- choices: Option<Vec<ChoiceText>>,132+ choices: Option<Vec<Choice>>,
60- correct: Option<i64>,133+ correct: Option<ChoiceId>,
61 /// The exam question this template was saved from, if any.134 /// The exam question this template was saved from, if any.
62 source_exam: Option<ExamId>,135 source_exam: Option<ExamId>,
136+ /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile
137+ /// here): rows written before the field existed decode as `private`.
138+ #[surreal(default)]
139+ visibility: BankVisibility,
63 created_at: Timestamp,140 created_at: Timestamp,
64 }141 }
65 142
@@ -72,8 +149,8 @@ impl BankQuestion {
72 &self.owner149 &self.owner
73 }150 }
74 151
75- pub fn get_subject(&self) -> &SubjectId {152+ pub fn get_subject(&self) -> Option<&SubjectId> {
76- &self.subject153+ self.subject.as_ref()
77 }154 }
78 155
79 pub fn get_text(&self) -> &QuestionText {156 pub fn get_text(&self) -> &QuestionText {
@@ -88,36 +165,33 @@ impl BankQuestion {
88 self.points165 self.points
89 }166 }
90 167
91- pub fn get_choices(&self) -> Option<&[ChoiceText]> {168+ pub fn get_choices(&self) -> Option<&[Choice]> {
92 self.choices.as_deref()169 self.choices.as_deref()
93 }170 }
94 171
95- pub fn get_correct(&self) -> Option<i64> {172+ pub fn get_correct(&self) -> Option<&ChoiceId> {
96- self.correct173+ self.correct.as_ref()
97 }174 }
98 175
99 pub fn get_source_exam(&self) -> Option<&ExamId> {176 pub fn get_source_exam(&self) -> Option<&ExamId> {
100 self.source_exam.as_ref()177 self.source_exam.as_ref()
101 }178 }
102 179
180+ pub fn get_visibility(&self) -> &BankVisibility {
181+ &self.visibility
182+ }
183+
103 pub fn get_created_at(&self) -> Timestamp {184 pub fn get_created_at(&self) -> Timestamp {
104 self.created_at185 self.created_at
105 }186 }
106 187
107 /// The stored kind-dependent fields as the validated bundle (for188 /// The stored kind-dependent fields as the validated bundle (for
108- /// merge-on-update). Bypasses `try_new`: the fields were written through a189+ /// merge-on-update, and for copying into an exam). Bypasses `try_new`: the
109- /// `QuestionSpec`, so the invariants already hold.190+ /// fields were written through a `QuestionSpec`, so the invariants already
191+ /// hold — and a round-trip through `try_new` would mint *new* choice ids,
192+ /// detaching the copy's `correct` and option pictures from its choices.
110 pub fn spec(&self) -> QuestionSpec {193 pub fn spec(&self) -> QuestionSpec {
111- // `QuestionSpec` fields are private; rebuild through `try_new`, which194+ QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone())
112- // the stored values are guaranteed to satisfy.
113- QuestionSpec::try_new(
114- self.kind.clone(),
115- self.choices
116- .as_ref()
117- .map(|cs| cs.iter().map(|c| c.as_str().to_string()).collect()),
118- self.correct,
119- )
120- .expect("stored bank question fields satisfy the spec invariants")
121 }195 }
122 196
123 pub async fn create(197 pub async fn create(
@@ -158,11 +232,15 @@ impl BankQuestion {
158 let question = BankQuestion::from_parts(232 let question = BankQuestion::from_parts(
159 BankQuestionId::generate(),233 BankQuestionId::generate(),
160 owner,234 owner,
161- subject,235+ // Creation always carries a validated subject; only a subject
236+ // delete ever clears it.
237+ Some(subject),
162 text,238 text,
163 points,239 points,
164 spec,240 spec,
165 source_exam,241 source_exam,
242+ // Never published on creation — publishing is its own PATCH.
243+ BankVisibility::default(),
166 Timestamp::now(),244 Timestamp::now(),
167 );245 );
168 let created: Option<BankQuestion> =246 let created: Option<BankQuestion> =
@@ -170,62 +248,193 @@ impl BankQuestion {
170 created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))248 created.ok_or_else(|| AppError::Internal("failed to create bank question".into()))
171 }249 }
172 250
173- /// Whether any bank template references `subject` as its origin — the gate
174- /// that blocks deleting a subject still used by a template.
175- pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> {
176- let mut result = db
177- .query("SELECT VALUE id FROM bank_question WHERE subject = $subject LIMIT 1")
178- .bind(("subject", subject.record()))
179- .await?
180- .check()?;
181- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
182- }
183-
184 pub async fn read(id: &BankQuestionId, db: &Database) -> Result<Option<BankQuestion>, AppError> {251 pub async fn read(id: &BankQuestionId, db: &Database) -> Result<Option<BankQuestion>, AppError> {
185 Ok(db.select(id.record()).await?)252 Ok(db.select(id.record()).await?)
186 }253 }
187 254
188- /// Every template in the bank, school-wide (no owner filter), in creation255+ /// One page of the bank the caller may see, **newest first** (ULID ids sort by
189- /// order (ULID ids sort by creation).256+ /// creation, so `id DESC` is newest-first) — plus the total row count under
190- pub async fn list(db: &Database) -> Result<Vec<BankQuestion>, AppError> {257+ /// the same filters, so a client can page past the window.
258+ ///
259+ /// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`:
260+ /// the old version read the whole table and sliced it in memory, which hid
261+ /// every template past the client's first page. `q` is a case- and
262+ /// diacritic-insensitive fragment of the question text (blank = no text
263+ /// filter): needle and column both go through
264+ /// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back.
265+ ///
266+ /// `visible_to` is the security filter, and it is a WHERE clause like every
267+ /// other one — never a post-filter, or `total` would count templates the
268+ /// caller can't have and paging would return short pages of them:
269+ /// `Some(me)` sees the school-published templates plus their own,
270+ /// `None` (admins only) sees everything.
271+ ///
272+ /// `visibility` is the *user's* filter ("only mine" / "shared with the
273+ /// school") and is ANDed on top of that gate, so it can only ever narrow:
274+ /// `school` still hides another teacher's private rows, and `private`
275+ /// intersected with the gate leaves exactly the caller's own drafts. It
276+ /// joins the same `clauses` vec as the rest, so `total` honours it too —
277+ /// a count that ignored it would break paging.
278+ // Flat filter args, like every other `list` here — a builder struct for
279+ // four `Option`s and a window would be more machinery than the call sites.
280+ #[allow(clippy::too_many_arguments)]
281+ pub async fn list(
282+ visible_to: Option<&UserId>,
283+ owner: Option<&UserId>,
284+ subject: Option<&SubjectId>,
285+ visibility: Option<&BankVisibility>,
286+ q: Option<&str>,
287+ limit: Option<i64>,
288+ offset: i64,
289+ db: &Database,
290+ ) -> Result<(Vec<BankQuestion>, i64), AppError> {
291+ let needle = q.map(|q| fold(q.trim())).filter(|q| !q.is_empty());
292+ let mut clauses = Vec::new();
293+ if visible_to.is_some() {
294+ clauses.push("(visibility = 'school' OR owner = $viewer)");
295+ }
296+ if visibility.is_some() {
297+ clauses.push("visibility = $visibility");
298+ }
299+ if owner.is_some() {
300+ clauses.push("owner = $owner");
301+ }
302+ if subject.is_some() {
303+ clauses.push("subject = $subject");
304+ }
305+ let text_clause = format!("{} CONTAINS $q", fold_sql("text"));
306+ if needle.is_some() {
307+ clauses.push(text_clause.as_str());
308+ }
309+ let where_clause = if clauses.is_empty() {
310+ "true".to_string()
311+ } else {
312+ clauses.join(" AND ")
313+ };
314+ // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in.
315+ let window = match limit {
316+ Some(_) => "LIMIT $limit START $offset",
317+ None => "START $offset",
318+ };
319+ // The count runs over the *same* WHERE, so `total` can never disagree
320+ // with what paging through the list actually yields.
321+ let mut query = db
322+ .query(format!(
323+ "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window};
324+ SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;"
325+ ))
326+ .bind(("offset", offset));
327+ if let Some(viewer) = visible_to {
328+ query = query.bind(("viewer", viewer.record()));
329+ }
330+ if let Some(visibility) = visibility {
331+ query = query.bind(("visibility", visibility.as_str().to_string()));
332+ }
333+ if let Some(owner) = owner {
334+ query = query.bind(("owner", owner.record()));
335+ }
336+ if let Some(subject) = subject {
337+ query = query.bind(("subject", subject.record()));
338+ }
339+ if let Some(needle) = needle {
340+ query = query.bind(("q", needle));
341+ }
342+ if let Some(limit) = limit {
343+ query = query.bind(("limit", limit));
344+ }
345+ let mut result = query.await?.check()?;
346+ let questions = result.take::<Vec<BankQuestion>>(0)?;
347+ // `GROUP ALL` yields no row at all when nothing matched.
348+ let total = result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0);
349+ Ok((questions, total))
350+ }
351+
352+ /// How many exam questions were instantiated from each of `ids` — the
353+ /// `from_bank` side of the provenance link, tallied for a whole page in
354+ /// **one** grouped query (a `count()` per row would be the N+1 this page
355+ /// already had removed once). Keys are template record keys; a template
356+ /// nobody ever used has no entry at all, so the caller reads a miss as
357+ /// zero — and the UI can stay quiet rather than print "0".
358+ ///
359+ /// Counts *questions*, not distinct exams: one exam that inserted the same
360+ /// template twice counts twice, which is what "copies made from this
361+ /// template" means and what the divergence trap is actually about.
362+ pub async fn usage_counts(
363+ ids: &[&BankQuestionId],
364+ db: &Database,
365+ ) -> Result<HashMap<String, i64>, AppError> {
366+ if ids.is_empty() {
367+ return Ok(HashMap::new());
368+ }
369+ let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
191 let mut result = db370 let mut result = db
192- .query("SELECT * FROM bank_question ORDER BY id ASC")371+ .query(USAGE_COUNTS_SQL)
372+ .bind(("ids", records))
193 .await?373 .await?
194 .check()?;374 .check()?;
195- Ok(result.take::<Vec<BankQuestion>>(0)?)375+ Ok(result
376+ .take::<Vec<UsageCount>>(0)?
377+ .into_iter()
378+ .map(|row| (row.from_bank.key().to_string(), row.n))
379+ .collect())
196 }380 }
197 381
382+ /// Write the editable fields of the template.
383+ ///
384+ /// Field-scoped, never a whole-row content-replace save: the handler reads
385+ /// the row, then awaits an ownership check and a subject lookup before
386+ /// getting here, so a concurrent PATCH (or the subject-delete cascade that
387+ /// clears `subject`) can land inside that window — a whole-row save would
388+ /// silently revert it. Same shape, same reason as
389+ /// [`crate::domain::exam_question::ExamQuestion::link_banked_as`].
198 pub async fn update(390 pub async fn update(
199- mut self,391+ self,
200- subject: SubjectId,392+ subject: Option<SubjectId>,
201 text: QuestionText,393 text: QuestionText,
202 points: QuestionPoints,394 points: QuestionPoints,
203 spec: QuestionSpec,395 spec: QuestionSpec,
396+ visibility: BankVisibility,
204 db: &Database,397 db: &Database,
205 ) -> Result<BankQuestion, AppError> {398 ) -> Result<BankQuestion, AppError> {
206- self.subject = subject;
207- self.text = text;
208- self.points = points;
209 let (kind, choices, correct) = spec.into_parts();399 let (kind, choices, correct) = spec.into_parts();
210- self.kind = kind;400+ let mut result = db
211- self.choices = choices;401+ .query(
212- self.correct = correct;402+ "UPDATE $id SET subject = $subject, text = $text, points = $points,
213- let updated: Option<BankQuestion> = db.update(self.id.record()).content(self).await?;403+ kind = $kind, choices = $choices, correct = $correct,
214- updated.ok_or(AppError::NotFound)404+ visibility = $visibility RETURN AFTER",
405+ )
406+ .bind(("id", self.id.record()))
407+ .bind(("subject", subject.map(|s| s.record())))
408+ .bind(("text", text))
409+ .bind(("points", points))
410+ .bind(("kind", kind))
411+ .bind(("choices", choices))
412+ .bind(("correct", correct))
413+ .bind(("visibility", visibility))
414+ .await?
415+ .check()?;
416+ result
417+ .take::<Vec<BankQuestion>>(0)?
418+ .into_iter()
419+ .next()
420+ .ok_or(AppError::NotFound)
215 }421 }
216 422
217 /// Delete the template and cascade-remove its bank images, so none points423 /// Delete the template and cascade-remove its bank images, so none points
218 /// at a missing template. Bank rows have no answers. The image *blobs* are424 /// at a missing template. Bank rows have no answers. The image *blobs* are
219 /// the web layer's to remove — it collects their names before calling this.425 /// the web layer's to remove — it collects their names before calling this.
220 ///426 ///
221- /// Exam questions saved from this template keep living: only their427+ /// Exam questions tied to this template keep living: only their provenance
222- /// `source_bank` provenance link is cleared, field-scoped (never a whole-row428+ /// links are cleared, field-scoped (never a whole-row save — the question
223- /// save — the question isn't ours and may be edited concurrently), so the429+ /// isn't ours and may be edited concurrently), so nothing can read a link to
224- /// bank page can't read a link to a template that no longer exists.430+ /// a template that no longer exists. *Both* directions point at a template,
431+ /// so both are cleared: `from_bank` on the questions instantiated from it,
432+ /// and `banked_as` on the question it was saved out of.
225 pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> {433 pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> {
226 db.query(434 db.query(
227 "DELETE bank_question_image WHERE bank_question = $b;435 "DELETE bank_question_image WHERE bank_question = $b;
228- UPDATE exam_question SET source_bank = NONE WHERE source_bank = $b;",436+ UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b;
437+ UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b;",
229 )438 )
230 .bind(("b", self.id.record()))439 .bind(("b", self.id.record()))
231 .await?440 .await?
@@ -238,11 +447,12 @@ impl BankQuestion {
238 fn from_parts(447 fn from_parts(
239 id: BankQuestionId,448 id: BankQuestionId,
240 owner: UserId,449 owner: UserId,
241- subject: SubjectId,450+ subject: Option<SubjectId>,
242 text: QuestionText,451 text: QuestionText,
243 points: QuestionPoints,452 points: QuestionPoints,
244 spec: QuestionSpec,453 spec: QuestionSpec,
245 source_exam: Option<ExamId>,454 source_exam: Option<ExamId>,
455+ visibility: BankVisibility,
246 created_at: Timestamp,456 created_at: Timestamp,
247 ) -> BankQuestion {457 ) -> BankQuestion {
248 let (kind, choices, correct) = spec.into_parts();458 let (kind, choices, correct) = spec.into_parts();
@@ -256,6 +466,7 @@ impl BankQuestion {
256 choices,466 choices,
257 correct,467 correct,
258 source_exam,468 source_exam,
469+ visibility,
259 created_at,470 created_at,
260 }471 }
261 }472 }
@@ -266,14 +477,272 @@ mod tests {
266 use super::*;477 use super::*;
267 478
268 fn spec() -> QuestionSpec {479 fn spec() -> QuestionSpec {
480+ use crate::domain::exam_question::ChoiceInput;
269 QuestionSpec::try_new(481 QuestionSpec::try_new(
270 QuestionKind::try_new("choice").unwrap(),482 QuestionKind::try_new("choice").unwrap(),
271- Some(vec!["yes".into(), "no".into()]),483+ Some(vec![
272- Some(1),484+ ChoiceInput { id: Some("a".into()), text: "yes".into() },
485+ ChoiceInput { id: Some("b".into()), text: "no".into() },
486+ ]),
487+ Some("b".into()),
488+ &[],
273 )489 )
274 .unwrap()490 .unwrap()
275 }491 }
276 492
493+ /// A row stored before `visibility` existed has no such key — it must decode
494+ /// as `private`, the safe value. Asserted on the decoder itself, so no
495+ /// schema DEFAULT can paper over it: a `school` default here would publish
496+ /// every pre-existing template in the school at once.
497+ #[tokio::test]
498+ async fn a_row_without_the_field_decodes_private() {
499+ use surrealdb::types::Value;
500+
501+ let db = crate::database::init_mem().await.unwrap();
502+ let question = BankQuestion::create(
503+ UserId::generate(),
504+ SubjectId::generate(),
505+ QuestionText::try_new("q").unwrap(),
506+ QuestionPoints::try_new(1).unwrap(),
507+ spec(),
508+ &db,
509+ )
510+ .await
511+ .unwrap();
512+ assert_eq!(question.get_visibility().as_str(), BankVisibility::PRIVATE);
513+
514+ let mut stored = question.into_value();
515+ let Value::Object(ref mut map) = stored else {
516+ panic!("a bank question serializes to an object");
517+ };
518+ assert!(map.remove("visibility").is_some());
519+ let old = BankQuestion::from_value(stored).unwrap();
520+ assert_eq!(old.get_visibility().as_str(), BankVisibility::PRIVATE);
521+ assert!(!old.get_visibility().is_school());
522+ }
523+
524+ /// The visibility gate is a WHERE clause, so `total` counts exactly what the
525+ /// page can contain — never someone else's private templates.
526+ #[tokio::test]
527+ async fn list_hides_private_templates_from_others() {
528+ let db = crate::database::init_mem().await.unwrap();
529+ let owner = UserId::generate();
530+ let other = UserId::generate();
531+ let private = BankQuestion::create(
532+ owner.clone(),
533+ SubjectId::generate(),
534+ QuestionText::try_new("secret").unwrap(),
535+ QuestionPoints::try_new(1).unwrap(),
536+ spec(),
537+ &db,
538+ )
539+ .await
540+ .unwrap();
541+ let published = BankQuestion::create(
542+ owner.clone(),
543+ SubjectId::generate(),
544+ QuestionText::try_new("shared").unwrap(),
545+ QuestionPoints::try_new(1).unwrap(),
546+ spec(),
547+ &db,
548+ )
549+ .await
550+ .unwrap();
551+ let subject = published.get_subject().cloned();
552+ published
553+ .update(
554+ subject,
555+ QuestionText::try_new("shared").unwrap(),
556+ QuestionPoints::try_new(1).unwrap(),
557+ spec(),
558+ BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(),
559+ &db,
560+ )
561+ .await
562+ .unwrap();
563+
564+ // The stranger sees the published one alone, and `total` agrees.
565+ let (items, total) = BankQuestion::list(Some(&other), None, None, None, None, None, 0, &db)
566+ .await
567+ .unwrap();
568+ assert_eq!((items.len(), total), (1, 1));
569+ assert_eq!(items[0].get_text().as_str(), "shared");
570+ // The owner sees both; an admin (`None`) too.
571+ let (items, total) = BankQuestion::list(Some(&owner), None, None, None, None, None, 0, &db)
572+ .await
573+ .unwrap();
574+ assert_eq!((items.len(), total), (2, 2));
575+ let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db)
576+ .await
577+ .unwrap();
578+ assert_eq!((items.len(), total), (2, 2));
579+ // An explicit `owner=` filter can't widen the gate.
580+ let (items, total) =
581+ BankQuestion::list(Some(&other), Some(&owner), None, None, None, None, 0, &db)
582+ .await
583+ .unwrap();
584+ assert_eq!((items.len(), total), (1, 1));
585+ assert_eq!(private.get_visibility().as_str(), BankVisibility::PRIVATE);
586+ }
587+
588+ /// The `visibility` filter ANDs onto the security gate, so it narrows and
589+ /// never widens: a stranger asking for `school` still can't see a private
590+ /// row, and `private` means "my own drafts" for everyone but an admin.
591+ #[tokio::test]
592+ async fn visibility_filter_narrows_never_widens() {
593+ let db = crate::database::init_mem().await.unwrap();
594+ let owner = UserId::generate();
595+ let other = UserId::generate();
596+ let mine = |text: &str| {
597+ BankQuestion::create(
598+ owner.clone(),
599+ SubjectId::generate(),
600+ QuestionText::try_new(text).unwrap(),
601+ QuestionPoints::try_new(1).unwrap(),
602+ spec(),
603+ &db,
604+ )
605+ };
606+ mine("draft").await.unwrap();
607+ let published = mine("shared").await.unwrap();
608+ let subject = published.get_subject().cloned();
609+ published
610+ .update(
611+ subject,
612+ QuestionText::try_new("shared").unwrap(),
613+ QuestionPoints::try_new(1).unwrap(),
614+ spec(),
615+ BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(),
616+ &db,
617+ )
618+ .await
619+ .unwrap();
620+ let private = BankVisibility::try_new(BankVisibility::PRIVATE).unwrap();
621+ let school = BankVisibility::try_new(BankVisibility::SCHOOL).unwrap();
622+
623+ // Owner: `private` = their drafts, `school` = the published one.
624+ let (items, total) =
625+ BankQuestion::list(Some(&owner), None, None, Some(&private), None, None, 0, &db)
626+ .await
627+ .unwrap();
628+ assert_eq!((items.len(), total), (1, 1));
629+ assert_eq!(items[0].get_text().as_str(), "draft");
630+ let (items, total) =
631+ BankQuestion::list(Some(&owner), None, None, Some(&school), None, None, 0, &db)
632+ .await
633+ .unwrap();
634+ assert_eq!((items.len(), total), (1, 1));
635+ assert_eq!(items[0].get_text().as_str(), "shared");
636+ // A stranger's `private` is empty — never someone else's draft.
637+ let (items, total) =
638+ BankQuestion::list(Some(&other), None, None, Some(&private), None, None, 0, &db)
639+ .await
640+ .unwrap();
641+ assert!(items.is_empty());
642+ assert_eq!(total, 0);
643+ // …and their `school` stops at the published one, gate intact.
644+ let (items, total) =
645+ BankQuestion::list(Some(&other), None, None, Some(&school), None, None, 0, &db)
646+ .await
647+ .unwrap();
648+ assert_eq!((items.len(), total), (1, 1));
649+ // Composes with the other filters: right owner, wrong visibility.
650+ let (items, total) = BankQuestion::list(
651+ Some(&owner),
652+ Some(&owner),
653+ None,
654+ Some(&school),
655+ Some("draft"),
656+ None,
657+ 0,
658+ &db,
659+ )
660+ .await
661+ .unwrap();
662+ assert!(items.is_empty());
663+ assert_eq!(total, 0);
664+ }
665+
666+ /// The whole page's tally in one grouped statement: right number per
667+ /// template, unused templates absent (so the UI prints nothing rather than
668+ /// "0"), and questions authored by hand never counted.
669+ #[tokio::test]
670+ async fn usage_counts_tallies_a_page_in_one_statement() {
671+ use crate::domain::exam_question::ExamQuestion;
672+
673+ // One statement, so a page costs one round trip — a `;` here would mean
674+ // the per-row N+1 crept back in.
675+ assert!(!USAGE_COUNTS_SQL.contains(';'), "usage_counts must be one statement");
676+
677+ let db = crate::database::init_mem().await.unwrap();
678+ let owner = UserId::generate();
679+ let template = |text: &str| {
680+ BankQuestion::create(
681+ owner.clone(),
682+ SubjectId::generate(),
683+ QuestionText::try_new(text).unwrap(),
684+ QuestionPoints::try_new(1).unwrap(),
685+ spec(),
686+ &db,
687+ )
688+ };
689+ let used_twice = template("twice").await.unwrap();
690+ let used_once = template("once").await.unwrap();
691+ let unused = template("never").await.unwrap();
692+
693+ let exam = ExamId::generate();
694+ let other_exam = ExamId::generate();
695+ async fn instantiate(exam: &ExamId, source: &BankQuestion, db: &Database) {
696+ ExamQuestion::create_from_bank(
697+ exam,
698+ SubjectId::generate(),
699+ source.get_text().clone(),
700+ source.get_points(),
701+ source.spec(),
702+ source.get_id().clone(),
703+ db,
704+ )
705+ .await
706+ .unwrap();
707+ }
708+ // Two copies of the same template, in two different exams.
709+ instantiate(&exam, &used_twice, &db).await;
710+ instantiate(&other_exam, &used_twice, &db).await;
711+ instantiate(&exam, &used_once, &db).await;
712+ // A hand-authored question has no `from_bank` and must not be tallied.
713+ ExamQuestion::create(
714+ &exam,
715+ SubjectId::generate(),
716+ QuestionText::try_new("mine").unwrap(),
717+ QuestionPoints::try_new(1).unwrap(),
718+ spec(),
719+ &db,
720+ )
721+ .await
722+ .unwrap();
723+
724+ let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()];
725+ let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap();
726+ assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2));
727+ assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1));
728+ assert_eq!(counts.get(unused.get_id().key()), None, "unused stays absent");
729+ assert_eq!(counts.len(), 2);
730+
731+ // A template outside the page is never counted into it.
732+ let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db).await.unwrap();
733+ assert_eq!(narrow.len(), 1);
734+ assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1));
735+ // An empty page asks nothing at all.
736+ assert!(BankQuestion::usage_counts(&[], &db).await.unwrap().is_empty());
737+ }
738+
739+ #[test]
740+ fn visibility_rejects_anything_else() {
741+ assert!(BankVisibility::try_new("public").is_err());
742+ assert!(BankVisibility::try_new("").is_err());
743+ assert!(BankVisibility::try_new("school").unwrap().is_school());
744+ }
745+
277 #[tokio::test]746 #[tokio::test]
278 async fn list_is_school_wide() {747 async fn list_is_school_wide() {
279 let db = crate::database::init_mem().await.unwrap();748 let db = crate::database::init_mem().await.unwrap();
@@ -290,6 +759,80 @@ mod tests {
290 .unwrap();759 .unwrap();
291 }760 }
292 // Different owners, yet both listed.761 // Different owners, yet both listed.
293- assert_eq!(BankQuestion::list(&db).await.unwrap().len(), 2);762+ let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db)
763+ .await
764+ .unwrap();
765+ assert_eq!(items.len(), 2);
766+ assert_eq!(total, 2);
767+ }
768+
769+ /// The window is SQL, not an in-memory slice, and `total` ignores it.
770+ #[tokio::test]
771+ async fn list_pages_newest_first_and_filters_text() {
772+ let db = crate::database::init_mem().await.unwrap();
773+ let owner = UserId::generate();
774+ for i in 0..5 {
775+ BankQuestion::create(
776+ owner.clone(),
777+ SubjectId::generate(),
778+ QuestionText::try_new(&format!("question {i}")).unwrap(),
779+ QuestionPoints::try_new(1).unwrap(),
780+ spec(),
781+ &db,
782+ )
783+ .await
784+ .unwrap();
785+ }
786+ let (page, total) = BankQuestion::list(None, None, None, None, None, Some(2), 0, &db)
787+ .await
788+ .unwrap();
789+ assert_eq!(total, 5);
790+ assert_eq!(page.len(), 2);
791+ // Newest first: the last-created row leads.
792+ assert_eq!(page[0].get_text().as_str(), "question 4");
793+ // The tail is reachable by offset.
794+ let (tail, _) = BankQuestion::list(None, None, None, None, None, Some(2), 4, &db)
795+ .await
796+ .unwrap();
797+ assert_eq!(tail[0].get_text().as_str(), "question 0");
798+ // Text filter runs in SQL, case-insensitively, and narrows `total`.
799+ let (hits, total) = BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db)
800+ .await
801+ .unwrap();
802+ assert_eq!((hits.len(), total), (1, 1));
803+ // Owner filter with nobody's templates.
804+ let (none, total) =
805+ BankQuestion::list(None, Some(&UserId::generate()), None, None, None, None, 0, &db)
806+ .await
807+ .unwrap();
808+ assert!(none.is_empty());
809+ assert_eq!(total, 0);
810+ }
811+
812+ /// Turkish `İ`/`ı` must not split the search into two disjoint halves.
813+ #[tokio::test]
814+ async fn list_text_filter_folds_turkish_casing() {
815+ let db = crate::database::init_mem().await.unwrap();
816+ BankQuestion::create(
817+ UserId::generate(),
818+ SubjectId::generate(),
819+ QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(),
820+ QuestionPoints::try_new(1).unwrap(),
821+ spec(),
822+ &db,
823+ )
824+ .await
825+ .unwrap();
826+ for needle in ["istanbul", "İSTANBUL", "İstanbul", "ıstanbul", "ilçe", "ILCE"] {
827+ let (hits, total) = BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db)
828+ .await
829+ .unwrap();
830+ assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed");
831+ }
832+ let (miss, total) = BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db)
833+ .await
834+ .unwrap();
835+ assert!(miss.is_empty());
836+ assert_eq!(total, 0);
294 }837 }
295 }838 }
src/domain/bank_question_image.rsmodified+119 -33
@@ -1,5 +1,6 @@
1 //! An image pinned to a bank question — the question's own illustration1 //! An image pinned to a bank question — the question's own illustration
2-//! (`slot = NONE`) or one choice's picture (`slot = i`, choice questions only).2+//! (`slot = NONE`) or one choice's picture (`slot` = that choice's stable id,
3+//! choice questions only).
3 //! A structural copy of [`crate::domain::question_image`] with the exam FK4 //! A structural copy of [`crate::domain::question_image`] with the exam FK
4 //! dropped: a bank template belongs to no exam, and its owner is reachable5 //! dropped: a bank template belongs to no exam, and its owner is reachable
5 //! through the `bank_question` row. The row carries metadata; the bytes live6 //! through the `bank_question` row. The row carries metadata; the bytes live
@@ -14,6 +15,7 @@ use ulid::Ulid;
14 15
15 use crate::database::{BANK_QUESTION_IMAGE_TABLE, Database};16 use crate::database::{BANK_QUESTION_IMAGE_TABLE, Database};
16 use crate::domain::bank_question::BankQuestionId;17 use crate::domain::bank_question::BankQuestionId;
18+use crate::domain::exam_question::ChoiceId;
17 use crate::domain::note_file::FileContentType;19 use crate::domain::note_file::FileContentType;
18 use crate::error::AppError;20 use crate::error::AppError;
19 21
@@ -22,12 +24,15 @@ pub struct BankQuestionImageId(RecordId);
22 24
23 impl BankQuestionImageId {25 impl BankQuestionImageId {
24 /// The one id a (question, slot) pair can have: `{bid}_q` for the26 /// The one id a (question, slot) pair can have: `{bid}_q` for the
25- /// question's own image, `{bid}_{i}` for choice `i` — uniqueness per slot27+ /// question's own image, `{bid}_{choice id}` for one option's picture —
26- /// needs no index this way.28+ /// uniqueness per slot needs no index this way. Keyed by the option's
27- pub fn for_slot(question: &BankQuestionId, slot: Option<i64>) -> Self {29+ /// *stable id*, so reordering the choice list moves no picture.
30+ pub fn for_slot(question: &BankQuestionId, slot: Option<&ChoiceId>) -> Self {
31+ // `_` is not in Crockford base32 and a ULID is never `"q"`, so
32+ // `{qid}_{cid}` and `{qid}_q` can never collide.
28 let suffix = match slot {33 let suffix = match slot {
29- None => "q".to_string(),34+ None => "q",
30- Some(index) => index.to_string(),35+ Some(id) => id.as_str(),
31 };36 };
32 Self(RecordId::new(37 Self(RecordId::new(
33 BANK_QUESTION_IMAGE_TABLE,38 BANK_QUESTION_IMAGE_TABLE,
@@ -51,8 +56,9 @@ impl BankQuestionImageId {
51 pub struct BankQuestionImage {56 pub struct BankQuestionImage {
52 id: BankQuestionImageId,57 id: BankQuestionImageId,
53 bank_question: BankQuestionId,58 bank_question: BankQuestionId,
54- /// `NONE` = the question's illustration; `i` = the picture of choice `i`.59+ /// `NONE` = the question's illustration; otherwise the id of the option
55- slot: Option<i64>,60+ /// this picture belongs to.
61+ slot: Option<ChoiceId>,
56 /// The blob's on-disk name — a fresh ULID every upload.62 /// The blob's on-disk name — a fresh ULID every upload.
57 file: String,63 file: String,
58 content_type: FileContentType,64 content_type: FileContentType,
@@ -65,14 +71,14 @@ impl BankQuestionImage {
65 /// [`Self::upsert`] — so a stored row always points at a real blob.71 /// [`Self::upsert`] — so a stored row always points at a real blob.
66 pub fn new(72 pub fn new(
67 question: &BankQuestionId,73 question: &BankQuestionId,
68- slot: Option<i64>,74+ slot: Option<&ChoiceId>,
69 content_type: FileContentType,75 content_type: FileContentType,
70 size: i64,76 size: i64,
71 ) -> Self {77 ) -> Self {
72 Self {78 Self {
73 id: BankQuestionImageId::for_slot(question, slot),79 id: BankQuestionImageId::for_slot(question, slot),
74 bank_question: question.clone(),80 bank_question: question.clone(),
75- slot,81+ slot: slot.cloned(),
76 file: Ulid::new().to_string(),82 file: Ulid::new().to_string(),
77 content_type,83 content_type,
78 size,84 size,
@@ -83,8 +89,8 @@ impl BankQuestionImage {
83 &self.bank_question89 &self.bank_question
84 }90 }
85 91
86- pub fn get_slot(&self) -> Option<i64> {92+ pub fn get_slot(&self) -> Option<&ChoiceId> {
87- self.slot93+ self.slot.as_ref()
88 }94 }
89 95
90 pub fn get_file(&self) -> &str {96 pub fn get_file(&self) -> &str {
@@ -102,13 +108,14 @@ impl BankQuestionImage {
102 /// Create or replace the slot's image row — the deterministic id makes108 /// Create or replace the slot's image row — the deterministic id makes
103 /// this the whole "one image per slot" story.109 /// this the whole "one image per slot" story.
104 pub async fn upsert(self, db: &Database) -> Result<BankQuestionImage, AppError> {110 pub async fn upsert(self, db: &Database) -> Result<BankQuestionImage, AppError> {
111+ // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
105 let written: Option<BankQuestionImage> = db.upsert(self.id.record()).content(self).await?;112 let written: Option<BankQuestionImage> = db.upsert(self.id.record()).content(self).await?;
106 written.ok_or_else(|| AppError::Internal("failed to store bank question image".into()))113 written.ok_or_else(|| AppError::Internal("failed to store bank question image".into()))
107 }114 }
108 115
109 pub async fn read_slot(116 pub async fn read_slot(
110 question: &BankQuestionId,117 question: &BankQuestionId,
111- slot: Option<i64>,118+ slot: Option<&ChoiceId>,
112 db: &Database,119 db: &Database,
113 ) -> Result<Option<BankQuestionImage>, AppError> {120 ) -> Result<Option<BankQuestionImage>, AppError> {
114 Ok(db121 Ok(db
@@ -128,27 +135,46 @@ impl BankQuestionImage {
128 Ok(result.take::<Vec<BankQuestionImage>>(0)?)135 Ok(result.take::<Vec<BankQuestionImage>>(0)?)
129 }136 }
130 137
131- /// Every bank image row, school-wide — for bucketing onto a whole template138+ /// The image rows of several templates in one query — for bucketing onto a
132- /// list in one query (the bank list is itself school-wide).139+ /// listing's *page* (never the whole table: the bank spans the school).
133- pub async fn list_all(db: &Database) -> Result<Vec<BankQuestionImage>, AppError> {140+ pub async fn list_for_questions(
141+ questions: &[&BankQuestionId],
142+ db: &Database,
143+ ) -> Result<Vec<BankQuestionImage>, AppError> {
144+ if questions.is_empty() {
145+ return Ok(Vec::new());
146+ }
147+ let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect();
134 let mut result = db148 let mut result = db
135- .query("SELECT * FROM bank_question_image")149+ .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids")
150+ .bind(("ids", records))
136 .await?151 .await?
137 .check()?;152 .check()?;
138 Ok(result.take::<Vec<BankQuestionImage>>(0)?)153 Ok(result.take::<Vec<BankQuestionImage>>(0)?)
139 }154 }
140 155
141- /// Drop every *choice* image of the question (the question's own156+ /// Drop the option pictures whose choice is gone — every choice image of
142- /// illustration stays), returning the removed rows so the caller can take157+ /// the question whose `slot` is *not* in `keep` (the question's own
143- /// their blobs off disk. Runs when a PATCH replaces the choice list — the158+ /// illustration always stays), returning the removed rows so the caller can
144- /// old pictures belong to the old options.159+ /// take their blobs off disk.
145- pub async fn delete_choices_for(160+ ///
161+ /// This is what makes an edit non-destructive: a PATCH that reorders,
162+ /// renames, or drops options passes the surviving choice ids as `keep`, so
163+ /// only the pictures of genuinely removed options go. `keep = &[]` (a text
164+ /// question, or an all-new choice list) still clears the lot.
165+ pub async fn delete_choices_not_in(
146 question: &BankQuestionId,166 question: &BankQuestionId,
167+ keep: &[ChoiceId],
147 db: &Database,168 db: &Database,
148 ) -> Result<Vec<BankQuestionImage>, AppError> {169 ) -> Result<Vec<BankQuestionImage>, AppError> {
170+ let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
149 let mut result = db171 let mut result = db
150- .query("DELETE bank_question_image WHERE bank_question = $b AND slot != NONE RETURN BEFORE")172+ .query(
173+ "DELETE bank_question_image \
174+ WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",
175+ )
151 .bind(("b", question.record()))176 .bind(("b", question.record()))
177+ .bind(("keep", keep))
152 .await?178 .await?
153 .check()?;179 .check()?;
154 Ok(result.take::<Vec<BankQuestionImage>>(0)?)180 Ok(result.take::<Vec<BankQuestionImage>>(0)?)
@@ -163,25 +189,49 @@ impl BankQuestionImage {
163 #[cfg(test)]189 #[cfg(test)]
164 mod tests {190 mod tests {
165 use super::*;191 use super::*;
192+ use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
166 193
167 fn png() -> FileContentType {194 fn png() -> FileContentType {
168 FileContentType::try_new("image/png").unwrap()195 FileContentType::try_new("image/png").unwrap()
169 }196 }
170 197
198+ fn choice_ids() -> Vec<ChoiceId> {
199+ QuestionSpec::try_new(
200+ QuestionKind::try_new("choice").unwrap(),
201+ Some(
202+ ["a", "b", "c"]
203+ .iter()
204+ .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })
205+ .collect(),
206+ ),
207+ Some("a".into()),
208+ &[],
209+ )
210+ .unwrap()
211+ .into_parts()
212+ .1
213+ .unwrap()
214+ .iter()
215+ .map(|c| c.get_id().clone())
216+ .collect()
217+ }
218+
171 #[tokio::test]219 #[tokio::test]
172- async fn for_slot_keys_by_question_and_slot() {220+ async fn for_slot_keys_by_question_and_choice_id() {
173 let question = BankQuestionId::from_key("abc");221 let question = BankQuestionId::from_key("abc");
222+ let ids = choice_ids();
174 assert_eq!(223 assert_eq!(
175 BankQuestionImageId::for_slot(&question, None).key(),224 BankQuestionImageId::for_slot(&question, None).key(),
176 "abc_q"225 "abc_q"
177 );226 );
178 assert_eq!(227 assert_eq!(
179- BankQuestionImageId::for_slot(&question, Some(0)).key(),228+ BankQuestionImageId::for_slot(&question, Some(&ids[0])).key(),
180- "abc_0"229+ format!("abc_{}", ids[0].as_str())
181 );230 );
182- assert_eq!(231+ // Distinct options never share a row.
183- BankQuestionImageId::for_slot(&question, Some(3)).key(),232+ assert_ne!(
184- "abc_3"233+ BankQuestionImageId::for_slot(&question, Some(&ids[0])),
234+ BankQuestionImageId::for_slot(&question, Some(&ids[1]))
185 );235 );
186 }236 }
187 237
@@ -207,18 +257,54 @@ mod tests {
207 assert_eq!(rows[0].get_size(), 5);257 assert_eq!(rows[0].get_size(), 5);
208 }258 }
209 259
260+ /// The bank half of the non-destructive edit: keeping an option keeps its
261+ /// picture, and only a removed option's picture goes.
262+ #[tokio::test]
263+ async fn only_the_dropped_options_lose_their_pictures() {
264+ let db = crate::database::init_mem().await.unwrap();
265+ let question = BankQuestionId::generate();
266+ let ids = choice_ids();
267+ BankQuestionImage::new(&question, None, png(), 1)
268+ .upsert(&db)
269+ .await
270+ .unwrap();
271+ for id in &ids {
272+ BankQuestionImage::new(&question, Some(id), png(), 1)
273+ .upsert(&db)
274+ .await
275+ .unwrap();
276+ }
277+
278+ let keep = vec![ids[0].clone(), ids[1].clone()];
279+ let dropped = BankQuestionImage::delete_choices_not_in(&question, &keep, &db)
280+ .await
281+ .unwrap();
282+ assert_eq!(dropped.len(), 1);
283+ assert_eq!(dropped[0].get_slot(), Some(&ids[2]));
284+
285+ let left = BankQuestionImage::list_for_question(&question, &db)
286+ .await
287+ .unwrap();
288+ assert_eq!(left.len(), 3);
289+ }
290+
210 #[tokio::test]291 #[tokio::test]
211- async fn choice_wipe_spares_the_question_image() {292+ async fn an_empty_keep_set_clears_every_option_picture() {
212 let db = crate::database::init_mem().await.unwrap();293 let db = crate::database::init_mem().await.unwrap();
213 let question = BankQuestionId::generate();294 let question = BankQuestionId::generate();
214- for slot in [None, Some(0), Some(1)] {295+ let ids = choice_ids();
215- BankQuestionImage::new(&question, slot, png(), 1)296+ BankQuestionImage::new(&question, None, png(), 1)
297+ .upsert(&db)
298+ .await
299+ .unwrap();
300+ for id in &ids[..2] {
301+ BankQuestionImage::new(&question, Some(id), png(), 1)
216 .upsert(&db)302 .upsert(&db)
217 .await303 .await
218 .unwrap();304 .unwrap();
219 }305 }
220 306
221- let dropped = BankQuestionImage::delete_choices_for(&question, &db)307+ let dropped = BankQuestionImage::delete_choices_not_in(&question, &[], &db)
222 .await308 .await
223 .unwrap();309 .unwrap();
224 assert_eq!(dropped.len(), 2);310 assert_eq!(dropped.len(), 2);
src/domain/exam.rsmodified+13 -4
@@ -465,6 +465,7 @@ impl Exam {
465 self.allow_rejoin = allow_rejoin;465 self.allow_rejoin = allow_rejoin;
466 self.allow_review = allow_review;466 self.allow_review = allow_review;
467 self.draft = draft;467 self.draft = draft;
468+ // whole-row-save-ok: the only caller takes EXAM_LOCK.write() before the row read (web/exams.rs:354)
468 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;469 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;
469 updated.ok_or(AppError::NotFound)470 updated.ok_or(AppError::NotFound)
470 }471 }
@@ -489,15 +490,22 @@ impl Exam {
489 DELETE question_image WHERE exam = $ex;490 DELETE question_image WHERE exam = $ex;
490 DELETE exam_question WHERE exam = $ex;491 DELETE exam_question WHERE exam = $ex;
491 UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;492 UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex;
492- DELETE $ex RETURN BEFORE;493+ LET $before = (DELETE $ex RETURN BEFORE);
494+ RETURN $before;
493 COMMIT TRANSACTION;",495 COMMIT TRANSACTION;",
494 )496 )
495 .bind(("ex", self.id.record()))497 .bind(("ex", self.id.record()))
496 .await?498 .await?
497 .check()?;499 .check()?;
498- // Statement slots count BEGIN, the child deletes and the bank500+ // The deleted row comes back through the transaction's trailing
499- // provenance clear: the exam's own DELETE is slot 8.501+ // `RETURN`, never a hand-counted slot: the old `take(8)` turned a
500- let deleted: Option<Exam> = result.take::<Vec<Exam>>(8)?.into_iter().next();502+ // successful delete into a 404 the moment a cascade statement was
503+ // inserted above it (it already had to be bumped once). `RETURN` is
504+ // always the last statement before `COMMIT`, so its slot is derived
505+ // from the statement count and every insertion above it shifts it
506+ // along. `num_statements` counts BEGIN and COMMIT too, hence -2.
507+ let slot = result.num_statements().saturating_sub(2);
508+ let deleted: Option<Exam> = result.take::<Vec<Exam>>(slot)?.into_iter().next();
501 deleted.ok_or(AppError::NotFound)509 deleted.ok_or(AppError::NotFound)
502 }510 }
503 }511 }
@@ -612,3 +620,4 @@ mod tests {
612 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());620 assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err());
613 }621 }
614 }622 }
623+
src/domain/exam_answer.rsmodified+41 -22
@@ -3,7 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3 use crate::constant::MAX_ANSWER_TEXT_LEN;3 use crate::constant::MAX_ANSWER_TEXT_LEN;
4 use crate::database::{Database, EXAM_ANSWER_TABLE};4 use crate::database::{Database, EXAM_ANSWER_TABLE};
5 use crate::domain::exam::ExamId;5 use crate::domain::exam::ExamId;
6-use crate::domain::exam_question::{ExamQuestion, ExamQuestionId};6+use crate::domain::exam_question::{ChoiceId, ExamQuestion, ExamQuestionId};
7 use crate::domain::timestamp::Timestamp;7 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};9 use crate::error::{AppError, ValidationError};
@@ -68,7 +68,7 @@ pub struct ExamAnswer {
68 question: ExamQuestionId,68 question: ExamQuestionId,
69 user: UserId,69 user: UserId,
70 seq: i64,70 seq: i64,
71- selected: Option<i64>,71+ selected: Option<ChoiceId>,
72 text: Option<AnswerText>,72 text: Option<AnswerText>,
73 updated_at: Timestamp,73 updated_at: Timestamp,
74 }74 }
@@ -95,8 +95,8 @@ impl ExamAnswer {
95 self.seq95 self.seq
96 }96 }
97 97
98- pub fn get_selected(&self) -> Option<i64> {98+ pub fn get_selected(&self) -> Option<&ChoiceId> {
99- self.selected99+ self.selected.as_ref()
100 }100 }
101 101
102 pub fn get_text(&self) -> Option<&AnswerText> {102 pub fn get_text(&self) -> Option<&AnswerText> {
@@ -111,13 +111,13 @@ impl ExamAnswer {
111 /// text question — correctness is the grader's call, not the machine's.111 /// text question — correctness is the grader's call, not the machine's.
112 pub fn is_correct(&self, question: &ExamQuestion) -> Option<bool> {112 pub fn is_correct(&self, question: &ExamQuestion) -> Option<bool> {
113 let correct = question.get_correct()?;113 let correct = question.get_correct()?;
114- Some(self.selected == Some(correct))114+ Some(self.selected.as_ref() == Some(correct))
115 }115 }
116 116
117 /// Save (or overwrite) `user`'s answer to `question` for sitting `seq` —117 /// Save (or overwrite) `user`'s answer to `question` for sitting `seq` —
118 /// the one write path, shared by the REST handler and the WebSocket room.118 /// the one write path, shared by the REST handler and the WebSocket room.
119 /// The payload must match the question's kind: a choice question takes119 /// The payload must match the question's kind: a choice question takes
120- /// `selected` (indexing one of its choices), a text question takes `text`.120+ /// `selected` (the id of one of its choices), a text question takes `text`.
121 /// The caller has already checked that the attempt is in progress. Keyed121 /// The caller has already checked that the attempt is in progress. Keyed
122 /// by `seq`, so a retake's save is a new row, not an overwrite of an122 /// by `seq`, so a retake's save is a new row, not an overwrite of an
123 /// earlier sitting's answer.123 /// earlier sitting's answer.
@@ -125,7 +125,7 @@ impl ExamAnswer {
125 question: &ExamQuestion,125 question: &ExamQuestion,
126 user: &UserId,126 user: &UserId,
127 seq: i64,127 seq: i64,
128- selected: Option<i64>,128+ selected: Option<String>,
129 text: Option<String>,129 text: Option<String>,
130 db: &Database,130 db: &Database,
131 ) -> Result<ExamAnswer, AppError> {131 ) -> Result<ExamAnswer, AppError> {
@@ -142,14 +142,17 @@ impl ExamAnswer {
142 let Some(selected) = selected else {142 let Some(selected) = selected else {
143 return Err(invalid("selected", "required for a choice question"));143 return Err(invalid("selected", "required for a choice question"));
144 };144 };
145- let count = question.get_choices().map_or(0, <[_]>::len);145+ // Membership, not a range: `selected` names an option by its
146- if !(0..count as i64).contains(&selected) {146+ // stable id, so a reorder of the list can never repoint it.
147- return Err(invalid(147+ let picked = question
148- "selected",148+ .get_choices()
149- "must index one of the question's choices",149+ .unwrap_or_default()
150- ));150+ .iter()
151- }151+ .find(|choice| choice.get_id().as_str() == selected)
152- (Some(selected), None)152+ .ok_or_else(|| {
153+ invalid("selected", "must name one of the question's choices")
154+ })?;
155+ (Some(picked.get_id().clone()), None)
153 }156 }
154 _ => {157 _ => {
155 if selected.is_some() {158 if selected.is_some() {
@@ -297,13 +300,23 @@ pub fn auto_score(questions: &[ExamQuestion], answers: &[ExamAnswer]) -> (i64, i
297 #[cfg(test)]300 #[cfg(test)]
298 mod tests {301 mod tests {
299 use super::*;302 use super::*;
300- use crate::domain::exam_question::{QuestionKind, QuestionSpec};303+ use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
301 304
302- fn choice_question(exam: &ExamId, points: i64, correct: i64) -> ExamQuestion {305+ /// A three-option question whose `correct` is the option at `correct`.
306+ /// Positions are a *test* convenience only — the ids are minted, and every
307+ /// assertion below goes through `choice_id`.
308+ fn choice_question(exam: &ExamId, points: i64, correct: usize) -> ExamQuestion {
309+ let labels = ["a", "b", "c"];
303 let spec = QuestionSpec::try_new(310 let spec = QuestionSpec::try_new(
304 QuestionKind::try_new("choice").unwrap(),311 QuestionKind::try_new("choice").unwrap(),
305- Some(vec!["a".into(), "b".into(), "c".into()]),312+ Some(
306- Some(correct),313+ labels
314+ .iter()
315+ .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })
316+ .collect(),
317+ ),
318+ Some(labels[correct].into()),
319+ &[],
307 )320 )
308 .unwrap();321 .unwrap();
309 ExamQuestion::test_new(exam, "pick one", points, spec)322 ExamQuestion::test_new(exam, "pick one", points, spec)
@@ -311,21 +324,27 @@ mod tests {
311 324
312 fn text_question(exam: &ExamId, points: i64) -> ExamQuestion {325 fn text_question(exam: &ExamId, points: i64) -> ExamQuestion {
313 let spec =326 let spec =
314- QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None).unwrap();327+ QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap();
315 ExamQuestion::test_new(exam, "explain", points, spec)328 ExamQuestion::test_new(exam, "explain", points, spec)
316 }329 }
317 330
318- fn answer(question: &ExamQuestion, user: &UserId, selected: Option<i64>) -> ExamAnswer {331+ /// The minted id of the question's option at `index`.
332+ fn choice_id(question: &ExamQuestion, index: usize) -> ChoiceId {
333+ question.get_choices().unwrap()[index].get_id().clone()
334+ }
335+
336+ fn answer(question: &ExamQuestion, user: &UserId, selected: Option<usize>) -> ExamAnswer {
337+ let selected = selected.map(|index| choice_id(question, index));
319 ExamAnswer {338 ExamAnswer {
320 id: ExamAnswerId::composite(question.get_id(), user, 1),339 id: ExamAnswerId::composite(question.get_id(), user, 1),
321 exam: question.get_exam().clone(),340 exam: question.get_exam().clone(),
322 question: question.get_id().clone(),341 question: question.get_id().clone(),
323 user: user.clone(),342 user: user.clone(),
324 seq: 1,343 seq: 1,
325- selected,
326 text: selected344 text: selected
327 .is_none()345 .is_none()
328 .then(|| AnswerText::try_new("essay").unwrap()),346 .then(|| AnswerText::try_new("essay").unwrap()),
347+ selected,
329 updated_at: Timestamp::from_millis(1),348 updated_at: Timestamp::from_millis(1),
330 }349 }
331 }350 }
src/domain/exam_attempt.rsmodified+79 -9
@@ -210,10 +210,25 @@ impl ExamAttempt {
210 210
211 /// Stamp the submission time. The caller has already checked the deadline211 /// Stamp the submission time. The caller has already checked the deadline
212 /// and that the attempt isn't finished.212 /// and that the attempt isn't finished.
213- pub async fn finish(mut self, db: &Database) -> Result<ExamAttempt, AppError> {213+ ///
214- self.finished_at = Some(Timestamp::now());214+ /// Writes *only* `finished_at`, for the mirror image of
215- let updated: Option<ExamAttempt> = db.update(self.id.record()).content(self).await?;215+ /// [`ExamAttempt::set_left`]'s reason: the submit path reads the attempt,
216- updated.ok_or(AppError::NotFound)216+ /// then awaits its deadline and already-finished checks before writing, and
217+ /// the exam room stamps or clears `left_at` on the same row from a socket.
218+ /// A whole-row write from the pre-read snapshot would carry its stale
219+ /// `left_at` back over that stamp, erasing the recorded walk-out.
220+ pub async fn finish(self, db: &Database) -> Result<ExamAttempt, AppError> {
221+ let mut result = db
222+ .query("UPDATE $id SET finished_at = $at RETURN AFTER")
223+ .bind(("id", self.id.record()))
224+ .bind(("at", Some(Timestamp::now())))
225+ .await?
226+ .check()?;
227+ result
228+ .take::<Vec<ExamAttempt>>(0)?
229+ .into_iter()
230+ .next()
231+ .ok_or(AppError::NotFound)
217 }232 }
218 233
219 /// Stamp (or clear) the walked-out marker. The exam room sets it when the234 /// Stamp (or clear) the walked-out marker. The exam room sets it when the
@@ -316,7 +331,15 @@ mod tests {
316 ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,331 ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
317 };332 };
318 use crate::domain::exam_answer::ExamAnswer;333 use crate::domain::exam_answer::ExamAnswer;
319- use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec};334+ use crate::domain::exam_question::{
335+ ChoiceInput, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec,
336+ };
337+
338+ /// The id of the question's second option — what these tests used to write
339+ /// as the index `1`.
340+ fn second_choice(question: &ExamQuestion) -> String {
341+ question.get_choices().unwrap()[1].get_id().as_str().to_string()
342+ }
320 use crate::domain::settings::Settings;343 use crate::domain::settings::Settings;
321 344
322 /// An open exam with retakes allowed, plus one choice question — enough345 /// An open exam with retakes allowed, plus one choice question — enough
@@ -343,8 +366,12 @@ mod tests {
343 .unwrap();366 .unwrap();
344 let spec = QuestionSpec::try_new(367 let spec = QuestionSpec::try_new(
345 QuestionKind::try_new("choice").unwrap(),368 QuestionKind::try_new("choice").unwrap(),
346- Some(vec!["5".into(), "6".into()]),369+ Some(vec![
347- Some(1),370+ ChoiceInput { id: Some("a".into()), text: "5".into() },
371+ ChoiceInput { id: Some("b".into()), text: "6".into() },
372+ ]),
373+ Some("b".into()),
374+ &[],
348 )375 )
349 .unwrap();376 .unwrap();
350 let question = ExamQuestion::create(377 let question = ExamQuestion::create(
@@ -373,7 +400,7 @@ mod tests {
373 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();400 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
374 assert!(created);401 assert!(created);
375 assert_eq!(first.get_seq(), 1);402 assert_eq!(first.get_seq(), 1);
376- ExamAnswer::save(&question, &user, 1, Some(1), None, &db)403+ ExamAnswer::save(&question, &user, 1, Some(second_choice(&question)), None, &db)
377 .await404 .await
378 .unwrap();405 .unwrap();
379 first.finish(&db).await.unwrap();406 first.finish(&db).await.unwrap();
@@ -407,7 +434,7 @@ mod tests {
407 let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();434 let (winner, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
408 assert!(created);435 assert!(created);
409 assert_eq!(winner.get_seq(), 2);436 assert_eq!(winner.get_seq(), 2);
410- ExamAnswer::save(&question, &user, 2, Some(1), None, &db)437+ ExamAnswer::save(&question, &user, 2, Some(second_choice(&question)), None, &db)
411 .await438 .await
412 .unwrap();439 .unwrap();
413 440
@@ -441,6 +468,49 @@ mod tests {
441 assert_eq!(resumed.get_seq(), 2);468 assert_eq!(resumed.get_seq(), 2);
442 }469 }
443 470
471+ #[tokio::test]
472+ async fn submitting_never_reverts_a_walk_out_that_raced_it() {
473+ let db = init_mem().await.unwrap();
474+ let (exam, _question) = open_exam_with_question(&db, 1).await;
475+ let user = student();
476+
477+ let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
478+
479+ // The REST submit path reads the attempt, then checks the deadline and
480+ // the already-finished guard — several awaits before it writes.
481+ let stale = ExamAttempt::read(attempt.get_id(), &db)
482+ .await
483+ .unwrap()
484+ .expect("attempt exists");
485+ assert!(stale.get_left_at().is_none());
486+
487+ // In that gap the exam room's teardown stamps the walk-out (or a join
488+ // clears it) — a field-scoped write to the same row.
489+ ExamAttempt::read(attempt.get_id(), &db)
490+ .await
491+ .unwrap()
492+ .expect("attempt exists")
493+ .set_left(Some(Timestamp::now()), &db)
494+ .await
495+ .unwrap();
496+
497+ // The submit now writes from its stale snapshot. It owns `finished_at`
498+ // and nothing else: carrying the snapshot's blank `left_at` back over
499+ // the fresh stamp erases the recorded walk-out.
500+ let finished = stale.finish(&db).await.unwrap();
501+ assert!(finished.get_finished_at().is_some());
502+
503+ let after = ExamAttempt::read(attempt.get_id(), &db)
504+ .await
505+ .unwrap()
506+ .expect("attempt still exists");
507+ assert!(
508+ after.get_left_at().is_some(),
509+ "submitting must not revert a walk-out stamp that raced it"
510+ );
511+ assert!(after.get_finished_at().is_some(), "the submission stands");
512+ }
513+
444 #[tokio::test]514 #[tokio::test]
445 async fn stamping_left_never_reverts_a_submission() {515 async fn stamping_left_never_reverts_a_submission() {
446 let db = init_mem().await.unwrap();516 let db = init_mem().await.unwrap();
src/domain/exam_question.rsmodified+415 -78
@@ -81,8 +81,7 @@ impl QuestionPoints {
81 }81 }
82 }82 }
83 83
84-/// One option of a choice question: non-blank, at most `MAX_CHOICE_TEXT_LEN`84+/// One option's text: non-blank, at most `MAX_CHOICE_TEXT_LEN` characters.
85-/// characters.
86 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]85 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
87 pub struct ChoiceText(String);86 pub struct ChoiceText(String);
88 87
@@ -97,27 +96,94 @@ impl ChoiceText {
97 }96 }
98 }97 }
99 98
99+/// An option's stable identity — a server-minted ULID, never reused, never
100+/// taken from client input (it becomes part of an image row's record id and of
101+/// a URL path, so a client-shaped value would be an injection surface).
102+///
103+/// This id is the whole point of the choice remodel. `correct`, the per-option
104+/// pictures, and a student's `selected` all name an option *by id*, so
105+/// reordering the list or deleting an option moves none of them. They used to
106+/// be parallel arrays keyed by position, where any edit to the list silently
107+/// re-pointed the others.
108+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
109+pub struct ChoiceId(String);
110+
111+impl ChoiceId {
112+ fn generate() -> Self {
113+ Self(Ulid::new().to_string())
114+ }
115+
116+ pub fn as_str(&self) -> &str {
117+ &self.0
118+ }
119+}
120+
121+/// One option of a choice question: its identity plus its text.
122+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
123+pub struct Choice {
124+ id: ChoiceId,
125+ text: ChoiceText,
126+}
127+
128+impl Choice {
129+ pub fn get_id(&self) -> &ChoiceId {
130+ &self.id
131+ }
132+
133+ pub fn get_text(&self) -> &ChoiceText {
134+ &self.text
135+ }
136+}
137+
138+/// One option as a client submits it. `id` is the option's *key within this
139+/// payload* — see [`QuestionSpec::try_new`] for how it is resolved.
140+#[derive(Debug, Clone)]
141+pub struct ChoiceInput {
142+ pub id: Option<String>,
143+ pub text: String,
144+}
145+
100 /// The kind-dependent fields of a question, validated as a unit — they only146 /// The kind-dependent fields of a question, validated as a unit — they only
101 /// make sense together. `try_new` is the sole constructor, so a `QuestionSpec`147 /// make sense together. `try_new` is the sole constructor, so a `QuestionSpec`
102 /// in hand always satisfies:148 /// in hand always satisfies:
103 ///149 ///
104 /// - `text` → no `choices`, no `correct` (the grader judges the answer),150 /// - `text` → no `choices`, no `correct` (the grader judges the answer),
105-/// - `choice` → 2–10 `choices` plus a `correct` index into them.151+/// - `choice` → 2–10 `choices` plus a `correct` naming one of them.
106 #[derive(Debug, Clone)]152 #[derive(Debug, Clone)]
107 pub struct QuestionSpec {153 pub struct QuestionSpec {
108 kind: QuestionKind,154 kind: QuestionKind,
109- choices: Option<Vec<ChoiceText>>,155+ choices: Option<Vec<Choice>>,
110- correct: Option<i64>,156+ correct: Option<ChoiceId>,
111 }157 }
112 158
113 impl QuestionSpec {159 impl QuestionSpec {
160+ /// Validate the kind-dependent fields as a unit and resolve each submitted
161+ /// option to a stable [`ChoiceId`].
162+ ///
163+ /// **The identity rule, one sentence:** every submitted choice has a key —
164+ /// its `id` if one was sent — and a key that matches one of `existing` *is*
165+ /// that stored option (same id, so its picture survives); any other key
166+ /// names a brand-new option, whose submitted string is used only to resolve
167+ /// `correct` inside this payload and is never stored.
168+ ///
169+ /// `existing` is the question's stored choices (`&[]` on create, so every
170+ /// option there is new and every id is minted here). `correct` names one of
171+ /// the submitted keys.
172+ ///
173+ /// Why an unrecognised id mints instead of failing: `correct` has to be
174+ /// settable on create, where nothing is stored yet, so a client must be
175+ /// able to label an option the server has never seen. The failure mode is
176+ /// benign and visible — a stale id degrades to "this is a new option", which
177+ /// loses that option's picture but can never steal another option's, since
178+ /// it matches no stored id.
114 pub fn try_new(179 pub fn try_new(
115 kind: QuestionKind,180 kind: QuestionKind,
116- choices: Option<Vec<String>>,181+ choices: Option<Vec<ChoiceInput>>,
117- correct: Option<i64>,182+ correct: Option<String>,
183+ existing: &[Choice],
118 ) -> Result<Self, ValidationError> {184 ) -> Result<Self, ValidationError> {
119 let invalid = |field, reason| ValidationError::Invalid { field, reason };185 let invalid = |field, reason| ValidationError::Invalid { field, reason };
120- let choices = match (kind.as_str(), choices) {186+ let (choices, correct) = match (kind.as_str(), choices) {
121 ("text", Some(_)) => {187 ("text", Some(_)) => {
122 return Err(invalid("choices", "only choice questions take choices"));188 return Err(invalid("choices", "only choice questions take choices"));
123 }189 }
@@ -125,28 +191,47 @@ impl QuestionSpec {
125 if correct.is_some() {191 if correct.is_some() {
126 return Err(invalid(192 return Err(invalid(
127 "correct",193 "correct",
128- "only choice questions take a correct index",194+ "only choice questions take a correct choice",
129 ));195 ));
130 }196 }
131- None197+ (None, None)
132 }198 }
133 (_, None) => return Err(invalid("choices", "required for a choice question")),199 (_, None) => return Err(invalid("choices", "required for a choice question")),
134- (_, Some(choices)) => {200+ (_, Some(inputs)) => {
135- if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&choices.len()) {201+ if !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&inputs.len()) {
136 return Err(invalid("choices", "must list 2 to 10 choices"));202 return Err(invalid("choices", "must list 2 to 10 choices"));
137 }203 }
204+ let mut resolved: Vec<Choice> = Vec::with_capacity(inputs.len());
205+ // Submitted key -> the id it resolved to, so `correct` can name
206+ // a fresh option by the label the client gave it.
207+ let mut keys: Vec<(String, ChoiceId)> = Vec::new();
208+ for input in inputs {
209+ let id = match input.id {
210+ Some(key) => {
211+ if keys.iter().any(|(seen, _)| *seen == key) {
212+ return Err(invalid("choices", "duplicate choice id"));
213+ }
214+ let id = existing
215+ .iter()
216+ .find(|choice| choice.id.as_str() == key)
217+ .map_or_else(ChoiceId::generate, |choice| choice.id.clone());
218+ keys.push((key, id.clone()));
219+ id
220+ }
221+ None => ChoiceId::generate(),
222+ };
223+ resolved.push(Choice {
224+ id,
225+ text: ChoiceText::try_new(&input.text)?,
226+ });
227+ }
138 let Some(correct) = correct else {228 let Some(correct) = correct else {
139 return Err(invalid("correct", "required for a choice question"));229 return Err(invalid("correct", "required for a choice question"));
140 };230 };
141- if !(0..choices.len() as i64).contains(&correct) {231+ let Some((_, correct)) = keys.into_iter().find(|(key, _)| *key == correct) else {
142- return Err(invalid("correct", "must index one of the choices"));232+ return Err(invalid("correct", "must name one of the choices"));
143- }233+ };
144- Some(234+ (Some(resolved), Some(correct))
145- choices
146- .iter()
147- .map(|choice| ChoiceText::try_new(choice))
148- .collect::<Result<Vec<_>, _>>()?,
149- )
150 }235 }
151 };236 };
152 Ok(Self {237 Ok(Self {
@@ -156,13 +241,29 @@ impl QuestionSpec {
156 })241 })
157 }242 }
158 243
244+ /// The stored kind-dependent fields as the validated bundle, bypassing
245+ /// [`Self::try_new`] — the fields were written through one, so the
246+ /// invariants already hold. For merge-on-update and for copying a question
247+ /// between the exam and the bank.
248+ pub(crate) fn from_stored(
249+ kind: QuestionKind,
250+ choices: Option<Vec<Choice>>,
251+ correct: Option<ChoiceId>,
252+ ) -> Self {
253+ Self {
254+ kind,
255+ choices,
256+ correct,
257+ }
258+ }
259+
159 pub fn get_kind(&self) -> &QuestionKind {260 pub fn get_kind(&self) -> &QuestionKind {
160 &self.kind261 &self.kind
161 }262 }
162 263
163 /// The validated fields, consumed — for a writer in another module (the264 /// The validated fields, consumed — for a writer in another module (the
164 /// question bank) that stores the same three columns.265 /// question bank) that stores the same three columns.
165- pub fn into_parts(self) -> (QuestionKind, Option<Vec<ChoiceText>>, Option<i64>) {266+ pub fn into_parts(self) -> (QuestionKind, Option<Vec<Choice>>, Option<ChoiceId>) {
166 (self.kind, self.choices, self.correct)267 (self.kind, self.choices, self.correct)
167 }268 }
168 }269 }
@@ -180,10 +281,19 @@ pub struct ExamQuestion {
180 text: QuestionText,281 text: QuestionText,
181 kind: QuestionKind,282 kind: QuestionKind,
182 points: QuestionPoints,283 points: QuestionPoints,
183- choices: Option<Vec<ChoiceText>>,284+ choices: Option<Vec<Choice>>,
184- correct: Option<i64>,285+ correct: Option<ChoiceId>,
185- /// The bank template this question was instantiated from, if any.286+ /// The bank template this question was created *from*, if it was inserted
186- source_bank: Option<BankQuestionId>,287+ /// out of the bank. Written once, at insert.
288+ #[surreal(default)]
289+ from_bank: Option<BankQuestionId>,
290+ /// The bank template most recently created *by saving this question* into
291+ /// the bank, if any. Written by [`Self::link_banked_as`], repointed by every
292+ /// repeat save. Never set by an insert-from-bank: the two directions are
293+ /// separate columns precisely so "came from the bank" can't be misread as
294+ /// "already saved to the bank".
295+ #[surreal(default)]
296+ banked_as: Option<BankQuestionId>,
187 }297 }
188 298
189 impl ExamQuestion {299 impl ExamQuestion {
@@ -211,27 +321,26 @@ impl ExamQuestion {
211 self.points321 self.points
212 }322 }
213 323
214- pub fn get_choices(&self) -> Option<&[ChoiceText]> {324+ pub fn get_choices(&self) -> Option<&[Choice]> {
215 self.choices.as_deref()325 self.choices.as_deref()
216 }326 }
217 327
218- pub fn get_correct(&self) -> Option<i64> {328+ pub fn get_correct(&self) -> Option<&ChoiceId> {
219- self.correct329+ self.correct.as_ref()
220 }330 }
221 331
222- pub fn get_source_bank(&self) -> Option<&BankQuestionId> {332+ pub fn get_from_bank(&self) -> Option<&BankQuestionId> {
223- self.source_bank.as_ref()333+ self.from_bank.as_ref()
334+ }
335+
336+ pub fn get_banked_as(&self) -> Option<&BankQuestionId> {
337+ self.banked_as.as_ref()
224 }338 }
225 339
226 /// The stored kind-dependent fields as the validated bundle (for340 /// The stored kind-dependent fields as the validated bundle (for
227- /// merge-on-update). Bypasses `try_new`: the fields were written through a341+ /// merge-on-update, and for copying into the bank).
228- /// `QuestionSpec`, so the invariants already hold.
229 pub fn spec(&self) -> QuestionSpec {342 pub fn spec(&self) -> QuestionSpec {
230- QuestionSpec {343+ QuestionSpec::from_stored(self.kind.clone(), self.choices.clone(), self.correct.clone())
231- kind: self.kind.clone(),
232- choices: self.choices.clone(),
233- correct: self.correct,
234- }
235 }344 }
236 345
237 pub async fn create(346 pub async fn create(
@@ -266,7 +375,7 @@ impl ExamQuestion {
266 text: QuestionText,375 text: QuestionText,
267 points: QuestionPoints,376 points: QuestionPoints,
268 spec: QuestionSpec,377 spec: QuestionSpec,
269- source_bank: Option<BankQuestionId>,378+ from_bank: Option<BankQuestionId>,
270 db: &Database,379 db: &Database,
271 ) -> Result<ExamQuestion, AppError> {380 ) -> Result<ExamQuestion, AppError> {
272 let question = ExamQuestion {381 let question = ExamQuestion {
@@ -278,7 +387,9 @@ impl ExamQuestion {
278 kind: spec.kind,387 kind: spec.kind,
279 choices: spec.choices,388 choices: spec.choices,
280 correct: spec.correct,389 correct: spec.correct,
281- source_bank,390+ from_bank,
391+ // An insert never banks anything: only a to-bank save writes this.
392+ banked_as: None,
282 };393 };
283 let created: Option<ExamQuestion> =394 let created: Option<ExamQuestion> =
284 db.create(question.id.record()).content(question).await?;395 db.create(question.id.record()).content(question).await?;
@@ -330,29 +441,35 @@ impl ExamQuestion {
330 self.kind = spec.kind;441 self.kind = spec.kind;
331 self.choices = spec.choices;442 self.choices = spec.choices;
332 self.correct = spec.correct;443 self.correct = spec.correct;
444+ // whole-row-save-ok: callers hold EXAM_LOCK.write() across the read and this write
333 let updated: Option<ExamQuestion> = db.update(self.id.record()).content(self).await?;445 let updated: Option<ExamQuestion> = db.update(self.id.record()).content(self).await?;
334 updated.ok_or(AppError::NotFound)446 updated.ok_or(AppError::NotFound)
335 }447 }
336 448
337- /// Point the question at the bank template it was just saved into449+ /// Point the question's `banked_as` at the bank template it was just saved
338- /// (`POST …/questions/{qid}/to-bank`), the mirror of the `source_bank`450+ /// into (`POST …/questions/{qid}/to-bank`). The mirror direction of the
339- /// [`Self::create_from_bank`] writes on the other direction. Overwrites any451+ /// `from_bank` [`Self::create_from_bank`] writes, and deliberately a
340- /// earlier link: repeat saves mint a new template and the newest one wins.452+ /// *different* column: a question inserted from the bank has not been saved
453+ /// to it, and one field for both would make the client claim it was.
454+ /// Overwrites any earlier link: repeat saves mint a new template and the
455+ /// newest one wins.
341 ///456 ///
342- /// Field-scoped write, unlike [`Self::update`]: the caller holds only457+ /// Field-scoped write, unlike [`Self::update`]: the caller awaits a bank
343- /// `BANK_LOCK` (which guards the bank, not `exam_question`) and awaits a458+ /// insert plus the whole blob-copy loop between reading this row and
344- /// bank insert plus the whole blob-copy loop between reading this row and459+ /// linking it, so the row it holds is long stale by now — a whole-row save
345- /// linking it, so a concurrent `PATCH` of the question is entirely possible460+ /// would silently revert whatever landed in that window. (The caller takes
346- /// in that window — a whole-row save would silently revert it.461+ /// `EXAM_LOCK.read()` around this call, which is what keeps
347- pub async fn link_source_bank(462+ /// [`Self::update`]'s whole-row save from clobbering the link in the other
463+ /// direction; the lease guards the ordering, not the staleness.)
464+ pub async fn link_banked_as(
348 self,465 self,
349- source: BankQuestionId,466+ template: BankQuestionId,
350 db: &Database,467 db: &Database,
351 ) -> Result<ExamQuestion, AppError> {468 ) -> Result<ExamQuestion, AppError> {
352 let mut result = db469 let mut result = db
353- .query("UPDATE $id SET source_bank = $bank RETURN AFTER")470+ .query("UPDATE $id SET banked_as = $bank RETURN AFTER")
354 .bind(("id", self.id.record()))471 .bind(("id", self.id.record()))
355- .bind(("bank", source.record()))472+ .bind(("bank", template.record()))
356 .await?473 .await?
357 .check()?;474 .check()?;
358 result475 result
@@ -389,7 +506,8 @@ impl ExamQuestion {
389 kind: spec.kind,506 kind: spec.kind,
390 choices: spec.choices,507 choices: spec.choices,
391 correct: spec.correct,508 correct: spec.correct,
392- source_bank: None,509+ from_bank: None,
510+ banked_as: None,
393 }511 }
394 }512 }
395 }513 }
@@ -402,8 +520,23 @@ mod tests {
402 QuestionKind::try_new(value).unwrap()520 QuestionKind::try_new(value).unwrap()
403 }521 }
404 522
405- fn two_choices() -> Option<Vec<String>> {523+ /// Two options keyed `a` / `b` — the client-side labels a form sends for
406- Some(vec!["yes".into(), "no".into()])524+ /// rows the server has never seen.
525+ fn two_choices() -> Option<Vec<ChoiceInput>> {
526+ Some(vec![
527+ ChoiceInput {
528+ id: Some("a".into()),
529+ text: "yes".into(),
530+ },
531+ ChoiceInput {
532+ id: Some("b".into()),
533+ text: "no".into(),
534+ },
535+ ])
536+ }
537+
538+ fn spec(choices: Option<Vec<ChoiceInput>>, correct: Option<&str>) -> Result<QuestionSpec, ValidationError> {
539+ QuestionSpec::try_new(kind("choice"), choices, correct.map(str::to_string), &[])
407 }540 }
408 541
409 #[tokio::test]542 #[tokio::test]
@@ -440,40 +573,244 @@ mod tests {
440 573
441 #[tokio::test]574 #[tokio::test]
442 async fn spec_invariants_hold() {575 async fn spec_invariants_hold() {
443- // Text questions carry neither choices nor a correct index.576+ // Text questions carry neither choices nor a correct choice.
444- assert!(QuestionSpec::try_new(kind("text"), None, None).is_ok());577+ assert!(QuestionSpec::try_new(kind("text"), None, None, &[]).is_ok());
445- assert!(QuestionSpec::try_new(kind("text"), two_choices(), None).is_err());578+ assert!(QuestionSpec::try_new(kind("text"), two_choices(), None, &[]).is_err());
446- assert!(QuestionSpec::try_new(kind("text"), None, Some(0)).is_err());579+ assert!(QuestionSpec::try_new(kind("text"), None, Some("a".into()), &[]).is_err());
447- assert!(QuestionSpec::try_new(kind("text"), two_choices(), Some(0)).is_err());
448 580
449 // Choice questions need both.581 // Choice questions need both.
450- assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(0)).is_ok());582+ assert!(spec(two_choices(), Some("a")).is_ok());
451- assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(1)).is_ok());583+ assert!(spec(two_choices(), Some("b")).is_ok());
452- assert!(QuestionSpec::try_new(kind("choice"), None, None).is_err());584+ assert!(spec(None, None).is_err());
453- assert!(QuestionSpec::try_new(kind("choice"), None, Some(0)).is_err());585+ assert!(spec(None, Some("a")).is_err());
454- assert!(QuestionSpec::try_new(kind("choice"), two_choices(), None).is_err());586+ assert!(spec(two_choices(), None).is_err());
455 }587 }
456 588
457 #[tokio::test]589 #[tokio::test]
458- async fn spec_correct_must_index_a_choice() {590+ async fn spec_correct_must_name_a_submitted_choice() {
459- assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(-1)).is_err());591+ assert!(spec(two_choices(), Some("c")).is_err());
460- assert!(QuestionSpec::try_new(kind("choice"), two_choices(), Some(2)).is_err());592+ assert!(spec(two_choices(), Some("")).is_err());
593+ // An unlabelled option cannot be marked correct — there is nothing to
594+ // name it by until the server's minted id comes back in the response.
595+ let unlabelled = Some(vec![
596+ ChoiceInput { id: None, text: "yes".into() },
597+ ChoiceInput { id: None, text: "no".into() },
598+ ]);
599+ assert!(spec(unlabelled, Some("a")).is_err());
600+ }
601+
602+ #[tokio::test]
603+ async fn spec_mints_a_distinct_id_per_choice() {
604+ let built = spec(two_choices(), Some("b")).unwrap();
605+ let (_, choices, correct) = built.into_parts();
606+ let choices = choices.unwrap();
607+ // Client labels never reach storage.
608+ assert!(choices.iter().all(|c| c.get_id().as_str().len() == 26));
609+ assert_ne!(choices[0].get_id(), choices[1].get_id());
610+ // `correct` resolved to the *second* option's minted id, by label.
611+ assert_eq!(correct.as_ref(), Some(choices[1].get_id()));
612+ }
613+
614+ /// The heart of the remodel: an id that matches a stored option keeps that
615+ /// option's identity, so reordering and deleting move nothing.
616+ #[tokio::test]
617+ async fn existing_ids_are_preserved_across_an_edit() {
618+ let stored = spec(two_choices(), Some("a")).unwrap().into_parts().1.unwrap();
619+ let (first, second) = (stored[0].get_id().clone(), stored[1].get_id().clone());
620+
621+ // Resubmit reordered, renaming the first option's text, and marking the
622+ // option that used to be second as correct.
623+ let edited = QuestionSpec::try_new(
624+ kind("choice"),
625+ Some(vec![
626+ ChoiceInput { id: Some(second.as_str().into()), text: "no".into() },
627+ ChoiceInput { id: Some(first.as_str().into()), text: "YES".into() },
628+ ]),
629+ Some(second.as_str().into()),
630+ &stored,
631+ )
632+ .unwrap();
633+ let (_, choices, correct) = edited.into_parts();
634+ let choices = choices.unwrap();
635+ assert_eq!(choices[0].get_id(), &second);
636+ assert_eq!(choices[1].get_id(), &first);
637+ assert_eq!(choices[1].get_text().as_str(), "YES");
638+ assert_eq!(correct.as_ref(), Some(&second));
639+ }
640+
641+ #[tokio::test]
642+ async fn spec_rejects_a_duplicate_choice_id() {
643+ let dupes = Some(vec![
644+ ChoiceInput { id: Some("a".into()), text: "yes".into() },
645+ ChoiceInput { id: Some("a".into()), text: "no".into() },
646+ ]);
647+ assert!(spec(dupes, Some("a")).is_err());
461 }648 }
462 649
463 #[tokio::test]650 #[tokio::test]
464 async fn spec_choice_count_is_bounded() {651 async fn spec_choice_count_is_bounded() {
465- let n = |count: usize| Some(vec!["option".to_string(); count]);652+ let n = |count: usize| {
466- assert!(QuestionSpec::try_new(kind("choice"), n(1), Some(0)).is_err());653+ Some(
467- assert!(QuestionSpec::try_new(kind("choice"), n(2), Some(0)).is_ok());654+ (0..count)
468- assert!(QuestionSpec::try_new(kind("choice"), n(10), Some(0)).is_ok());655+ .map(|i| ChoiceInput { id: Some(i.to_string()), text: "option".into() })
469- assert!(QuestionSpec::try_new(kind("choice"), n(11), Some(0)).is_err());656+ .collect::<Vec<_>>(),
657+ )
658+ };
659+ assert!(spec(n(1), Some("0")).is_err());
660+ assert!(spec(n(2), Some("0")).is_ok());
661+ assert!(spec(n(10), Some("0")).is_ok());
662+ assert!(spec(n(11), Some("0")).is_err());
663+ }
664+
665+ /// Generated coverage of the §2-REVISED identity rules. The example tests
666+ /// above each pin one hand-picked payload; these generate arbitrary stored
667+ /// sets and arbitrary submissions over them (matching keys, stale keys,
668+ /// `null` ids, duplicates, blank and oversized texts) and assert the rules
669+ /// as one predicate, because every bug this remodel exists to kill lived in
670+ /// a *relation* between a submitted option and a stored one.
671+ mod props {
672+ use super::*;
673+ use proptest::prelude::*;
674+
675+ /// A stored question's options, built the only way they can be: through
676+ /// `try_new` on create, so the ids are real minted ULIDs.
677+ fn stored_set(n: usize) -> Vec<Choice> {
678+ let inputs = (0..n)
679+ .map(|i| ChoiceInput { id: Some(format!("s{i}")), text: format!("stored {i}") })
680+ .collect();
681+ QuestionSpec::try_new(kind("choice"), Some(inputs), Some("s0".into()), &[])
682+ .unwrap()
683+ .into_parts()
684+ .1
685+ .unwrap()
686+ }
687+
688+ /// How a submitted option names itself: as a stored option, as some
689+ /// other string (a client-minted label, a stale id, junk), or not at all.
690+ #[derive(Debug, Clone)]
691+ enum Key {
692+ Stored(usize),
693+ Other(String),
694+ Null,
695+ }
696+
697+ fn key() -> impl Strategy<Value = Key> {
698+ prop_oneof![
699+ 4 => (0usize..10).prop_map(Key::Stored),
700+ 3 => prop_oneof![
701+ Just(String::new()),
702+ Just("new:1".to_string()),
703+ "[a-z0-9]{1,5}",
704+ Just("01ARZ3NDEKTSV4RRFFQ69G5FAV".to_string()),
705+ ].prop_map(Key::Other),
706+ 1 => Just(Key::Null),
707+ ]
708+ }
709+
710+ fn text() -> impl Strategy<Value = String> {
711+ prop_oneof![
712+ 6 => "[a-z ]{1,6}",
713+ 1 => Just(String::new()),
714+ 1 => Just(" ".to_string()),
715+ 1 => Just("x".repeat(501)),
716+ ]
717+ }
718+
719+ proptest! {
720+ #![proptest_config(ProptestConfig::with_cases(400))]
721+
722+ #[test]
723+ fn a_matching_key_is_that_choice_and_nothing_else_can_be(
724+ stored_n in 2usize..=10,
725+ submitted in prop::collection::vec((key(), text()), 0..=12),
726+ correct in prop::option::of(key()),
727+ ) {
728+ let stored = stored_set(stored_n);
729+ let name = |k: &Key| match k {
730+ Key::Stored(i) => Some(stored[i % stored_n].id.as_str().to_string()),
731+ Key::Other(s) => Some(s.clone()),
732+ Key::Null => None,
733+ };
734+ let keys: Vec<Option<String>> = submitted.iter().map(|(k, _)| name(k)).collect();
735+ let texts: Vec<String> = submitted.iter().map(|(_, t)| t.clone()).collect();
736+ let correct = correct.as_ref().map(|k| name(k).unwrap_or_default());
737+
738+ let inputs: Vec<ChoiceInput> = keys
739+ .iter()
740+ .zip(&texts)
741+ .map(|(id, text)| ChoiceInput { id: id.clone(), text: text.clone() })
742+ .collect();
743+ let built = QuestionSpec::try_new(
744+ kind("choice"),
745+ Some(inputs),
746+ correct.clone(),
747+ &stored,
748+ );
749+
750+ // Every way a payload can be rejected, stated independently of
751+ // the implementation's order of checks.
752+ let bad_len = !(MIN_QUESTION_CHOICES..=MAX_QUESTION_CHOICES).contains(&submitted.len());
753+ let mut seen: Vec<&String> = Vec::new();
754+ let mut dup = false;
755+ for k in keys.iter().flatten() {
756+ if seen.contains(&k) { dup = true; break; }
757+ seen.push(k);
758+ }
759+ let bad_text = texts.iter().any(|t| t.trim().is_empty() || t.chars().count() > MAX_CHOICE_TEXT_LEN);
760+ // `correct` must name a *submitted key*; an option sent with
761+ // `id: null` has no key, so it is unnameable.
762+ let named = correct.as_ref().is_some_and(|c| keys.iter().flatten().any(|k| k == c));
763+
764+ if bad_len || dup || bad_text || !named {
765+ prop_assert!(built.is_err());
766+ return Ok(());
767+ }
768+
769+ let (_, choices, resolved) = built.unwrap().into_parts();
770+ let choices = choices.unwrap();
771+ prop_assert_eq!(choices.len(), submitted.len());
772+
773+ let stored_ids: Vec<&str> = stored.iter().map(|c| c.id.as_str()).collect();
774+ for (i, choice) in choices.iter().enumerate() {
775+ // Order and text are passed through untouched.
776+ prop_assert_eq!(choice.text.as_str(), texts[i].as_str());
777+ match keys[i].as_deref().and_then(|k| stored.iter().find(|c| c.id.as_str() == k)) {
778+ // A key matching a stored choice IS that choice: same
779+ // id, so its picture stays with it.
780+ Some(existing) => prop_assert_eq!(&choice.id, &existing.id),
781+ // Any other key (stale, junk, absent) is a NEW option:
782+ // freshly minted, so it can never take over a stored
783+ // option's identity or its picture.
784+ None => {
785+ prop_assert_eq!(choice.id.as_str().len(), 26);
786+ prop_assert!(!stored_ids.contains(&choice.id.as_str()));
787+ }
788+ }
789+ }
790+ // No id is invented twice.
791+ let mut out: Vec<&str> = choices.iter().map(|c| c.id.as_str()).collect();
792+ out.sort_unstable();
793+ let unique = out.len();
794+ out.dedup();
795+ prop_assert_eq!(out.len(), unique);
796+
797+ // `correct` resolves to the option that carried that key.
798+ let correct = correct.unwrap();
799+ let at = keys.iter().position(|k| k.as_ref() == Some(&correct)).unwrap();
800+ prop_assert_eq!(resolved.as_ref(), Some(&choices[at].id));
801+ }
802+ }
470 }803 }
471 804
472 #[tokio::test]805 #[tokio::test]
473 async fn spec_rejects_blank_or_oversized_choices() {806 async fn spec_rejects_blank_or_oversized_choices() {
474- let blank = Some(vec!["yes".to_string(), " ".to_string()]);807+ let with = |text: String| {
475- assert!(QuestionSpec::try_new(kind("choice"), blank, Some(0)).is_err());808+ Some(vec![
476- let oversized = Some(vec!["yes".to_string(), "x".repeat(501)]);809+ ChoiceInput { id: Some("a".into()), text: "yes".into() },
477- assert!(QuestionSpec::try_new(kind("choice"), oversized, Some(0)).is_err());810+ ChoiceInput { id: Some("b".into()), text },
811+ ])
812+ };
813+ assert!(spec(with(" ".into()), Some("a")).is_err());
814+ assert!(spec(with("x".repeat(501)), Some("a")).is_err());
478 }815 }
479 }816 }
src/domain/mod.rsmodified+2 -0
@@ -24,6 +24,7 @@ pub mod homework_file;
24 pub mod homework_result;24 pub mod homework_result;
25 pub mod homework_submission;25 pub mod homework_submission;
26 pub mod message;26 pub mod message;
27+pub mod monotonic_id;
27 pub mod note;28 pub mod note;
28 pub mod note_file;29 pub mod note_file;
29 pub mod parent_link;30 pub mod parent_link;
@@ -40,6 +41,7 @@ pub mod settings;
40 pub mod solution;41 pub mod solution;
41 pub mod subject;42 pub mod subject;
42 pub mod term;43 pub mod term;
44+pub mod text_fold;
43 pub mod timestamp;45 pub mod timestamp;
44 pub mod user;46 pub mod user;
45 pub mod work_entry;47 pub mod work_entry;
src/domain/monotonic_id.rsadded+47 -0
@@ -0,0 +1,47 @@
1+//! Ids that sort in write order, for tables whose listings lean on `id` to
2+//! break ties (or to mean "newest first" outright).
3+//!
4+//! `Ulid::new()` fills the low 80 bits at random, so two ids minted in the
5+//! *same millisecond* sort arbitrarily against each other — millisecond-
6+//! accurate ordering only. That is not enough when a burst of writes lands
7+//! inside one tick (a recurring appointment publish expanding a series, a
8+//! teacher saving templates back to back, a test creating rows in a loop):
9+//! `ORDER BY id DESC` then scrambles them. [`next_ulid`] mints from one
10+//! process-wide [`Generator`], which keeps ids strictly increasing within a
11+//! millisecond by incrementing the random part instead of redrawing it.
12+
13+use std::sync::{LazyLock, Mutex};
14+
15+use ulid::{Generator, Ulid};
16+
17+static IDS: LazyLock<Mutex<Generator>> = LazyLock::new(|| Mutex::new(Generator::new()));
18+
19+/// The next id in write order. Process-wide: two processes writing the same
20+/// table still only get millisecond accuracy, which is what a distributed id
21+/// can promise anyway.
22+pub fn next_ulid() -> Ulid {
23+ let mut ids = IDS.lock().expect("monotonic id generator poisoned");
24+ // The only error is exhausting the random bits *within* one millisecond
25+ // (2^80 ids deep); it clears itself as the clock ticks, so retry rather
26+ // than fall back to a random id and silently reintroduce the defect.
27+ loop {
28+ if let Ok(ulid) = ids.generate() {
29+ break ulid;
30+ }
31+ }
32+}
33+
34+#[cfg(test)]
35+mod tests {
36+ use super::*;
37+
38+ /// The defect this module exists for: ids minted back to back (well inside
39+ /// one millisecond) must still sort in mint order.
40+ #[test]
41+ fn ids_sort_in_mint_order_within_a_millisecond() {
42+ let ids: Vec<String> = (0..1000).map(|_| next_ulid().to_string()).collect();
43+ let mut sorted = ids.clone();
44+ sorted.sort();
45+ assert_eq!(ids, sorted);
46+ }
47+}
src/domain/question_image.rsmodified+111 -29
@@ -1,6 +1,6 @@
1 //! An image pinned to an exam question — the question's own illustration1 //! An image pinned to an exam question — the question's own illustration
2 //! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture2 //! (`slot = NONE`, any kind: a map above the prompt) or one choice's picture
3-//! (`slot = i`, choice questions only). The row carries metadata; the bytes3+//! (`slot` = that choice's stable id, choice questions only). The row carries metadata; the bytes
4 //! live on disk under [`crate::config::Config::files_path`] in a file named by4 //! live on disk under [`crate::config::Config::files_path`] in a file named by
5 //! `file` — a fresh server-generated ULID per upload, so no user input ever5 //! `file` — a fresh server-generated ULID per upload, so no user input ever
6 //! shapes a disk path and a replace never overwrites bytes in place. The row6 //! shapes a disk path and a replace never overwrites bytes in place. The row
@@ -15,7 +15,7 @@ use ulid::Ulid;
15 use crate::database::{Database, QUESTION_IMAGE_TABLE};15 use crate::database::{Database, QUESTION_IMAGE_TABLE};
16 use crate::domain::course::CourseId;16 use crate::domain::course::CourseId;
17 use crate::domain::exam::ExamId;17 use crate::domain::exam::ExamId;
18-use crate::domain::exam_question::ExamQuestionId;18+use crate::domain::exam_question::{ChoiceId, ExamQuestionId};
19 use crate::domain::note_file::FileContentType;19 use crate::domain::note_file::FileContentType;
20 use crate::error::AppError;20 use crate::error::AppError;
21 21
@@ -24,12 +24,15 @@ pub struct QuestionImageId(RecordId);
24 24
25 impl QuestionImageId {25 impl QuestionImageId {
26 /// The one id a (question, slot) pair can have: `{qid}_q` for the26 /// The one id a (question, slot) pair can have: `{qid}_q` for the
27- /// question's own image, `{qid}_{i}` for choice `i` — uniqueness per slot27+ /// question's own image, `{qid}_{choice id}` for one option's picture —
28- /// needs no index this way.28+ /// uniqueness per slot needs no index this way. Keyed by the option's
29- pub fn for_slot(question: &ExamQuestionId, slot: Option<i64>) -> Self {29+ /// *stable id*, so reordering the choice list moves no picture.
30+ pub fn for_slot(question: &ExamQuestionId, slot: Option<&ChoiceId>) -> Self {
31+ // `_` is not in Crockford base32 and a ULID is never `"q"`, so
32+ // `{qid}_{cid}` and `{qid}_q` can never collide.
30 let suffix = match slot {33 let suffix = match slot {
31- None => "q".to_string(),34+ None => "q",
32- Some(index) => index.to_string(),35+ Some(id) => id.as_str(),
33 };36 };
34 Self(RecordId::new(37 Self(RecordId::new(
35 QUESTION_IMAGE_TABLE,38 QUESTION_IMAGE_TABLE,
@@ -54,8 +57,9 @@ pub struct QuestionImage {
54 id: QuestionImageId,57 id: QuestionImageId,
55 exam: ExamId,58 exam: ExamId,
56 question: ExamQuestionId,59 question: ExamQuestionId,
57- /// `NONE` = the question's illustration; `i` = the picture of choice `i`.60+ /// `NONE` = the question's illustration; otherwise the id of the option
58- slot: Option<i64>,61+ /// this picture belongs to.
62+ slot: Option<ChoiceId>,
59 /// The blob's on-disk name — a fresh ULID every upload.63 /// The blob's on-disk name — a fresh ULID every upload.
60 file: String,64 file: String,
61 content_type: FileContentType,65 content_type: FileContentType,
@@ -69,7 +73,7 @@ impl QuestionImage {
69 pub fn new(73 pub fn new(
70 exam: &ExamId,74 exam: &ExamId,
71 question: &ExamQuestionId,75 question: &ExamQuestionId,
72- slot: Option<i64>,76+ slot: Option<&ChoiceId>,
73 content_type: FileContentType,77 content_type: FileContentType,
74 size: i64,78 size: i64,
75 ) -> Self {79 ) -> Self {
@@ -77,7 +81,7 @@ impl QuestionImage {
77 id: QuestionImageId::for_slot(question, slot),81 id: QuestionImageId::for_slot(question, slot),
78 exam: exam.clone(),82 exam: exam.clone(),
79 question: question.clone(),83 question: question.clone(),
80- slot,84+ slot: slot.cloned(),
81 file: Ulid::new().to_string(),85 file: Ulid::new().to_string(),
82 content_type,86 content_type,
83 size,87 size,
@@ -88,8 +92,8 @@ impl QuestionImage {
88 &self.question92 &self.question
89 }93 }
90 94
91- pub fn get_slot(&self) -> Option<i64> {95+ pub fn get_slot(&self) -> Option<&ChoiceId> {
92- self.slot96+ self.slot.as_ref()
93 }97 }
94 98
95 pub fn get_file(&self) -> &str {99 pub fn get_file(&self) -> &str {
@@ -107,13 +111,14 @@ impl QuestionImage {
107 /// Create or replace the slot's image row — the deterministic id makes111 /// Create or replace the slot's image row — the deterministic id makes
108 /// this the whole "one image per slot" story.112 /// this the whole "one image per slot" story.
109 pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {113 pub async fn upsert(self, db: &Database) -> Result<QuestionImage, AppError> {
114+ // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic
110 let written: Option<QuestionImage> = db.upsert(self.id.record()).content(self).await?;115 let written: Option<QuestionImage> = db.upsert(self.id.record()).content(self).await?;
111 written.ok_or_else(|| AppError::Internal("failed to store question image".into()))116 written.ok_or_else(|| AppError::Internal("failed to store question image".into()))
112 }117 }
113 118
114 pub async fn read_slot(119 pub async fn read_slot(
115 question: &ExamQuestionId,120 question: &ExamQuestionId,
116- slot: Option<i64>,121+ slot: Option<&ChoiceId>,
117 db: &Database,122 db: &Database,
118 ) -> Result<Option<QuestionImage>, AppError> {123 ) -> Result<Option<QuestionImage>, AppError> {
119 Ok(db124 Ok(db
@@ -146,17 +151,28 @@ impl QuestionImage {
146 Ok(result.take::<Vec<QuestionImage>>(0)?)151 Ok(result.take::<Vec<QuestionImage>>(0)?)
147 }152 }
148 153
149- /// Drop every *choice* image of the question (the question's own154+ /// Drop the option pictures whose choice is gone — every choice image of
150- /// illustration stays), returning the removed rows so the caller can take155+ /// the question whose `slot` is *not* in `keep` (the question's own
151- /// their blobs off disk. Runs when a PATCH replaces the choice list — the156+ /// illustration always stays), returning the removed rows so the caller can
152- /// old pictures belong to the old options.157+ /// take their blobs off disk.
153- pub async fn delete_choices_for(158+ ///
159+ /// This is what makes an edit non-destructive: a PATCH that reorders,
160+ /// renames, or drops options passes the surviving choice ids as `keep`, so
161+ /// only the pictures of genuinely removed options go. `keep = &[]` (a text
162+ /// question, or an all-new choice list) still clears the lot.
163+ pub async fn delete_choices_not_in(
154 question: &ExamQuestionId,164 question: &ExamQuestionId,
165+ keep: &[ChoiceId],
155 db: &Database,166 db: &Database,
156 ) -> Result<Vec<QuestionImage>, AppError> {167 ) -> Result<Vec<QuestionImage>, AppError> {
168+ let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect();
157 let mut result = db169 let mut result = db
158- .query("DELETE question_image WHERE question = $q AND slot != NONE RETURN BEFORE")170+ .query(
171+ "DELETE question_image \
172+ WHERE question = $q AND slot != NONE AND slot NOT IN $keep RETURN BEFORE",
173+ )
159 .bind(("q", question.record()))174 .bind(("q", question.record()))
175+ .bind(("keep", keep))
160 .await?176 .await?
161 .check()?;177 .check()?;
162 Ok(result.take::<Vec<QuestionImage>>(0)?)178 Ok(result.take::<Vec<QuestionImage>>(0)?)
@@ -188,16 +204,40 @@ impl QuestionImage {
188 #[cfg(test)]204 #[cfg(test)]
189 mod tests {205 mod tests {
190 use super::*;206 use super::*;
207+ use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec};
191 208
192 fn png() -> FileContentType {209 fn png() -> FileContentType {
193 FileContentType::try_new("image/png").unwrap()210 FileContentType::try_new("image/png").unwrap()
194 }211 }
195 212
213+ /// Three minted choice ids to slot pictures against.
214+ fn choice_ids() -> Vec<ChoiceId> {
215+ QuestionSpec::try_new(
216+ QuestionKind::try_new("choice").unwrap(),
217+ Some(
218+ ["a", "b", "c"]
219+ .iter()
220+ .map(|l| ChoiceInput { id: Some((*l).into()), text: (*l).into() })
221+ .collect(),
222+ ),
223+ Some("a".into()),
224+ &[],
225+ )
226+ .unwrap()
227+ .into_parts()
228+ .1
229+ .unwrap()
230+ .iter()
231+ .map(|c| c.get_id().clone())
232+ .collect()
233+ }
234+
196 #[tokio::test]235 #[tokio::test]
197 async fn upsert_replaces_per_slot() {236 async fn upsert_replaces_per_slot() {
198 let db = crate::database::init_mem().await.unwrap();237 let db = crate::database::init_mem().await.unwrap();
199 let exam = ExamId::generate();238 let exam = ExamId::generate();
200 let question = ExamQuestionId::generate();239 let question = ExamQuestionId::generate();
240+ let ids = choice_ids();
201 241
202 let first = QuestionImage::new(&exam, &question, None, png(), 3)242 let first = QuestionImage::new(&exam, &question, None, png(), 3)
203 .upsert(&db)243 .upsert(&db)
@@ -215,8 +255,8 @@ mod tests {
215 assert_eq!(rows.len(), 1);255 assert_eq!(rows.len(), 1);
216 assert_eq!(rows[0].get_size(), 5);256 assert_eq!(rows[0].get_size(), 5);
217 257
218- // A choice slot is its own row.258+ // A choice slot is its own row, keyed by the option's id.
219- QuestionImage::new(&exam, &question, Some(0), png(), 7)259+ QuestionImage::new(&exam, &question, Some(&ids[0]), png(), 7)
220 .upsert(&db)260 .upsert(&db)
221 .await261 .await
222 .unwrap();262 .unwrap();
@@ -227,32 +267,74 @@ mod tests {
227 .len(),267 .len(),
228 2268 2
229 );269 );
230- let choice = QuestionImage::read_slot(&question, Some(0), &db)270+ let choice = QuestionImage::read_slot(&question, Some(&ids[0]), &db)
231 .await271 .await
232 .unwrap()272 .unwrap()
233 .unwrap();273 .unwrap();
234- assert_eq!(choice.get_slot(), Some(0));274+ assert_eq!(choice.get_slot(), Some(&ids[0]));
235 assert!(275 assert!(
236- QuestionImage::read_slot(&question, Some(1), &db)276+ QuestionImage::read_slot(&question, Some(&ids[1]), &db)
237 .await277 .await
238 .unwrap()278 .unwrap()
239 .is_none()279 .is_none()
240 );280 );
241 }281 }
242 282
283+ /// The behaviour the whole remodel exists for: an edit that keeps some
284+ /// options keeps exactly their pictures, and drops only the removed one's.
243 #[tokio::test]285 #[tokio::test]
244- async fn choice_wipe_spares_the_question_image() {286+ async fn only_the_dropped_options_lose_their_pictures() {
245 let db = crate::database::init_mem().await.unwrap();287 let db = crate::database::init_mem().await.unwrap();
246 let exam = ExamId::generate();288 let exam = ExamId::generate();
247 let question = ExamQuestionId::generate();289 let question = ExamQuestionId::generate();
248- for slot in [None, Some(0), Some(1)] {290+ let ids = choice_ids();
249- QuestionImage::new(&exam, &question, slot, png(), 1)291+ QuestionImage::new(&exam, &question, None, png(), 1)
292+ .upsert(&db)
293+ .await
294+ .unwrap();
295+ for id in &ids {
296+ QuestionImage::new(&exam, &question, Some(id), png(), 1)
297+ .upsert(&db)
298+ .await
299+ .unwrap();
300+ }
301+
302+ // Keep the first and last option (reordered — order is irrelevant now).
303+ let keep = vec![ids[2].clone(), ids[0].clone()];
304+ let dropped = QuestionImage::delete_choices_not_in(&question, &keep, &db)
305+ .await
306+ .unwrap();
307+ assert_eq!(dropped.len(), 1);
308+ assert_eq!(dropped[0].get_slot(), Some(&ids[1]));
309+
310+ let left = QuestionImage::list_for_question(&question, &db)
311+ .await
312+ .unwrap();
313+ // The question illustration plus the two surviving option pictures.
314+ assert_eq!(left.len(), 3);
315+ assert!(QuestionImage::read_slot(&question, Some(&ids[0]), &db).await.unwrap().is_some());
316+ assert!(QuestionImage::read_slot(&question, Some(&ids[2]), &db).await.unwrap().is_some());
317+ assert!(QuestionImage::read_slot(&question, None, &db).await.unwrap().is_some());
318+ }
319+
320+ #[tokio::test]
321+ async fn an_empty_keep_set_clears_every_option_picture_but_not_the_illustration() {
322+ let db = crate::database::init_mem().await.unwrap();
323+ let exam = ExamId::generate();
324+ let question = ExamQuestionId::generate();
325+ let ids = choice_ids();
326+ QuestionImage::new(&exam, &question, None, png(), 1)
327+ .upsert(&db)
328+ .await
329+ .unwrap();
330+ for id in &ids[..2] {
331+ QuestionImage::new(&exam, &question, Some(id), png(), 1)
250 .upsert(&db)332 .upsert(&db)
251 .await333 .await
252 .unwrap();334 .unwrap();
253 }335 }
254 336
255- let dropped = QuestionImage::delete_choices_for(&question, &db)337+ let dropped = QuestionImage::delete_choices_not_in(&question, &[], &db)
256 .await338 .await
257 .unwrap();339 .unwrap();
258 assert_eq!(dropped.len(), 2);340 assert_eq!(dropped.len(), 2);
src/domain/subject.rsmodified+53 -7
@@ -108,6 +108,21 @@ impl Subject {
108 Ok(db.select(id.record()).await?)108 Ok(db.select(id.record()).await?)
109 }109 }
110 110
111+ /// Several subjects in one query — the bulk half of a list endpoint that
112+ /// names each row's subject (a read per row would be an N+1).
113+ pub async fn list_by_ids(ids: &[&SubjectId], db: &Database) -> Result<Vec<Subject>, AppError> {
114+ if ids.is_empty() {
115+ return Ok(Vec::new());
116+ }
117+ let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();
118+ let mut result = db
119+ .query("SELECT * FROM subject WHERE id IN $ids")
120+ .bind(("ids", records))
121+ .await?
122+ .check()?;
123+ Ok(result.take::<Vec<Subject>>(0)?)
124+ }
125+
111 /// The course's subjects in curriculum order (ULID ids sort by creation).126 /// The course's subjects in curriculum order (ULID ids sort by creation).
112 pub async fn list_for_course(127 pub async fn list_for_course(
113 course: &CourseId,128 course: &CourseId,
@@ -127,14 +142,45 @@ impl Subject {
127 description: SubjectDescription,142 description: SubjectDescription,
128 db: &Database,143 db: &Database,
129 ) -> Result<Subject, AppError> {144 ) -> Result<Subject, AppError> {
130- self.name = name;145+ // Field-scoped: the handler holds no lock across its read and this
131- self.description = description;146+ // write, so a whole-row save would revert a concurrent edit of the
132- let updated: Option<Subject> = db.update(self.id.record()).content(self).await?;147+ // other field.
133- updated.ok_or(AppError::NotFound)148+ let mut result = db
134- }149+ .query("UPDATE $id SET name = $name, description = $description RETURN AFTER")
135-150+ .bind(("id", self.id.record()))
151+ .bind(("name", name))
152+ .bind(("description", description))
153+ .await?
154+ .check()?;
155+ result.take::<Vec<Subject>>(0)?.into_iter().next().ok_or(AppError::NotFound)
156+ }
157+
158+ /// Delete the subject and clear it off every bank template that carried it
159+ /// as origin metadata — one transaction, so a template can't be left
160+ /// pointing at a subject that no longer exists.
161+ ///
162+ /// Exam questions and homework are *not* cascaded: their `subject` is a
163+ /// required field the web layer refuses to orphan (both still block the
164+ /// delete with a 409). The bank's is optional metadata, and blocking on it
165+ /// was a dead end — only the template's owner may re-tag it, so a manager
166+ /// could never clear their own 409, and a private template raising it
167+ /// leaked its existence.
136 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {168 pub async fn delete(self, db: &Database) -> Result<Subject, AppError> {
137- let deleted: Option<Subject> = db.delete(self.id.record()).await?;169+ let mut result = db
170+ .query(
171+ "BEGIN TRANSACTION;
172+ UPDATE bank_question SET subject = NONE WHERE subject = $sub;
173+ LET $before = (DELETE $sub RETURN BEFORE);
174+ RETURN $before;
175+ COMMIT TRANSACTION;",
176+ )
177+ .bind(("sub", self.id.record()))
178+ .await?
179+ .check()?;
180+ // Read through the trailing `RETURN`, not a counted slot — see
181+ // [`crate::domain::exam::Exam::delete`].
182+ let slot = result.num_statements().saturating_sub(2);
183+ let deleted: Option<Subject> = result.take::<Vec<Subject>>(slot)?.into_iter().next();
138 deleted.ok_or(AppError::NotFound)184 deleted.ok_or(AppError::NotFound)
139 }185 }
140 }186 }
src/domain/text_fold.rsadded+81 -0
@@ -0,0 +1,81 @@
1+//! Case- and diacritic-insensitive folding for search, shared by the needle
2+//! (Rust side) and the column (SurrealQL side) so the two can never disagree.
3+//!
4+//! Rust's `to_lowercase` and SurrealQL's `string::lowercase` are both
5+//! locale-invariant: Turkish `İ` (U+0130) lowercases to `i` + U+0307
6+//! (combining dot above), so plain `string::lowercase(text) CONTAINS $q` never
7+//! matched `İSTANBUL` for a teacher who typed `istanbul`. Folding strips that
8+//! leftover dot and maps the Turkish letters onto their ASCII base, which also
9+//! makes the search work in both directions (`istanbul` ↔ `İSTANBUL`,
10+//! `ıgdır` ↔ `Iğdır`).
11+
12+/// Replacements applied *after* lowercasing, in order. One table, two
13+/// consumers ([`fold`] and [`fold_sql`]): the needle and the column are folded
14+/// by the same rules by construction, which is the whole point.
15+const REPLACEMENTS: &[(&str, &str)] = &[
16+ ("\u{307}", ""), // combining dot above, left behind by İ → i̇
17+ ("ı", "i"),
18+ ("ş", "s"),
19+ ("ğ", "g"),
20+ ("ç", "c"),
21+ ("ö", "o"),
22+ ("ü", "u"),
23+ ("â", "a"),
24+ ("î", "i"),
25+ ("û", "u"),
26+];
27+
28+/// Fold a search needle (or any Rust-side string) for comparison.
29+pub fn fold(text: &str) -> String {
30+ let mut folded = text.to_lowercase();
31+ for (from, to) in REPLACEMENTS {
32+ folded = folded.replace(from, to);
33+ }
34+ folded
35+}
36+
37+/// The same folding as a SurrealQL expression over `column`, for use inside a
38+/// `WHERE`. `column` is always a literal field name we wrote — never user
39+/// input.
40+pub fn fold_sql(column: &str) -> String {
41+ let mut expr = format!("string::lowercase({column})");
42+ for (from, to) in REPLACEMENTS {
43+ expr = format!("string::replace({expr}, '{from}', '{to}')");
44+ }
45+ expr
46+}
47+
48+#[cfg(test)]
49+mod tests {
50+ use super::*;
51+
52+ #[test]
53+ fn folds_turkish_casing_both_ways() {
54+ assert_eq!(fold("İSTANBUL"), "istanbul");
55+ assert_eq!(fold("istanbul"), "istanbul");
56+ assert_eq!(fold("İstanbul"), "istanbul");
57+ assert_eq!(fold("ISTANBUL"), "istanbul");
58+ assert_eq!(fold("ıstanbul"), "istanbul");
59+ assert_eq!(fold("Iğdır"), "igdir");
60+ assert_eq!(fold("ÇÖZÜM"), "cozum");
61+ assert_eq!(fold("Şekil"), "sekil");
62+ }
63+
64+ /// The SQL side must fold a literal exactly like the Rust side does, or the
65+ /// needle and the column disagree again.
66+ #[tokio::test]
67+ async fn sql_folding_matches_rust_folding() {
68+ let db = crate::database::init_mem().await.unwrap();
69+ for sample in ["İSTANBUL", "Iğdır", "ÇÖZÜM", "istanbul"] {
70+ let mut result = db
71+ .query(format!("RETURN {};", fold_sql("$text")))
72+ .bind(("text", sample.to_string()))
73+ .await
74+ .unwrap()
75+ .check()
76+ .unwrap();
77+ let got = result.take::<Option<String>>(0).unwrap().unwrap();
78+ assert_eq!(got, fold(sample), "sql fold disagrees for {sample}");
79+ }
80+ }
81+}
src/lib.rsmodified+1 -1
@@ -53,7 +53,7 @@ use crate::state::AppState;
53 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),53 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
54 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),54 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
55 (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),55 (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),
56- (name = "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"),56+ (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"),
57 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),57 (name = "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"),
58 (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"),58 (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"),
59 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),59 (name = "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"),
src/web/bank_questions.rsmodified+323 -124
@@ -1,8 +1,12 @@
1-//! The school-wide question bank: a shared library of reusable question1+//! The question bank: a library of reusable question templates. A template is
2-//! templates. Any teacher+ reads the whole bank and instantiates any template2+//! born `private` — visible to its owner (and admins) alone — and becomes
3-//! into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, in3+//! school-wide only when its owner PATCHes `visibility` to `school`, because a
4-//! `web/exams`), but only a template's owner (admins aside) may edit or delete4+//! template carries `correct`, the answer key, and saving a live exam's
5-//! it. A template carries the same content an exam question does — text,5+//! question to the bank must not broadcast it. Teacher+ read and instantiate
6+//! every template they can see (`POST /exams/{id}/questions/from-bank/{bid}`,
7+//! in `web/exams`); a template they cannot see is a 404 on every route, never a
8+//! 403, since a 403 would confirm it exists. Only the owner (admins aside) may
9+//! edit or delete one. A template carries the same content an exam question does — text,
6 //! points, a `choice`/`text` spec, an optional illustration, and per-option10 //! points, a `choice`/`text` spec, an optional illustration, and per-option
7 //! pictures — minus any exam tie: its `subject` is origin metadata only (the11 //! pictures — minus any exam tie: its `subject` is origin metadata only (the
8 //! same-course rule is checked at instantiate time against the target exam's12 //! same-course rule is checked at instantiate time against the target exam's
@@ -21,29 +25,34 @@ use utoipa_axum::router::OpenApiRouter;
21 use utoipa_axum::routes;25 use utoipa_axum::routes;
22 26
23 use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};27 use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
24-use crate::domain::bank_question::{BankQuestion, BankQuestionId};28+use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
25 use crate::domain::bank_question_image::BankQuestionImage;29 use crate::domain::bank_question_image::BankQuestionImage;
26-use crate::domain::exam_question::{QuestionKind, QuestionPoints, QuestionSpec, QuestionText};30+use crate::domain::exam_question::{
31+ Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
32+};
27 use crate::domain::note_file::FileContentType;33 use crate::domain::note_file::FileContentType;
28 use crate::domain::role::Role;34 use crate::domain::role::Role;
29 use crate::domain::settings::Settings;35 use crate::domain::settings::Settings;
30-use crate::domain::subject::SubjectId;36+use crate::domain::subject::{Subject, SubjectId};
31 use crate::domain::user::{User, UserId};37 use crate::domain::user::{User, UserId};
32 use crate::error::{AppError, ErrorResponse, ValidationError};38 use crate::error::{AppError, ErrorResponse, ValidationError};
33 use crate::state::AppState;39 use crate::state::AppState;
34 40
41+use super::dto::person_map;
35 use super::subjects::subject_must_exist;42 use super::subjects::subject_must_exist;
43+use super::exams::ChoiceResponse;
36 use super::{44 use super::{
37- Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type,45+ ChoiceBody, Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type,
38- paginate, read_upload, remove_blob, serve_inline_blob, set_or_clear,46+ read_upload, remove_blob, serve_inline_blob, set_or_clear,
39 };47 };
40 48
41 /// Serializes bank writes that adopt a `subject` against a concurrent subject49 /// Serializes bank writes that adopt a `subject` against a concurrent subject
42 /// delete. Bank create/update take the reader lease across their50 /// delete. Bank create/update take the reader lease across their
43-/// subject-exists check and the insert; the subject delete-guard takes the51+/// subject-exists check and the write; the subject delete takes the writer
44-/// writer lease across its `any_for_subject` check and the delete, so a52+/// lease across the cascade that clears `subject` off every template, so a
45-/// template can't land on a subject that vanished mid-flight — the bank twin53+/// template can't land on a subject that vanished mid-flight (it would outlive
46-/// of the [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards.54+/// the sweep) — the bank twin of the
55+/// [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards.
47 /// Save-to-bank (`question_to_bank`) takes the same reader lease across its56 /// Save-to-bank (`question_to_bank`) takes the same reader lease across its
48 /// question read and insert: the source question can be re-tagged/deleted, so57 /// question read and insert: the source question can be re-tagged/deleted, so
49 /// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in58 /// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in
@@ -91,16 +100,19 @@ struct CreateBankQuestion {
91 #[schema(example = 10)]100 #[schema(example = 10)]
92 points: i64,101 points: i64,
93 /// The options of a `choice` question (2–10 of them); omit for `text`.102 /// The options of a `choice` question (2–10 of them); omit for `text`.
94- choices: Option<Vec<String>>,103+ /// Each carries an `id` naming it within this payload — the server mints
95- /// Zero-based index of the right option; required for `choice`, absent104+ /// the stored ids and returns them.
96- /// for `text`.105+ choices: Option<Vec<ChoiceBody>>,
97- #[schema(example = 1)]106+ /// The `id` of the right option, as sent in `choices`; required for
98- correct: Option<i64>,107+ /// `choice`, absent for `text`.
108+ #[schema(example = "b")]
109+ correct: Option<String>,
99 }110 }
100 111
101 #[derive(Deserialize, ToSchema)]112 #[derive(Deserialize, ToSchema)]
102 struct UpdateBankQuestion {113 struct UpdateBankQuestion {
103- /// Re-tag the template's origin subject. Omit to keep the current one.114+ /// Re-tag the template's origin subject. Omit to keep the current one
115+ /// (which is `null` if that subject has since been deleted).
104 subject_id: Option<String>,116 subject_id: Option<String>,
105 text: Option<String>,117 text: Option<String>,
106 points: Option<i64>,118 points: Option<i64>,
@@ -109,15 +121,22 @@ struct UpdateBankQuestion {
109 /// when moving to `text`.121 /// when moving to `text`.
110 kind: Option<String>,122 kind: Option<String>,
111 /// Omit to keep the stored options; send `null` to drop them (text123 /// Omit to keep the stored options; send `null` to drop them (text
112- /// questions only). Replacing or clearing the list also drops every option124+ /// questions only). Send each option back with the `id` it was returned
113- /// picture — the old images belong to the old options.125+ /// with to keep it — its picture rides along. Only options whose id is
126+ /// absent from the new list lose their picture.
114 #[serde(default, deserialize_with = "set_or_clear")]127 #[serde(default, deserialize_with = "set_or_clear")]
115- #[schema(value_type = Option<Vec<String>>)]128+ #[schema(value_type = Option<Vec<ChoiceBody>>)]
116- choices: Option<Option<Vec<String>>>,129+ choices: Option<Option<Vec<ChoiceBody>>>,
117- /// Omit to keep; `null` to clear (text questions only).130+ /// The `id` of the right option. Omit to keep; `null` to clear (text
131+ /// questions only).
118 #[serde(default, deserialize_with = "set_or_clear")]132 #[serde(default, deserialize_with = "set_or_clear")]
119- #[schema(value_type = Option<i64>)]133+ #[schema(value_type = Option<String>)]
120- correct: Option<Option<i64>>,134+ correct: Option<Option<String>>,
135+ /// `private` (owner + admins only) or `school` (every teacher). Publishing
136+ /// hands the template's `correct` answer key — and its pictures — to every
137+ /// teacher in the school, so it is only ever an explicit choice.
138+ #[schema(example = "school")]
139+ visibility: Option<String>,
121 }140 }
122 141
123 /// Filters for the bank list.142 /// Filters for the bank list.
@@ -129,6 +148,16 @@ struct BankQuestionFilter {
129 /// Narrow to templates owned by this user (a user id, or `me` for the148 /// Narrow to templates owned by this user (a user id, or `me` for the
130 /// caller). Omit for every owner's templates.149 /// caller). Omit for every owner's templates.
131 owner: Option<String>,150 owner: Option<String>,
151+ /// Case-insensitive fragment of the question text. Blank or omitted
152+ /// matches every template.
153+ #[param(example = "photosynthesis")]
154+ q: Option<String>,
155+ /// `private` or `school`. Narrows what the caller can already see, never
156+ /// widens it: `private` is effectively "my drafts" (nobody else's private
157+ /// template is ever visible), `school` is the published library. Omit for
158+ /// both.
159+ #[param(example = "school")]
160+ visibility: Option<String>,
132 }161 }
133 162
134 /// A bank template as its readers see it — `correct` included (teacher+ only,163 /// A bank template as its readers see it — `correct` included (teacher+ only,
@@ -140,15 +169,18 @@ pub(crate) struct BankQuestionResponse {
140 /// The teacher who owns the template (only they, or an admin, may edit it).169 /// The teacher who owns the template (only they, or an admin, may edit it).
141 owner: String,170 owner: String,
142 /// The origin subject (metadata only — not enforced against a course).171 /// The origin subject (metadata only — not enforced against a course).
143- subject: String,172+ /// `null` once that subject was deleted: deleting a subject clears the
173+ /// bank's copy of it rather than being blocked by it.
174+ subject: Option<String>,
144 text: String,175 text: String,
145 /// `choice` or `text`.176 /// `choice` or `text`.
146 #[schema(example = "choice")]177 #[schema(example = "choice")]
147 kind: String,178 kind: String,
148 points: i64,179 points: i64,
149- choices: Option<Vec<String>>,180+ /// The options with their stable ids (`choice` templates only).
150- /// Zero-based index of the right option (`choice` templates only).181+ choices: Option<Vec<ChoiceResponse>>,
151- correct: Option<i64>,182+ /// The id of the right option (`choice` templates only).
183+ correct: Option<String>,
152 /// The template's illustration, if one was uploaded (any kind).184 /// The template's illustration, if one was uploaded (any kind).
153 image: Option<BankImageMeta>,185 image: Option<BankImageMeta>,
154 /// Per-option pictures, aligned with `choices` (`choice` templates only).186 /// Per-option pictures, aligned with `choices` (`choice` templates only).
@@ -156,59 +188,122 @@ pub(crate) struct BankQuestionResponse {
156 /// The exam this template was saved off, if any (a direct-authored188 /// The exam this template was saved off, if any (a direct-authored
157 /// template has none).189 /// template has none).
158 source_exam: Option<String>,190 source_exam: Option<String>,
191+ /// `private` (owner + admins only) or `school` (every teacher). New
192+ /// templates start `private`.
193+ #[schema(example = "private")]
194+ visibility: String,
159 /// When the template was saved, UTC unix-milliseconds.195 /// When the template was saved, UTC unix-milliseconds.
160 created_at: i64,196 created_at: i64,
197+ /// The origin subject's name, resolved for display. Empty when the subject
198+ /// is gone (deleted, so `subject` is `null` too) — and on the
199+ /// single-template endpoints, which don't join.
200+ #[schema(example = "Limits and continuity")]
201+ subject_name: String,
202+ /// The owner's display name (full name, else username). Empty when the user
203+ /// is gone — and on the single-template endpoints, which don't join.
204+ #[schema(example = "Ada Lovelace")]
205+ owner_name: String,
206+ /// How many exam questions were created from this template — the
207+ /// divergence surface, since each of them is a detached copy that a later
208+ /// edit here does *not* reach. `0` for an unused template, and `0` on the
209+ /// single-template endpoints, which don't join (list-only, exactly like
210+ /// `subject_name`/`owner_name`).
211+ #[schema(example = 3)]
212+ used_count: i64,
161 }213 }
162 214
163 impl BankQuestionResponse {215 impl BankQuestionResponse {
216+ /// The names and the usage tally are joined on by the list endpoint alone
217+ /// (see [`Self::with_names`]); every other endpoint returns one template
218+ /// and leaves them empty/zero.
219+ pub(crate) fn with_names(
220+ question: &BankQuestion,
221+ images: &[BankQuestionImage],
222+ subject_name: String,
223+ owner_name: String,
224+ used_count: i64,
225+ ) -> Self {
226+ Self {
227+ subject_name,
228+ owner_name,
229+ used_count,
230+ ..Self::new(question, images)
231+ }
232+ }
233+
164 pub(crate) fn new(question: &BankQuestion, images: &[BankQuestionImage]) -> Self {234 pub(crate) fn new(question: &BankQuestion, images: &[BankQuestionImage]) -> Self {
165 Self {235 Self {
236+ subject_name: String::new(),
237+ owner_name: String::new(),
238+ used_count: 0,
166 id: question.get_id().key().to_string(),239 id: question.get_id().key().to_string(),
167 owner: question.get_owner().key().to_string(),240 owner: question.get_owner().key().to_string(),
168- subject: question.get_subject().key().to_string(),241+ subject: question.get_subject().map(|s| s.key().to_string()),
169 text: question.get_text().as_str().to_string(),242 text: question.get_text().as_str().to_string(),
170 kind: question.get_kind().as_str().to_string(),243 kind: question.get_kind().as_str().to_string(),
171 points: question.get_points().as_i64(),244 points: question.get_points().as_i64(),
172- choices: question245+ choices: ChoiceResponse::list(question.get_choices()),
173- .get_choices()246+ correct: question.get_correct().map(|id| id.as_str().to_string()),
174- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
175- correct: question.get_correct(),
176 image: bank_image_meta(images, None),247 image: bank_image_meta(images, None),
177 choice_images: bank_choice_image_metas(question, images),248 choice_images: bank_choice_image_metas(question, images),
178 source_exam: question.get_source_exam().map(|e| e.key().to_string()),249 source_exam: question.get_source_exam().map(|e| e.key().to_string()),
250+ visibility: question.get_visibility().as_str().to_string(),
179 created_at: question.get_created_at().as_millis(),251 created_at: question.get_created_at().as_millis(),
180 }252 }
181 }253 }
182 }254 }
183 255
256+/// The template's option named by `choice_id` — a 400 for a text template or an
257+/// id the template doesn't have, mirroring `exams::choice_slot`.
258+fn bank_choice_slot(question: &BankQuestion, choice_id: &str) -> Result<ChoiceId, AppError> {
259+ let Some(choices) = question.get_choices() else {
260+ return Err(AppError::Validation(ValidationError::Invalid {
261+ field: "choice_id",
262+ reason: "only choice questions take option pictures",
263+ }));
264+ };
265+ choices
266+ .iter()
267+ .find(|choice| choice.get_id().as_str() == choice_id)
268+ .map(|choice| choice.get_id().clone())
269+ .ok_or(AppError::Validation(ValidationError::Invalid {
270+ field: "choice_id",
271+ reason: "must name one of the choices",
272+ }))
273+}
274+
184 /// The template's slot out of its image rows.275 /// The template's slot out of its image rows.
185-fn bank_image_meta(images: &[BankQuestionImage], slot: Option<i64>) -> Option<BankImageMeta> {276+fn bank_image_meta(images: &[BankQuestionImage], slot: Option<&ChoiceId>) -> Option<BankImageMeta> {
186 images277 images
187 .iter()278 .iter()
188 .find(|image| image.get_slot() == slot)279 .find(|image| image.get_slot() == slot)
189 .map(BankImageMeta::new)280 .map(BankImageMeta::new)
190 }281 }
191 282
192-/// The per-choice metas, aligned index-for-index with `choices` (`None`283+/// The per-choice metas, aligned position-for-position with `choices` (`None`
193 /// entries = that option has no picture); `None` whole for text templates.284 /// entries = that option has no picture); `None` whole for text templates.
285+/// A response-only projection rebuilt from the current list — the pictures
286+/// themselves are stored against choice ids.
194 fn bank_choice_image_metas(287 fn bank_choice_image_metas(
195 question: &BankQuestion,288 question: &BankQuestion,
196 images: &[BankQuestionImage],289 images: &[BankQuestionImage],
197 ) -> Option<Vec<Option<BankImageMeta>>> {290 ) -> Option<Vec<Option<BankImageMeta>>> {
198 question.get_choices().map(|choices| {291 question.get_choices().map(|choices| {
199- (0..choices.len() as i64)292+ choices
200- .map(|index| bank_image_meta(images, Some(index)))293+ .iter()
294+ .map(|choice| bank_image_meta(images, Some(choice.get_id())))
201 .collect()295 .collect()
202 })296 })
203 }297 }
204 298
205-/// Every bank image row bucketed by template key — one query feeding a whole299+/// The image rows of `questions` bucketed by template key — one query feeding
206-/// template list (avoids an image query per row).300+/// a whole page (neither an image query per row, nor the school's every image).
207 async fn bank_images_by_question(301 async fn bank_images_by_question(
302+ questions: &[&BankQuestionId],
208 db: &crate::database::Database,303 db: &crate::database::Database,
209 ) -> Result<HashMap<String, Vec<BankQuestionImage>>, AppError> {304 ) -> Result<HashMap<String, Vec<BankQuestionImage>>, AppError> {
210 let mut buckets: HashMap<String, Vec<BankQuestionImage>> = HashMap::new();305 let mut buckets: HashMap<String, Vec<BankQuestionImage>> = HashMap::new();
211- for image in BankQuestionImage::list_all(db).await? {306+ for image in BankQuestionImage::list_for_questions(questions, db).await? {
212 buckets307 buckets
213 .entry(image.get_bank_question().key().to_string())308 .entry(image.get_bank_question().key().to_string())
214 .or_default()309 .or_default()
@@ -242,8 +337,23 @@ async fn question_or_404(st: &AppState, bid: &str) -> Result<BankQuestion, AppEr
242 .ok_or(AppError::NotFound)337 .ok_or(AppError::NotFound)
243 }338 }
244 339
245-/// Reads are school-wide, but a mutation needs ownership: the caller owns the340+/// Whether `user` may read the template at all: it is published to the school,
246-/// template, or is an admin. Everyone else gets a 403.341+/// or it is theirs, or they are an admin.
342+///
343+/// Admins **do** see `private` templates. They already read every exam's
344+/// questions — `correct` included — through `can_manage_course`, and
345+/// `ensure_owner` already lets them edit and delete any template; letting them
346+/// delete a row they may not look at would be the odd rule, not this one.
347+pub(crate) fn can_see(question: &BankQuestion, user: &User) -> bool {
348+ question.get_visibility().is_school()
349+ || question.get_owner() == user.get_id()
350+ || user.get_role().at_least(Role::Admin)
351+}
352+
353+/// Reads are gated by [`can_see`], and a mutation additionally needs ownership:
354+/// the caller owns the template, or is an admin. Everyone else gets a 403 —
355+/// but only for a template they can see; an invisible one is a 404 long before
356+/// this runs, so a 403 never doubles as proof the template exists.
247 fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> {357 fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> {
248 if question.get_owner() == user.get_id() || user.get_role().at_least(Role::Admin) {358 if question.get_owner() == user.get_id() || user.get_role().at_least(Role::Admin) {
249 return Ok(());359 return Ok(());
@@ -253,10 +363,25 @@ fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> {
253 ))363 ))
254 }364 }
255 365
366+/// The template, provided the caller may see it — the shared front half of
367+/// every read. A template the caller may not see is a **404, not a 403**: a
368+/// 403 would confirm that someone else's template exists under that id.
369+pub(crate) async fn visible_question(
370+ st: &AppState,
371+ user: &User,
372+ bid: &str,
373+) -> Result<BankQuestion, AppError> {
374+ let question = question_or_404(st, bid).await?;
375+ if !can_see(&question, user) {
376+ return Err(AppError::NotFound);
377+ }
378+ Ok(question)
379+}
380+
256 /// The template, provided the caller may edit it — the shared front half of381 /// The template, provided the caller may edit it — the shared front half of
257 /// every owner-gated write (PATCH, delete, image writes).382 /// every owner-gated write (PATCH, delete, image writes).
258 async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQuestion, AppError> {383 async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQuestion, AppError> {
259- let question = question_or_404(st, bid).await?;384+ let question = visible_question(st, user, bid).await?;
260 ensure_owner(&question, user)?;385 ensure_owner(&question, user)?;
261 Ok(question)386 Ok(question)
262 }387 }
@@ -267,7 +392,7 @@ async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQue
267 pub(crate) async fn store_image(392 pub(crate) async fn store_image(
268 st: &AppState,393 st: &AppState,
269 question: &BankQuestionId,394 question: &BankQuestionId,
270- slot: Option<i64>,395+ slot: Option<&ChoiceId>,
271 content_type: FileContentType,396 content_type: FileContentType,
272 data: &[u8],397 data: &[u8],
273 ) -> Result<BankQuestionImage, AppError> {398 ) -> Result<BankQuestionImage, AppError> {
@@ -321,7 +446,14 @@ async fn create_question(
321 let subject = subject_must_exist(&req.subject_id, &st.db).await?;446 let subject = subject_must_exist(&req.subject_id, &st.db).await?;
322 let text = QuestionText::try_new(&req.text)?;447 let text = QuestionText::try_new(&req.text)?;
323 let points = QuestionPoints::try_new(req.points)?;448 let points = QuestionPoints::try_new(req.points)?;
324- let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?;449+ // Nothing stored to match against on create: every option is new and every
450+ // id is minted here.
451+ let spec = QuestionSpec::try_new(
452+ QuestionKind::try_new(&req.kind)?,
453+ ChoiceBody::into_inputs(req.choices),
454+ req.correct,
455+ &[],
456+ )?;
325 let question =457 let question =
326 BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?;458 BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?;
327 Ok((459 Ok((
@@ -330,10 +462,17 @@ async fn create_question(
330 ))462 ))
331 }463 }
332 464
333-/// The whole bank, school-wide, in creation order — every teacher+ reads every465+/// The bank the caller may see — their own templates plus the ones published
334-/// template. `?subject=` narrows to one origin subject; `?owner=` to one owner466+/// to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner
335-/// (a user id, or `me` for the caller). Paged via `?limit=&offset=` (omit467+/// (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of
336-/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope.468+/// the question text; `?visibility=private|school` to one shelf — it narrows
469+/// what the caller may already see and never widens it, so `private` is "my
470+/// drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of
471+/// them); returns a `{items, total, limit, offset}` envelope, where `total`
472+/// counts every match under the same filters, not just this page. Each item
473+/// carries the resolved `subject_name`/`owner_name` so a client needn't look
474+/// them up per row, plus `used_count` — how many exam questions were copied out
475+/// of that template (one grouped query for the page, not one per row).
337 #[utoipa::path(476 #[utoipa::path(
338 get,477 get,
339 path = "/",478 path = "/",
@@ -342,7 +481,7 @@ async fn create_question(
342 params(BankQuestionFilter, PageParams),481 params(BankQuestionFilter, PageParams),
343 responses(482 responses(
344 (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page<BankQuestionResponse>),483 (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page<BankQuestionResponse>),
345- (status = 400, description = "Invalid limit or offset", body = ErrorResponse),484+ (status = 400, description = "Invalid limit, offset, or visibility", body = ErrorResponse),
346 (status = 401, description = "Not authenticated", body = ErrorResponse),485 (status = 401, description = "Not authenticated", body = ErrorResponse),
347 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),486 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
348 ),487 ),
@@ -354,35 +493,83 @@ async fn list_questions(
354 Query(page): Query<PageParams>,493 Query(page): Query<PageParams>,
355 ) -> Result<Json<Page<BankQuestionResponse>>, AppError> {494 ) -> Result<Json<Page<BankQuestionResponse>>, AppError> {
356 let (limit, offset) = page.resolve()?;495 let (limit, offset) = page.resolve()?;
357- let mut questions = BankQuestion::list(&st.db).await?;496+ let subject = filter.subject.as_deref().map(SubjectId::from_key);
358- if let Some(ref subject) = filter.subject {497+ let owner = filter.owner.as_deref().map(|owner| match owner {
359- let subject = SubjectId::from_key(subject);498+ "me" => user.get_id().clone(),
360- questions.retain(|question| question.get_subject() == &subject);499+ id => UserId::from_key(id),
361- }500+ });
362- if let Some(ref owner) = filter.owner {501+ // Same newtype the PATCH validates against, so an unknown shelf is the same
363- let owner = if owner == "me" {502+ // 400 ("visibility must be private or school") on both routes.
364- user.get_id().clone()503+ let visibility = filter
365- } else {504+ .visibility
366- UserId::from_key(owner)505+ .as_deref()
367- };506+ .map(BankVisibility::try_new)
368- questions.retain(|question| question.get_owner() == &owner);507+ .transpose()?;
369- }508+ // The visibility gate is one of those SQL filters, never a post-filter over
370- let total = questions.len() as i64;509+ // the page: `total` counts what the caller may see, so paging can't hand
371- // One image query for the whole bank, bucketed by template — no per-row510+ // back short pages full of holes where someone else's private templates sat.
372- // fetch on the page.511+ let viewer = (!user.get_role().at_least(Role::Admin)).then(|| user.get_id().clone());
373- let buckets = bank_images_by_question(&st.db).await?;512+ // Filters, order, and window are all SQL — `total` comes from a count over
513+ // the same WHERE, so a client can page past the first window.
514+ let (questions, total) = BankQuestion::list(
515+ viewer.as_ref(),
516+ owner.as_ref(),
517+ subject.as_ref(),
518+ visibility.as_ref(),
519+ filter.q.as_deref(),
520+ limit,
521+ offset,
522+ &st.db,
523+ )
524+ .await?;
525+
526+ // Four bulk joins over the page alone: its images, its subjects' names,
527+ // its owners' names, and how many exam questions each template spawned.
528+ // A missing row renders empty, never fails the list.
529+ let ids: Vec<&BankQuestionId> = questions.iter().map(BankQuestion::get_id).collect();
530+ let buckets = bank_images_by_question(&ids, &st.db).await?;
531+ // One grouped query for the whole page — never a count per row.
532+ let used = BankQuestion::usage_counts(&ids, &st.db).await?;
533+ let subject_ids: Vec<&SubjectId> = questions.iter().filter_map(BankQuestion::get_subject).collect();
534+ let subject_names: HashMap<String, String> = Subject::list_by_ids(&subject_ids, &st.db)
535+ .await?
536+ .iter()
537+ .map(|subject| {
538+ (
539+ subject.get_id().key().to_string(),
540+ subject.get_name().as_str().to_string(),
541+ )
542+ })
543+ .collect();
544+ let people = person_map(questions.iter().map(|q| q.get_owner().clone()), &st.db).await?;
545+
374 let empty: Vec<BankQuestionImage> = Vec::new();546 let empty: Vec<BankQuestionImage> = Vec::new();
375- let items = paginate(&questions, limit, offset)547+ let items = questions
376 .iter()548 .iter()
377 .map(|question| {549 .map(|question| {
378 let images = buckets.get(question.get_id().key()).unwrap_or(&empty);550 let images = buckets.get(question.get_id().key()).unwrap_or(&empty);
379- BankQuestionResponse::new(question, images)551+ let subject_name = question
552+ .get_subject()
553+ .and_then(|subject| subject_names.get(subject.key()).cloned())
554+ .unwrap_or_default();
555+ let owner_name = people
556+ .get(question.get_owner().key())
557+ .map(|person| {
558+ person
559+ .display_name
560+ .clone()
561+ .unwrap_or_else(|| person.username.clone())
562+ })
563+ .unwrap_or_default();
564+ let used_count = used.get(question.get_id().key()).copied().unwrap_or(0);
565+ BankQuestionResponse::with_names(question, images, subject_name, owner_name, used_count)
380 })566 })
381 .collect();567 .collect();
382 Ok(Json(Page::new(items, total, limit, offset)))568 Ok(Json(Page::new(items, total, limit, offset)))
383 }569 }
384 570
385-/// One template by id. School-wide — any teacher+ reads any template.571+/// One template by id. Visible ones only: a `private` template belonging to
572+/// someone else is a 404, not a 403 — a 403 would confirm it exists.
386 #[utoipa::path(573 #[utoipa::path(
387 get,574 get,
388 path = "/{bid}",575 path = "/{bid}",
@@ -393,15 +580,15 @@ async fn list_questions(
393 (status = 200, description = "The template", body = BankQuestionResponse),580 (status = 200, description = "The template", body = BankQuestionResponse),
394 (status = 401, description = "Not authenticated", body = ErrorResponse),581 (status = 401, description = "Not authenticated", body = ErrorResponse),
395 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),582 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
396- (status = 404, description = "No such template", body = ErrorResponse),583+ (status = 404, description = "No such template, or one the caller may not see", body = ErrorResponse),
397 ),584 ),
398 )]585 )]
399 async fn get_question(586 async fn get_question(
400 State(st): State<AppState>,587 State(st): State<AppState>,
401- RequireTeacher(_user): RequireTeacher,588+ RequireTeacher(user): RequireTeacher,
402 Path(bid): Path<String>,589 Path(bid): Path<String>,
403 ) -> Result<Json<BankQuestionResponse>, AppError> {590 ) -> Result<Json<BankQuestionResponse>, AppError> {
404- let question = question_or_404(&st, &bid).await?;591+ let question = visible_question(&st, &user, &bid).await?;
405 let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?;592 let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?;
406 Ok(Json(BankQuestionResponse::new(&question, &images)))593 Ok(Json(BankQuestionResponse::new(&question, &images)))
407 }594 }
@@ -411,6 +598,12 @@ async fn get_question(
411 /// a kind switch must bring the matching fields along. Replacing or clearing598 /// a kind switch must bring the matching fields along. Replacing or clearing
412 /// `choices` drops the old options' pictures. Bank templates never freeze —599 /// `choices` drops the old options' pictures. Bank templates never freeze —
413 /// they have no exam tie.600 /// they have no exam tie.
601+///
602+/// This is also the publish switch: `visibility: "school"` shares the template
603+/// with every teacher, `"private"` pulls it back. By design an **admin can
604+/// publish (or unpublish) another teacher's private template** — the ownership
605+/// gate here is the same admin-bypassing one that lets an admin edit or delete
606+/// any template, and it is not narrowed for this field.
414 #[utoipa::path(607 #[utoipa::path(
415 patch,608 patch,
416 path = "/{bid}",609 path = "/{bid}",
@@ -437,9 +630,11 @@ async fn update_question(
437 // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a630 // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a
438 // re-tag to a subject that's being deleted can't straddle the delete-guard.631 // re-tag to a subject that's being deleted can't straddle the delete-guard.
439 let _guard = BANK_LOCK.read().await;632 let _guard = BANK_LOCK.read().await;
633+ // Omitted keeps the stored subject — which may already be `None`, cleared
634+ // by that subject's delete.
440 let subject = match req.subject_id {635 let subject = match req.subject_id {
441- Some(ref subject_id) => subject_must_exist(subject_id, &st.db).await?,636+ Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?),
442- None => question.get_subject().clone(),637+ None => question.get_subject().cloned(),
443 };638 };
444 let text = match req.text {639 let text = match req.text {
445 Some(ref text) => QuestionText::try_new(text)?,640 Some(ref text) => QuestionText::try_new(text)?,
@@ -455,27 +650,37 @@ async fn update_question(
455 Some(ref kind) => QuestionKind::try_new(kind)?,650 Some(ref kind) => QuestionKind::try_new(kind)?,
456 None => question.get_kind().clone(),651 None => question.get_kind().clone(),
457 };652 };
458- let choices_replaced = req.choices.is_some();653+ // Omitting `choices` re-submits the stored options *with their ids*, so a
654+ // text-only edit keeps every identity (and every picture) untouched.
459 let choices = match req.choices {655 let choices = match req.choices {
460- Some(update) => update,656+ Some(update) => ChoiceBody::into_inputs(update),
461- None => question657+ None => ChoiceBody::from_stored(question.get_choices()),
462- .get_choices()
463- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
464 };658 };
465 let correct = match req.correct {659 let correct = match req.correct {
466 Some(update) => update,660 Some(update) => update,
467- None => question.get_correct(),661+ None => question.get_correct().map(|id| id.as_str().to_string()),
662+ };
663+ let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();
664+ let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;
665+ let visibility = match req.visibility {
666+ Some(ref visibility) => BankVisibility::try_new(visibility)?,
667+ None => question.get_visibility().clone(),
468 };668 };
469- let spec = QuestionSpec::try_new(kind, choices, correct)?;
470 669
471 let bid = question.get_id().clone();670 let bid = question.get_id().clone();
472- let updated = question.update(subject, text, points, spec, &st.db).await?;671+ let updated = question
473- // A replaced (or cleared) choice list orphans the old options' pictures —672+ .update(subject, text, points, spec, visibility, &st.db)
474- // drop them all; the template's own illustration stays.673+ .await?;
475- if choices_replaced {674+ // Only the options that are actually *gone* lose their pictures — an option
476- for image in BankQuestionImage::delete_choices_for(&bid, &st.db).await? {675+ // that survives the edit keeps its image wherever it moved in the list.
477- remove_blob(&st.files_path, image.get_file()).await;676+ let keep: Vec<ChoiceId> = updated
478- }677+ .get_choices()
678+ .unwrap_or_default()
679+ .iter()
680+ .map(|choice| choice.get_id().clone())
681+ .collect();
682+ for image in BankQuestionImage::delete_choices_not_in(&bid, &keep, &st.db).await? {
683+ remove_blob(&st.files_path, image.get_file()).await;
479 }684 }
480 let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?;685 let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?;
481 Ok(Json(BankQuestionResponse::new(&updated, &images)))686 Ok(Json(BankQuestionResponse::new(&updated, &images)))
@@ -515,7 +720,8 @@ async fn delete_question(
515 // ---- template images --------------------------------------------------------720 // ---- template images --------------------------------------------------------
516 // A template may carry one illustration (any kind) and, on choice templates,721 // A template may carry one illustration (any kind) and, on choice templates,
517 // one picture per option — mirroring exam question images, minus the exam tie722 // one picture per option — mirroring exam question images, minus the exam tie
518-// and the freeze. Mutations are owner-gated; reads are school-wide (teacher+).723+// and the freeze. Mutations are owner-gated; reads follow the template's
724+// visibility (a template the caller can't see 404s, images included).
519 725
520 /// Attach (or replace) a template's illustration. Owner only (admins aside).726 /// Attach (or replace) a template's illustration. Owner only (admins aside).
521 /// `multipart/form-data` with the image under a `file` field; the declared727 /// `multipart/form-data` with the image under a `file` field; the declared
@@ -552,7 +758,8 @@ async fn upload_question_image(
552 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))758 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))
553 }759 }
554 760
555-/// A template's illustration bytes. School-wide — any teacher+ reads it.761+/// A template's illustration bytes. Readable by anyone who may see the
762+/// template — 404 otherwise, never a 403.
556 #[utoipa::path(763 #[utoipa::path(
557 get,764 get,
558 path = "/{bid}/image",765 path = "/{bid}/image",
@@ -568,10 +775,10 @@ async fn upload_question_image(
568 )]775 )]
569 async fn get_question_image(776 async fn get_question_image(
570 State(st): State<AppState>,777 State(st): State<AppState>,
571- RequireTeacher(_user): RequireTeacher,778+ RequireTeacher(user): RequireTeacher,
572 Path(bid): Path<String>,779 Path(bid): Path<String>,
573 ) -> Result<Response, AppError> {780 ) -> Result<Response, AppError> {
574- let question = question_or_404(&st, &bid).await?;781+ let question = visible_question(&st, &user, &bid).await?;
575 let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db)782 let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db)
576 .await?783 .await?
577 .ok_or(AppError::NotFound)?;784 .ok_or(AppError::NotFound)?;
@@ -612,17 +819,17 @@ async fn delete_question_image(
612 /// drops all its option pictures.819 /// drops all its option pictures.
613 #[utoipa::path(820 #[utoipa::path(
614 post,821 post,
615- path = "/{bid}/choices/{index}/image",822+ path = "/{bid}/choices/{choice_id}/image",
616 tag = "bank",823 tag = "bank",
617 security(("session_cookie" = [])),824 security(("session_cookie" = [])),
618 params(825 params(
619 ("bid" = String, Path, description = "Bank question id"),826 ("bid" = String, Path, description = "Bank question id"),
620- ("index" = i64, Path, description = "Zero-based choice index"),827+ ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"),
621 ),828 ),
622 request_body(content = UploadFileForm, content_type = "multipart/form-data"),829 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
623 responses(830 responses(
624 (status = 201, description = "Image stored", body = BankImageMeta),831 (status = 201, description = "Image stored", body = BankImageMeta),
625- (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),832+ (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),
626 (status = 401, description = "Not authenticated", body = ErrorResponse),833 (status = 401, description = "Not authenticated", body = ErrorResponse),
627 (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse),834 (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse),
628 (status = 404, description = "No such template", body = ErrorResponse),835 (status = 404, description = "No such template", body = ErrorResponse),
@@ -632,29 +839,18 @@ async fn delete_question_image(
632 async fn upload_choice_image(839 async fn upload_choice_image(
633 State(st): State<AppState>,840 State(st): State<AppState>,
634 RequireTeacher(user): RequireTeacher,841 RequireTeacher(user): RequireTeacher,
635- Path((bid, index)): Path<(String, i64)>,842+ Path((bid, choice_id)): Path<(String, String)>,
636 mut multipart: Multipart,843 mut multipart: Multipart,
637 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {844 ) -> Result<(StatusCode, Json<BankImageMeta>), AppError> {
638 let question = owned_question(&st, &user, &bid).await?;845 let question = owned_question(&st, &user, &bid).await?;
639- let Some(choices) = question.get_choices() else {846+ let slot = bank_choice_slot(&question, &choice_id)?;
640- return Err(AppError::Validation(ValidationError::Invalid {
641- field: "index",
642- reason: "only choice questions take option pictures",
643- }));
644- };
645- if !(0..choices.len() as i64).contains(&index) {
646- return Err(AppError::Validation(ValidationError::Invalid {
647- field: "index",
648- reason: "must index one of the choices",
649- }));
650- }
651 let limit = Settings::load(&st.db).await?.get_max_file_bytes();847 let limit = Settings::load(&st.db).await?.get_max_file_bytes();
652 let upload = read_upload(&mut multipart, limit).await?;848 let upload = read_upload(&mut multipart, limit).await?;
653 let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;849 let content_type = image_content_type(&upload.content_type.unwrap_or_default())?;
654 let stored = store_image(850 let stored = store_image(
655 &st,851 &st,
656 question.get_id(),852 question.get_id(),
657- Some(index),853+ Some(&slot),
658 content_type,854 content_type,
659 &upload.data,855 &upload.data,
660 )856 )
@@ -662,15 +858,16 @@ async fn upload_choice_image(
662 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))858 Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored))))
663 }859 }
664 860
665-/// One option's picture bytes. School-wide — any teacher+ reads it.861+/// One option's picture bytes. Readable by anyone who may see the template —
862+/// 404 otherwise, never a 403.
666 #[utoipa::path(863 #[utoipa::path(
667 get,864 get,
668- path = "/{bid}/choices/{index}/image",865+ path = "/{bid}/choices/{choice_id}/image",
669 tag = "bank",866 tag = "bank",
670 security(("session_cookie" = [])),867 security(("session_cookie" = [])),
671 params(868 params(
672 ("bid" = String, Path, description = "Bank question id"),869 ("bid" = String, Path, description = "Bank question id"),
673- ("index" = i64, Path, description = "Zero-based choice index"),870+ ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"),
674 ),871 ),
675 responses(872 responses(
676 (status = 200, description = "The image bytes", content_type = "image/*"),873 (status = 200, description = "The image bytes", content_type = "image/*"),
@@ -681,11 +878,12 @@ async fn upload_choice_image(
681 )]878 )]
682 async fn get_choice_image(879 async fn get_choice_image(
683 State(st): State<AppState>,880 State(st): State<AppState>,
684- RequireTeacher(_user): RequireTeacher,881+ RequireTeacher(user): RequireTeacher,
685- Path((bid, index)): Path<(String, i64)>,882+ Path((bid, choice_id)): Path<(String, String)>,
686 ) -> Result<Response, AppError> {883 ) -> Result<Response, AppError> {
687- let question = question_or_404(&st, &bid).await?;884+ let question = visible_question(&st, &user, &bid).await?;
688- let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db)885+ let slot = bank_choice_slot(&question, &choice_id)?;
886+ let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
689 .await?887 .await?
690 .ok_or(AppError::NotFound)?;888 .ok_or(AppError::NotFound)?;
691 serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await889 serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await
@@ -694,12 +892,12 @@ async fn get_choice_image(
694 /// Remove one option's picture. Owner only (admins aside).892 /// Remove one option's picture. Owner only (admins aside).
695 #[utoipa::path(893 #[utoipa::path(
696 delete,894 delete,
697- path = "/{bid}/choices/{index}/image",895+ path = "/{bid}/choices/{choice_id}/image",
698 tag = "bank",896 tag = "bank",
699 security(("session_cookie" = [])),897 security(("session_cookie" = [])),
700 params(898 params(
701 ("bid" = String, Path, description = "Bank question id"),899 ("bid" = String, Path, description = "Bank question id"),
702- ("index" = i64, Path, description = "Zero-based choice index"),900+ ("choice_id" = String, Path, description = "Choice id, as returned in the template's `choices`"),
703 ),901 ),
704 responses(902 responses(
705 (status = 204, description = "Deleted"),903 (status = 204, description = "Deleted"),
@@ -711,10 +909,11 @@ async fn get_choice_image(
711 async fn delete_choice_image(909 async fn delete_choice_image(
712 State(st): State<AppState>,910 State(st): State<AppState>,
713 RequireTeacher(user): RequireTeacher,911 RequireTeacher(user): RequireTeacher,
714- Path((bid, index)): Path<(String, i64)>,912+ Path((bid, choice_id)): Path<(String, String)>,
715 ) -> Result<StatusCode, AppError> {913 ) -> Result<StatusCode, AppError> {
716 let question = owned_question(&st, &user, &bid).await?;914 let question = owned_question(&st, &user, &bid).await?;
717- let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db)915+ let slot = bank_choice_slot(&question, &choice_id)?;
916+ let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
718 .await?917 .await?
719 .ok_or(AppError::NotFound)?;918 .ok_or(AppError::NotFound)?;
720 let image = image.delete(&st.db).await?;919 let image = image.delete(&st.db).await?;
src/web/exam_ws.rsmodified+2 -2
@@ -17,7 +17,7 @@
17 //! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline17 //! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline
18 //!18 //!
19 //! client → server19 //! client → server
20-//! - `{"type":"answer", question_id, selected? | text?}`20+//! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id)
21 //! - `{"type":"finish"}`21 //! - `{"type":"finish"}`
22 //! - `{"type":"ping"}`22 //! - `{"type":"ping"}`
23 //!23 //!
@@ -89,7 +89,7 @@ enum ClientMessage {
89 Answer {89 Answer {
90 question_id: String,90 question_id: String,
91 #[serde(default)]91 #[serde(default)]
92- selected: Option<i64>,92+ selected: Option<String>,
93 #[serde(default)]93 #[serde(default)]
94 text: Option<String>,94 text: Option<String>,
95 },95 },
src/web/exams.rsmodified+331 -106
@@ -23,7 +23,8 @@ use crate::domain::exam::{
23 use crate::domain::exam_answer::{ExamAnswer, auto_score};23 use crate::domain::exam_answer::{ExamAnswer, auto_score};
24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
25 use crate::domain::exam_question::{25 use crate::domain::exam_question::{
26- ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,26+ Choice, ChoiceId, ExamQuestion, ExamQuestionId, QuestionKind, QuestionPoints, QuestionSpec,
27+ QuestionText,
27 };28 };
28 use crate::domain::exam_result::{ExamResult, Mark};29 use crate::domain::exam_result::{ExamResult, Mark};
29 use crate::domain::note_file::FileContentType;30 use crate::domain::note_file::FileContentType;
@@ -39,9 +40,9 @@ use super::bank_questions::BankQuestionResponse;
39 use super::courses::{can_manage_course, can_view_course, visible_courses};40 use super::courses::{can_manage_course, can_view_course, visible_courses};
40 use super::subjects::subject_in_course;41 use super::subjects::subject_in_course;
41 use super::{42 use super::{
42- CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, UploadFileForm,43+ ChoiceBody, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher,
43- blob_path, check_not_past, image_content_type, paginate, person_map, read_upload, remove_blob,44+ UploadFileForm, blob_path, check_not_past, image_content_type, paginate, person_map,
44- set_or_clear,45+ read_upload, remove_blob, set_or_clear,
45 };46 };
46 47
47 /// Serializes the exam subsystem's cross-record check-then-writes, which48 /// Serializes the exam subsystem's cross-record check-then-writes, which
@@ -81,6 +82,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
81 .routes(routes!(update_question, delete_question))82 .routes(routes!(update_question, delete_question))
82 .routes(routes!(question_from_bank))83 .routes(routes!(question_from_bank))
83 .routes(routes!(question_to_bank))84 .routes(routes!(question_to_bank))
85+ .routes(routes!(question_refresh_from_bank))
84 .routes(routes!(attempt_questions))86 .routes(routes!(attempt_questions))
85 .routes(routes!(save_answer))87 .routes(routes!(save_answer))
86 .routes(routes!(attempt_answers))88 .routes(routes!(attempt_answers))
@@ -1316,11 +1318,13 @@ struct CreateQuestion {
1316 #[schema(example = 10)]1318 #[schema(example = 10)]
1317 points: i64,1319 points: i64,
1318 /// The options of a `choice` question (2–10 of them); omit for `text`.1320 /// The options of a `choice` question (2–10 of them); omit for `text`.
1319- choices: Option<Vec<String>>,1321+ /// Each carries an `id` naming it within this payload — the server mints
1320- /// Zero-based index of the right option; required for `choice`, absent1322+ /// the stored ids and returns them.
1321- /// for `text`.1323+ choices: Option<Vec<ChoiceBody>>,
1322- #[schema(example = 1)]1324+ /// The `id` of the right option, as sent in `choices`; required for
1323- correct: Option<i64>,1325+ /// `choice`, absent for `text`.
1326+ #[schema(example = "b")]
1327+ correct: Option<String>,
1324 }1328 }
1325 1329
1326 #[derive(Deserialize, ToSchema)]1330 #[derive(Deserialize, ToSchema)]
@@ -1336,19 +1340,22 @@ struct UpdateQuestion {
1336 /// when moving to `text`.1340 /// when moving to `text`.
1337 kind: Option<String>,1341 kind: Option<String>,
1338 /// Omit to keep the stored options; send `null` to drop them (text1342 /// Omit to keep the stored options; send `null` to drop them (text
1339- /// questions only). Replacing or clearing the list also drops every1343+ /// questions only). Send each option back with the `id` it was returned
1340- /// option picture — the old images belong to the old options.1344+ /// with to keep it — its picture rides along. Only options whose id is
1345+ /// absent from the new list lose their picture, so reordering, renaming,
1346+ /// and deleting one option leave the rest untouched.
1341 #[serde(default, deserialize_with = "set_or_clear")]1347 #[serde(default, deserialize_with = "set_or_clear")]
1342- #[schema(value_type = Option<Vec<String>>)]1348+ #[schema(value_type = Option<Vec<ChoiceBody>>)]
1343- choices: Option<Option<Vec<String>>>,1349+ choices: Option<Option<Vec<ChoiceBody>>>,
1344- /// Omit to keep; `null` to clear (text questions only).1350+ /// The `id` of the right option. Omit to keep; `null` to clear (text
1351+ /// questions only).
1345 #[serde(default, deserialize_with = "set_or_clear")]1352 #[serde(default, deserialize_with = "set_or_clear")]
1346- #[schema(value_type = Option<i64>)]1353+ #[schema(value_type = Option<String>)]
1347- correct: Option<Option<i64>>,1354+ correct: Option<Option<String>>,
1348 }1355 }
1349 1356
1350 /// A stored question image's metadata; the bytes come from the image1357 /// A stored question image's metadata; the bytes come from the image
1351-/// endpoints (`GET .../image`, `GET .../choices/{index}/image`).1358+/// endpoints (`GET .../image`, `GET .../choices/{choice_id}/image`).
1352 #[derive(Serialize, ToSchema)]1359 #[derive(Serialize, ToSchema)]
1353 struct ImageMetaResponse {1360 struct ImageMetaResponse {
1354 /// MIME type as declared on upload (always one of the raster allowlist).1361 /// MIME type as declared on upload (always one of the raster allowlist).
@@ -1376,22 +1383,26 @@ impl ImageMetaResponse {
1376 }1383 }
1377 1384
1378 /// The question's slot out of its image rows.1385 /// The question's slot out of its image rows.
1379-fn image_meta(images: &[QuestionImage], slot: Option<i64>) -> Option<ImageMetaResponse> {1386+fn image_meta(images: &[QuestionImage], slot: Option<&ChoiceId>) -> Option<ImageMetaResponse> {
1380 images1387 images
1381 .iter()1388 .iter()
1382 .find(|image| image.get_slot() == slot)1389 .find(|image| image.get_slot() == slot)
1383 .map(ImageMetaResponse::new)1390 .map(ImageMetaResponse::new)
1384 }1391 }
1385 1392
1386-/// The per-choice metas, aligned index-for-index with `choices` (`None`1393+/// The per-choice metas, aligned position-for-position with `choices` (`None`
1387 /// entries = that option has no picture); `None` whole for text questions.1394 /// entries = that option has no picture); `None` whole for text questions.
1395+/// A response-only projection: the pictures are *stored* against choice ids, so
1396+/// this alignment is rebuilt from the current list on every read and can never
1397+/// go stale.
1388 fn choice_image_metas(1398 fn choice_image_metas(
1389 question: &ExamQuestion,1399 question: &ExamQuestion,
1390 images: &[QuestionImage],1400 images: &[QuestionImage],
1391 ) -> Option<Vec<Option<ImageMetaResponse>>> {1401 ) -> Option<Vec<Option<ImageMetaResponse>>> {
1392 question.get_choices().map(|choices| {1402 question.get_choices().map(|choices| {
1393- (0..choices.len() as i64)1403+ choices
1394- .map(|index| image_meta(images, Some(index)))1404+ .iter()
1405+ .map(|choice| image_meta(images, Some(choice.get_id())))
1395 .collect()1406 .collect()
1396 })1407 })
1397 }1408 }
@@ -1412,7 +1423,31 @@ async fn images_by_question(
1412 Ok(buckets)1423 Ok(buckets)
1413 }1424 }
1414 1425
1415-/// A question as its author sees it — including the `correct` index. Never1426+/// One option on the wire: its stable id and its text. Carries **no** answer
1427+/// key — `correct` is a sibling field on the question, and only on the
1428+/// author-facing DTO, so a student response cannot contain one by construction.
1429+#[derive(Serialize, ToSchema)]
1430+pub(crate) struct ChoiceResponse {
1431+ /// Send this back in a PATCH to keep the option (and its picture).
1432+ id: String,
1433+ text: String,
1434+}
1435+
1436+impl ChoiceResponse {
1437+ pub(crate) fn list(choices: Option<&[Choice]>) -> Option<Vec<Self>> {
1438+ choices.map(|choices| {
1439+ choices
1440+ .iter()
1441+ .map(|choice| Self {
1442+ id: choice.get_id().as_str().to_string(),
1443+ text: choice.get_text().as_str().to_string(),
1444+ })
1445+ .collect()
1446+ })
1447+ }
1448+}
1449+
1450+/// A question as its author sees it — including the `correct` option. Never
1416 /// serialized to students; they get [`AttemptQuestionResponse`].1451 /// serialized to students; they get [`AttemptQuestionResponse`].
1417 #[derive(Serialize, ToSchema)]1452 #[derive(Serialize, ToSchema)]
1418 struct QuestionResponse {1453 struct QuestionResponse {
@@ -1425,15 +1460,21 @@ struct QuestionResponse {
1425 #[schema(example = "choice")]1460 #[schema(example = "choice")]
1426 kind: String,1461 kind: String,
1427 points: i64,1462 points: i64,
1428- choices: Option<Vec<String>>,1463+ /// The options with their stable ids (`choice` questions only).
1429- /// Zero-based index of the right option (`choice` questions only).1464+ choices: Option<Vec<ChoiceResponse>>,
1430- correct: Option<i64>,1465+ /// The id of the right option (`choice` questions only).
1466+ correct: Option<String>,
1431 /// The question's illustration, if one was uploaded (any kind).1467 /// The question's illustration, if one was uploaded (any kind).
1432 image: Option<ImageMetaResponse>,1468 image: Option<ImageMetaResponse>,
1433 /// Per-option pictures, aligned with `choices` (`choice` questions only).1469 /// Per-option pictures, aligned with `choices` (`choice` questions only).
1434 choice_images: Option<Vec<Option<ImageMetaResponse>>>,1470 choice_images: Option<Vec<Option<ImageMetaResponse>>>,
1435- /// The bank template this question was instantiated from, if any.1471+ /// The bank template this question was created from, if it was added out of
1436- source_bank: Option<String>,1472+ /// the bank (`GET /bank-questions/{id}`).
1473+ from_bank: Option<String>,
1474+ /// The bank template most recently created by saving this question into the
1475+ /// bank, if any — set only by `POST …/questions/{qid}/to-bank`. Null on a
1476+ /// question that came *from* the bank and was never saved back.
1477+ banked_as: Option<String>,
1437 }1478 }
1438 1479
1439 impl QuestionResponse {1480 impl QuestionResponse {
@@ -1445,13 +1486,14 @@ impl QuestionResponse {
1445 text: question.get_text().as_str().to_string(),1486 text: question.get_text().as_str().to_string(),
1446 kind: question.get_kind().as_str().to_string(),1487 kind: question.get_kind().as_str().to_string(),
1447 points: question.get_points().as_i64(),1488 points: question.get_points().as_i64(),
1448- choices: question1489+ choices: ChoiceResponse::list(question.get_choices()),
1449- .get_choices()1490+ correct: question
1450- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),1491+ .get_correct()
1451- correct: question.get_correct(),1492+ .map(|id| id.as_str().to_string()),
1452 image: image_meta(images, None),1493 image: image_meta(images, None),
1453 choice_images: choice_image_metas(question, images),1494 choice_images: choice_image_metas(question, images),
1454- source_bank: question.get_source_bank().map(|b| b.key().to_string()),1495+ from_bank: question.get_from_bank().map(|b| b.key().to_string()),
1496+ banked_as: question.get_banked_as().map(|b| b.key().to_string()),
1455 }1497 }
1456 }1498 }
1457 }1499 }
@@ -1483,6 +1525,26 @@ async fn question_of_exam(
1483 Ok(question)1525 Ok(question)
1484 }1526 }
1485 1527
1528+/// The question's option named by `choice_id` — a 400 for a text question or an
1529+/// id the question doesn't have, so an option picture can only ever be
1530+/// addressed through an option that exists.
1531+fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<ChoiceId, AppError> {
1532+ let Some(choices) = question.get_choices() else {
1533+ return Err(AppError::Validation(ValidationError::Invalid {
1534+ field: "choice_id",
1535+ reason: "only choice questions take option pictures",
1536+ }));
1537+ };
1538+ choices
1539+ .iter()
1540+ .find(|choice| choice.get_id().as_str() == choice_id)
1541+ .map(|choice| choice.get_id().clone())
1542+ .ok_or(AppError::Validation(ValidationError::Invalid {
1543+ field: "choice_id",
1544+ reason: "must name one of the choices",
1545+ }))
1546+}
1547+
1486 /// Add a question to an exam. Requires teacher+ and management rights over the1548 /// Add a question to an exam. Requires teacher+ and management rights over the
1487 /// exam's course. `subject_id` must name one of the course's subjects1549 /// exam's course. `subject_id` must name one of the course's subjects
1488 /// (`GET /courses/{id}/subjects`) — every question belongs to a subject.1550 /// (`GET /courses/{id}/subjects`) — every question belongs to a subject.
@@ -1528,7 +1590,14 @@ async fn create_question(
1528 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;1590 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
1529 let text = QuestionText::try_new(&req.text)?;1591 let text = QuestionText::try_new(&req.text)?;
1530 let points = QuestionPoints::try_new(req.points)?;1592 let points = QuestionPoints::try_new(req.points)?;
1531- let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?;1593+ // No stored choices to match against on create, so every option is new and
1594+ // every id is minted here.
1595+ let spec = QuestionSpec::try_new(
1596+ QuestionKind::try_new(&req.kind)?,
1597+ ChoiceBody::into_inputs(req.choices),
1598+ req.correct,
1599+ &[],
1600+ )?;
1532 let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;1601 let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?;
1533 // A question is born imageless — uploads come after, against its id.1602 // A question is born imageless — uploads come after, against its id.
1534 Ok((1603 Ok((
@@ -1664,27 +1733,32 @@ async fn update_question(
1664 Some(ref kind) => QuestionKind::try_new(kind)?,1733 Some(ref kind) => QuestionKind::try_new(kind)?,
1665 None => question.get_kind().clone(),1734 None => question.get_kind().clone(),
1666 };1735 };
1667- let choices_replaced = req.choices.is_some();1736+ // Omitting `choices` re-submits the stored options *with their ids*, so a
1737+ // text-only edit keeps every identity (and every picture) untouched.
1668 let choices = match req.choices {1738 let choices = match req.choices {
1669- Some(update) => update,1739+ Some(update) => ChoiceBody::into_inputs(update),
1670- None => question1740+ None => ChoiceBody::from_stored(question.get_choices()),
1671- .get_choices()
1672- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
1673 };1741 };
1674 let correct = match req.correct {1742 let correct = match req.correct {
1675 Some(update) => update,1743 Some(update) => update,
1676- None => question.get_correct(),1744+ None => question.get_correct().map(|id| id.as_str().to_string()),
1677 };1745 };
1678- let spec = QuestionSpec::try_new(kind, choices, correct)?;1746+ let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec();
1747+ let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?;
1679 1748
1680 let updated = question.update(subject, text, points, spec, &st.db).await?;1749 let updated = question.update(subject, text, points, spec, &st.db).await?;
1681- // A replaced (or cleared) choice list orphans the old options' pictures —1750+ // Only the options that are actually *gone* lose their pictures: keyed by
1682- // drop them all; the question's own illustration stays. Uploads re-attach1751+ // choice id, an option that survives the edit keeps its image no matter
1683- // against the new list.1752+ // where it moved in the list. (This used to wipe every option picture
1684- if choices_replaced {1753+ // whenever the request so much as carried a `choices` key.)
1685- for image in QuestionImage::delete_choices_for(updated.get_id(), &st.db).await? {1754+ let keep: Vec<ChoiceId> = updated
1686- remove_blob(&st.files_path, image.get_file()).await;1755+ .get_choices()
1687- }1756+ .unwrap_or_default()
1757+ .iter()
1758+ .map(|choice| choice.get_id().clone())
1759+ .collect();
1760+ for image in QuestionImage::delete_choices_not_in(updated.get_id(), &keep, &st.db).await? {
1761+ remove_blob(&st.files_path, image.get_file()).await;
1688 }1762 }
1689 let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;1763 let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
1690 Ok(Json(QuestionResponse::new(&updated, &images)))1764 Ok(Json(QuestionResponse::new(&updated, &images)))
@@ -1754,7 +1828,9 @@ struct InstantiateFromBank {
1754 }1828 }
1755 1829
1756 /// Instantiate a bank template into this exam as a fresh question. Requires1830 /// Instantiate a bank template into this exam as a fresh question. Requires
1757-/// teacher+ and management rights over the exam's course. `subject_id` must1831+/// teacher+, management rights over the exam's course, and a template the
1832+/// caller may see (their own, or one published to the school) — anything else
1833+/// is a 404. `subject_id` must
1758 /// name one of the course's subjects — the template's own subject is origin1834 /// name one of the course's subjects — the template's own subject is origin
1759 /// metadata and does not carry over. The template (and its blobs) stay1835 /// metadata and does not carry over. The template (and its blobs) stay
1760 /// untouched; a full copy — text, points, spec, illustration, and option1836 /// untouched; a full copy — text, points, spec, illustration, and option
@@ -1774,7 +1850,7 @@ struct InstantiateFromBank {
1774 (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),1850 (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse),
1775 (status = 401, description = "Not authenticated", body = ErrorResponse),1851 (status = 401, description = "Not authenticated", body = ErrorResponse),
1776 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),1852 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1777- (status = 404, description = "No such exam, or no such bank template", body = ErrorResponse),1853+ (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse),
1778 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),1854 (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1779 ),1855 ),
1780 )]1856 )]
@@ -1802,6 +1878,12 @@ async fn question_from_bank(
1802 let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db)1878 let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db)
1803 .await?1879 .await?
1804 .ok_or(AppError::NotFound)?;1880 .ok_or(AppError::NotFound)?;
1881+ // A template the caller may not see is a 404, exactly as it is on the bank's
1882+ // own routes — instantiating is a read of `correct`, and a 403 here would
1883+ // confirm that someone else's private template exists under that id.
1884+ if !super::bank_questions::can_see(&template, &user) {
1885+ return Err(AppError::NotFound);
1886+ }
1805 let question = ExamQuestion::create_from_bank(1887 let question = ExamQuestion::create_from_bank(
1806 exam.get_id(),1888 exam.get_id(),
1807 subject,1889 subject,
@@ -1859,14 +1941,159 @@ async fn question_from_bank(
1859 ))1941 ))
1860 }1942 }
1861 1943
1944+/// Re-copy a bank template's *current* content over the exam question that was
1945+/// instantiated from it — the escape hatch for the divergence a deep copy
1946+/// creates: fixing a typo in the template does not reach the copies, so this is
1947+/// how a copy is brought back in line, explicitly and per question. Requires
1948+/// teacher+, management rights over the exam's course, and a template the
1949+/// caller may still see.
1950+///
1951+/// Replaces text, points, kind, choices, `correct`, the illustration, and the
1952+/// option pictures with the template's; the question keeps its own id, its
1953+/// exam, its `subject` (exam-course-scoped — the template's subject is
1954+/// unrelated metadata) and its provenance links. Anything edited on the exam
1955+/// copy since it was inserted is overwritten.
1956+///
1957+/// **Choice ids come from the template**, exactly as
1958+/// [`question_from_bank`] mints them — the copy adopts the template's ids, so
1959+/// its option pictures key off the same slots the template's do, and a
1960+/// re-copy after a template edit re-lands the right picture on the right
1961+/// option. A recorded `selected` can never be stranded by that: the freeze
1962+/// below refuses the whole route once *any* attempt exists, and an
1963+/// `exam_answer` only exists under an attempt — so at refresh time no answer
1964+/// points at any choice id at all.
1965+///
1966+/// - No `from_bank` (never came from the bank, or its template was deleted and
1967+/// the cascade cleared the link) → `400`; there is nothing to refresh from.
1968+/// - Template gone or not visible to the caller → `404`, never a 403.
1969+/// - Any attempt started → `409`, the same `ensure_questions_editable` freeze
1970+/// every other question mutation answers to.
1971+#[utoipa::path(
1972+ post,
1973+ path = "/{id}/questions/{qid}/refresh-from-bank",
1974+ tag = "exams",
1975+ security(("session_cookie" = [])),
1976+ params(
1977+ ("id" = String, Path, description = "Exam id"),
1978+ ("qid" = String, Path, description = "Question id"),
1979+ ),
1980+ responses(
1981+ (status = 200, description = "Question refreshed from its template", body = QuestionResponse),
1982+ (status = 400, description = "The question did not come from the bank", body = ErrorResponse),
1983+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1984+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1985+ (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse),
1986+ (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse),
1987+ ),
1988+)]
1989+async fn question_refresh_from_bank(
1990+ State(st): State<AppState>,
1991+ RequireTeacher(user): RequireTeacher,
1992+ Path((id, qid)): Path<(String, String)>,
1993+) -> Result<Json<QuestionResponse>, AppError> {
1994+ let exam = Exam::read(&ExamId::from_key(&id), &st.db)
1995+ .await?
1996+ .ok_or(AppError::NotFound)?;
1997+ let course = course_of(&exam, &st.db).await?;
1998+ if !can_manage_course(&course, &user) {
1999+ return Err(AppError::Forbidden(
2000+ "only the course creator, an assigned teacher, or a manager/admin can edit questions",
2001+ ));
2002+ }
2003+ // Writer lease of [`EXAM_LOCK`]: the freeze gate, the read, and the
2004+ // overwrite are one unit — same reasoning as `update_question`, which this
2005+ // is a canned variant of.
2006+ let _guard = EXAM_LOCK.write().await;
2007+ ensure_questions_editable(exam.get_id(), &st.db).await?;
2008+ let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2009+
2010+ let Some(source) = question.get_from_bank().cloned() else {
2011+ return Err(AppError::Validation(ValidationError::Invalid {
2012+ field: "question",
2013+ reason: "this question did not come from a bank template",
2014+ }));
2015+ };
2016+ let template = BankQuestion::read(&source, &st.db)
2017+ .await?
2018+ .ok_or(AppError::NotFound)?;
2019+ if !super::bank_questions::can_see(&template, &user) {
2020+ return Err(AppError::NotFound);
2021+ }
2022+
2023+ // Every source blob is read up front, *before* anything is written: a
2024+ // missing one is server-side damage and must surface as a 500 with the
2025+ // question untouched, since a half-applied refresh has no old content left
2026+ // to roll back to. Bounded — at most one illustration plus ten option
2027+ // pictures, each under the school's file cap.
2028+ let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?;
2029+ let mut incoming: Vec<(&BankQuestionImage, Vec<u8>)> = Vec::with_capacity(sources.len());
2030+ for source in &sources {
2031+ let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file()))
2032+ .await
2033+ .map_err(|err| {
2034+ AppError::Internal(format!(
2035+ "missing blob for bank image {}: {err}",
2036+ source.get_file()
2037+ ))
2038+ })?;
2039+ incoming.push((source, bytes));
2040+ }
2041+
2042+ // The question's own subject stays: it is checked against the exam's
2043+ // course, and the template's is origin metadata from anywhere in school.
2044+ let subject = question.get_subject().clone();
2045+ // `spec()` hands over the template's stored choices *with their ids* rather
2046+ // than re-minting any — the same funnel `question_from_bank` uses.
2047+ let updated = question
2048+ .update(
2049+ subject,
2050+ template.get_text().clone(),
2051+ template.get_points(),
2052+ template.spec(),
2053+ &st.db,
2054+ )
2055+ .await?;
2056+
2057+ // Make the pictures match the template exactly: drop every slot the
2058+ // template has no picture for (including the illustration, and every option
2059+ // that is gone after the re-copy), then write the template's over the rest.
2060+ // `store_image` upserts per slot, so a slot both sides have is replaced.
2061+ let incoming_slots: Vec<Option<&ChoiceId>> =
2062+ incoming.iter().map(|(image, _)| image.get_slot()).collect();
2063+ for stale in QuestionImage::list_for_question(updated.get_id(), &st.db).await? {
2064+ if incoming_slots.contains(&stale.get_slot()) {
2065+ continue;
2066+ }
2067+ let file = stale.get_file().to_string();
2068+ stale.delete(&st.db).await?;
2069+ remove_blob(&st.files_path, &file).await;
2070+ }
2071+ for (source, bytes) in &incoming {
2072+ store_image(
2073+ &st,
2074+ &exam,
2075+ &updated,
2076+ source.get_slot(),
2077+ source.get_content_type().clone(),
2078+ bytes,
2079+ )
2080+ .await?;
2081+ }
2082+
2083+ let images = QuestionImage::list_for_question(updated.get_id(), &st.db).await?;
2084+ Ok(Json(QuestionResponse::new(&updated, &images)))
2085+}
2086+
1862 /// Save one of this exam's questions into the school-wide bank as a reusable2087 /// Save one of this exam's questions into the school-wide bank as a reusable
1863 /// template. Requires teacher+ and management rights over the exam's course.2088 /// template. Requires teacher+ and management rights over the exam's course.
1864 /// The caller becomes the template's owner; the question's subject rides along2089 /// The caller becomes the template's owner; the question's subject rides along
1865 /// as origin metadata. A full copy — text, points, spec, illustration, and2090 /// as origin metadata. A full copy — text, points, spec, illustration, and
1866 /// option pictures — lands under a new bank id. Provenance rides both ways: the2091 /// option pictures — lands under a new bank id. Provenance rides both ways: the
1867 /// origin exam is recorded on the template as `source_exam`, and the exam2092 /// origin exam is recorded on the template as `source_exam`, and the exam
1868-/// question's `source_bank` is pointed at the new template (a repeat save is2093+/// question's `banked_as` is pointed at the new template (a repeat save is
1869-/// allowed and repoints it at the newest one).2094+/// allowed and repoints it at the newest one). `from_bank` is left alone — it
2095+/// records the other direction and a save never changes where a question came
2096+/// from.
1870 #[utoipa::path(2097 #[utoipa::path(
1871 post,2098 post,
1872 path = "/{id}/questions/{qid}/to-bank",2099 path = "/{id}/questions/{qid}/to-bank",
@@ -1898,10 +2125,10 @@ async fn question_to_bank(
1898 ));2125 ));
1899 }2126 }
1900 // Reader lease of [`BANK_LOCK`] across the question read and the insert: the2127 // Reader lease of [`BANK_LOCK`] across the question read and the insert: the
1901- // template adopts the question's subject, and a re-tag/delete of this2128+ // template adopts the question's subject, so without it a subject delete
1902- // question could otherwise let that subject's delete-guard slip between the2129+ // could slip between the two and leave the fresh template pointing at a
1903- // read and our insert (its `any_for_subject` check runs under BANK_LOCK's2130+ // subject its cascade had already swept (that cascade runs under BANK_LOCK's
1904- // writer lease, so holding the reader lease forces it to see our new row).2131+ // writer lease, so holding the reader lease orders us either side of it).
1905 let _bank_guard = super::bank_questions::BANK_LOCK.read().await;2132 let _bank_guard = super::bank_questions::BANK_LOCK.read().await;
1906 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;2133 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
1907 2134
@@ -1964,8 +2191,20 @@ async fn question_to_bank(
1964 // template silently vanishing over a metadata write is worse than a2191 // template silently vanishing over a metadata write is worse than a
1965 // template with no back-link (the next save re-links it).2192 // template with no back-link (the next save re-links it).
1966 let question_key = question.get_id().key().to_string();2193 let question_key = question.get_id().key().to_string();
2194+ // The bank lease has done its job (the template is inserted, its subject
2195+ // pinned); hand it back *before* taking the exam one, so this handler never
2196+ // holds both — the subject delete goes EXAM_LOCK then BANK_LOCK, and taking
2197+ // them the other way round here would be a deadlock.
2198+ drop(_bank_guard);
2199+ // Reader lease of [`EXAM_LOCK`] around the back-link, the one write this
2200+ // handler makes to `exam_question`. `ExamQuestion::update` is a whole-row
2201+ // save taken under `EXAM_LOCK.write()`; without this lease the link could
2202+ // land between that handler's read and its write, and the pre-link snapshot
2203+ // would be written straight back over it — the provenance silently lost.
2204+ // Held around the link alone, never across the blob copy above.
2205+ let _exam_guard = EXAM_LOCK.read().await;
1967 if let Err(err) = question2206 if let Err(err) = question
1968- .link_source_bank(template.get_id().clone(), &st.db)2207+ .link_banked_as(template.get_id().clone(), &st.db)
1969 .await2208 .await
1970 {2209 {
1971 tracing::warn!(2210 tracing::warn!(
@@ -2031,7 +2270,7 @@ async fn store_image(
2031 st: &AppState,2270 st: &AppState,
2032 exam: &Exam,2271 exam: &Exam,
2033 question: &ExamQuestion,2272 question: &ExamQuestion,
2034- slot: Option<i64>,2273+ slot: Option<&ChoiceId>,
2035 content_type: FileContentType,2274 content_type: FileContentType,
2036 data: &[u8],2275 data: &[u8],
2037 ) -> Result<QuestionImage, AppError> {2276 ) -> Result<QuestionImage, AppError> {
@@ -2192,18 +2431,18 @@ async fn delete_question_image(
2192 /// drops all its option pictures — re-upload against the new list.2431 /// drops all its option pictures — re-upload against the new list.
2193 #[utoipa::path(2432 #[utoipa::path(
2194 post,2433 post,
2195- path = "/{id}/questions/{qid}/choices/{index}/image",2434+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
2196 tag = "exams",2435 tag = "exams",
2197 security(("session_cookie" = [])),2436 security(("session_cookie" = [])),
2198 params(2437 params(
2199 ("id" = String, Path, description = "Exam id"),2438 ("id" = String, Path, description = "Exam id"),
2200 ("qid" = String, Path, description = "Question id"),2439 ("qid" = String, Path, description = "Question id"),
2201- ("index" = i64, Path, description = "Zero-based choice index"),2440+ ("choice_id" = String, Path, description = "Choice id, as returned in the question's `choices`"),
2202 ),2441 ),
2203 request_body(content = UploadFileForm, content_type = "multipart/form-data"),2442 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
2204 responses(2443 responses(
2205 (status = 201, description = "Image stored", body = ImageMetaResponse),2444 (status = 201, description = "Image stored", body = ImageMetaResponse),
2206- (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),2445+ (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),
2207 (status = 401, description = "Not authenticated", body = ErrorResponse),2446 (status = 401, description = "Not authenticated", body = ErrorResponse),
2208 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),2447 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
2209 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),2448 (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse),
@@ -2214,7 +2453,7 @@ async fn delete_question_image(
2214 async fn upload_choice_image(2453 async fn upload_choice_image(
2215 State(st): State<AppState>,2454 State(st): State<AppState>,
2216 RequireTeacher(user): RequireTeacher,2455 RequireTeacher(user): RequireTeacher,
2217- Path((id, qid, index)): Path<(String, String, i64)>,2456+ Path((id, qid, choice_id)): Path<(String, String, String)>,
2218 mut multipart: Multipart,2457 mut multipart: Multipart,
2219 ) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {2458 ) -> Result<(StatusCode, Json<ImageMetaResponse>), AppError> {
2220 let exam = image_managed_exam(&st, &user, &id).await?;2459 let exam = image_managed_exam(&st, &user, &id).await?;
@@ -2224,40 +2463,21 @@ async fn upload_choice_image(
2224 let _guard = EXAM_LOCK.write().await;2463 let _guard = EXAM_LOCK.write().await;
2225 ensure_questions_editable(exam.get_id(), &st.db).await?;2464 ensure_questions_editable(exam.get_id(), &st.db).await?;
2226 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;2465 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2227- let Some(choices) = question.get_choices() else {2466+ let slot = choice_slot(&question, &choice_id)?;
2228- return Err(AppError::Validation(ValidationError::Invalid {2467+ let stored = store_image(&st, &exam, &question, Some(&slot), content_type, &upload.data).await?;
2229- field: "index",
2230- reason: "only choice questions take option pictures",
2231- }));
2232- };
2233- if !(0..choices.len() as i64).contains(&index) {
2234- return Err(AppError::Validation(ValidationError::Invalid {
2235- field: "index",
2236- reason: "must index one of the choices",
2237- }));
2238- }
2239- let stored = store_image(
2240- &st,
2241- &exam,
2242- &question,
2243- Some(index),
2244- content_type,
2245- &upload.data,
2246- )
2247- .await?;
2248 Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))2468 Ok((StatusCode::CREATED, Json(ImageMetaResponse::new(&stored))))
2249 }2469 }
2250 2470
2251 /// One option's picture bytes. Same access wall as the question-image read.2471 /// One option's picture bytes. Same access wall as the question-image read.
2252 #[utoipa::path(2472 #[utoipa::path(
2253 get,2473 get,
2254- path = "/{id}/questions/{qid}/choices/{index}/image",2474+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
2255 tag = "exams",2475 tag = "exams",
2256 security(("session_cookie" = [])),2476 security(("session_cookie" = [])),
2257 params(2477 params(
2258 ("id" = String, Path, description = "Exam id"),2478 ("id" = String, Path, description = "Exam id"),
2259 ("qid" = String, Path, description = "Question id"),2479 ("qid" = String, Path, description = "Question id"),
2260- ("index" = i64, Path, description = "Zero-based choice index"),2480+ ("choice_id" = String, Path, description = "Choice id"),
2261 ),2481 ),
2262 responses(2482 responses(
2263 (status = 200, description = "The image bytes", content_type = "image/*"),2483 (status = 200, description = "The image bytes", content_type = "image/*"),
@@ -2269,14 +2489,15 @@ async fn upload_choice_image(
2269 async fn get_choice_image(2489 async fn get_choice_image(
2270 State(st): State<AppState>,2490 State(st): State<AppState>,
2271 CurrentUser(user): CurrentUser,2491 CurrentUser(user): CurrentUser,
2272- Path((id, qid, index)): Path<(String, String, i64)>,2492+ Path((id, qid, choice_id)): Path<(String, String, String)>,
2273 ) -> Result<Response, AppError> {2493 ) -> Result<Response, AppError> {
2274 let exam = Exam::read(&ExamId::from_key(&id), &st.db)2494 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
2275 .await?2495 .await?
2276 .ok_or(AppError::NotFound)?;2496 .ok_or(AppError::NotFound)?;
2277 ensure_question_content_visible(&st, &exam, &user).await?;2497 ensure_question_content_visible(&st, &exam, &user).await?;
2278 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;2498 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2279- let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db)2499+ let slot = choice_slot(&question, &choice_id)?;
2500+ let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
2280 .await?2501 .await?
2281 .ok_or(AppError::NotFound)?;2502 .ok_or(AppError::NotFound)?;
2282 serve_image(&st, &image).await2503 serve_image(&st, &image).await
@@ -2286,13 +2507,13 @@ async fn get_choice_image(
2286 /// the exam's course; frozen once attempts exist.2507 /// the exam's course; frozen once attempts exist.
2287 #[utoipa::path(2508 #[utoipa::path(
2288 delete,2509 delete,
2289- path = "/{id}/questions/{qid}/choices/{index}/image",2510+ path = "/{id}/questions/{qid}/choices/{choice_id}/image",
2290 tag = "exams",2511 tag = "exams",
2291 security(("session_cookie" = [])),2512 security(("session_cookie" = [])),
2292 params(2513 params(
2293 ("id" = String, Path, description = "Exam id"),2514 ("id" = String, Path, description = "Exam id"),
2294 ("qid" = String, Path, description = "Question id"),2515 ("qid" = String, Path, description = "Question id"),
2295- ("index" = i64, Path, description = "Zero-based choice index"),2516+ ("choice_id" = String, Path, description = "Choice id"),
2296 ),2517 ),
2297 responses(2518 responses(
2298 (status = 204, description = "Deleted"),2519 (status = 204, description = "Deleted"),
@@ -2305,13 +2526,14 @@ async fn get_choice_image(
2305 async fn delete_choice_image(2526 async fn delete_choice_image(
2306 State(st): State<AppState>,2527 State(st): State<AppState>,
2307 RequireTeacher(user): RequireTeacher,2528 RequireTeacher(user): RequireTeacher,
2308- Path((id, qid, index)): Path<(String, String, i64)>,2529+ Path((id, qid, choice_id)): Path<(String, String, String)>,
2309 ) -> Result<StatusCode, AppError> {2530 ) -> Result<StatusCode, AppError> {
2310 let exam = image_managed_exam(&st, &user, &id).await?;2531 let exam = image_managed_exam(&st, &user, &id).await?;
2311 let _guard = EXAM_LOCK.write().await;2532 let _guard = EXAM_LOCK.write().await;
2312 ensure_questions_editable(exam.get_id(), &st.db).await?;2533 ensure_questions_editable(exam.get_id(), &st.db).await?;
2313 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;2534 let question = question_of_exam(exam.get_id(), &qid, &st.db).await?;
2314- let image = QuestionImage::read_slot(question.get_id(), Some(index), &st.db)2535+ let slot = choice_slot(&question, &choice_id)?;
2536+ let image = QuestionImage::read_slot(question.get_id(), Some(&slot), &st.db)
2315 .await?2537 .await?
2316 .ok_or(AppError::NotFound)?;2538 .ok_or(AppError::NotFound)?;
2317 let image = image.delete(&st.db).await?;2539 let image = image.delete(&st.db).await?;
@@ -2327,8 +2549,8 @@ async fn delete_choice_image(
2327 /// A student's own saved answer, embedded in their question view.2549 /// A student's own saved answer, embedded in their question view.
2328 #[derive(Serialize, ToSchema)]2550 #[derive(Serialize, ToSchema)]
2329 struct AnswerStateResponse {2551 struct AnswerStateResponse {
2330- /// The picked option's zero-based index (`choice` questions).2552+ /// The picked option's id (`choice` questions).
2331- selected: Option<i64>,2553+ selected: Option<String>,
2332 /// The typed answer (`text` questions).2554 /// The typed answer (`text` questions).
2333 text: Option<String>,2555 text: Option<String>,
2334 /// When this answer was last saved, UTC unix-milliseconds.2556 /// When this answer was last saved, UTC unix-milliseconds.
@@ -2341,7 +2563,7 @@ struct AnswerStateResponse {
2341 impl AnswerStateResponse {2563 impl AnswerStateResponse {
2342 fn new(answer: &ExamAnswer, answer_image: Option<ImageMetaResponse>) -> Self {2564 fn new(answer: &ExamAnswer, answer_image: Option<ImageMetaResponse>) -> Self {
2343 Self {2565 Self {
2344- selected: answer.get_selected(),2566+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
2345 text: answer.get_text().map(|t| t.as_str().to_string()),2567 text: answer.get_text().map(|t| t.as_str().to_string()),
2346 updated_at: answer.get_updated_at().as_millis(),2568 updated_at: answer.get_updated_at().as_millis(),
2347 answer_image,2569 answer_image,
@@ -2361,12 +2583,15 @@ struct AttemptQuestionResponse {
2361 #[schema(example = "choice")]2583 #[schema(example = "choice")]
2362 kind: String,2584 kind: String,
2363 points: i64,2585 points: i64,
2364- choices: Option<Vec<String>>,2586+ /// The options with their ids — and deliberately *not* `correct`: this DTO
2587+ /// leaks no answer key because it has no field to carry one, and
2588+ /// `ChoiceResponse` carries none either.
2589+ choices: Option<Vec<ChoiceResponse>>,
2365 /// The question's illustration, if any — bytes at2590 /// The question's illustration, if any — bytes at
2366 /// `GET /exams/{id}/questions/{qid}/image`.2591 /// `GET /exams/{id}/questions/{qid}/image`.
2367 image: Option<ImageMetaResponse>,2592 image: Option<ImageMetaResponse>,
2368 /// Per-option pictures aligned with `choices`, if any — bytes at2593 /// Per-option pictures aligned with `choices`, if any — bytes at
2369- /// `GET /exams/{id}/questions/{qid}/choices/{index}/image`.2594+ /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`.
2370 choice_images: Option<Vec<Option<ImageMetaResponse>>>,2595 choice_images: Option<Vec<Option<ImageMetaResponse>>>,
2371 /// The caller's saved answer; `null` while unanswered.2596 /// The caller's saved answer; `null` while unanswered.
2372 answer: Option<AnswerStateResponse>,2597 answer: Option<AnswerStateResponse>,
@@ -2376,8 +2601,8 @@ struct AttemptQuestionResponse {
2376 struct SaveAnswer {2601 struct SaveAnswer {
2377 /// The question being answered.2602 /// The question being answered.
2378 question_id: String,2603 question_id: String,
2379- /// The picked option's zero-based index — required for `choice` questions.2604+ /// The picked option's `id` — required for `choice` questions.
2380- selected: Option<i64>,2605+ selected: Option<String>,
2381 /// The typed answer — required for `text` questions (empty clears the draft).2606 /// The typed answer — required for `text` questions (empty clears the draft).
2382 text: Option<String>,2607 text: Option<String>,
2383 }2608 }
@@ -2385,7 +2610,8 @@ struct SaveAnswer {
2385 #[derive(Serialize, ToSchema)]2610 #[derive(Serialize, ToSchema)]
2386 struct AnswerSavedResponse {2611 struct AnswerSavedResponse {
2387 question: String,2612 question: String,
2388- selected: Option<i64>,2613+ /// The picked option's id.
2614+ selected: Option<String>,
2389 text: Option<String>,2615 text: Option<String>,
2390 /// Save instant by the server clock, UTC unix-milliseconds.2616 /// Save instant by the server clock, UTC unix-milliseconds.
2391 updated_at: i64,2617 updated_at: i64,
@@ -2432,7 +2658,7 @@ pub(crate) async fn save_answer_checked(
2432 exam: &Exam,2658 exam: &Exam,
2433 user: &UserId,2659 user: &UserId,
2434 question_id: &str,2660 question_id: &str,
2435- selected: Option<i64>,2661+ selected: Option<String>,
2436 text: Option<String>,2662 text: Option<String>,
2437 db: &Database,2663 db: &Database,
2438 ) -> Result<ExamAnswer, AppError> {2664 ) -> Result<ExamAnswer, AppError> {
@@ -2452,7 +2678,7 @@ pub(crate) async fn save_answer_in(
2452 exam: &Exam,2678 exam: &Exam,
2453 attempt: &ExamAttempt,2679 attempt: &ExamAttempt,
2454 question_id: &str,2680 question_id: &str,
2455- selected: Option<i64>,2681+ selected: Option<String>,
2456 text: Option<String>,2682 text: Option<String>,
2457 db: &Database,2683 db: &Database,
2458 ) -> Result<ExamAnswer, AppError> {2684 ) -> Result<ExamAnswer, AppError> {
@@ -2580,9 +2806,7 @@ async fn attempt_questions(
2580 text: question.get_text().as_str().to_string(),2806 text: question.get_text().as_str().to_string(),
2581 kind: question.get_kind().as_str().to_string(),2807 kind: question.get_kind().as_str().to_string(),
2582 points: question.get_points().as_i64(),2808 points: question.get_points().as_i64(),
2583- choices: question2809+ choices: ChoiceResponse::list(question.get_choices()),
2584- .get_choices()
2585- .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()),
2586 image: image_meta(question_images, None),2810 image: image_meta(question_images, None),
2587 choice_images: choice_image_metas(question, question_images),2811 choice_images: choice_image_metas(question, question_images),
2588 answer: answers.get(question.get_id().key()).map(|answer| {2812 answer: answers.get(question.get_id().key()).map(|answer| {
@@ -2643,7 +2867,7 @@ async fn save_answer(
2643 .await?;2867 .await?;
2644 Ok(Json(AnswerSavedResponse {2868 Ok(Json(AnswerSavedResponse {
2645 question: answer.get_question().key().to_string(),2869 question: answer.get_question().key().to_string(),
2646- selected: answer.get_selected(),2870+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
2647 text: answer.get_text().map(|t| t.as_str().to_string()),2871 text: answer.get_text().map(|t| t.as_str().to_string()),
2648 updated_at: answer.get_updated_at().as_millis(),2872 updated_at: answer.get_updated_at().as_millis(),
2649 }))2873 }))
@@ -2727,7 +2951,7 @@ async fn answer_sheet(
2727 .iter()2951 .iter()
2728 .map(|answer| StudentAnswerResponse {2952 .map(|answer| StudentAnswerResponse {
2729 question: answer.get_question().key().to_string(),2953 question: answer.get_question().key().to_string(),
2730- selected: answer.get_selected(),2954+ selected: answer.get_selected().map(|id| id.as_str().to_string()),
2731 text: answer.get_text().map(|t| t.as_str().to_string()),2955 text: answer.get_text().map(|t| t.as_str().to_string()),
2732 updated_at: answer.get_updated_at().as_millis(),2956 updated_at: answer.get_updated_at().as_millis(),
2733 is_correct: by_question2957 is_correct: by_question
@@ -2746,7 +2970,8 @@ async fn answer_sheet(
2746 #[derive(Serialize, ToSchema)]2970 #[derive(Serialize, ToSchema)]
2747 struct StudentAnswerResponse {2971 struct StudentAnswerResponse {
2748 question: String,2972 question: String,
2749- selected: Option<i64>,2973+ /// The picked option's id.
2974+ selected: Option<String>,
2750 text: Option<String>,2975 text: Option<String>,
2751 /// When the answer was last saved, UTC unix-milliseconds.2976 /// When the answer was last saved, UTC unix-milliseconds.
2752 updated_at: i64,2977 updated_at: i64,
src/web/mod.rsmodified+44 -0
@@ -50,6 +50,7 @@ use utoipa::ToSchema;
50 50
51 use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};51 use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
52 use crate::database::Database;52 use crate::database::Database;
53+use crate::domain::exam_question::{Choice, ChoiceInput};
53 use crate::domain::note_file::FileContentType;54 use crate::domain::note_file::FileContentType;
54 use crate::domain::parent_link::ParentLink;55 use crate::domain::parent_link::ParentLink;
55 use crate::domain::role::Role;56 use crate::domain::role::Role;
@@ -269,6 +270,49 @@ pub(crate) async fn read_upload(
269 })270 })
270 }271 }
271 272
273+/// One option of a choice question as a client sends it — the wire form of
274+/// [`crate::domain::exam_question::ChoiceInput`], shared by the exam-question
275+/// and bank-template routes.
276+///
277+/// `id` is the option's key within the payload: send back the `id` the server
278+/// returned to keep that option (and its picture) across an edit, or any fresh
279+/// string to introduce a new one. The server mints the stored id either way, so
280+/// nothing a client sends here ever reaches storage.
281+#[derive(Debug, Clone, Deserialize, ToSchema)]
282+pub(crate) struct ChoiceBody {
283+ #[serde(default)]
284+ pub id: Option<String>,
285+ #[schema(example = "42")]
286+ pub text: String,
287+}
288+
289+impl ChoiceBody {
290+ pub(crate) fn into_input(self) -> ChoiceInput {
291+ ChoiceInput {
292+ id: self.id,
293+ text: self.text,
294+ }
295+ }
296+
297+ /// The whole submitted list, or `None` when the field was omitted/cleared.
298+ pub(crate) fn into_inputs(choices: Option<Vec<Self>>) -> Option<Vec<ChoiceInput>> {
299+ choices.map(|list| list.into_iter().map(Self::into_input).collect())
300+ }
301+
302+ /// The stored choices as a payload that re-submits them unchanged — how a
303+ /// PATCH that omits `choices` keeps every option's identity.
304+ pub(crate) fn from_stored(choices: Option<&[Choice]>) -> Option<Vec<ChoiceInput>> {
305+ choices.map(|list| {
306+ list.iter()
307+ .map(|choice| ChoiceInput {
308+ id: Some(choice.get_id().as_str().to_string()),
309+ text: choice.get_text().as_str().to_string(),
310+ })
311+ .collect()
312+ })
313+ }
314+}
315+
272 /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never316 /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never
273 /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the317 /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the
274 /// stored value); `null` or a value lands here as `Some(inner)` (clear or set).318 /// stored value); `null` or a value lands here as `Some(inner)` (clear or set).
src/web/subjects.rsmodified+17 -16
@@ -7,7 +7,6 @@ use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;7 use utoipa_axum::routes;
8 8
9 use crate::database::Database;9 use crate::database::Database;
10-use crate::domain::bank_question::BankQuestion;
11 use crate::domain::course::{Course, CourseId};10 use crate::domain::course::{Course, CourseId};
12 use crate::domain::exam_question::ExamQuestion;11 use crate::domain::exam_question::ExamQuestion;
13 use crate::domain::homework::Homework;12 use crate::domain::homework::Homework;
@@ -158,9 +157,15 @@ async fn update_subject(
158 }157 }
159 158
160 /// Delete a subject. Requires teacher+ and management rights over its course.159 /// Delete a subject. Requires teacher+ and management rights over its course.
161-/// Refused with a 409 while any exam question, homework, or bank question still160+/// Refused with a 409 while any exam question or homework still references it —
162-/// references it — re-tag or delete those first, so nothing is left pointing at161+/// re-tag or delete those first, so nothing is left pointing at a subject that
163-/// a subject that no longer exists.162+/// no longer exists.
163+///
164+/// Bank templates are the exception: their `subject` is optional origin
165+/// metadata, so the delete simply clears it on every template that carried it
166+/// instead of refusing. Blocking there was unresolvable (only a template's
167+/// owner may re-tag it, so a manager could not clear their own 409) and leaked
168+/// the existence of other teachers' private templates.
164 #[utoipa::path(169 #[utoipa::path(
165 delete,170 delete,
166 path = "/{id}",171 path = "/{id}",
@@ -172,7 +177,7 @@ async fn update_subject(
172 (status = 401, description = "Not authenticated", body = ErrorResponse),177 (status = 401, description = "Not authenticated", body = ErrorResponse),
173 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),178 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
174 (status = 404, description = "Not found", body = ErrorResponse),179 (status = 404, description = "Not found", body = ErrorResponse),
175- (status = 409, description = "Exam questions, homework, or bank questions still reference this subject", body = ErrorResponse),180+ (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse),
176 ),181 ),
177 )]182 )]
178 async fn delete_subject(183 async fn delete_subject(
@@ -207,18 +212,14 @@ async fn delete_subject(
207 "homework still references this subject — re-tag or delete it first",212 "homework still references this subject — re-tag or delete it first",
208 ));213 ));
209 }214 }
210- // Bank templates carry this subject as origin metadata; a deleted subject215+ // Bank templates carry this subject as optional origin metadata, so they
211- // would leave them pointing at nothing. Writer lease of [`BANK_LOCK`], the216+ // don't block: `Subject::delete` clears it off them in the delete's own
212- // bank twin of the two guards above: bank create/update validate their217+ // transaction. Writer lease of [`BANK_LOCK`] all the same — bank
213- // subject and insert under the reader lease, so the no-templates check and218+ // create/update validate their subject and write under the reader lease, so
214- // the delete can't straddle a template that just adopted this subject. Held219+ // without it a template could adopt this subject *after* the cascade ran
215- // last; the order is EXAM_LOCK, then HOMEWORK_LOCK, then BANK_LOCK.220+ // and outlive it. Held last; the order is EXAM_LOCK, then HOMEWORK_LOCK,
221+ // then BANK_LOCK.
216 let _bank_guard = BANK_LOCK.write().await;222 let _bank_guard = BANK_LOCK.write().await;
217- if BankQuestion::any_for_subject(subject.get_id(), &st.db).await? {
218- return Err(AppError::Conflict(
219- "bank questions still reference this subject — re-tag or delete them first",
220- ));
221- }
222 subject.delete(&st.db).await?;223 subject.delete(&st.db).await?;
223 Ok(StatusCode::NO_CONTENT)224 Ok(StatusCode::NO_CONTENT)
224 }225 }
tests/e2e.rsmodified+39 -21
@@ -508,6 +508,9 @@ struct ExamRoom {
508 subject_id: String,508 subject_id: String,
509 exam_id: String,509 exam_id: String,
510 question_id: String,510 question_id: String,
511+ /// The fixture question's minted choice ids, in list order — what the
512+ /// tests below used to write as the indexes 0 and 1.
513+ choice_ids: Vec<String>,
511 }514 }
512 515
513 async fn exam_room_fixture(window_ms: i64) -> ExamRoom {516 async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
@@ -583,7 +586,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
583 .post(format!("{base}/exams/{exam_id}/questions"))586 .post(format!("{base}/exams/{exam_id}/questions"))
584 .json(587 .json(
585 &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",588 &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",
586- "points": 10, "choices": ["3", "4"], "correct": 1 }),589+ "points": 10, "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}], "correct": "b" }),
587 )590 )
588 .send()591 .send()
589 .await592 .await
@@ -592,6 +595,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
592 .await595 .await
593 .unwrap();596 .unwrap();
594 let question_id = question["id"].as_str().unwrap().to_string();597 let question_id = question["id"].as_str().unwrap().to_string();
598+ let choice_ids = choice_ids(&question);
595 let cookie = raw_session_cookie(&base, "veli").await;599 let cookie = raw_session_cookie(&base, "veli").await;
596 ExamRoom {600 ExamRoom {
597 base,601 base,
@@ -604,9 +608,20 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
604 subject_id,608 subject_id,
605 exam_id,609 exam_id,
606 question_id,610 question_id,
611+ choice_ids,
607 }612 }
608 }613 }
609 614
615+/// The minted ids of a question response's options, in list order.
616+fn choice_ids(question: &Value) -> Vec<String> {
617+ question["choices"]
618+ .as_array()
619+ .unwrap()
620+ .iter()
621+ .map(|choice| choice["id"].as_str().unwrap().to_string())
622+ .collect()
623+}
624+
610 /// The student exam room over a real TCP WebSocket: connect with the session625 /// The student exam room over a real TCP WebSocket: connect with the session
611 /// cookie, get the state frame, autosave an answer, survive junk input,626 /// cookie, get the state frame, autosave an answer, survive junk input,
612 /// finish, and watch the server close the room — with the result visible to627 /// finish, and watch the server close the room — with the result visible to
@@ -667,7 +682,7 @@ async fn exam_room_websocket_round_trip() {
667 // Autosave: answer -> saved ack -> a state showing the progress.682 // Autosave: answer -> saved ack -> a state showing the progress.
668 ws_send(683 ws_send(
669 &mut ws,684 &mut ws,
670- json!({ "type": "answer", "question_id": question_id, "selected": 1 }),685+ json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }),
671 )686 )
672 .await;687 .await;
673 let saved = ws_frame_of_type(&mut ws, "saved").await;688 let saved = ws_frame_of_type(&mut ws, "saved").await;
@@ -848,7 +863,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() {
848 // While the sitter is a student the sheet is open — save one answer.863 // While the sitter is a student the sheet is open — save one answer.
849 ws_send(864 ws_send(
850 &mut ws,865 &mut ws,
851- json!({ "type": "answer", "question_id": question_id, "selected": 1 }),866+ json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }),
852 )867 )
853 .await;868 .await;
854 ws_frame_of_type(&mut ws, "saved").await;869 ws_frame_of_type(&mut ws, "saved").await;
@@ -859,7 +874,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() {
859 // The very next save is refused over the same socket...874 // The very next save is refused over the same socket...
860 ws_send(875 ws_send(
861 &mut ws,876 &mut ws,
862- json!({ "type": "answer", "question_id": question_id, "selected": 0 }),877+ json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }),
863 )878 )
864 .await;879 .await;
865 let error = ws_frame_of_type(&mut ws, "error").await;880 let error = ws_frame_of_type(&mut ws, "error").await;
@@ -871,7 +886,7 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() {
871 // ... and over REST — the two paths share the wall.886 // ... and over REST — the two paths share the wall.
872 let res = student887 let res = student
873 .post(format!("{base}/exams/{exam_id}/attempt/answers"))888 .post(format!("{base}/exams/{exam_id}/attempt/answers"))
874- .json(&json!({ "question_id": question_id, "selected": 0 }))889+ .json(&json!({ "question_id": question_id, "selected": room.choice_ids[0] }))
875 .send()890 .send()
876 .await891 .await
877 .unwrap();892 .unwrap();
@@ -889,13 +904,13 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() {
889 .await904 .await
890 .unwrap();905 .unwrap();
891 assert_eq!(sheet["answers"].as_array().unwrap().len(), 1);906 assert_eq!(sheet["answers"].as_array().unwrap().len(), 1);
892- assert_eq!(sheet["answers"][0]["selected"], 1);907+ assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]);
893 908
894 // Demoted back, the same socket writes again — no reconnect required.909 // Demoted back, the same socket writes again — no reconnect required.
895 promote(db, "veli", "student").await;910 promote(db, "veli", "student").await;
896 ws_send(911 ws_send(
897 &mut ws,912 &mut ws,
898- json!({ "type": "answer", "question_id": question_id, "selected": 0 }),913+ json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }),
899 )914 )
900 .await;915 .await;
901 ws_frame_of_type(&mut ws, "saved").await;916 ws_frame_of_type(&mut ws, "saved").await;
@@ -967,7 +982,7 @@ async fn exam_room_expires_mid_session() {
967 // One answer lands inside the window.982 // One answer lands inside the window.
968 ws_send(983 ws_send(
969 &mut ws,984 &mut ws,
970- json!({ "type": "answer", "question_id": room.question_id, "selected": 1 }),985+ json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }),
971 )986 )
972 .await;987 .await;
973 ws_frame_of_type(&mut ws, "saved").await;988 ws_frame_of_type(&mut ws, "saved").await;
@@ -987,7 +1002,7 @@ async fn exam_room_expires_mid_session() {
987 "{}/exams/{}/attempt/answers",1002 "{}/exams/{}/attempt/answers",
988 room.base, room.exam_id1003 room.base, room.exam_id
989 ))1004 ))
990- .json(&json!({ "question_id": room.question_id, "selected": 0 }))1005+ .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
991 .send()1006 .send()
992 .await1007 .await
993 .unwrap();1008 .unwrap();
@@ -1015,7 +1030,7 @@ async fn exam_room_expires_mid_session() {
1015 .json()1030 .json()
1016 .await1031 .await
1017 .unwrap();1032 .unwrap();
1018- assert_eq!(sheet["answers"][0]["selected"], 1);1033+ assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]);
1019 assert_eq!(sheet["auto_score"]["earned"], 10);1034 assert_eq!(sheet["auto_score"]["earned"], 10);
1020 }1035 }
1021 1036
@@ -1088,7 +1103,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() {
1088 "{}/exams/{}/attempt/answers",1103 "{}/exams/{}/attempt/answers",
1089 room.base, room.exam_id1104 room.base, room.exam_id
1090 ))1105 ))
1091- .json(&json!({ "question_id": room.question_id, "selected": 1 }))1106+ .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] }))
1092 .send()1107 .send()
1093 .await1108 .await
1094 .unwrap();1109 .unwrap();
@@ -1121,7 +1136,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() {
1121 );1136 );
1122 ws_send(1137 ws_send(
1123 &mut ws,1138 &mut ws,
1124- json!({ "type": "answer", "question_id": room.question_id, "selected": 1 }),1139+ json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }),
1125 )1140 )
1126 .await;1141 .await;
1127 ws_frame_of_type(&mut ws, "saved").await;1142 ws_frame_of_type(&mut ws, "saved").await;
@@ -1136,7 +1151,7 @@ async fn exam_room_rejoin_door_is_the_teachers_call() {
1136 "{}/exams/{}/attempt/answers",1151 "{}/exams/{}/attempt/answers",
1137 room.base, room.exam_id1152 room.base, room.exam_id
1138 ))1153 ))
1139- .json(&json!({ "question_id": room.question_id, "selected": 0 }))1154+ .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
1140 .send()1155 .send()
1141 .await1156 .await
1142 .unwrap();1157 .unwrap();
@@ -1193,7 +1208,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1193 .post(format!("{}/exams/{exam_id}/questions", room.base))1208 .post(format!("{}/exams/{exam_id}/questions", room.base))
1194 .json(1209 .json(
1195 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",1210 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1196- "points": 5, "choices": ["5", "6"], "correct": 1 }),1211+ "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1197 )1212 )
1198 .send()1213 .send()
1199 .await1214 .await
@@ -1202,6 +1217,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1202 .await1217 .await
1203 .unwrap();1218 .unwrap();
1204 let question_id = question["id"].as_str().unwrap().to_string();1219 let question_id = question["id"].as_str().unwrap().to_string();
1220+ let opts = choice_ids(&question);
1205 1221
1206 // Sit sitting #1 and open its room.1222 // Sit sitting #1 and open its room.
1207 let res = room1223 let res = room
@@ -1259,7 +1275,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1259 let res = room1275 let res = room
1260 .student1276 .student
1261 .post(format!("{}/exams/{exam_id}/attempt/answers", room.base))1277 .post(format!("{}/exams/{exam_id}/attempt/answers", room.base))
1262- .json(&json!({ "question_id": question_id, "selected": 1 }))1278+ .json(&json!({ "question_id": question_id, "selected": opts[1] }))
1263 .send()1279 .send()
1264 .await1280 .await
1265 .unwrap();1281 .unwrap();
@@ -1299,7 +1315,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() {
1299 .post(format!("{}/exams/{exam_id}/questions", room.base))1315 .post(format!("{}/exams/{exam_id}/questions", room.base))
1300 .json(1316 .json(
1301 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",1317 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1302- "points": 5, "choices": ["5", "6"], "correct": 1 }),1318+ "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1303 )1319 )
1304 .send()1320 .send()
1305 .await1321 .await
@@ -1308,6 +1324,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() {
1308 .await1324 .await
1309 .unwrap();1325 .unwrap();
1310 let question_id = question["id"].as_str().unwrap().to_string();1326 let question_id = question["id"].as_str().unwrap().to_string();
1327+ let opts = choice_ids(&question);
1311 1328
1312 // Sit sitting #1 and open its room.1329 // Sit sitting #1 and open its room.
1313 let res = room1330 let res = room
@@ -1346,7 +1363,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() {
1346 // blank sheet of sitting #2.1363 // blank sheet of sitting #2.
1347 ws_send(1364 ws_send(
1348 &mut ws,1365 &mut ws,
1349- json!({ "type": "answer", "question_id": question_id, "selected": 1 }),1366+ json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }),
1350 )1367 )
1351 .await;1368 .await;
1352 let error = ws_frame_of_type(&mut ws, "error").await;1369 let error = ws_frame_of_type(&mut ws, "error").await;
@@ -1432,7 +1449,7 @@ async fn exam_room_second_tab_keeps_the_student_present() {
1432 "{}/exams/{}/attempt/answers",1449 "{}/exams/{}/attempt/answers",
1433 room.base, room.exam_id1450 room.base, room.exam_id
1434 ))1451 ))
1435- .json(&json!({ "question_id": room.question_id, "selected": 1 }))1452+ .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] }))
1436 .send()1453 .send()
1437 .await1454 .await
1438 .unwrap();1455 .unwrap();
@@ -1452,7 +1469,7 @@ async fn exam_room_second_tab_keeps_the_student_present() {
1452 "{}/exams/{}/attempt/answers",1469 "{}/exams/{}/attempt/answers",
1453 room.base, room.exam_id1470 room.base, room.exam_id
1454 ))1471 ))
1455- .json(&json!({ "question_id": room.question_id, "selected": 0 }))1472+ .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
1456 .send()1473 .send()
1457 .await1474 .await
1458 .unwrap();1475 .unwrap();
@@ -1486,7 +1503,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() {
1486 .post(format!("{}/exams/{exam_id}/questions", room.base))1503 .post(format!("{}/exams/{exam_id}/questions", room.base))
1487 .json(1504 .json(
1488 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",1505 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1489- "points": 5, "choices": ["5", "6"], "correct": 1 }),1506+ "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1490 )1507 )
1491 .send()1508 .send()
1492 .await1509 .await
@@ -1495,6 +1512,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() {
1495 .await1512 .await
1496 .unwrap();1513 .unwrap();
1497 let question_id = question["id"].as_str().unwrap().to_string();1514 let question_id = question["id"].as_str().unwrap().to_string();
1515+ let opts = choice_ids(&question);
1498 1516
1499 let res = room1517 let res = room
1500 .student1518 .student
@@ -1515,7 +1533,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() {
1515 1533
1516 ws_send(1534 ws_send(
1517 &mut ws,1535 &mut ws,
1518- json!({ "type": "answer", "question_id": question_id, "selected": 1 }),1536+ json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }),
1519 )1537 )
1520 .await;1538 .await;
1521 ws_frame_of_type(&mut ws, "saved").await;1539 ws_frame_of_type(&mut ws, "saved").await;
tests/integration.rsmodified+1347 -202

Diff too large; view file

@@ -4965,7 +4965,7 @@ async fn promotion_out_of_student_freezes_the_seat() {
4965 "POST",4965 "POST",
4966 &format!("/exams/{exam}/attempt/answers"),4966 &format!("/exams/{exam}/attempt/answers"),
4967 Some(&student),4967 Some(&student),
4968- Some(json!({ "question_id": "nope", "selected": 0 })),4968+ Some(json!({ "question_id": "nope", "selected": "c0" })),
4969 )4969 )
4970 .await;4970 .await;
4971 assert_eq!(4971 assert_eq!(
@@ -6610,15 +6610,16 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() {
6610 "mode": "open", "max_attempts": 2 }),6610 "mode": "open", "max_attempts": 2 }),
6611 )6611 )
6612 .await;6612 .await;
6613- let question = create_question(6613+ let question_body = create_question_body(
6614 &app,6614 &app,
6615 &teacher,6615 &teacher,
6616 &exam,6616 &exam,
6617 &subject,6617 &subject,
6618 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,6618 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
6619- "choices": ["3", "4"], "correct": 1 }),6619+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
6620 )6620 )
6621 .await;6621 .await;
6622+ let question = id_of(&question_body);
6622 6623
6623 // First sitting starts right away — no window to wait for — and runs6624 // First sitting starts right away — no window to wait for — and runs
6624 // without a deadline: it can only end by submission.6625 // without a deadline: it can only end by submission.
@@ -6644,7 +6645,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() {
6644 "POST",6645 "POST",
6645 &format!("/exams/{exam}/attempt/answers"),6646 &format!("/exams/{exam}/attempt/answers"),
6646 Some(&student),6647 Some(&student),
6647- Some(json!({ "question_id": question, "selected": 1 })),6648+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })),
6648 )6649 )
6649 .await;6650 .await;
6650 assert_eq!(res.status, StatusCode::OK, "{}", res.body);6651 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -7086,7 +7087,7 @@ async fn subject_delete_blocks_while_questions_reference_it() {
7086 let tagged = create_subject(&app, &teacher, &course, "antiquity").await;7087 let tagged = create_subject(&app, &teacher, &course, "antiquity").await;
7087 let spare = create_subject(&app, &teacher, &course, "middle ages").await;7088 let spare = create_subject(&app, &teacher, &course, "middle ages").await;
7088 let exam = create_exam(&app, &teacher, &course, "final", "final").await;7089 let exam = create_exam(&app, &teacher, &course, "final", "final").await;
7089- let question = create_question(7090+ let question_body = create_question_body(
7090 &app,7091 &app,
7091 &teacher,7092 &teacher,
7092 &exam,7093 &exam,
@@ -7094,6 +7095,7 @@ async fn subject_delete_blocks_while_questions_reference_it() {
7094 json!({ "text": "When?", "kind": "text", "points": 10 }),7095 json!({ "text": "When?", "kind": "text", "points": 10 }),
7095 )7096 )
7096 .await;7097 .await;
7098+ let question = id_of(&question_body);
7097 7099
7098 // Referenced: the delete is a conflict, and the subject survives.7100 // Referenced: the delete is a conflict, and the subject survives.
7099 let res = send(7101 let res = send(
@@ -7175,8 +7177,21 @@ async fn create_question(
7175 cookie: &str,7177 cookie: &str,
7176 exam: &str,7178 exam: &str,
7177 subject: &str,7179 subject: &str,
7178- mut body: serde_json::Value,7180+ body: serde_json::Value,
7179 ) -> String {7181 ) -> String {
7182+ id_of(&create_question_body(app, cookie, exam, subject, body).await)
7183+}
7184+
7185+/// Like [`create_question`], but hands back the whole response: choice ids are
7186+/// minted by the server, so a test that answers a question — or pictures one of
7187+/// its options — has to read them off the response rather than count positions.
7188+async fn create_question_body(
7189+ app: &axum::Router,
7190+ cookie: &str,
7191+ exam: &str,
7192+ subject: &str,
7193+ mut body: serde_json::Value,
7194+) -> serde_json::Value {
7180 body["subject_id"] = json!(subject);7195 body["subject_id"] = json!(subject);
7181 let res = send(7196 let res = send(
7182 app,7197 app,
@@ -7192,7 +7207,16 @@ async fn create_question(
7192 "create question: {}",7207 "create question: {}",
7193 res.body7208 res.body
7194 );7209 );
7195- id_of(&res.body)7210+ res.body
7211+}
7212+
7213+/// The minted id of the option at `index` of a question (or bank template)
7214+/// response — what these tests used to write as a bare choice index.
7215+fn choice_of(question: &serde_json::Value, index: usize) -> String {
7216+ question["choices"][index]["id"]
7217+ .as_str()
7218+ .unwrap_or_else(|| panic!("choice {index} of {question}"))
7219+ .to_string()
7196 }7220 }
7197 7221
7198 /// A course with an open sync window, one subject, and one enrolled student —7222 /// A course with an open sync window, one subject, and one enrolled student —
@@ -7236,7 +7260,7 @@ async fn question_crud_validation_and_rbac() {
7236 Some(&teacher),7260 Some(&teacher),
7237 Some(7261 Some(
7238 json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10,7262 json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10,
7239- "choices": ["3", "4", "5"], "correct": 1 }),7263+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }),
7240 ),7264 ),
7241 )7265 )
7242 .await;7266 .await;
@@ -7245,8 +7269,8 @@ async fn question_crud_validation_and_rbac() {
7245 assert_eq!(res.body["subject"], subject);7269 assert_eq!(res.body["subject"], subject);
7246 assert_eq!(res.body["kind"], "choice");7270 assert_eq!(res.body["kind"], "choice");
7247 assert_eq!(res.body["points"], 10);7271 assert_eq!(res.body["points"], 10);
7248- assert_eq!(res.body["choices"][1], "4");7272+ assert_eq!(res.body["choices"][1]["text"], "4");
7249- assert_eq!(res.body["correct"], 1);7273+ assert_eq!(res.body["correct"], res.body["choices"][1]["id"]);
7250 let choice_q = id_of(&res.body);7274 let choice_q = id_of(&res.body);
7251 7275
7252 // A text question carries neither choices nor correct.7276 // A text question carries neither choices nor correct.
@@ -7298,40 +7322,51 @@ async fn question_crud_validation_and_rbac() {
7298 ),7322 ),
7299 (7323 (
7300 "choice without choices",7324 "choice without choices",
7301- json!({ "text": "x", "kind": "choice", "points": 1, "correct": 0 }),7325+ json!({ "text": "x", "kind": "choice", "points": 1, "correct": "c0" }),
7302 ),7326 ),
7303 (7327 (
7304 "choice without correct",7328 "choice without correct",
7305- json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"] }),7329+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }),
7330+ ),
7331+ (
7332+ "correct names no submitted choice",
7333+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c2" }),
7334+ ),
7335+ (
7336+ "correct is blank",
7337+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "" }),
7306 ),7338 ),
7307 (7339 (
7308- "correct out of range",7340+ // Two options under one key: the payload can't say which one
7309- json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": 2 }),7341+ // `correct` (or a picture) means, so it is refused outright.
7342+ "duplicate choice id in one payload",
7343+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c0", "text": "b"}], "correct": "c0" }),
7310 ),7344 ),
7311 (7345 (
7312- "negative correct",7346+ // An option with no key cannot be named by `correct`.
7313- json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": -1 }),7347+ "correct names an unkeyed option",
7348+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"text": "a"}, {"text": "b"}], "correct": "c0" }),
7314 ),7349 ),
7315 (7350 (
7316 "one choice",7351 "one choice",
7317- json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a"], "correct": 0 }),7352+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}], "correct": "c0" }),
7318 ),7353 ),
7319 (7354 (
7320 "eleven choices",7355 "eleven choices",
7321 json!({ "text": "x", "kind": "choice", "points": 1,7356 json!({ "text": "x", "kind": "choice", "points": 1,
7322- "choices": ["a","b","c","d","e","f","g","h","i","j","k"], "correct": 0 }),7357+ "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" }),
7323 ),7358 ),
7324 (7359 (
7325 "blank choice",7360 "blank choice",
7326- json!({ "text": "x", "kind": "choice", "points": 1, "choices": ["a", " "], "correct": 0 }),7361+ json!({ "text": "x", "kind": "choice", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": " "}], "correct": "c0" }),
7327 ),7362 ),
7328 (7363 (
7329 "text with choices",7364 "text with choices",
7330- json!({ "text": "x", "kind": "text", "points": 1, "choices": ["a", "b"] }),7365+ json!({ "text": "x", "kind": "text", "points": 1, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] }),
7331 ),7366 ),
7332 (7367 (
7333 "text with correct",7368 "text with correct",
7334- json!({ "text": "x", "kind": "text", "points": 1, "correct": 0 }),7369+ json!({ "text": "x", "kind": "text", "points": 1, "correct": "c0" }),
7335 ),7370 ),
7336 ] {7371 ] {
7337 let mut body = body;7372 let mut body = body;
@@ -7410,7 +7445,7 @@ async fn question_crud_validation_and_rbac() {
7410 .await;7445 .await;
7411 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7446 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
7412 assert_eq!(res.body["points"], 15);7447 assert_eq!(res.body["points"], 15);
7413- assert_eq!(res.body["correct"], 1, "kind bundle kept");7448+ assert_eq!(res.body["correct"], res.body["choices"][1]["id"], "kind bundle kept");
7414 assert_eq!(res.body["subject"], subject, "subject kept by omission");7449 assert_eq!(res.body["subject"], subject, "subject kept by omission");
7415 7450
7416 // Re-tagging stays inside the course: another of its subjects is fine, a7451 // Re-tagging stays inside the course: another of its subjects is fine, a
@@ -7468,7 +7503,7 @@ async fn question_crud_validation_and_rbac() {
7468 "PATCH",7503 "PATCH",
7469 &format!("/exams/{exam}/questions/{choice_q}"),7504 &format!("/exams/{exam}/questions/{choice_q}"),
7470 Some(&teacher),7505 Some(&teacher),
7471- Some(json!({ "kind": "choice", "choices": ["yes", "no"], "correct": 0 })),7506+ Some(json!({ "kind": "choice", "choices": [{"id": "c0", "text": "yes"}, {"id": "c1", "text": "no"}], "correct": "c0" })),
7472 )7507 )
7473 .await;7508 .await;
7474 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7509 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -7546,15 +7581,16 @@ async fn questions_freeze_once_attempts_start() {
7546 let student_id = me_id(&app, &student).await;7581 let student_id = me_id(&app, &student).await;
7547 let (_course, exam, subject) =7582 let (_course, exam, subject) =
7548 open_exam_with_student(&app, &teacher, &student_id, "algo").await;7583 open_exam_with_student(&app, &teacher, &student_id, "algo").await;
7549- let question = create_question(7584+ let question_body = create_question_body(
7550 &app,7585 &app,
7551 &teacher,7586 &teacher,
7552 &exam,7587 &exam,
7553 &subject,7588 &subject,
7554 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,7589 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
7555- "choices": ["3", "4"], "correct": 1 }),7590+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
7556 )7591 )
7557 .await;7592 .await;
7593+ let question = id_of(&question_body);
7558 7594
7559 let res = send(7595 let res = send(
7560 &app,7596 &app,
@@ -7603,15 +7639,16 @@ async fn student_question_view_hides_correct_and_embeds_answers() {
7603 let student = login(&app, "sona").await;7639 let student = login(&app, "sona").await;
7604 let student_id = me_id(&app, &student).await;7640 let student_id = me_id(&app, &student).await;
7605 let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "art").await;7641 let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "art").await;
7606- let choice_q = create_question(7642+ let choice_q_body = create_question_body(
7607 &app,7643 &app,
7608 &teacher,7644 &teacher,
7609 &exam,7645 &exam,
7610 &subject,7646 &subject,
7611 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,7647 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
7612- "choices": ["3", "4"], "correct": 1 }),7648+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
7613 )7649 )
7614 .await;7650 .await;
7651+ let choice_q = id_of(&choice_q_body);
7615 create_question(7652 create_question(
7616 &app,7653 &app,
7617 &teacher,7654 &teacher,
@@ -7641,7 +7678,7 @@ async fn student_question_view_hides_correct_and_embeds_answers() {
7641 let questions = res.body.as_array().expect("questions");7678 let questions = res.body.as_array().expect("questions");
7642 assert_eq!(questions.len(), 2);7679 assert_eq!(questions.len(), 2);
7643 assert_eq!(questions[0]["kind"], "choice");7680 assert_eq!(questions[0]["kind"], "choice");
7644- assert_eq!(questions[0]["choices"][1], "4");7681+ assert_eq!(questions[0]["choices"][1]["text"], "4");
7645 for question in questions {7682 for question in questions {
7646 assert!(7683 assert!(
7647 question.as_object().unwrap().get("correct").is_none(),7684 question.as_object().unwrap().get("correct").is_none(),
@@ -7656,17 +7693,17 @@ async fn student_question_view_hides_correct_and_embeds_answers() {
7656 "POST",7693 "POST",
7657 &format!("/exams/{exam}/attempt/answers"),7694 &format!("/exams/{exam}/attempt/answers"),
7658 Some(&student),7695 Some(&student),
7659- Some(json!({ "question_id": choice_q, "selected": 0 })),7696+ Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })),
7660 )7697 )
7661 .await;7698 .await;
7662 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7699 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
7663 assert_eq!(res.body["question"], choice_q);7700 assert_eq!(res.body["question"], choice_q);
7664- assert_eq!(res.body["selected"], 0);7701+ assert_eq!(res.body["selected"], choice_of(&choice_q_body, 0));
7665 let saved_at = res.body["updated_at"].as_i64().expect("updated_at");7702 let saved_at = res.body["updated_at"].as_i64().expect("updated_at");
7666 7703
7667 let res = send(&app, "GET", &uri, Some(&student), None).await;7704 let res = send(&app, "GET", &uri, Some(&student), None).await;
7668 let questions = res.body.as_array().expect("questions");7705 let questions = res.body.as_array().expect("questions");
7669- assert_eq!(questions[0]["answer"]["selected"], 0);7706+ assert_eq!(questions[0]["answer"]["selected"], choice_of(&choice_q_body, 0));
7670 assert_eq!(questions[0]["answer"]["updated_at"], saved_at);7707 assert_eq!(questions[0]["answer"]["updated_at"], saved_at);
7671 assert!(questions[1]["answer"].is_null());7708 assert!(questions[1]["answer"].is_null());
7672 }7709 }
@@ -7678,16 +7715,17 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7678 let student = login(&app, "arda").await;7715 let student = login(&app, "arda").await;
7679 let student_id = me_id(&app, &student).await;7716 let student_id = me_id(&app, &student).await;
7680 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "phys").await;7717 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "phys").await;
7681- let choice_q = create_question(7718+ let choice_q_body = create_question_body(
7682 &app,7719 &app,
7683 &teacher,7720 &teacher,
7684 &exam,7721 &exam,
7685 &subject,7722 &subject,
7686 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,7723 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
7687- "choices": ["3", "4", "5"], "correct": 1 }),7724+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" }),
7688 )7725 )
7689 .await;7726 .await;
7690- let text_q = create_question(7727+ let choice_q = id_of(&choice_q_body);
7728+ let text_q_body = create_question_body(
7691 &app,7729 &app,
7692 &teacher,7730 &teacher,
7693 &exam,7731 &exam,
@@ -7695,6 +7733,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7695 json!({ "text": "Explain.", "kind": "text", "points": 20 }),7733 json!({ "text": "Explain.", "kind": "text", "points": 20 }),
7696 )7734 )
7697 .await;7735 .await;
7736+ let text_q = id_of(&text_q_body);
7698 let answers_uri = format!("/exams/{exam}/attempt/answers");7737 let answers_uri = format!("/exams/{exam}/attempt/answers");
7699 7738
7700 // Saving needs an attempt (404 before start).7739 // Saving needs an attempt (404 before start).
@@ -7703,7 +7742,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7703 "POST",7742 "POST",
7704 &answers_uri,7743 &answers_uri,
7705 Some(&student),7744 Some(&student),
7706- Some(json!({ "question_id": choice_q, "selected": 0 })),7745+ Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })),
7707 )7746 )
7708 .await;7747 .await;
7709 assert_eq!(res.status, StatusCode::NOT_FOUND, "attempt first");7748 assert_eq!(res.status, StatusCode::NOT_FOUND, "attempt first");
@@ -7723,7 +7762,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7723 "POST",7762 "POST",
7724 &answers_uri,7763 &answers_uri,
7725 Some(&student),7764 Some(&student),
7726- Some(json!({ "question_id": choice_q, "selected": 0 })),7765+ Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 0) })),
7727 )7766 )
7728 .await;7767 .await;
7729 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7768 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -7734,11 +7773,11 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7734 "POST",7773 "POST",
7735 &answers_uri,7774 &answers_uri,
7736 Some(&student),7775 Some(&student),
7737- Some(json!({ "question_id": choice_q, "selected": 2 })),7776+ Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 2) })),
7738 )7777 )
7739 .await;7778 .await;
7740 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7779 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
7741- assert_eq!(res.body["selected"], 2);7780+ assert_eq!(res.body["selected"], choice_of(&choice_q_body, 2));
7742 assert!(7781 assert!(
7743 res.body["updated_at"].as_i64().expect("updated_at") > first_saved_at,7782 res.body["updated_at"].as_i64().expect("updated_at") > first_saved_at,
7744 "a re-save moves updated_at forward"7783 "a re-save moves updated_at forward"
@@ -7774,20 +7813,16 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7774 ),7813 ),
7775 (7814 (
7776 "both fields",7815 "both fields",
7777- json!({ "question_id": choice_q, "selected": 1, "text": "4" }),7816+ json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1), "text": "4" }),
7778 ),7817 ),
7779 (7818 (
7780- "selected out of range",7819+ "selected names no choice of this question",
7781- json!({ "question_id": choice_q, "selected": 3 }),7820+ json!({ "question_id": choice_q, "selected": "01NOTACHOICEOFTHISQUEST" }),
7782- ),
7783- (
7784- "negative selected",
7785- json!({ "question_id": choice_q, "selected": -1 }),
7786 ),7821 ),
7787 ("nothing to save", json!({ "question_id": choice_q })),7822 ("nothing to save", json!({ "question_id": choice_q })),
7788 (7823 (
7789 "selected on a text question",7824 "selected on a text question",
7790- json!({ "question_id": text_q, "selected": 0 }),7825+ json!({ "question_id": text_q, "selected": choice_of(&choice_q_body, 0) }),
7791 ),7826 ),
7792 (7827 (
7793 "oversized text",7828 "oversized text",
@@ -7804,26 +7839,27 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7804 "POST",7839 "POST",
7805 &answers_uri,7840 &answers_uri,
7806 Some(&student),7841 Some(&student),
7807- Some(json!({ "question_id": "missing", "selected": 0 })),7842+ Some(json!({ "question_id": "missing", "selected": "c0" })),
7808 )7843 )
7809 .await;7844 .await;
7810 assert_eq!(res.status, StatusCode::NOT_FOUND);7845 assert_eq!(res.status, StatusCode::NOT_FOUND);
7811 let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz").await;7846 let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz").await;
7812- let foreign_q = create_question(7847+ let foreign_q_body = create_question_body(
7813 &app,7848 &app,
7814 &teacher,7849 &teacher,
7815 &foreign_exam,7850 &foreign_exam,
7816 &subject,7851 &subject,
7817 json!({ "text": "not yours", "kind": "choice", "points": 1,7852 json!({ "text": "not yours", "kind": "choice", "points": 1,
7818- "choices": ["a", "b"], "correct": 0 }),7853+ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }),
7819 )7854 )
7820 .await;7855 .await;
7856+ let foreign_q = id_of(&foreign_q_body);
7821 let res = send(7857 let res = send(
7822 &app,7858 &app,
7823 "POST",7859 "POST",
7824 &answers_uri,7860 &answers_uri,
7825 Some(&student),7861 Some(&student),
7826- Some(json!({ "question_id": foreign_q, "selected": 0 })),7862+ Some(json!({ "question_id": foreign_q, "selected": choice_of(&foreign_q_body, 0) })),
7827 )7863 )
7828 .await;7864 .await;
7829 assert_eq!(7865 assert_eq!(
@@ -7848,7 +7884,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7848 "POST",7884 "POST",
7849 &answers_uri,7885 &answers_uri,
7850 Some(&student),7886 Some(&student),
7851- Some(json!({ "question_id": choice_q, "selected": 1 })),7887+ Some(json!({ "question_id": choice_q, "selected": choice_of(&choice_q_body, 1) })),
7852 )7888 )
7853 .await;7889 .await;
7854 assert_eq!(7890 assert_eq!(
@@ -7873,7 +7909,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
7873 "review after submit: {}",7909 "review after submit: {}",
7874 res.body7910 res.body
7875 );7911 );
7876- assert_eq!(res.body[0]["answer"]["selected"], 2);7912+ assert_eq!(res.body[0]["answer"]["selected"], choice_of(&choice_q_body, 2));
7877 assert_eq!(res.body[1]["answer"]["text"], "because");7913 assert_eq!(res.body[1]["answer"]["text"], "because");
7878 }7914 }
7879 7915
@@ -7884,15 +7920,16 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() {
7884 let student = login(&app, "cansu").await;7920 let student = login(&app, "cansu").await;
7885 let student_id = me_id(&app, &student).await;7921 let student_id = me_id(&app, &student).await;
7886 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await;7922 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await;
7887- let question = create_question(7923+ let question_body = create_question_body(
7888 &app,7924 &app,
7889 &teacher,7925 &teacher,
7890 &exam,7926 &exam,
7891 &subject,7927 &subject,
7892 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,7928 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
7893- "choices": ["3", "4"], "correct": 1 }),7929+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
7894 )7930 )
7895 .await;7931 .await;
7932+ let question = id_of(&question_body);
7896 7933
7897 // Enrolled: start the attempt, read the questions, save an answer.7934 // Enrolled: start the attempt, read the questions, save an answer.
7898 let res = send(7935 let res = send(
@@ -7918,7 +7955,7 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() {
7918 "POST",7955 "POST",
7919 &format!("/exams/{exam}/attempt/answers"),7956 &format!("/exams/{exam}/attempt/answers"),
7920 Some(&student),7957 Some(&student),
7921- Some(json!({ "question_id": question, "selected": 1 })),7958+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })),
7922 )7959 )
7923 .await;7960 .await;
7924 assert_eq!(res.status, StatusCode::OK, "{}", res.body);7961 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -7955,7 +7992,7 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() {
7955 "POST",7992 "POST",
7956 &format!("/exams/{exam}/attempt/answers"),7993 &format!("/exams/{exam}/attempt/answers"),
7957 Some(&student),7994 Some(&student),
7958- Some(json!({ "question_id": question, "selected": 0 })),7995+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })),
7959 )7996 )
7960 .await;7997 .await;
7961 assert_eq!(7998 assert_eq!(
@@ -8015,15 +8052,16 @@ async fn answer_saves_stop_at_the_deadline() {
8015 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }),8052 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }),
8016 )8053 )
8017 .await;8054 .await;
8018- let question = create_question(8055+ let question_body = create_question_body(
8019 &app,8056 &app,
8020 &teacher,8057 &teacher,
8021 &exam,8058 &exam,
8022 &subject,8059 &subject,
8023 json!({ "text": "quick", "kind": "choice", "points": 1,8060 json!({ "text": "quick", "kind": "choice", "points": 1,
8024- "choices": ["a", "b"], "correct": 0 }),8061+ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }),
8025 )8062 )
8026 .await;8063 .await;
8064+ let question = id_of(&question_body);
8027 let res = send(8065 let res = send(
8028 &app,8066 &app,
8029 "POST",8067 "POST",
@@ -8038,7 +8076,7 @@ async fn answer_saves_stop_at_the_deadline() {
8038 "POST",8076 "POST",
8039 &format!("/exams/{exam}/attempt/answers"),8077 &format!("/exams/{exam}/attempt/answers"),
8040 Some(&student),8078 Some(&student),
8041- Some(json!({ "question_id": question, "selected": 0 })),8079+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 0) })),
8042 )8080 )
8043 .await;8081 .await;
8044 assert_eq!(8082 assert_eq!(
@@ -8055,7 +8093,7 @@ async fn answer_saves_stop_at_the_deadline() {
8055 "POST",8093 "POST",
8056 &format!("/exams/{exam}/attempt/answers"),8094 &format!("/exams/{exam}/attempt/answers"),
8057 Some(&student),8095 Some(&student),
8058- Some(json!({ "question_id": question, "selected": 1 })),8096+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })),
8059 )8097 )
8060 .await;8098 .await;
8061 assert_eq!(res.status, StatusCode::CONFLICT, "expired: {}", res.body);8099 assert_eq!(res.status, StatusCode::CONFLICT, "expired: {}", res.body);
@@ -8070,7 +8108,7 @@ async fn answer_saves_stop_at_the_deadline() {
8070 )8108 )
8071 .await;8109 .await;
8072 assert_eq!(res.status, StatusCode::OK, "{}", res.body);8110 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
8073- assert_eq!(res.body["answers"][0]["selected"], 0);8111+ assert_eq!(res.body["answers"][0]["selected"], choice_of(&question_body, 0));
8074 }8112 }
8075 8113
8076 #[tokio::test]8114 #[tokio::test]
@@ -8081,24 +8119,26 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() {
8081 let student_id = me_id(&app, &student).await;8119 let student_id = me_id(&app, &student).await;
8082 let (_course, exam, subject) =8120 let (_course, exam, subject) =
8083 open_exam_with_student(&app, &teacher, &student_id, "chem").await;8121 open_exam_with_student(&app, &teacher, &student_id, "chem").await;
8084- let q1 = create_question(8122+ let q1_body = create_question_body(
8085 &app,8123 &app,
8086 &teacher,8124 &teacher,
8087 &exam,8125 &exam,
8088 &subject,8126 &subject,
8089 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,8127 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
8090- "choices": ["3", "4"], "correct": 1 }),8128+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
8091 )8129 )
8092 .await;8130 .await;
8093- let q2 = create_question(8131+ let q1 = id_of(&q1_body);
8132+ let q2_body = create_question_body(
8094 &app,8133 &app,
8095 &teacher,8134 &teacher,
8096 &exam,8135 &exam,
8097 &subject,8136 &subject,
8098 json!({ "text": "3 + 3?", "kind": "choice", "points": 20,8137 json!({ "text": "3 + 3?", "kind": "choice", "points": 20,
8099- "choices": ["6", "7"], "correct": 0 }),8138+ "choices": [{"id": "c0", "text": "6"}, {"id": "c1", "text": "7"}], "correct": "c0" }),
8100 )8139 )
8101 .await;8140 .await;
8141+ let q2 = id_of(&q2_body);
8102 let q3 = create_question(8142 let q3 = create_question(
8103 &app,8143 &app,
8104 &teacher,8144 &teacher,
@@ -8123,8 +8163,8 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() {
8123 .await;8163 .await;
8124 assert_eq!(res.status, StatusCode::CREATED);8164 assert_eq!(res.status, StatusCode::CREATED);
8125 for body in [8165 for body in [
8126- json!({ "question_id": q1, "selected": 1 }), // right8166+ json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }), // right
8127- json!({ "question_id": q2, "selected": 1 }), // wrong8167+ json!({ "question_id": q2, "selected": choice_of(&q2_body, 1) }), // wrong
8128 json!({ "question_id": q3, "text": "entropy grows" }),8168 json!({ "question_id": q3, "text": "entropy grows" }),
8129 ] {8169 ] {
8130 let res = send(8170 let res = send(
@@ -8174,15 +8214,16 @@ async fn live_monitor_tracks_answer_progress() {
8174 let bora_id = me_id(&app, &bora).await;8214 let bora_id = me_id(&app, &bora).await;
8175 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await;8215 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await;
8176 enroll(&app, &teacher, &course, &bora_id).await;8216 enroll(&app, &teacher, &course, &bora_id).await;
8177- let question = create_question(8217+ let question_body = create_question_body(
8178 &app,8218 &app,
8179 &teacher,8219 &teacher,
8180 &exam,8220 &exam,
8181 &subject,8221 &subject,
8182 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,8222 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
8183- "choices": ["3", "4"], "correct": 1 }),8223+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
8184 )8224 )
8185 .await;8225 .await;
8226+ let question = id_of(&question_body);
8186 create_question(8227 create_question(
8187 &app,8228 &app,
8188 &teacher,8229 &teacher,
@@ -8210,7 +8251,7 @@ async fn live_monitor_tracks_answer_progress() {
8210 "POST",8251 "POST",
8211 &format!("/exams/{exam}/attempt/answers"),8252 &format!("/exams/{exam}/attempt/answers"),
8212 Some(&ayla),8253 Some(&ayla),
8213- Some(json!({ "question_id": question, "selected": 1 })),8254+ Some(json!({ "question_id": question, "selected": choice_of(&question_body, 1) })),
8214 )8255 )
8215 .await;8256 .await;
8216 assert_eq!(res.status, StatusCode::OK);8257 assert_eq!(res.status, StatusCode::OK);
@@ -8246,16 +8287,17 @@ async fn questions_and_answers_cascade_with_deletes() {
8246 let student = login(&app, "cem").await;8287 let student = login(&app, "cem").await;
8247 let student_id = me_id(&app, &student).await;8288 let student_id = me_id(&app, &student).await;
8248 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await;8289 let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await;
8249- let q1 = create_question(8290+ let q1_body = create_question_body(
8250 &app,8291 &app,
8251 &teacher,8292 &teacher,
8252 &exam,8293 &exam,
8253 &subject,8294 &subject,
8254 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,8295 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
8255- "choices": ["3", "4"], "correct": 1 }),8296+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
8256 )8297 )
8257 .await;8298 .await;
8258- let q2 = create_question(8299+ let q1 = id_of(&q1_body);
8300+ let q2_body = create_question_body(
8259 &app,8301 &app,
8260 &teacher,8302 &teacher,
8261 &exam,8303 &exam,
@@ -8263,6 +8305,7 @@ async fn questions_and_answers_cascade_with_deletes() {
8263 json!({ "text": "Explain.", "kind": "text", "points": 20 }),8305 json!({ "text": "Explain.", "kind": "text", "points": 20 }),
8264 )8306 )
8265 .await;8307 .await;
8308+ let q2 = id_of(&q2_body);
8266 let res = send(8309 let res = send(
8267 &app,8310 &app,
8268 "POST",8311 "POST",
@@ -8273,7 +8316,7 @@ async fn questions_and_answers_cascade_with_deletes() {
8273 .await;8316 .await;
8274 assert_eq!(res.status, StatusCode::CREATED);8317 assert_eq!(res.status, StatusCode::CREATED);
8275 for body in [8318 for body in [
8276- json!({ "question_id": q1, "selected": 1 }),8319+ json!({ "question_id": q1, "selected": choice_of(&q1_body, 1) }),
8277 json!({ "question_id": q2, "text": "so" }),8320 json!({ "question_id": q2, "text": "so" }),
8278 ] {8321 ] {
8279 let res = send(8322 let res = send(
@@ -8361,15 +8404,16 @@ async fn questions_and_answers_cascade_with_deletes() {
8361 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),8404 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
8362 )8405 )
8363 .await;8406 .await;
8364- let q = create_question(8407+ let q_body = create_question_body(
8365 &app,8408 &app,
8366 &teacher,8409 &teacher,
8367 &exam2,8410 &exam2,
8368 &subject,8411 &subject,
8369 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,8412 json!({ "text": "2 + 2?", "kind": "choice", "points": 10,
8370- "choices": ["3", "4"], "correct": 1 }),8413+ "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
8371 )8414 )
8372 .await;8415 .await;
8416+ let q = id_of(&q_body);
8373 let res = send(8417 let res = send(
8374 &app,8418 &app,
8375 "POST",8419 "POST",
@@ -8384,7 +8428,7 @@ async fn questions_and_answers_cascade_with_deletes() {
8384 "POST",8428 "POST",
8385 &format!("/exams/{exam2}/attempt/answers"),8429 &format!("/exams/{exam2}/attempt/answers"),
8386 Some(&student),8430 Some(&student),
8387- Some(json!({ "question_id": q, "selected": 1 })),8431+ Some(json!({ "question_id": q, "selected": choice_of(&q_body, 1) })),
8388 )8432 )
8389 .await;8433 .await;
8390 assert_eq!(res.status, StatusCode::OK);8434 assert_eq!(res.status, StatusCode::OK);
@@ -8431,15 +8475,16 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8431 let course = create_course(&app, &teacher, "sets").await;8475 let course = create_course(&app, &teacher, "sets").await;
8432 let subject = create_subject(&app, &teacher, &course, "unions").await;8476 let subject = create_subject(&app, &teacher, &course, "unions").await;
8433 let exam = create_exam(&app, &teacher, &course, "final", "final").await;8477 let exam = create_exam(&app, &teacher, &course, "final", "final").await;
8434- let question = create_question(8478+ let question_body = create_question_body(
8435 &app,8479 &app,
8436 &teacher,8480 &teacher,
8437 &exam,8481 &exam,
8438 &subject,8482 &subject,
8439 json!({ "text": "pick", "kind": "choice", "points": 10,8483 json!({ "text": "pick", "kind": "choice", "points": 10,
8440- "choices": ["a", "b", "c"], "correct": 2 }),8484+ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c2" }),
8441 )8485 )
8442 .await;8486 .await;
8487+ let question = id_of(&question_body);
8443 let uri = format!("/exams/{exam}/questions/{question}");8488 let uri = format!("/exams/{exam}/questions/{question}");
8444 8489
8445 // Shrinking the options while keeping the old `correct` would leave it8490 // Shrinking the options while keeping the old `correct` would leave it
@@ -8449,7 +8494,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8449 "PATCH",8494 "PATCH",
8450 &uri,8495 &uri,
8451 Some(&teacher),8496 Some(&teacher),
8452- Some(json!({ "choices": ["a", "b"] })),8497+ Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}] })),
8453 )8498 )
8454 .await;8499 .await;
8455 assert_eq!(8500 assert_eq!(
@@ -8465,11 +8510,11 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8465 "PATCH",8510 "PATCH",
8466 &uri,8511 &uri,
8467 Some(&teacher),8512 Some(&teacher),
8468- Some(json!({ "choices": ["a", "b"], "correct": 1 })),8513+ Some(json!({ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c1" })),
8469 )8514 )
8470 .await;8515 .await;
8471 assert_eq!(res.status, StatusCode::OK, "{}", res.body);8516 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
8472- assert_eq!(res.body["correct"], 1);8517+ assert_eq!(res.body["correct"], res.body["choices"][1]["id"]);
8473 8518
8474 // A lone out-of-range `correct` against the kept choices is caught too.8519 // A lone out-of-range `correct` against the kept choices is caught too.
8475 let res = send(8520 let res = send(
@@ -8477,7 +8522,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8477 "PATCH",8522 "PATCH",
8478 &uri,8523 &uri,
8479 Some(&teacher),8524 Some(&teacher),
8480- Some(json!({ "correct": 5 })),8525+ Some(json!({ "correct": "c5" })),
8481 )8526 )
8482 .await;8527 .await;
8483 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);8528 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
@@ -8509,7 +8554,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
8509 .len(),8554 .len(),
8510 28555 2
8511 );8556 );
8512- assert_eq!(common::items(&res.body)[0]["correct"], 1);8557+ assert_eq!(common::items(&res.body)[0]["correct"], common::items(&res.body)[0]["choices"][1]["id"]);
8513 }8558 }
8514 8559
8515 #[tokio::test]8560 #[tokio::test]
@@ -8523,15 +8568,16 @@ async fn question_authoring_follows_course_management() {
8523 8568
8524 // A manager+ authors questions in anyone's course, like every other8569 // A manager+ authors questions in anyone's course, like every other
8525 // course-management write.8570 // course-management write.
8526- let question = create_question(8571+ let question_body = create_question_body(
8527 &app,8572 &app,
8528 &boss,8573 &boss,
8529 &exam,8574 &exam,
8530 &subject,8575 &subject,
8531 json!({ "text": "pick", "kind": "choice", "points": 10,8576 json!({ "text": "pick", "kind": "choice", "points": 10,
8532- "choices": ["a", "b"], "correct": 0 }),8577+ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }),
8533 )8578 )
8534 .await;8579 .await;
8580+ let question = id_of(&question_body);
8535 let res = send(8581 let res = send(
8536 &app,8582 &app,
8537 "PATCH",8583 "PATCH",
@@ -8560,15 +8606,16 @@ async fn concurrent_answer_saves_never_collide() {
8560 let student_id = me_id(&app, &student).await;8606 let student_id = me_id(&app, &student).await;
8561 let (_course, exam, subject) =8607 let (_course, exam, subject) =
8562 open_exam_with_student(&app, &teacher, &student_id, "race").await;8608 open_exam_with_student(&app, &teacher, &student_id, "race").await;
8563- let question = create_question(8609+ let question_body = create_question_body(
8564 &app,8610 &app,
8565 &teacher,8611 &teacher,
8566 &exam,8612 &exam,
8567 &subject,8613 &subject,
8568 json!({ "text": "pick", "kind": "choice", "points": 10,8614 json!({ "text": "pick", "kind": "choice", "points": 10,
8569- "choices": ["a", "b", "c"], "correct": 0 }),8615+ "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}, {"id": "c2", "text": "c"}], "correct": "c0" }),
8570 )8616 )
8571 .await;8617 .await;
8618+ let question = id_of(&question_body);
8572 let res = send(8619 let res = send(
8573 &app,8620 &app,
8574 "POST",8621 "POST",
@@ -8586,7 +8633,7 @@ async fn concurrent_answer_saves_never_collide() {
8586 let app = app.clone();8633 let app = app.clone();
8587 let student = student.clone();8634 let student = student.clone();
8588 let uri = format!("/exams/{exam}/attempt/answers");8635 let uri = format!("/exams/{exam}/attempt/answers");
8589- let body = json!({ "question_id": question, "selected": i % 3 });8636+ let body = json!({ "question_id": question, "selected": choice_of(&question_body, (i % 3) as usize) });
8590 handles.push(tokio::spawn(async move {8637 handles.push(tokio::spawn(async move {
8591 send(&app, "POST", &uri, Some(&student), Some(body))8638 send(&app, "POST", &uri, Some(&student), Some(body))
8592 .await8639 .await
@@ -10670,15 +10717,16 @@ async fn question_images_author_serve_and_cascade() {
10670 json!({ "title": "map quiz", "kind": "quiz", "mode": "open" }),10717 json!({ "title": "map quiz", "kind": "quiz", "mode": "open" }),
10671 )10718 )
10672 .await;10719 .await;
10673- let question = create_question(10720+ let question_body = create_question_body(
10674 &app,10721 &app,
10675 &teacher,10722 &teacher,
10676 &exam,10723 &exam,
10677 &subject,10724 &subject,
10678 json!({ "text": "Which city is marked?", "kind": "choice", "points": 10,10725 json!({ "text": "Which city is marked?", "kind": "choice", "points": 10,
10679- "choices": ["Ankara", "İzmir"], "correct": 0 }),10726+ "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" }),
10680 )10727 )
10681 .await;10728 .await;
10729+ let question = id_of(&question_body);
10682 let essay = create_question(10730 let essay = create_question(
10683 &app,10731 &app,
10684 &teacher,10732 &teacher,
@@ -10715,7 +10763,7 @@ async fn question_images_author_serve_and_cascade() {
10715 let (status, _) = post_image(10763 let (status, _) = post_image(
10716 &app,10764 &app,
10717 &teacher,10765 &teacher,
10718- &format!("/exams/{exam}/questions/{essay}/choices/0/image"),10766+ &format!("/exams/{exam}/questions/{essay}/choices/{}/image", choice_of(&question_body, 0)),
10719 "image/png",10767 "image/png",
10720 b"x",10768 b"x",
10721 )10769 )
@@ -10728,15 +10776,18 @@ async fn question_images_author_serve_and_cascade() {
10728 let (status, _) = post_image(10776 let (status, _) = post_image(
10729 &app,10777 &app,
10730 &teacher,10778 &teacher,
10731- &format!("/exams/{exam}/questions/{question}/choices/2/image"),10779+ &format!("/exams/{exam}/questions/{question}/choices/01NOTACHOICEOFTHISQUEST/image"),
10732 "image/png",10780 "image/png",
10733 b"x",10781 b"x",
10734 )10782 )
10735 .await;10783 .await;
10736- assert_eq!(status, StatusCode::BAD_REQUEST, "slot must index a choice");10784+ assert_eq!(status, StatusCode::BAD_REQUEST, "slot must name a choice");
10737 10785
10738 // Option picture on choice 1, and the author view carries all the metas.10786 // Option picture on choice 1, and the author view carries all the metas.
10739- let choice_image = format!("/exams/{exam}/questions/{question}/choices/1/image");10787+ let choice_image = format!(
10788+ "/exams/{exam}/questions/{question}/choices/{}/image",
10789+ choice_of(&question_body, 1)
10790+ );
10740 let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await;10791 let (status, _) = post_image(&app, &teacher, &choice_image, "image/webp", b"webp-choice").await;
10741 assert_eq!(status, StatusCode::CREATED);10792 assert_eq!(status, StatusCode::CREATED);
10742 let res = send(10793 let res = send(
@@ -10874,7 +10925,7 @@ async fn student_answer_images_serve_and_cascade() {
10874 json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }),10925 json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }),
10875 )10926 )
10876 .await;10927 .await;
10877- let question = create_question(10928+ let question_body = create_question_body(
10878 &app,10929 &app,
10879 &teacher,10930 &teacher,
10880 &exam,10931 &exam,
@@ -10882,6 +10933,7 @@ async fn student_answer_images_serve_and_cascade() {
10882 json!({ "text": "Draw a cell.", "kind": "text", "points": 10 }),10933 json!({ "text": "Draw a cell.", "kind": "text", "points": 10 }),
10883 )10934 )
10884 .await;10935 .await;
10936+ let question = id_of(&question_body);
10885 10937
10886 let own = format!("/exams/{exam}/attempt/answers/{question}/image");10938 let own = format!("/exams/{exam}/attempt/answers/{question}/image");
10887 let png = b"png-drawing".as_slice();10939 let png = b"png-drawing".as_slice();
@@ -11087,7 +11139,7 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() {
11087 json!({ "title": "sketch", "kind": "quiz", "mode": "open" }),11139 json!({ "title": "sketch", "kind": "quiz", "mode": "open" }),
11088 )11140 )
11089 .await;11141 .await;
11090- let question = create_question(11142+ let question_body = create_question_body(
11091 &app,11143 &app,
11092 &teacher,11144 &teacher,
11093 &exam,11145 &exam,
@@ -11095,6 +11147,7 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() {
11095 json!({ "text": "Draw a triangle.", "kind": "text", "points": 5 }),11147 json!({ "text": "Draw a triangle.", "kind": "text", "points": 5 }),
11096 )11148 )
11097 .await;11149 .await;
11150+ let question = id_of(&question_body);
11098 11151
11099 // Sit, then upload a drawing WITHOUT ever saving a text answer.11152 // Sit, then upload a drawing WITHOUT ever saving a text answer.
11100 let res = send(11153 let res = send(
@@ -11161,10 +11214,13 @@ async fn answer_image_surfaces_for_a_drawing_only_answer() {
11161 );11214 );
11162 }11215 }
11163 11216
11164-/// The authoring edits that reshape a question also groom its images: a11217+/// The authoring edits that reshape a question also groom its images — and
11165-/// replaced `choices` list drops the option pictures (the illustration11218+/// **only** the pictures of options that are actually gone. Reordering the list
11166-/// stays), an explicit image DELETE removes row + blob, and deleting the11219+/// and deleting one option leaves every surviving option's picture attached to
11167-/// question sweeps the rest.11220+/// *that option*, and leaves `correct` naming the option the author marked.
11221+/// This is the behaviour stable choice ids exist for: the images used to be
11222+/// keyed by position, so any edit that carried a `choices` key wiped all of
11223+/// them.
11168 #[tokio::test]11224 #[tokio::test]
11169 async fn question_image_edits_follow_the_choices() {11225 async fn question_image_edits_follow_the_choices() {
11170 let (app, db) = app_and_db().await;11226 let (app, db) = app_and_db().await;
@@ -11178,20 +11234,28 @@ async fn question_image_edits_follow_the_choices() {
11178 json!({ "title": "eras", "kind": "quiz", "mode": "open" }),11234 json!({ "title": "eras", "kind": "quiz", "mode": "open" }),
11179 )11235 )
11180 .await;11236 .await;
11181- let question = create_question(11237+ let question_body = create_question_body(
11182 &app,11238 &app,
11183 &teacher,11239 &teacher,
11184 &exam,11240 &exam,
11185 &subject,11241 &subject,
11186 json!({ "text": "Pick the era.", "kind": "choice", "points": 5,11242 json!({ "text": "Pick the era.", "kind": "choice", "points": 5,
11187- "choices": ["Bronze", "Iron"], "correct": 1 }),11243+ "choices": [{"id": "c0", "text": "Stone"}, {"id": "c1", "text": "Bronze"},
11244+ {"id": "c2", "text": "Iron"}], "correct": "c2" }),
11188 )11245 )
11189 .await;11246 .await;
11247+ let question = id_of(&question_body);
11248+ let (stone, bronze, iron) = (
11249+ choice_of(&question_body, 0),
11250+ choice_of(&question_body, 1),
11251+ choice_of(&question_body, 2),
11252+ );
11190 let base = format!("/exams/{exam}/questions/{question}");11253 let base = format!("/exams/{exam}/questions/{question}");
11191 for (path, bytes) in [11254 for (path, bytes) in [
11192 (format!("{base}/image"), b"illustration".as_slice()),11255 (format!("{base}/image"), b"illustration".as_slice()),
11193- (format!("{base}/choices/0/image"), b"bronze".as_slice()),11256+ (format!("{base}/choices/{stone}/image"), b"stone".as_slice()),
11194- (format!("{base}/choices/1/image"), b"iron".as_slice()),11257+ (format!("{base}/choices/{bronze}/image"), b"bronze".as_slice()),
11258+ (format!("{base}/choices/{iron}/image"), b"iron".as_slice()),
11195 ] {11259 ] {
11196 let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await;11260 let (status, body) = post_image(&app, &teacher, &path, "image/png", bytes).await;
11197 assert_eq!(status, StatusCode::CREATED, "{body}");11261 assert_eq!(status, StatusCode::CREATED, "{body}");
@@ -11208,40 +11272,91 @@ async fn question_image_edits_follow_the_choices() {
11208 .await;11272 .await;
11209 assert_eq!(res.status, StatusCode::OK, "{}", res.body);11273 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11210 assert!(res.body["image"].is_object());11274 assert!(res.body["image"].is_object());
11211- assert!(res.body["choice_images"][0].is_object());11275+ for slot in 0..3 {
11212- assert!(res.body["choice_images"][1].is_object());11276+ assert!(res.body["choice_images"][slot].is_object());
11277+ }
11278+ assert_eq!(res.body["correct"], iron, "the answer key must not move");
11213 11279
11214- // Replacing the choices drops the option pictures, keeps the illustration.11280+ // The edit this whole remodel exists for: reorder the list (Iron first),
11281+ // rename one option, and drop Bronze entirely.
11215 let keys_before = image_blob_keys(&db).await;11282 let keys_before = image_blob_keys(&db).await;
11216 let res = send(11283 let res = send(
11217 &app,11284 &app,
11218 "PATCH",11285 "PATCH",
11219 &base,11286 &base,
11220 Some(&teacher),11287 Some(&teacher),
11221- Some(json!({ "choices": ["Stone", "Bronze", "Iron"], "correct": 2 })),11288+ Some(json!({ "choices": [
11289+ {"id": iron, "text": "Iron Age"},
11290+ {"id": stone, "text": "Stone"},
11291+ ], "correct": iron })),
11222 )11292 )
11223 .await;11293 .await;
11224 assert_eq!(res.status, StatusCode::OK, "{}", res.body);11294 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11295+ // The surviving options kept their identities, in their new order…
11296+ assert_eq!(res.body["choices"][0]["id"], iron);
11297+ assert_eq!(res.body["choices"][0]["text"], "Iron Age");
11298+ assert_eq!(res.body["choices"][1]["id"], stone);
11299+ // …the answer key still names the option the author marked, though it moved
11300+ // from position 2 to position 0…
11301+ assert_eq!(res.body["correct"], iron, "correct must follow its option");
11302+ // …and each survivor kept *its own* picture, illustration included.
11225 assert!(res.body["image"].is_object(), "illustration must survive");11303 assert!(res.body["image"].is_object(), "illustration must survive");
11226- assert_eq!(11304+ assert!(
11227- res.body["choice_images"],11305+ res.body["choice_images"][0].is_object(),
11228- json!([null, null, null]),11306+ "Iron kept its picture across the reorder"
11229- "option pictures must not follow a replaced list"11307+ );
11308+ assert!(
11309+ res.body["choice_images"][1].is_object(),
11310+ "Stone kept its picture across the reorder"
11230 );11311 );
11312+
11313+ // Exactly one blob went: the removed option's.
11231 let keys_after = image_blob_keys(&db).await;11314 let keys_after = image_blob_keys(&db).await;
11232- assert_eq!(keys_after.len(), 1);11315+ assert_eq!(
11233- for dropped in keys_before.iter().filter(|k| !keys_after.contains(k)) {11316+ keys_after.len(),
11317+ 3,
11318+ "illustration + two surviving option pictures"
11319+ );
11320+ let dropped: Vec<_> = keys_before
11321+ .iter()
11322+ .filter(|k| !keys_after.contains(k))
11323+ .collect();
11324+ assert_eq!(dropped.len(), 1, "only the removed option's blob may go");
11325+ for key in dropped {
11234 assert!(11326 assert!(
11235- !common::files_dir().join(dropped).exists(),11327+ !common::files_dir().join(key).exists(),
11236 "dropped option blob lingers"11328 "dropped option blob lingers"
11237 );11329 );
11238 }11330 }
11239 11331
11332+ // The remaining wipe path, now opt-in: a list of all-new options (no id
11333+ // matches a stored one) is a genuinely new set, so every option picture
11334+ // goes — and the illustration still stays.
11335+ let res = send(
11336+ &app,
11337+ "PATCH",
11338+ &base,
11339+ Some(&teacher),
11340+ Some(json!({ "choices": [{"id": "fresh-a", "text": "Iron"}, {"id": "fresh-b", "text": "Stone"}],
11341+ "correct": "fresh-a" })),
11342+ )
11343+ .await;
11344+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
11345+ assert_ne!(res.body["choices"][0]["id"], iron, "a new option, not Iron");
11346+ assert_eq!(
11347+ res.body["choice_images"],
11348+ json!([null, null]),
11349+ "an all-new option list keeps no pictures"
11350+ );
11351+ assert!(res.body["image"].is_object(), "illustration must survive");
11352+ assert_eq!(image_blob_keys(&db).await.len(), 1);
11353+
11240 // Explicit image DELETE: 204 once, 404 after, blob gone.11354 // Explicit image DELETE: 204 once, 404 after, blob gone.
11355+ let fresh = choice_of(&res.body, 0);
11241 let (status, _) = post_image(11356 let (status, _) = post_image(
11242 &app,11357 &app,
11243 &teacher,11358 &teacher,
11244- &format!("{base}/choices/0/image"),11359+ &format!("{base}/choices/{fresh}/image"),
11245 "image/gif",11360 "image/gif",
11246 b"gif",11361 b"gif",
11247 )11362 )
@@ -11250,7 +11365,7 @@ async fn question_image_edits_follow_the_choices() {
11250 let res = send(11365 let res = send(
11251 &app,11366 &app,
11252 "DELETE",11367 "DELETE",
11253- &format!("{base}/choices/0/image"),11368+ &format!("{base}/choices/{fresh}/image"),
11254 Some(&teacher),11369 Some(&teacher),
11255 None,11370 None,
11256 )11371 )
@@ -11259,7 +11374,7 @@ async fn question_image_edits_follow_the_choices() {
11259 let res = send(11374 let res = send(
11260 &app,11375 &app,
11261 "DELETE",11376 "DELETE",
11262- &format!("{base}/choices/0/image"),11377+ &format!("{base}/choices/{fresh}/image"),
11263 Some(&teacher),11378 Some(&teacher),
11264 None,11379 None,
11265 )11380 )
@@ -12712,7 +12827,7 @@ async fn answer_image_round_trip_keeps_the_stroke_text_chunk_intact() {
12712 json!({ "title": "sketch quiz", "kind": "quiz", "mode": "open" }),12827 json!({ "title": "sketch quiz", "kind": "quiz", "mode": "open" }),
12713 )12828 )
12714 .await;12829 .await;
12715- let question = create_question(12830+ let question_body = create_question_body(
12716 &app,12831 &app,
12717 &teacher,12832 &teacher,
12718 &exam,12833 &exam,
@@ -12720,6 +12835,7 @@ async fn answer_image_round_trip_keeps_the_stroke_text_chunk_intact() {
12720 json!({ "text": "Draw a triangle.", "kind": "text", "points": 10 }),12835 json!({ "text": "Draw a triangle.", "kind": "text", "points": 10 }),
12721 )12836 )
12722 .await;12837 .await;
12838+ let question = id_of(&question_body);
12723 let res = send(12839 let res = send(
12724 &app,12840 &app,
12725 "POST",12841 "POST",
@@ -16255,7 +16371,7 @@ async fn attempt_history_preserves_each_prior_sitting() {
16255 json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }),16371 json!({ "title": "cell quiz", "kind": "quiz", "mode": "open", "max_attempts": 2 }),
16256 )16372 )
16257 .await;16373 .await;
16258- let question = create_question(16374+ let question_body = create_question_body(
16259 &app,16375 &app,
16260 &teacher,16376 &teacher,
16261 &exam,16377 &exam,
@@ -16263,6 +16379,7 @@ async fn attempt_history_preserves_each_prior_sitting() {
16263 json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }),16379 json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }),
16264 )16380 )
16265 .await;16381 .await;
16382+ let question = id_of(&question_body);
16266 let own_image = format!("/exams/{exam}/attempt/answers/{question}/image");16383 let own_image = format!("/exams/{exam}/attempt/answers/{question}/image");
16267 16384
16268 // Seq 1: answer, draw, finish.16385 // Seq 1: answer, draw, finish.
@@ -16572,7 +16689,7 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16572 }),16689 }),
16573 )16690 )
16574 .await;16691 .await;
16575- let question = create_question(16692+ let question_body = create_question_body(
16576 &app,16693 &app,
16577 &teacher,16694 &teacher,
16578 &exam,16695 &exam,
@@ -16580,6 +16697,7 @@ async fn self_review_returns_own_seqs_and_per_sitting_answers() {
16580 json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }),16697 json!({ "text": "Name an organelle.", "kind": "text", "points": 10 }),
16581 )16698 )
16582 .await;16699 .await;
16700+ let question = id_of(&question_body);
16583 let results_uri = format!("/exams/{exam}/results");16701 let results_uri = format!("/exams/{exam}/results");
16584 16702
16585 // Seq 1: answer, grade, finish.16703 // Seq 1: answer, grade, finish.
@@ -16695,7 +16813,7 @@ async fn self_review_is_own_scoped_between_students() {
16695 json!({ "title": "quiz", "kind": "quiz", "mode": "open", "allow_review": true }),16813 json!({ "title": "quiz", "kind": "quiz", "mode": "open", "allow_review": true }),
16696 )16814 )
16697 .await;16815 .await;
16698- let question = create_question(16816+ let question_body = create_question_body(
16699 &app,16817 &app,
16700 &teacher,16818 &teacher,
16701 &exam,16819 &exam,
@@ -16703,6 +16821,7 @@ async fn self_review_is_own_scoped_between_students() {
16703 json!({ "text": "Name a consul.", "kind": "text", "points": 10 }),16821 json!({ "text": "Name a consul.", "kind": "text", "points": 10 }),
16704 )16822 )
16705 .await;16823 .await;
16824+ let question = id_of(&question_body);
16706 let results_uri = format!("/exams/{exam}/results");16825 let results_uri = format!("/exams/{exam}/results");
16707 16826
16708 for (who, id, text, mark) in [16827 for (who, id, text, mark) in [
@@ -16767,12 +16886,12 @@ async fn bank_question_create_get_list_and_instantiate() {
16767 "/bank-questions",16886 "/bank-questions",
16768 Some(&teacher),16887 Some(&teacher),
16769 Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice",16888 Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice",
16770- "points": 10, "choices": ["3", "4", "5"], "correct": 1 })),16889+ "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}, {"id": "c2", "text": "5"}], "correct": "c1" })),
16771 )16890 )
16772 .await;16891 .await;
16773 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);16892 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16774 assert_eq!(res.body["kind"], "choice");16893 assert_eq!(res.body["kind"], "choice");
16775- assert_eq!(res.body["correct"], 1);16894+ assert_eq!(res.body["correct"], res.body["choices"][1]["id"]);
16776 assert_eq!(res.body["subject"], subject);16895 assert_eq!(res.body["subject"], subject);
16777 let bid = id_of(&res.body);16896 let bid = id_of(&res.body);
16778 16897
@@ -16810,14 +16929,341 @@ async fn bank_question_create_get_list_and_instantiate() {
16810 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);16929 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16811 assert_eq!(res.body["exam"], exam);16930 assert_eq!(res.body["exam"], exam);
16812 assert_eq!(res.body["subject"], subject);16931 assert_eq!(res.body["subject"], subject);
16813- assert_eq!(res.body["correct"], 1);16932+ assert_eq!(res.body["correct"], res.body["choices"][1]["id"]);
16814- assert_eq!(res.body["choices"][1], "4");16933+ assert_eq!(res.body["choices"][1]["text"], "4");
16815 16934
16816 // The copy is independent — the template still stands.16935 // The copy is independent — the template still stands.
16817 let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;16936 let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;
16818 assert_eq!(res.status, StatusCode::OK);16937 assert_eq!(res.status, StatusCode::OK);
16819 }16938 }
16820 16939
16940+/// The bank list pages in SQL: newest first, every row reachable by offset,
16941+/// `total` counting the matches rather than the page, and `?q=` filtering
16942+/// server-side. Regression for the whole-table-then-slice version, which hid
16943+/// template #101 onward from a client asking for `limit=100`.
16944+#[tokio::test]
16945+async fn bank_question_list_pages_filters_and_names() {
16946+ let (app, db) = app_and_db().await;
16947+ let teacher = login_as(&app, &db, "bank_p", "teacher").await;
16948+ let other = login_as(&app, &db, "bank_p2", "teacher").await;
16949+ let course = create_course(&app, &teacher, "algebra").await;
16950+ let subject = create_subject(&app, &teacher, &course, "linear").await;
16951+ let other_subject = create_subject(&app, &teacher, &course, "quadratic").await;
16952+
16953+ // 120 templates — more than the clients' `limit=100`.
16954+ for i in 0..120 {
16955+ let res = send(
16956+ &app,
16957+ "POST",
16958+ "/bank-questions",
16959+ Some(&teacher),
16960+ Some(json!({ "subject_id": subject, "text": format!("template {i:03}"),
16961+ "kind": "text", "points": 1 })),
16962+ )
16963+ .await;
16964+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16965+ }
16966+ // A foreign owner + subject, to prove the filters actually narrow.
16967+ let res = send(
16968+ &app,
16969+ "POST",
16970+ "/bank-questions",
16971+ Some(&other),
16972+ Some(json!({ "subject_id": other_subject, "text": "someone else's",
16973+ "kind": "text", "points": 1 })),
16974+ )
16975+ .await;
16976+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16977+ // Published, so it shows up in the first teacher's paging assertions below;
16978+ // a private one would (correctly) be invisible to them.
16979+ let foreign = id_of(&res.body);
16980+ let res = send(&app, "PATCH", &format!("/bank-questions/{foreign}"), Some(&other), Some(json!({ "visibility": "school" }))).await;
16981+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16982+
16983+ // Page 1: newest first, full window, honest total.
16984+ let res = send(&app, "GET", "/bank-questions?limit=100", Some(&teacher), None).await;
16985+ assert_eq!(common::items(&res.body).len(), 100);
16986+ assert_eq!(res.body["total"], 121);
16987+ assert_eq!(common::items(&res.body)[0]["text"], "someone else's");
16988+ assert_eq!(common::items(&res.body)[1]["text"], "template 119");
16989+ // The names are joined on, not left for the client to look up per row.
16990+ assert_eq!(common::items(&res.body)[1]["subject_name"], "linear");
16991+ assert_eq!(common::items(&res.body)[1]["owner_name"], "bank_p");
16992+
16993+ // Item #101 onward is reachable — the bug was that it never was.
16994+ let res = send(
16995+ &app,
16996+ "GET",
16997+ "/bank-questions?limit=100&offset=100",
16998+ Some(&teacher),
16999+ None,
17000+ )
17001+ .await;
17002+ assert_eq!(common::items(&res.body).len(), 21);
17003+ assert_eq!(res.body["total"], 121);
17004+ assert_eq!(common::items(&res.body)[0]["text"], "template 020");
17005+ assert_eq!(common::items(&res.body)[20]["text"], "template 000");
17006+
17007+ // `?q=` filters server-side: "template 005" sits on page 2 unfiltered, but
17008+ // leads page 1 once filtered — and matches case-insensitively.
17009+ let res = send(
17010+ &app,
17011+ "GET",
17012+ "/bank-questions?limit=100&q=TEMPLATE%20005",
17013+ Some(&teacher),
17014+ None,
17015+ )
17016+ .await;
17017+ assert_eq!(res.body["total"], 1);
17018+ assert_eq!(common::items(&res.body).len(), 1);
17019+ assert_eq!(common::items(&res.body)[0]["text"], "template 005");
17020+ // A blank `q` is no filter at all.
17021+ let res = send(&app, "GET", "/bank-questions?q=", Some(&teacher), None).await;
17022+ assert_eq!(res.body["total"], 121);
17023+
17024+ // `owner=me` + `subject=` combine, and still page.
17025+ let res = send(
17026+ &app,
17027+ "GET",
17028+ &format!("/bank-questions?owner=me&subject={subject}&limit=100&offset=100"),
17029+ Some(&teacher),
17030+ None,
17031+ )
17032+ .await;
17033+ assert_eq!(res.body["total"], 120);
17034+ assert_eq!(common::items(&res.body).len(), 20);
17035+ assert_eq!(common::items(&res.body)[0]["text"], "template 019");
17036+ // The other teacher's `me` is their own single template.
17037+ let res = send(&app, "GET", "/bank-questions?owner=me", Some(&other), None).await;
17038+ assert_eq!(res.body["total"], 1);
17039+ assert_eq!(common::items(&res.body)[0]["owner_name"], "bank_p2");
17040+ // Owner and subject that never co-occur → an empty page, total 0.
17041+ let res = send(
17042+ &app,
17043+ "GET",
17044+ &format!("/bank-questions?owner=me&subject={other_subject}"),
17045+ Some(&teacher),
17046+ None,
17047+ )
17048+ .await;
17049+ assert_eq!(res.body["total"], 0);
17050+ assert!(common::items(&res.body).is_empty());
17051+}
17052+
17053+/// `?visibility=` is a real SQL filter (so the client never has to fetch the
17054+/// bank unpaged and window it in memory — the very bug the SQL paging fixed),
17055+/// and it narrows the caller's view without ever widening it.
17056+#[tokio::test]
17057+async fn bank_question_list_filters_by_visibility() {
17058+ let (app, db) = app_and_db().await;
17059+ let teacher = login_as(&app, &db, "bank_v", "teacher").await;
17060+ let other = login_as(&app, &db, "bank_v2", "teacher").await;
17061+ let course = create_course(&app, &teacher, "biology").await;
17062+ let subject = create_subject(&app, &teacher, &course, "cells").await;
17063+ let other_subject = create_subject(&app, &teacher, &course, "genes").await;
17064+
17065+ // Mine: 3 drafts on `subject`, 2 published on `other_subject`.
17066+ let mut published = Vec::new();
17067+ for i in 0..5 {
17068+ let on = if i < 3 { &subject } else { &other_subject };
17069+ let res = send(
17070+ &app,
17071+ "POST",
17072+ "/bank-questions",
17073+ Some(&teacher),
17074+ Some(json!({ "subject_id": on, "text": format!("mine {i}"),
17075+ "kind": "text", "points": 1 })),
17076+ )
17077+ .await;
17078+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17079+ if i >= 3 {
17080+ published.push(id_of(&res.body));
17081+ }
17082+ }
17083+ for bid in &published {
17084+ let res = send(
17085+ &app,
17086+ "PATCH",
17087+ &format!("/bank-questions/{bid}"),
17088+ Some(&teacher),
17089+ Some(json!({ "visibility": "school" })),
17090+ )
17091+ .await;
17092+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17093+ }
17094+ // The other teacher keeps one private template — nobody else may ever see
17095+ // it, whatever they pass in `?visibility=`.
17096+ let res = send(
17097+ &app,
17098+ "POST",
17099+ "/bank-questions",
17100+ Some(&other),
17101+ Some(json!({ "subject_id": subject, "text": "their secret",
17102+ "kind": "text", "points": 1 })),
17103+ )
17104+ .await;
17105+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17106+
17107+ // `private` = my drafts; `total` honours the filter, not the whole bank.
17108+ let res = send(
17109+ &app,
17110+ "GET",
17111+ "/bank-questions?visibility=private",
17112+ Some(&teacher),
17113+ None,
17114+ )
17115+ .await;
17116+ assert_eq!(res.body["total"], 3, "{}", res.body);
17117+ assert_eq!(common::items(&res.body).len(), 3);
17118+ assert_eq!(common::items(&res.body)[0]["text"], "mine 2");
17119+ // `school` = the published shelf — and NOT the other teacher's private row.
17120+ let res = send(
17121+ &app,
17122+ "GET",
17123+ "/bank-questions?visibility=school",
17124+ Some(&teacher),
17125+ None,
17126+ )
17127+ .await;
17128+ assert_eq!(res.body["total"], 2, "{}", res.body);
17129+ let texts: Vec<&str> = common::items(&res.body)
17130+ .iter()
17131+ .map(|item| item["text"].as_str().unwrap())
17132+ .collect();
17133+ assert_eq!(texts, ["mine 4", "mine 3"]);
17134+ assert!(!texts.contains(&"their secret"));
17135+ // The stranger's `private` view is empty: the filter can't widen the gate.
17136+ let res = send(
17137+ &app,
17138+ "GET",
17139+ "/bank-questions?visibility=private",
17140+ Some(&teacher),
17141+ None,
17142+ )
17143+ .await;
17144+ assert!(
17145+ !common::items(&res.body)
17146+ .iter()
17147+ .any(|item| item["text"] == "their secret")
17148+ );
17149+ let res = send(
17150+ &app,
17151+ "GET",
17152+ "/bank-questions?visibility=private",
17153+ Some(&other),
17154+ None,
17155+ )
17156+ .await;
17157+ assert_eq!(res.body["total"], 1, "{}", res.body);
17158+ assert_eq!(common::items(&res.body)[0]["text"], "their secret");
17159+
17160+ // Composes with `q`, `subject`, `owner`, and with paging.
17161+ let res = send(
17162+ &app,
17163+ "GET",
17164+ &format!("/bank-questions?visibility=private&subject={subject}&owner=me&q=MINE%201"),
17165+ Some(&teacher),
17166+ None,
17167+ )
17168+ .await;
17169+ assert_eq!(res.body["total"], 1, "{}", res.body);
17170+ assert_eq!(common::items(&res.body)[0]["text"], "mine 1");
17171+ // Right owner and subject, wrong shelf → nothing.
17172+ let res = send(
17173+ &app,
17174+ "GET",
17175+ &format!("/bank-questions?visibility=school&subject={subject}&owner=me"),
17176+ Some(&teacher),
17177+ None,
17178+ )
17179+ .await;
17180+ assert_eq!(res.body["total"], 0, "{}", res.body);
17181+ assert!(common::items(&res.body).is_empty());
17182+ // Paging windows the filtered set, and `total` stays the filtered total.
17183+ let res = send(
17184+ &app,
17185+ "GET",
17186+ "/bank-questions?visibility=private&limit=2&offset=2",
17187+ Some(&teacher),
17188+ None,
17189+ )
17190+ .await;
17191+ assert_eq!(res.body["total"], 3, "{}", res.body);
17192+ assert_eq!(common::items(&res.body).len(), 1);
17193+ assert_eq!(common::items(&res.body)[0]["text"], "mine 0");
17194+
17195+ // An unknown shelf is a 400, worded like the other param errors.
17196+ let res = send(
17197+ &app,
17198+ "GET",
17199+ "/bank-questions?visibility=public",
17200+ Some(&teacher),
17201+ None,
17202+ )
17203+ .await;
17204+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
17205+ assert!(
17206+ res.body["error"]
17207+ .as_str()
17208+ .unwrap()
17209+ .contains("must be private or school"),
17210+ "{}",
17211+ res.body
17212+ );
17213+}
17214+
17215+/// The app is EN/TR, so `?q=` must fold Turkish casing: `İ` lowercases to
17216+/// `i` + U+0307 in both Rust and SurrealQL, which used to make `istanbul` and
17217+/// `İSTANBUL` two disjoint searches — a teacher typing lowercase got an empty
17218+/// bank.
17219+#[tokio::test]
17220+async fn bank_question_search_folds_turkish_casing() {
17221+ let (app, db) = app_and_db().await;
17222+ let teacher = login_as(&app, &db, "bank_tr", "teacher").await;
17223+ let course = create_course(&app, &teacher, "cografya").await;
17224+ let subject = create_subject(&app, &teacher, &course, "iller").await;
17225+ for text in ["İSTANBUL kaç ilçedir?", "istanbul boğazı nerededir?"] {
17226+ let res = send(
17227+ &app,
17228+ "POST",
17229+ "/bank-questions",
17230+ Some(&teacher),
17231+ Some(json!({ "subject_id": subject, "text": text,
17232+ "kind": "text", "points": 1 })),
17233+ )
17234+ .await;
17235+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17236+ }
17237+
17238+ // Lowercase needle finds the uppercase row, and every casing finds both.
17239+ for needle in ["istanbul", "%C4%B0STANBUL", "%C4%B1stanbul", "ISTANBUL"] {
17240+ let res = send(
17241+ &app,
17242+ "GET",
17243+ &format!("/bank-questions?q={needle}"),
17244+ Some(&teacher),
17245+ None,
17246+ )
17247+ .await;
17248+ assert_eq!(res.body["total"], 2, "needle {needle} missed: {}", res.body);
17249+ }
17250+ // Diacritics fold too, in both directions.
17251+ for needle in ["ilce", "il%C3%A7e", "bogaz", "bo%C4%9Faz"] {
17252+ let res = send(
17253+ &app,
17254+ "GET",
17255+ &format!("/bank-questions?q={needle}"),
17256+ Some(&teacher),
17257+ None,
17258+ )
17259+ .await;
17260+ assert_eq!(res.body["total"], 1, "needle {needle} missed: {}", res.body);
17261+ }
17262+ // Folding widens the match, it does not match everything.
17263+ let res = send(&app, "GET", "/bank-questions?q=ankara", Some(&teacher), None).await;
17264+ assert_eq!(res.body["total"], 0);
17265+}
17266+
16821 #[tokio::test]17267 #[tokio::test]
16822 async fn bank_question_owner_gate_cross_course_and_freeze() {17268 async fn bank_question_owner_gate_cross_course_and_freeze() {
16823 let (app, db) = app_and_db().await;17269 let (app, db) = app_and_db().await;
@@ -16836,6 +17282,10 @@ async fn bank_question_owner_gate_cross_course_and_freeze() {
16836 )17282 )
16837 .await;17283 .await;
16838 let bid = id_of(&res.body);17284 let bid = id_of(&res.body);
17285+ // Published, so this test is about the *owner* gate alone — the visibility
17286+ // gate (404 while private) has its own test below.
17287+ let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&owner), Some(json!({ "visibility": "school" }))).await;
17288+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
16839 17289
16840 // A non-owner teacher reads it, but may not edit or delete.17290 // A non-owner teacher reads it, but may not edit or delete.
16841 let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&other), None).await;17291 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() {
16888 assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);17338 assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
16889 }17339 }
16890 17340
17341+/// A bank template carries `correct` — the answer key — so it is `private`
17342+/// until its owner publishes it. Regression for the one-click answer-key
17343+/// broadcast: saving a live exam's question to the bank used to hand the key
17344+/// (and the pictures) to every teacher in the school, permanently and silently.
17345+///
17346+/// Every read path is checked from a second teacher's seat, and each one must
17347+/// answer **404, not 403** — a 403 confirms the template exists.
16891 #[tokio::test]17348 #[tokio::test]
16892-async fn exam_question_saves_to_bank() {17349+async fn bank_private_template_is_invisible_until_published() {
16893 let (app, db) = app_and_db().await;17350 let (app, db) = app_and_db().await;
16894- let teacher = login_as(&app, &db, "s2b_t", "teacher").await;17351+ let owner = login_as(&app, &db, "bvis_o", "teacher").await;
16895- let course = create_course(&app, &teacher, "phys").await;17352+ let other = login_as(&app, &db, "bvis_x", "teacher").await;
16896- let subject = create_subject(&app, &teacher, &course, "kinematics").await;17353+ let course = create_course(&app, &owner, "bio").await;
16897- let exam = create_exam(&app, &teacher, &course, "final", "final").await;17354+ let subject = create_subject(&app, &owner, &course, "cells").await;
16898- let qid = create_question(17355+
17356+ // Two templates; only the second is ever published.
17357+ let res = send(
16899 &app,17358 &app,
16900- &teacher,17359+ "POST",
16901- &exam,17360+ "/bank-questions",
16902- &subject,17361+ Some(&owner),
16903- json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }),17362+ Some(json!({ "subject_id": subject, "text": "Which organelle?", "kind": "choice",
17363+ "points": 10, "choices": [{"id": "c0", "text": "nucleus"}, {"id": "c1", "text": "ribosome"}], "correct": "c0" })),
16904 )17364 )
16905 .await;17365 .await;
16906-
16907- let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;
16908 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17366 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16909- assert_eq!(res.body["text"], "v=?");17367+ // New templates are born private — nothing has to opt in to be safe.
16910- assert_eq!(res.body["correct"], 0);17368+ assert_eq!(res.body["visibility"], "private");
16911- assert_eq!(res.body["subject"], subject);17369+ let secret = id_of(&res.body);
16912- assert_eq!(res.body["owner"], me_id(&app, &teacher).await);17370+ let opt = choice_of(&res.body, 0);
17371+ let res = send(
17372+ &app,
17373+ "POST",
17374+ "/bank-questions",
17375+ Some(&owner),
17376+ Some(json!({ "subject_id": subject, "text": "shared later", "kind": "text", "points": 1 })),
17377+ )
17378+ .await;
17379+ let shared = id_of(&res.body);
17380+
17381+ let illus = b"private-illustration".as_slice();
17382+ let pic = b"private-choice-pic".as_slice();
17383+ let (status, _) =
17384+ post_image(&app, &owner, &format!("/bank-questions/{secret}/image"), "image/png", illus).await;
17385+ assert_eq!(status, StatusCode::CREATED);
17386+ let (status, _) = post_image(
17387+ &app,
17388+ &owner,
17389+ &format!("/bank-questions/{secret}/choices/{opt}/image"),
17390+ "image/webp",
17391+ pic,
17392+ )
17393+ .await;
17394+ assert_eq!(status, StatusCode::CREATED);
17395+
17396+ // The other teacher's own exam, to attempt an instantiate from.
17397+ let course2 = create_course(&app, &other, "bio2").await;
17398+ let subject2 = create_subject(&app, &other, &course2, "cells2").await;
17399+ let exam2 = create_exam(&app, &other, &course2, "quiz", "final").await;
17400+ let owner_id = me_id(&app, &owner).await;
17401+
17402+ // --- the stranger sees nothing, and is told nothing ---
17403+ let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;
17404+ assert!(common::items(&res.body).is_empty());
17405+ assert_eq!(res.body["total"], 0, "total must count only visible templates");
17406+ let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await;
17407+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17408+ let (status, _, _) = common::send_raw(
17409+ &app,
17410+ "GET",
17411+ &format!("/bank-questions/{secret}/image"),
17412+ Some(&other),
17413+ None,
17414+ Vec::new(),
17415+ )
17416+ .await;
17417+ assert_eq!(status, StatusCode::NOT_FOUND);
17418+ let (status, _, _) = common::send_raw(
17419+ &app,
17420+ "GET",
17421+ &format!("/bank-questions/{secret}/choices/{opt}/image"),
17422+ Some(&other),
17423+ None,
17424+ Vec::new(),
17425+ )
17426+ .await;
17427+ assert_eq!(status, StatusCode::NOT_FOUND);
17428+ let res = send(
17429+ &app,
17430+ "POST",
17431+ &format!("/exams/{exam2}/questions/from-bank/{secret}"),
17432+ Some(&other),
17433+ Some(json!({ "subject_id": subject2 })),
17434+ )
17435+ .await;
17436+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17437+ // Not even by asking for the owner's templates by name.
17438+ let res = send(&app, "GET", &format!("/bank-questions?owner={owner_id}"), Some(&other), None).await;
17439+ assert_eq!(res.body["total"], 0);
17440+
17441+ // --- the owner still has full use of their own template ---
17442+ let res = send(&app, "GET", "/bank-questions", Some(&owner), None).await;
17443+ assert_eq!(res.body["total"], 2);
17444+ let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&owner), None).await;
17445+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17446+ assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);
17447+ let (status, _, bytes) = common::send_raw(
17448+ &app,
17449+ "GET",
17450+ &format!("/bank-questions/{secret}/image"),
17451+ Some(&owner),
17452+ None,
17453+ Vec::new(),
17454+ )
17455+ .await;
17456+ assert_eq!((status, bytes.as_slice()), (StatusCode::OK, illus));
17457+ let (status, _, bytes) = common::send_raw(
17458+ &app,
17459+ "GET",
17460+ &format!("/bank-questions/{secret}/choices/{opt}/image"),
17461+ Some(&owner),
17462+ None,
17463+ Vec::new(),
17464+ )
17465+ .await;
17466+ assert_eq!((status, bytes.as_slice()), (StatusCode::OK, pic));
17467+ let exam = create_exam(&app, &owner, &course, "midterm", "final").await;
17468+ let res = send(
17469+ &app,
17470+ "POST",
17471+ &format!("/exams/{exam}/questions/from-bank/{secret}"),
17472+ Some(&owner),
17473+ Some(json!({ "subject_id": subject })),
17474+ )
17475+ .await;
17476+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17477+
17478+ // --- publishing one template opens exactly that one ---
17479+ let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "school" }))).await;
17480+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17481+ assert_eq!(res.body["visibility"], "school");
17482+ let res = send(&app, "GET", "/bank-questions", Some(&other), None).await;
17483+ assert_eq!(res.body["total"], 1, "the private one must still be hidden");
17484+ assert_eq!(common::items(&res.body)[0]["id"], shared);
17485+ let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await;
17486+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17487+ let res = send(
17488+ &app,
17489+ "POST",
17490+ &format!("/exams/{exam2}/questions/from-bank/{shared}"),
17491+ Some(&other),
17492+ Some(json!({ "subject_id": subject2 })),
17493+ )
17494+ .await;
17495+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17496+ // The still-private one stays shut on every path.
17497+ let res = send(&app, "GET", &format!("/bank-questions/{secret}"), Some(&other), None).await;
17498+ assert_eq!(res.status, StatusCode::NOT_FOUND);
17499+ let res = send(
17500+ &app,
17501+ "POST",
17502+ &format!("/exams/{exam2}/questions/from-bank/{secret}"),
17503+ Some(&other),
17504+ Some(json!({ "subject_id": subject2 })),
17505+ )
17506+ .await;
17507+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
17508+ // Unpublishing closes it again.
17509+ let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "private" }))).await;
17510+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17511+ let res = send(&app, "GET", &format!("/bank-questions/{shared}"), Some(&other), None).await;
17512+ assert_eq!(res.status, StatusCode::NOT_FOUND);
17513+ // A bogus value is a 400, not a silent publish.
17514+ let res = send(&app, "PATCH", &format!("/bank-questions/{shared}"), Some(&owner), Some(json!({ "visibility": "public" }))).await;
17515+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
17516+}
17517+
17518+/// Admins see private templates: they already read every exam's `correct` via
17519+/// course management, and they may already delete any template.
17520+#[tokio::test]
17521+async fn bank_private_template_is_visible_to_admins() {
17522+ let (app, db) = app_and_db().await;
17523+ let owner = login_as(&app, &db, "badm_o", "teacher").await;
17524+ let admin = login_as(&app, &db, "badm_a", "admin").await;
17525+ let course = create_course(&app, &owner, "hist").await;
17526+ let subject = create_subject(&app, &owner, &course, "ottoman").await;
17527+ let res = send(
17528+ &app,
17529+ "POST",
17530+ "/bank-questions",
17531+ Some(&owner),
17532+ Some(json!({ "subject_id": subject, "text": "when?", "kind": "text", "points": 1 })),
17533+ )
17534+ .await;
17535+ let bid = id_of(&res.body);
17536+
17537+ let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&admin), None).await;
17538+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17539+ let res = send(&app, "GET", "/bank-questions", Some(&admin), None).await;
17540+ assert_eq!(res.body["total"], 1);
17541+}
17542+
17543+#[tokio::test]
17544+async fn exam_question_saves_to_bank() {
17545+ let (app, db) = app_and_db().await;
17546+ let teacher = login_as(&app, &db, "s2b_t", "teacher").await;
17547+ let course = create_course(&app, &teacher, "phys").await;
17548+ let subject = create_subject(&app, &teacher, &course, "kinematics").await;
17549+ let exam = create_exam(&app, &teacher, &course, "final", "final").await;
17550+ let qid = create_question(
17551+ &app,
17552+ &teacher,
17553+ &exam,
17554+ &subject,
17555+ json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }),
17556+ )
17557+ .await;
17558+
17559+ let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;
17560+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17561+ assert_eq!(res.body["text"], "v=?");
17562+ assert_eq!(res.body["correct"], res.body["choices"][0]["id"]);
17563+ assert_eq!(res.body["subject"], subject);
17564+ assert_eq!(res.body["owner"], me_id(&app, &teacher).await);
17565+ // The one-click broadcast that was: the saved key stays the teacher's until
17566+ // they publish it.
17567+ assert_eq!(res.body["visibility"], "private");
16913 let bid = id_of(&res.body);17568 let bid = id_of(&res.body);
16914 17569
16915- // It now lives in the school-wide bank.17570+ // It now lives in their bank.
16916 let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;17571 let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;
16917 assert_eq!(res.status, StatusCode::OK);17572 assert_eq!(res.status, StatusCode::OK);
16918 }17573 }
@@ -16934,11 +17589,12 @@ async fn bank_instantiate_copies_images() {
16934 "/bank-questions",17589 "/bank-questions",
16935 Some(&teacher),17590 Some(&teacher),
16936 Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice",17591 Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice",
16937- "points": 10, "choices": ["Ankara", "İzmir"], "correct": 0 })),17592+ "points": 10, "choices": [{"id": "c0", "text": "Ankara"}, {"id": "c1", "text": "İzmir"}], "correct": "c0" })),
16938 )17593 )
16939 .await;17594 .await;
16940 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17595 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
16941 let bid = id_of(&res.body);17596 let bid = id_of(&res.body);
17597+ let opt = choice_of(&res.body, 0);
16942 17598
16943 let illus = b"bank-illustration".as_slice();17599 let illus = b"bank-illustration".as_slice();
16944 let choice = b"bank-choice-pic".as_slice();17600 let choice = b"bank-choice-pic".as_slice();
@@ -16948,7 +17604,7 @@ async fn bank_instantiate_copies_images() {
16948 let (status, _) = post_image(17604 let (status, _) = post_image(
16949 &app,17605 &app,
16950 &teacher,17606 &teacher,
16951- &format!("/bank-questions/{bid}/choices/0/image"),17607+ &format!("/bank-questions/{bid}/choices/{opt}/image"),
16952 "image/webp",17608 "image/webp",
16953 choice,17609 choice,
16954 )17610 )
@@ -16985,7 +17641,7 @@ async fn bank_instantiate_copies_images() {
16985 let (status, _, bytes) = common::send_raw(17641 let (status, _, bytes) = common::send_raw(
16986 &app,17642 &app,
16987 "GET",17643 "GET",
16988- &format!("/exams/{exam}/questions/{qid}/choices/0/image"),17644+ &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"),
16989 Some(&teacher),17645 Some(&teacher),
16990 None,17646 None,
16991 Vec::new(),17647 Vec::new(),
@@ -17016,7 +17672,7 @@ async fn bank_instantiate_copies_images() {
17016 let (status, _, bytes) = common::send_raw(17672 let (status, _, bytes) = common::send_raw(
17017 &app,17673 &app,
17018 "GET",17674 "GET",
17019- &format!("/bank-questions/{bid}/choices/0/image"),17675+ &format!("/bank-questions/{bid}/choices/{opt}/image"),
17020 Some(&teacher),17676 Some(&teacher),
17021 None,17677 None,
17022 Vec::new(),17678 Vec::new(),
@@ -17036,14 +17692,16 @@ async fn bank_save_copies_images() {
17036 let course = create_course(&app, &teacher, "phys1").await;17692 let course = create_course(&app, &teacher, "phys1").await;
17037 let subject = create_subject(&app, &teacher, &course, "kin1").await;17693 let subject = create_subject(&app, &teacher, &course, "kin1").await;
17038 let exam = create_exam(&app, &teacher, &course, "final", "final").await;17694 let exam = create_exam(&app, &teacher, &course, "final", "final").await;
17039- let qid = create_question(17695+ let qid_body = create_question_body(
17040 &app,17696 &app,
17041 &teacher,17697 &teacher,
17042 &exam,17698 &exam,
17043 &subject,17699 &subject,
17044- json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }),17700+ json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" }),
17045 )17701 )
17046 .await;17702 .await;
17703+ let qid = id_of(&qid_body);
17704+ let opt = choice_of(&qid_body, 0);
17047 17705
17048 let illus = b"exam-illustration".as_slice();17706 let illus = b"exam-illustration".as_slice();
17049 let choice = b"exam-choice-pic".as_slice();17707 let choice = b"exam-choice-pic".as_slice();
@@ -17059,7 +17717,7 @@ async fn bank_save_copies_images() {
17059 let (status, _) = post_image(17717 let (status, _) = post_image(
17060 &app,17718 &app,
17061 &teacher,17719 &teacher,
17062- &format!("/exams/{exam}/questions/{qid}/choices/0/image"),17720+ &format!("/exams/{exam}/questions/{qid}/choices/{opt}/image"),
17063 "image/jpeg",17721 "image/jpeg",
17064 choice,17722 choice,
17065 )17723 )
@@ -17078,6 +17736,7 @@ async fn bank_save_copies_images() {
17078 .await;17736 .await;
17079 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);17737 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17080 let bid = id_of(&res.body);17738 let bid = id_of(&res.body);
17739+ let opt = choice_of(&res.body, 0);
17081 17740
17082 // The new bank question carries both images, bytes equal.17741 // The new bank question carries both images, bytes equal.
17083 let (status, _, bytes) = common::send_raw(17742 let (status, _, bytes) = common::send_raw(
@@ -17094,7 +17753,7 @@ async fn bank_save_copies_images() {
17094 let (status, _, bytes) = common::send_raw(17753 let (status, _, bytes) = common::send_raw(
17095 &app,17754 &app,
17096 "GET",17755 "GET",
17097- &format!("/bank-questions/{bid}/choices/0/image"),17756+ &format!("/bank-questions/{bid}/choices/{opt}/image"),
17098 Some(&teacher),17757 Some(&teacher),
17099 None,17758 None,
17100 Vec::new(),17759 Vec::new(),
@@ -17206,17 +17865,18 @@ async fn bank_instantiate_rolls_back_on_missing_source_blob() {
17206 "/bank-questions",17865 "/bank-questions",
17207 Some(&teacher),17866 Some(&teacher),
17208 Some(json!({ "subject_id": subject, "text": "q", "kind": "choice",17867 Some(json!({ "subject_id": subject, "text": "q", "kind": "choice",
17209- "points": 10, "choices": ["a", "b"], "correct": 0 })),17868+ "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })),
17210 )17869 )
17211 .await;17870 .await;
17212 let bid = id_of(&res.body);17871 let bid = id_of(&res.body);
17872+ let opt = choice_of(&res.body, 0);
17213 let (status, _) =17873 let (status, _) =
17214 post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await;17874 post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await;
17215 assert_eq!(status, StatusCode::CREATED);17875 assert_eq!(status, StatusCode::CREATED);
17216 let (status, _) = post_image(17876 let (status, _) = post_image(
17217 &app,17877 &app,
17218 &teacher,17878 &teacher,
17219- &format!("/bank-questions/{bid}/choices/0/image"),17879+ &format!("/bank-questions/{bid}/choices/{opt}/image"),
17220 "image/png",17880 "image/png",
17221 b"opt",17881 b"opt",
17222 )17882 )
@@ -17307,38 +17967,72 @@ async fn bank_rejects_unknown_subject() {
17307 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);17967 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
17308 }17968 }
17309 17969
17310-/// A subject with bank templates referencing it can't be deleted (409) until17970+/// Deleting a subject clears it off the bank templates that carried it as
17311-/// those templates are gone — mirrors the exam-question / homework guard.17971+/// origin metadata, instead of being refused. Blocking would have been a dead
17972+/// end (only a template's owner may re-tag it, so a manager could not clear
17973+/// their own 409) and an existence oracle for other teachers' private
17974+/// templates — hence the cascade.
17312 #[tokio::test]17975 #[tokio::test]
17313-async fn subject_delete_blocked_by_bank_question() {17976+async fn subject_delete_clears_the_bank_templates_subject() {
17314 let (app, db) = app_and_db().await;17977 let (app, db) = app_and_db().await;
17315 let teacher = login_as(&app, &db, "bdel_t", "teacher").await;17978 let teacher = login_as(&app, &db, "bdel_t", "teacher").await;
17979+ let manager = login_as(&app, &db, "bdel_m", "manager").await;
17316 let course = create_course(&app, &teacher, "bdel_c").await;17980 let course = create_course(&app, &teacher, "bdel_c").await;
17317 let subject = create_subject(&app, &teacher, &course, "bdel_s").await;17981 let subject = create_subject(&app, &teacher, &course, "bdel_s").await;
17982+ let other = create_subject(&app, &teacher, &course, "bdel_s2").await;
17983+
17984+ let mut ids = Vec::new();
17985+ for subject_id in [&subject, &other] {
17986+ let res = send(
17987+ &app,
17988+ "POST",
17989+ "/bank-questions",
17990+ Some(&teacher),
17991+ Some(json!({ "subject_id": subject_id, "text": "q", "kind": "text", "points": 5 })),
17992+ )
17993+ .await;
17994+ ids.push(id_of(&res.body));
17995+ }
17996+ let (bid, kept) = (&ids[0], &ids[1]);
17997+
17998+ // The manager owns none of these templates, yet the delete goes through.
17999+ let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&manager), None).await;
18000+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
17318 18001
18002+ // The template survives with a cleared origin; the other one is untouched.
18003+ let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;
18004+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
18005+ assert_eq!(res.body["subject"], serde_json::Value::Null);
18006+ assert_eq!(res.body["text"], "q");
18007+ let res = send(&app, "GET", &format!("/bank-questions/{kept}"), Some(&teacher), None).await;
18008+ assert_eq!(res.body["subject"], json!(other));
18009+
18010+ // The list join renders the cleared one with an empty subject name.
18011+ let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await;
18012+ let cleared = common::items(&res.body)
18013+ .iter()
18014+ .find(|q| q["id"] == *bid)
18015+ .expect("template in list")
18016+ .clone();
18017+ assert_eq!(cleared["subject"], serde_json::Value::Null);
18018+ assert_eq!(cleared["subject_name"], "");
18019+
18020+ // A cleared template still edits: PATCH without `subject_id` keeps it null.
17319 let res = send(18021 let res = send(
17320 &app,18022 &app,
17321- "POST",18023+ "PATCH",
17322- "/bank-questions",18024+ &format!("/bank-questions/{bid}"),
17323 Some(&teacher),18025 Some(&teacher),
17324- Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })),18026+ Some(json!({ "text": "still editable" })),
17325 )18027 )
17326 .await;18028 .await;
17327- let bid = id_of(&res.body);18029+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17328-18030+ assert_eq!(res.body["subject"], serde_json::Value::Null);
17329- // Guarded while the template stands.18031+ assert_eq!(res.body["text"], "still editable");
17330- let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await;
17331- assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
17332-
17333- // Drop the template — the subject frees up.
17334- let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;
17335- assert_eq!(res.status, StatusCode::NO_CONTENT);
17336- let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await;
17337- assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
17338 }18032 }
17339 18033
17340-/// `?owner=me` (and an explicit owner id) narrows the school-wide bank to one18034+/// `?owner=me` (and an explicit owner id) narrows the bank to one owner's
17341-/// owner's templates.18035+/// templates — on top of the visibility gate, never around it.
17342 #[tokio::test]18036 #[tokio::test]
17343 async fn bank_owner_filter() {18037 async fn bank_owner_filter() {
17344 let (app, db) = app_and_db().await;18038 let (app, db) = app_and_db().await;
@@ -17348,7 +18042,7 @@ async fn bank_owner_filter() {
17348 let subject = create_subject(&app, &alice, &course, "bown_s").await;18042 let subject = create_subject(&app, &alice, &course, "bown_s").await;
17349 18043
17350 for who in [&alice, &bob] {18044 for who in [&alice, &bob] {
17351- send(18045+ let res = send(
17352 &app,18046 &app,
17353 "POST",18047 "POST",
17354 "/bank-questions",18048 "/bank-questions",
@@ -17356,6 +18050,10 @@ async fn bank_owner_filter() {
17356 Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })),18050 Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })),
17357 )18051 )
17358 .await;18052 .await;
18053+ // Published, so this test is about the owner filter, not visibility.
18054+ let bid = id_of(&res.body);
18055+ let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(who), Some(json!({ "visibility": "school" }))).await;
18056+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17359 }18057 }
17360 let alice_id = me_id(&app, &alice).await;18058 let alice_id = me_id(&app, &alice).await;
17361 let bob_id = me_id(&app, &bob).await;18059 let bob_id = me_id(&app, &bob).await;
@@ -17391,10 +18089,11 @@ async fn bank_response_carries_image_metas() {
17391 "/bank-questions",18089 "/bank-questions",
17392 Some(&teacher),18090 Some(&teacher),
17393 Some(json!({ "subject_id": subject, "text": "q", "kind": "choice",18091 Some(json!({ "subject_id": subject, "text": "q", "kind": "choice",
17394- "points": 10, "choices": ["a", "b"], "correct": 0 })),18092+ "points": 10, "choices": [{"id": "c0", "text": "a"}, {"id": "c1", "text": "b"}], "correct": "c0" })),
17395 )18093 )
17396 .await;18094 .await;
17397 let bid = id_of(&res.body);18095 let bid = id_of(&res.body);
18096+ let opt = choice_of(&res.body, 0);
17398 18097
17399 // No images yet: metas are null / all-empty.18098 // No images yet: metas are null / all-empty.
17400 assert!(res.body["image"].is_null());18099 assert!(res.body["image"].is_null());
@@ -17406,7 +18105,7 @@ async fn bank_response_carries_image_metas() {
17406 let (status, _) = post_image(18105 let (status, _) = post_image(
17407 &app,18106 &app,
17408 &teacher,18107 &teacher,
17409- &format!("/bank-questions/{bid}/choices/0/image"),18108+ &format!("/bank-questions/{bid}/choices/{opt}/image"),
17410 "image/jpeg",18109 "image/jpeg",
17411 b"opt",18110 b"opt",
17412 )18111 )
@@ -17426,8 +18125,11 @@ async fn bank_response_carries_image_metas() {
17426 assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg");18125 assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg");
17427 }18126 }
17428 18127
17429-/// Provenance rides both directions: instantiate records `source_bank` on the18128+/// Provenance rides both directions, one column per direction: instantiate
17430-/// new exam question; save-to-bank records `source_exam` on the new template.18129+/// records `from_bank` on the new exam question (and leaves `banked_as` null —
18130+/// coming *from* the bank is not being saved *to* it); save-to-bank records
18131+/// `source_exam` on the new template and `banked_as` on the question, without
18132+/// touching `from_bank`.
17431 #[tokio::test]18133 #[tokio::test]
17432 async fn bank_provenance_both_directions() {18134 async fn bank_provenance_both_directions() {
17433 let (app, db) = app_and_db().await;18135 let (app, db) = app_and_db().await;
@@ -17435,7 +18137,7 @@ async fn bank_provenance_both_directions() {
17435 let course = create_course(&app, &teacher, "bprov_c").await;18137 let course = create_course(&app, &teacher, "bprov_c").await;
17436 let subject = create_subject(&app, &teacher, &course, "bprov_s").await;18138 let subject = create_subject(&app, &teacher, &course, "bprov_s").await;
17437 18139
17438- // Bank -> exam: source_bank is the template id.18140+ // Bank -> exam: from_bank is the template id, banked_as stays null.
17439 let res = send(18141 let res = send(
17440 &app,18142 &app,
17441 "POST",18143 "POST",
@@ -17455,9 +18157,32 @@ async fn bank_provenance_both_directions() {
17455 )18157 )
17456 .await;18158 .await;
17457 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18159 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17458- assert_eq!(res.body["source_bank"], bid);18160+ assert_eq!(res.body["from_bank"], bid);
18161+ // The lie the split fixes: an inserted question must not read as banked.
18162+ assert!(res.body["banked_as"].is_null(), "{}", res.body);
18163+ let inserted = id_of(&res.body);
17459 18164
17460- // A directly authored exam question has no source_bank.18165+ // Saving that inserted question sets banked_as and leaves from_bank alone.
18166+ let res = send(
18167+ &app,
18168+ "POST",
18169+ &format!("/exams/{exam}/questions/{inserted}/to-bank"),
18170+ Some(&teacher),
18171+ None,
18172+ )
18173+ .await;
18174+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18175+ let template = id_of(&res.body);
18176+ let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;
18177+ let question = common::items(&res.body)
18178+ .iter()
18179+ .find(|q| q["id"] == inserted)
18180+ .expect("question in list")
18181+ .clone();
18182+ assert_eq!(question["from_bank"], bid, "{question}");
18183+ assert_eq!(question["banked_as"], template, "{question}");
18184+
18185+ // A directly authored exam question has neither link.
17461 let qid = create_question(18186 let qid = create_question(
17462 &app,18187 &app,
17463 &teacher,18188 &teacher,
@@ -17497,21 +18222,21 @@ async fn to_bank_links_the_question_at_the_new_template() {
17497 .await;18222 .await;
17498 18223
17499 // Fresh question: no link yet.18224 // Fresh question: no link yet.
17500- let source_bank_of = |body: &serde_json::Value| -> serde_json::Value {18225+ let banked_as_of = |body: &serde_json::Value| -> serde_json::Value {
17501 common::items(body)18226 common::items(body)
17502 .iter()18227 .iter()
17503 .find(|q| q["id"] == qid)18228 .find(|q| q["id"] == qid)
17504- .expect("question in list")["source_bank"]18229+ .expect("question in list")["banked_as"]
17505 .clone()18230 .clone()
17506 };18231 };
17507 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18232 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;
17508- assert!(source_bank_of(&res.body).is_null());18233+ assert!(banked_as_of(&res.body).is_null());
17509 18234
17510 let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18235 let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;
17511 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);18236 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
17512 let first = id_of(&res.body);18237 let first = id_of(&res.body);
17513 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18238 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;
17514- assert_eq!(source_bank_of(&res.body), json!(first));18239+ assert_eq!(banked_as_of(&res.body), json!(first));
17515 18240
17516 // Second save: still 201, a distinct template, and the link follows it.18241 // Second save: still 201, a distinct template, and the link follows it.
17517 let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;18242 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() {
17519 let second = id_of(&res.body);18244 let second = id_of(&res.body);
17520 assert_ne!(first, second);18245 assert_ne!(first, second);
17521 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;18246 let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await;
17522- assert_eq!(source_bank_of(&res.body), json!(second));18247+ assert_eq!(banked_as_of(&res.body), json!(second));
17523 }18248 }
17524 18249
17525 /// The back-link is a field-scoped write. `question_to_bank` reads the question,18250 /// 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() {
17528 /// whole-row save from the stale struct would silently revert it. Driven at the18253 /// whole-row save from the stale struct would silently revert it. Driven at the
17529 /// domain level: HTTP offers no way to interleave inside the handler.18254 /// domain level: HTTP offers no way to interleave inside the handler.
17530 #[tokio::test]18255 #[tokio::test]
17531-async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() {18256+async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() {
17532 use hezarfen_backend::domain::bank_question::BankQuestionId;18257 use hezarfen_backend::domain::bank_question::BankQuestionId;
17533 use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId};18258 use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId};
17534 18259
@@ -17571,7 +18296,7 @@ async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() {
17571 assert_eq!(res.status, StatusCode::OK, "{}", res.body);18296 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
17572 18297
17573 stale18298 stale
17574- .link_source_bank(BankQuestionId::from_key(&bid), &db)18299+ .link_banked_as(BankQuestionId::from_key(&bid), &db)
17575 .await18300 .await
17576 .expect("link written");18301 .expect("link written");
17577 18302
@@ -17584,19 +18309,87 @@ async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() {
17584 .clone();18309 .clone();
17585 assert_eq!(question["text"], "edited by someone else");18310 assert_eq!(question["text"], "edited by someone else");
17586 assert_eq!(question["points"], 9);18311 assert_eq!(question["points"], 9);
17587- assert_eq!(question["source_bank"], bid);18312+ assert_eq!(question["banked_as"], bid);
18313+}
18314+
18315+/// A bank PATCH writes only the fields it was given: the handler reads the
18316+/// template, then awaits an ownership check, a subject lookup and (on a choice
18317+/// replace) an image sweep, so another write can land in that window — here the
18318+/// exam-delete cascade clearing `source_exam`, a field the PATCH never sets.
18319+/// A whole-row save from the stale struct would resurrect the dead exam link.
18320+#[tokio::test]
18321+async fn a_bank_patch_does_not_clobber_a_concurrent_write() {
18322+ use hezarfen_backend::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility};
18323+ use hezarfen_backend::domain::exam_question::{
18324+ QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
18325+ };
18326+
18327+ let (app, db) = app_and_db().await;
18328+ let teacher = login_as(&app, &db, "bpatch_t", "teacher").await;
18329+ let course = create_course(&app, &teacher, "bpatch_c").await;
18330+ let subject = create_subject(&app, &teacher, &course, "bpatch_s").await;
18331+ let exam = create_exam(&app, &teacher, &course, "midterm", "final").await;
18332+ let qid = create_question(
18333+ &app,
18334+ &teacher,
18335+ &exam,
18336+ &subject,
18337+ json!({ "text": "original", "kind": "text", "points": 5 }),
18338+ )
18339+ .await;
18340+ let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await;
18341+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
18342+ let bid = id_of(&res.body);
18343+ assert_eq!(res.body["source_exam"], json!(exam));
18344+
18345+ // The handler's read, then the exam delete lands mid-window and clears the
18346+ // template's `source_exam`.
18347+ let stale = BankQuestion::read(&BankQuestionId::from_key(&bid), &db)
18348+ .await
18349+ .unwrap()
18350+ .expect("template exists");
18351+ assert!(stale.get_source_exam().is_some());
18352+ let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await;
18353+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
18354+
18355+ // The stale struct writes its own fields only.
18356+ let updated = stale
18357+ .update(
18358+ None,
18359+ QuestionText::try_new("edited").unwrap(),
18360+ QuestionPoints::try_new(7).unwrap(),
18361+ QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(),
18362+ BankVisibility::try_new(BankVisibility::SCHOOL).unwrap(),
18363+ &db,
18364+ )
18365+ .await
18366+ .expect("update written");
18367+ assert_eq!(updated.get_text().as_str(), "edited");
18368+ assert!(updated.get_source_exam().is_none(), "the dead exam link came back");
18369+
18370+ // The edit landed and the cleared provenance stayed cleared.
18371+ let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await;
18372+ assert_eq!(res.body["source_exam"], serde_json::Value::Null);
18373+ assert_eq!(res.body["subject"], serde_json::Value::Null);
18374+ assert_eq!(res.body["text"], "edited");
tests/persistence.rsmodified+4 -2
@@ -350,12 +350,14 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
350 Some(&cookie),350 Some(&cookie),
351 Some(351 Some(
352 json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",352 json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",
353- "points": 10, "choices": ["3", "4"], "correct": 1 }),353+ "points": 10, "choices": [{"id": "c0", "text": "3"}, {"id": "c1", "text": "4"}], "correct": "c1" }),
354 ),354 ),
355 )355 )
356 .await;356 .await;
357 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);357 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
358 let question_id = common::id_of(&res.body);358 let question_id = common::id_of(&res.body);
359+ // Choice ids are minted server-side, so the answer names one off the response.
360+ let picked = res.body["choices"][1]["id"].as_str().expect("choice id").to_string();
359 let res = send(361 let res = send(
360 &app,362 &app,
361 "POST",363 "POST",
@@ -370,7 +372,7 @@ async fn legacy_subjectless_questions_are_destroyed_on_boot() {
370 "POST",372 "POST",
371 &format!("/exams/{exam_id}/attempt/answers"),373 &format!("/exams/{exam_id}/attempt/answers"),
372 Some(&student_cookie),374 Some(&student_cookie),
373- Some(json!({ "question_id": question_id, "selected": 1 })),375+ Some(json!({ "question_id": question_id, "selected": picked })),
374 )376 )
375 .await;377 .await;
376 assert_eq!(res.status, StatusCode::OK, "{}", res.body);378 assert_eq!(res.status, StatusCode::OK, "{}", res.body);