diff --git a/README.md b/README.md index 3dea46c..7b4c593 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,11 @@ governed by a teacher-controlled rejoin door. Writing an exam takes a while, so when it's ready. Questions can carry **images**: any question may hold one illustration (a map above the prompt), and each option of a choice question may be a picture of its own (pick the right city off the map) — raster -uploads capped by the same `max_file_bytes` policy as note files. Teachers +uploads capped by the same `max_file_bytes` policy as note files. Good +questions get reused, so a teacher+ can bank one in a school-wide **question +bank** — detached templates (with their own images) that any teacher copies +into a fresh exam question across years, editable and deletable only by +whoever saved them. Teachers watch attendance, per-student remaining time, sittings, walk-outs, no-shows (`absent` once the window closes), submissions, and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out @@ -305,6 +309,8 @@ course enrollments. | Ask into the school question pool | student | **Students only** (exact); born `pending` — visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending | | Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any | | Approve a pending pool question; delete any question or solution | teacher | Approval publishes school-wide and **freezes** the content; rejection = deletion — moderation never edits, so teacher+ cannot rewrite a solution | +| Read the school **question bank**; save / instantiate bank questions | teacher | Every bank row is school-wide (reads + copy into an exam); saving one makes the caller its owner | +| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze | | Read **own** attendance report | student | | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all; a `parent` sees a linked student's in full | | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created + assigned; `manager`+: all); exam **drafts** show only to the course's managers | @@ -515,6 +521,8 @@ their existing shapes: the student exam-room reads | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | +| POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a **bank question** into this exam — copies it to a fresh exam-scoped question (new id, own images + answers; records the template in `source_bank`); body `{subject_id}` retags it against the course's subjects (`400` cross-course; course manager; `409` once attempted) | +| POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save an existing exam question into the school **question bank** — copies it to a detached bank row (new id, own images; records the origin exam in `source_exam`); the source question is untouched (course manager) | | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) | | POST | `/exams/{id}/questions/{qid}/image` | teacher | Attach/replace the question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (course manager; frozen once attempted) | | GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) | @@ -538,6 +546,17 @@ their existing shapes: the student exam-room reads | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current | +| GET | `/bank-questions` | teacher | The school-wide question bank — `?subject=` filters by origin subject, `?owner=` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) · paged | +| POST | `/bank-questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` — save a reusable question template into the bank (owner = caller; `subject_id` is origin metadata, but must exist — `400` otherwise) | +| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) | +| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question — the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze) | +| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) | +| POST | `/bank-questions/{bid}/image` | teacher | Attach/replace the bank question's illustration: `multipart/form-data`, one `file` part — raster images only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` (**owner only**, admin bypass) | +| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) | +| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) | +| POST | `/bank-questions/{bid}/choices/{index}/image` | teacher | Attach/replace option `index`'s picture (`choice` questions; same form and limits as above; **owner only**, admin bypass) | +| GET | `/bank-questions/{bid}/choices/{index}/image` | teacher | The option picture's bytes (any teacher+) | +| DELETE | `/bank-questions/{bid}/choices/{index}/image` | teacher | Remove one option picture (**owner only**, admin bypass) | | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) | | GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) · paged | | GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) · paged | @@ -1222,6 +1241,53 @@ The live monitor rides along: each roster row now carries `answered` and The student's own `GET /exams/{id}/attempt` echoes the same `answered`/`question_count` pair. +## Question bank + +Writing good questions is slow, and the same one gets asked year after year, so +the school keeps a reusable **question bank**. A bank question is an +`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`, +`text`, `kind`, `points`, and — for a `choice` — `choices` + `correct`), the +same image slots (one illustration, plus a picture per option), and the same +newtype validation, but it carries **no exam link**. Because nothing sits it, +a bank row **never freezes** — its owner can edit or delete it forever. + +`POST /bank-questions` (teacher+) saves one, stamping the caller as its +**owner**. `subject_id` is origin metadata, but it must **exist** — an unknown +subject is a `400` (create and PATCH alike); the reverse guard holds too, so +deleting a subject a template still references is a `409` (same as exam +questions and homework). Reads are school-wide: `GET /bank-questions` lists the +whole bank (paged, `?subject=` narrows by origin subject, `?owner=` — or +`?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with +`correct` included — any teacher+ can browse and reuse what any colleague +banked. Each response carries its **image metadata** — an `image` meta for the +illustration and a `choice_images` array aligned with `choices` (per-slot +`{content_type, size}`, `null` where a slot has no picture) — the same shape an +exam question's response uses; the bytes still come from the image endpoints. +Mutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}` +revalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the +row and its image blobs. The illustration and option pictures work exactly like +an exam question's — `POST|GET|DELETE /bank-questions/{bid}/image` and +`…/choices/{index}/image`, `multipart/form-data` with one `file` part, raster +only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` — reads school-wide, +writes owner-only. + +The bank feeds exams by **copying**, never linking. `POST +/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the +exam: it mints a **fresh** exam-scoped question (new id, its own answer rows, +its image blobs copied to new files), so later edits on either side never +touch the other. The subject on the bank row is origin metadata only — the +call takes its own `{subject_id}`, re-checked against the target course's +subjects (`400` on a cross-course subject), and instantiating into an exam +that already has attempts is a `409`, the same freeze that guards hand-authored +questions. The instantiated question records the template it came from in +`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies +an existing exam question **into** the bank (new detached row, images copied to +new files, owner = caller); the source question is left untouched, and the new +template records the origin exam in `source_exam`. Both provenance fields are +nullable — a hand-authored question or template carries `null` — and one-way +metadata (the copies stay fully detached). All bank routes are course-agnostic +and require teacher+. + ## Homework A course hands out **homework**: `POST /courses/{id}/homework` with a title, @@ -1782,6 +1848,10 @@ src/ metadata; bytes on disk under FILES_PATH) answer_image.rs AnswerImageId · AnswerImage (student answer-drawing metadata; bytes on disk under FILES_PATH) + bank_question.rs BankQuestionId · BankQuestion (school-wide reusable + question template, copied into exams; no exam FK) + bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank + question/choice picture metadata; bytes on disk under FILES_PATH) profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) preferences.rs Theme · Language (own UI preferences) message.rs MessageId · MessageSubject · MessageBody · MessageLabel · @@ -1827,8 +1897,8 @@ src/ page.rs PageParams · Page (shared pagination) auth.rs users.rs notes.rs messages.rs events.rs appointments.rs courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs - marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs - ai.rs chatbot.rs + bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs + settings.rs terms.rs ai.rs chatbot.rs ``` Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory diff --git a/src/database.rs b/src/database.rs index 99cdd1c..6e83d79 100644 --- a/src/database.rs +++ b/src/database.rs @@ -38,6 +38,8 @@ pub const EXAM_QUESTION_TABLE: &str = "exam_question"; pub const QUESTION_IMAGE_TABLE: &str = "question_image"; pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; pub const ANSWER_IMAGE_TABLE: &str = "answer_image"; +pub const BANK_QUESTION_TABLE: &str = "bank_question"; +pub const BANK_QUESTION_IMAGE_TABLE: &str = "bank_question_image"; pub const COURSE_TABLE: &str = "course"; pub const ENROLLMENT_TABLE: &str = "enrollment"; pub const PARENT_LINK_TABLE: &str = "parent_link"; @@ -274,6 +276,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option>; DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option; DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; + DEFINE FIELD IF NOT EXISTS source_bank ON exam_question TYPE option>; DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; @@ -287,6 +290,27 @@ const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; + DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record; + DEFINE FIELD IF NOT EXISTS subject ON bank_question TYPE record; + DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; + DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; + DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; + DEFINE FIELD IF NOT EXISTS choices ON bank_question TYPE option>; + DEFINE FIELD IF NOT EXISTS correct ON bank_question TYPE option; + DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option>; + DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; + DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; + + DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record; + DEFINE FIELD IF NOT EXISTS slot ON bank_question_image TYPE option; + DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; + DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; + DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; + DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; + DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record; diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs new file mode 100644 index 0000000..42a2fd1 --- /dev/null +++ b/src/domain/bank_question.rs @@ -0,0 +1,287 @@ +//! A reusable question template in the school-wide question bank. Unlike an +//! [`crate::domain::exam_question::ExamQuestion`], a bank row is fully detached +//! from any exam: no exam FK, so no attempt ever freezes it, and its images +//! live in their own [`crate::domain::bank_question_image`] slot table. Teachers +//! save templates here and later *copy* them into an exam — the copy is a fresh +//! `ExamQuestion` with its own id, images, and answers; the two never share a +//! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants +//! because every write goes through one. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{BANK_QUESTION_TABLE, Database}; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ + ChoiceText, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, +}; +use crate::domain::subject::SubjectId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BankQuestionId(RecordId); + +impl BankQuestionId { + pub fn generate() -> Self { + Self(RecordId::new(BANK_QUESTION_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(BANK_QUESTION_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One template in the shared question bank. `owner` is the teacher who saved +/// it (the only one who may edit or delete it, admins aside); `subject` is +/// origin metadata only — the same-course rule is checked against the caller's +/// subject when a template is copied into an exam, not here. +#[derive(Debug, Clone, SurrealValue)] +pub struct BankQuestion { + id: BankQuestionId, + owner: UserId, + subject: SubjectId, + text: QuestionText, + kind: QuestionKind, + points: QuestionPoints, + choices: Option>, + correct: Option, + /// The exam question this template was saved from, if any. + source_exam: Option, + created_at: Timestamp, +} + +impl BankQuestion { + pub fn get_id(&self) -> &BankQuestionId { + &self.id + } + + pub fn get_owner(&self) -> &UserId { + &self.owner + } + + pub fn get_subject(&self) -> &SubjectId { + &self.subject + } + + pub fn get_text(&self) -> &QuestionText { + &self.text + } + + pub fn get_kind(&self) -> &QuestionKind { + &self.kind + } + + pub fn get_points(&self) -> QuestionPoints { + self.points + } + + pub fn get_choices(&self) -> Option<&[ChoiceText]> { + self.choices.as_deref() + } + + pub fn get_correct(&self) -> Option { + self.correct + } + + pub fn get_source_exam(&self) -> Option<&ExamId> { + self.source_exam.as_ref() + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// The stored kind-dependent fields as the validated bundle (for + /// merge-on-update). Bypasses `try_new`: the fields were written through a + /// `QuestionSpec`, so the invariants already hold. + pub fn spec(&self) -> QuestionSpec { + // `QuestionSpec` fields are private; rebuild through `try_new`, which + // the stored values are guaranteed to satisfy. + QuestionSpec::try_new( + self.kind.clone(), + self.choices + .as_ref() + .map(|cs| cs.iter().map(|c| c.as_str().to_string()).collect()), + self.correct, + ) + .expect("stored bank question fields satisfy the spec invariants") + } + + pub async fn create( + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + db: &Database, + ) -> Result { + Self::insert(owner, subject, text, points, spec, None, db).await + } + + /// Like [`Self::create`], but records the origin exam the template was + /// saved from (`POST …/questions/{qid}/to-bank`). + pub async fn create_from_exam( + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: ExamId, + db: &Database, + ) -> Result { + Self::insert(owner, subject, text, points, spec, Some(source), db).await + } + + #[allow(clippy::too_many_arguments)] + async fn insert( + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source_exam: Option, + db: &Database, + ) -> Result { + let question = BankQuestion::from_parts( + BankQuestionId::generate(), + owner, + subject, + text, + points, + spec, + source_exam, + Timestamp::now(), + ); + let created: Option = + db.create(question.id.record()).content(question).await?; + created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) + } + + /// Whether any bank template references `subject` as its origin — the gate + /// that blocks deleting a subject still used by a template. + pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result { + let mut result = db + .query("SELECT VALUE id FROM bank_question WHERE subject = $subject LIMIT 1") + .bind(("subject", subject.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + + pub async fn read(id: &BankQuestionId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every template in the bank, school-wide (no owner filter), in creation + /// order (ULID ids sort by creation). + pub async fn list(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM bank_question ORDER BY id ASC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + db: &Database, + ) -> Result { + self.subject = subject; + self.text = text; + self.points = points; + let (kind, choices, correct) = spec.into_parts(); + self.kind = kind; + self.choices = choices; + self.correct = correct; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the template and cascade-remove its bank images, so none points + /// at a missing template. Bank rows have no answers. The image *blobs* are + /// the web layer's to remove — it collects their names before calling this. + pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE bank_question_image WHERE bank_question = $b;") + .bind(("b", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } + + #[allow(clippy::too_many_arguments)] + fn from_parts( + id: BankQuestionId, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source_exam: Option, + created_at: Timestamp, + ) -> BankQuestion { + let (kind, choices, correct) = spec.into_parts(); + BankQuestion { + id, + owner, + subject, + text, + kind, + points, + choices, + correct, + source_exam, + created_at, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec() -> QuestionSpec { + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec!["yes".into(), "no".into()]), + Some(1), + ) + .unwrap() + } + + #[tokio::test] + async fn list_is_school_wide() { + let db = crate::database::init_mem().await.unwrap(); + for _ in 0..2 { + BankQuestion::create( + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("q").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + &db, + ) + .await + .unwrap(); + } + // Different owners, yet both listed. + assert_eq!(BankQuestion::list(&db).await.unwrap().len(), 2); + } +} diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs new file mode 100644 index 0000000..67ad865 --- /dev/null +++ b/src/domain/bank_question_image.rs @@ -0,0 +1,233 @@ +//! An image pinned to a bank question — the question's own illustration +//! (`slot = NONE`) or one choice's picture (`slot = i`, choice questions only). +//! A structural copy of [`crate::domain::question_image`] with the exam FK +//! dropped: a bank template belongs to no exam, and its owner is reachable +//! through the `bank_question` row. The row carries metadata; the bytes live +//! on disk under [`crate::config::Config::files_path`] in a file named by +//! `file` — a fresh server-generated ULID per upload. The row id is +//! *deterministic* per (question, slot), so "one image per slot" holds by +//! construction and a replace is a plain UPSERT. The web layer owns the blob +//! I/O and its ordering; this module owns the rows. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{BANK_QUESTION_IMAGE_TABLE, Database}; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::note_file::FileContentType; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct BankQuestionImageId(RecordId); + +impl BankQuestionImageId { + /// The one id a (question, slot) pair can have: `{bid}_q` for the + /// question's own image, `{bid}_{i}` for choice `i` — uniqueness per slot + /// needs no index this way. + pub fn for_slot(question: &BankQuestionId, slot: Option) -> Self { + let suffix = match slot { + None => "q".to_string(), + Some(index) => index.to_string(), + }; + Self(RecordId::new( + BANK_QUESTION_IMAGE_TABLE, + format!("{}_{suffix}", question.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct BankQuestionImage { + id: BankQuestionImageId, + bank_question: BankQuestionId, + /// `NONE` = the question's illustration; `i` = the picture of choice `i`. + slot: Option, + /// The blob's on-disk name — a fresh ULID every upload. + file: String, + content_type: FileContentType, + size: i64, +} + +impl BankQuestionImage { + /// Assemble a row (fresh blob name generated here) without persisting it. + /// The caller writes the blob under [`Self::get_file`] first, then calls + /// [`Self::upsert`] — so a stored row always points at a real blob. + pub fn new( + question: &BankQuestionId, + slot: Option, + content_type: FileContentType, + size: i64, + ) -> Self { + Self { + id: BankQuestionImageId::for_slot(question, slot), + bank_question: question.clone(), + slot, + file: Ulid::new().to_string(), + content_type, + size, + } + } + + pub fn get_bank_question(&self) -> &BankQuestionId { + &self.bank_question + } + + pub fn get_slot(&self) -> Option { + self.slot + } + + pub fn get_file(&self) -> &str { + &self.file + } + + pub fn get_content_type(&self) -> &FileContentType { + &self.content_type + } + + pub fn get_size(&self) -> i64 { + self.size + } + + /// Create or replace the slot's image row — the deterministic id makes + /// this the whole "one image per slot" story. + pub async fn upsert(self, db: &Database) -> Result { + let written: Option = db.upsert(self.id.record()).content(self).await?; + written.ok_or_else(|| AppError::Internal("failed to store bank question image".into())) + } + + pub async fn read_slot( + question: &BankQuestionId, + slot: Option, + db: &Database, + ) -> Result, AppError> { + Ok(db + .select(BankQuestionImageId::for_slot(question, slot).record()) + .await?) + } + + pub async fn list_for_question( + question: &BankQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM bank_question_image WHERE bank_question = $b") + .bind(("b", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Every bank image row, school-wide — for bucketing onto a whole template + /// list in one query (the bank list is itself school-wide). + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM bank_question_image") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Drop every *choice* image of the question (the question's own + /// illustration stays), returning the removed rows so the caller can take + /// their blobs off disk. Runs when a PATCH replaces the choice list — the + /// old pictures belong to the old options. + pub async fn delete_choices_for( + question: &BankQuestionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE bank_question_image WHERE bank_question = $b AND slot != NONE RETURN BEFORE") + .bind(("b", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png() -> FileContentType { + FileContentType::try_new("image/png").unwrap() + } + + #[tokio::test] + async fn for_slot_keys_by_question_and_slot() { + let question = BankQuestionId::from_key("abc"); + assert_eq!( + BankQuestionImageId::for_slot(&question, None).key(), + "abc_q" + ); + assert_eq!( + BankQuestionImageId::for_slot(&question, Some(0)).key(), + "abc_0" + ); + assert_eq!( + BankQuestionImageId::for_slot(&question, Some(3)).key(), + "abc_3" + ); + } + + #[tokio::test] + async fn upsert_replaces_per_slot() { + let db = crate::database::init_mem().await.unwrap(); + let question = BankQuestionId::generate(); + + let first = BankQuestionImage::new(&question, None, png(), 3) + .upsert(&db) + .await + .unwrap(); + let second = BankQuestionImage::new(&question, None, png(), 5) + .upsert(&db) + .await + .unwrap(); + // Same slot, same row — the replace swapped the blob pointer. + assert_ne!(first.get_file(), second.get_file()); + let rows = BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_size(), 5); + } + + #[tokio::test] + async fn choice_wipe_spares_the_question_image() { + let db = crate::database::init_mem().await.unwrap(); + let question = BankQuestionId::generate(); + for slot in [None, Some(0), Some(1)] { + BankQuestionImage::new(&question, slot, png(), 1) + .upsert(&db) + .await + .unwrap(); + } + + let dropped = BankQuestionImage::delete_choices_for(&question, &db) + .await + .unwrap(); + assert_eq!(dropped.len(), 2); + assert!(dropped.iter().all(|image| image.get_slot().is_some())); + + let left = BankQuestionImage::list_for_question(&question, &db) + .await + .unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].get_slot(), None); + } +} diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index 2734660..f3faa85 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -5,6 +5,7 @@ use crate::constant::{ MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, }; use crate::database::{Database, EXAM_QUESTION_TABLE}; +use crate::domain::bank_question::BankQuestionId; use crate::domain::exam::ExamId; use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; @@ -158,6 +159,12 @@ impl QuestionSpec { pub fn get_kind(&self) -> &QuestionKind { &self.kind } + + /// The validated fields, consumed — for a writer in another module (the + /// question bank) that stores the same three columns. + pub fn into_parts(self) -> (QuestionKind, Option>, Option) { + (self.kind, self.choices, self.correct) + } } /// One question of an exam. Order within the exam is the id's ULID order @@ -175,6 +182,8 @@ pub struct ExamQuestion { points: QuestionPoints, choices: Option>, correct: Option, + /// The bank template this question was instantiated from, if any. + source_bank: Option, } impl ExamQuestion { @@ -210,6 +219,10 @@ impl ExamQuestion { self.correct } + pub fn get_source_bank(&self) -> Option<&BankQuestionId> { + self.source_bank.as_ref() + } + /// The stored kind-dependent fields as the validated bundle (for /// merge-on-update). Bypasses `try_new`: the fields were written through a /// `QuestionSpec`, so the invariants already hold. @@ -228,6 +241,33 @@ impl ExamQuestion { points: QuestionPoints, spec: QuestionSpec, db: &Database, + ) -> Result { + Self::insert(exam, subject, text, points, spec, None, db).await + } + + /// Like [`Self::create`], but records the bank template this question was + /// instantiated from (`POST …/questions/from-bank/{bid}`). + pub async fn create_from_bank( + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: BankQuestionId, + db: &Database, + ) -> Result { + Self::insert(exam, subject, text, points, spec, Some(source), db).await + } + + #[allow(clippy::too_many_arguments)] + async fn insert( + exam: &ExamId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source_bank: Option, + db: &Database, ) -> Result { let question = ExamQuestion { id: ExamQuestionId::generate(), @@ -238,6 +278,7 @@ impl ExamQuestion { kind: spec.kind, choices: spec.choices, correct: spec.correct, + source_bank, }; let created: Option = db.create(question.id.record()).content(question).await?; @@ -320,6 +361,7 @@ impl ExamQuestion { kind: spec.kind, choices: spec.choices, correct: spec.correct, + source_bank: None, } } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index b8e612b..ea4d4ff 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -6,6 +6,8 @@ pub mod answer_image; pub mod appointment; pub mod appointment_slot; pub mod attendance; +pub mod bank_question; +pub mod bank_question_image; pub mod chatbot_message; pub mod chatbot_thread; pub mod course; diff --git a/src/lib.rs b/src/lib.rs index 9735569..2e977c4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,6 +53,7 @@ use crate::state::AppState; (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), + (name = "bank", description = "The school-wide question bank: a shared library of reusable question templates. Any teacher+ reads the whole bank (`GET /bank-questions`, optional `?subject=` origin filter) and instantiates any template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Reads and instantiate are school-wide, but editing or deleting a template needs ownership (its owner, or an admin — 403 otherwise); templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and school-wide to read"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), @@ -103,6 +104,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/work", web::work::routes()) .nest("/pomodoro", web::pomodoro::routes()) .nest("/questions", web::questions::routes()) + .nest("/bank-questions", web::bank_questions::routes()) .nest("/attendance", web::attendance::routes()) .nest("/settings", web::settings::routes()) .nest("/subjects", web::subjects::routes()) diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs new file mode 100644 index 0000000..6d5734f --- /dev/null +++ b/src/web/bank_questions.rs @@ -0,0 +1,723 @@ +//! The school-wide question bank: a shared library of reusable question +//! templates. Any teacher+ reads the whole bank and instantiates any template +//! into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, in +//! `web/exams`), but only a template's owner (admins aside) may edit or delete +//! it. A template carries the same content an exam question does — text, +//! points, a `choice`/`text` spec, an optional illustration, and per-option +//! pictures — minus any exam tie: its `subject` is origin metadata only (the +//! same-course rule is checked at instantiate time against the target exam's +//! course, never here, since the bank spans courses). Instantiate and +//! save-to-bank both *copy* rows and blobs; the two sides never share one. + +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; +use axum::http::StatusCode; +use axum::response::Response; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::domain::bank_question::{BankQuestion, BankQuestionId}; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::domain::exam_question::{QuestionKind, QuestionPoints, QuestionSpec, QuestionText}; +use crate::domain::note_file::FileContentType; +use crate::domain::role::Role; +use crate::domain::settings::Settings; +use crate::domain::subject::SubjectId; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::subjects::subject_must_exist; +use super::{ + Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type, + paginate, read_upload, remove_blob, serve_inline_blob, set_or_clear, +}; + +/// Serializes bank writes that adopt a `subject` against a concurrent subject +/// delete. Bank create/update take the reader lease across their +/// subject-exists check and the insert; the subject delete-guard takes the +/// writer lease across its `any_for_subject` check and the delete, so a +/// template can't land on a subject that vanished mid-flight — the bank twin +/// of the [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards. +/// Save-to-bank (`question_to_bank`) takes the same reader lease across its +/// question read and insert: the source question can be re-tagged/deleted, so +/// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in +/// the delete path; bank writers take only this one, so no cycle. +pub(crate) static BANK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_question, list_questions)) + .routes(routes!(get_question, update_question, delete_question)) + // The image routes get their own HTTP body cap, like the exam and + // note-file ones: the server-wide hard ceiling plus multipart framing. + .merge( + OpenApiRouter::new() + .routes(routes!( + upload_question_image, + get_question_image, + delete_question_image + )) + .routes(routes!( + upload_choice_image, + get_choice_image, + delete_choice_image + )) + .layer(DefaultBodyLimit::max( + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, + )), + ) +} + +#[derive(Deserialize, ToSchema)] +struct CreateBankQuestion { + /// The subject this template came from — origin metadata only. Any of the + /// school's subjects; it is *not* held to a course here (the bank spans + /// courses), only checked against the target exam's course when the + /// template is instantiated. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, + #[schema(example = "What is 2 + 2?")] + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + /// This template's default point value, `1`–`100`. + #[schema(example = 10)] + points: i64, + /// The options of a `choice` question (2–10 of them); omit for `text`. + choices: Option>, + /// Zero-based index of the right option; required for `choice`, absent + /// for `text`. + #[schema(example = 1)] + correct: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateBankQuestion { + /// Re-tag the template's origin subject. Omit to keep the current one. + subject_id: Option, + text: Option, + points: Option, + /// `choice` or `text`. Switching kinds needs the other fields to follow: + /// send `choices` + `correct` when moving to `choice`, explicit `null`s + /// when moving to `text`. + kind: Option, + /// Omit to keep the stored options; send `null` to drop them (text + /// questions only). Replacing or clearing the list also drops every option + /// picture — the old images belong to the old options. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option>)] + choices: Option>>, + /// Omit to keep; `null` to clear (text questions only). + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + correct: Option>, +} + +/// Filters for the bank list. +#[derive(Deserialize, IntoParams)] +struct BankQuestionFilter { + /// Narrow to templates whose origin `subject` matches this id. Omit for + /// the whole bank. + subject: Option, + /// Narrow to templates owned by this user (a user id, or `me` for the + /// caller). Omit for every owner's templates. + owner: Option, +} + +/// A bank template as its readers see it — `correct` included (teacher+ only, +/// so the answer key is theirs to see). Its images, if any, are fetched +/// through the image endpoints. +#[derive(Serialize, ToSchema)] +pub(crate) struct BankQuestionResponse { + id: String, + /// The teacher who owns the template (only they, or an admin, may edit it). + owner: String, + /// The origin subject (metadata only — not enforced against a course). + subject: String, + text: String, + /// `choice` or `text`. + #[schema(example = "choice")] + kind: String, + points: i64, + choices: Option>, + /// Zero-based index of the right option (`choice` templates only). + correct: Option, + /// The template's illustration, if one was uploaded (any kind). + image: Option, + /// Per-option pictures, aligned with `choices` (`choice` templates only). + choice_images: Option>>, + /// The exam this template was saved off, if any (a direct-authored + /// template has none). + source_exam: Option, + /// When the template was saved, UTC unix-milliseconds. + created_at: i64, +} + +impl BankQuestionResponse { + pub(crate) fn new(question: &BankQuestion, images: &[BankQuestionImage]) -> Self { + Self { + id: question.get_id().key().to_string(), + owner: question.get_owner().key().to_string(), + subject: question.get_subject().key().to_string(), + text: question.get_text().as_str().to_string(), + kind: question.get_kind().as_str().to_string(), + points: question.get_points().as_i64(), + choices: question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + correct: question.get_correct(), + image: bank_image_meta(images, None), + choice_images: bank_choice_image_metas(question, images), + source_exam: question.get_source_exam().map(|e| e.key().to_string()), + created_at: question.get_created_at().as_millis(), + } + } +} + +/// The template's slot out of its image rows. +fn bank_image_meta(images: &[BankQuestionImage], slot: Option) -> Option { + images + .iter() + .find(|image| image.get_slot() == slot) + .map(BankImageMeta::new) +} + +/// The per-choice metas, aligned index-for-index with `choices` (`None` +/// entries = that option has no picture); `None` whole for text templates. +fn bank_choice_image_metas( + question: &BankQuestion, + images: &[BankQuestionImage], +) -> Option>> { + question.get_choices().map(|choices| { + (0..choices.len() as i64) + .map(|index| bank_image_meta(images, Some(index))) + .collect() + }) +} + +/// Every bank image row bucketed by template key — one query feeding a whole +/// template list (avoids an image query per row). +async fn bank_images_by_question( + db: &crate::database::Database, +) -> Result>, AppError> { + let mut buckets: HashMap> = HashMap::new(); + for image in BankQuestionImage::list_all(db).await? { + buckets + .entry(image.get_bank_question().key().to_string()) + .or_default() + .push(image); + } + Ok(buckets) +} + +/// A stored bank image's metadata; the bytes come from the image endpoints. +#[derive(Serialize, ToSchema)] +struct BankImageMeta { + #[schema(example = "image/png")] + content_type: String, + #[schema(example = 24_576)] + size: i64, +} + +impl BankImageMeta { + fn new(image: &BankQuestionImage) -> Self { + Self { + content_type: image.get_content_type().as_str().to_string(), + size: image.get_size(), + } + } +} + +/// The template, or a 404. +async fn question_or_404(st: &AppState, bid: &str) -> Result { + BankQuestion::read(&BankQuestionId::from_key(bid), &st.db) + .await? + .ok_or(AppError::NotFound) +} + +/// Reads are school-wide, but a mutation needs ownership: the caller owns the +/// template, or is an admin. Everyone else gets a 403. +fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> { + if question.get_owner() == user.get_id() || user.get_role().at_least(Role::Admin) { + return Ok(()); + } + Err(AppError::Forbidden( + "only the template's owner or an admin can change it", + )) +} + +/// The template, provided the caller may edit it — the shared front half of +/// every owner-gated write (PATCH, delete, image writes). +async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result { + let question = question_or_404(st, bid).await?; + ensure_owner(&question, user)?; + Ok(question) +} + +/// The whole bank-image write tail: new blob to disk, row UPSERT (the +/// deterministic per-slot id makes it a replace), then the replaced blob off +/// disk. A failed row write takes the fresh blob back out. +pub(crate) async fn store_image( + st: &AppState, + question: &BankQuestionId, + slot: Option, + content_type: FileContentType, + data: &[u8], +) -> Result { + let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?; + let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); + let path = blob_path(&st.files_path, image.get_file()); + tokio::fs::write(&path, data) + .await + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; + match image.upsert(&st.db).await { + Ok(stored) => { + if let Some(replaced) = replaced { + remove_blob(&st.files_path, replaced.get_file()).await; + } + Ok(stored) + } + Err(err) => { + let _ = tokio::fs::remove_file(&path).await; + Err(err) + } + } +} + +/// Add a template to the bank. Requires teacher+. `subject_id` is origin +/// metadata (any subject — the same-course rule lives at instantiate time), +/// so it need only exist (an unknown subject is a `400`). `choice` templates +/// carry 2–10 `choices` plus the `correct` index; `text` templates carry +/// neither. The caller becomes the owner. +#[utoipa::path( + post, + path = "/", + tag = "bank", + security(("session_cookie" = [])), + request_body = CreateBankQuestion, + responses( + (status = 201, description = "Template created", body = BankQuestionResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn create_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + // Reader lease of [`BANK_LOCK`]: the exists-check and the insert are one + // unit, so a subject delete can't slip between them (see the lock's doc). + let _guard = BANK_LOCK.read().await; + // Origin metadata only — no course to check it against, but it must exist. + let subject = subject_must_exist(&req.subject_id, &st.db).await?; + let text = QuestionText::try_new(&req.text)?; + let points = QuestionPoints::try_new(req.points)?; + let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; + let question = + BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(BankQuestionResponse::new(&question, &[])), + )) +} + +/// The whole bank, school-wide, in creation order — every teacher+ reads every +/// template. `?subject=` narrows to one origin subject; `?owner=` to one owner +/// (a user id, or `me` for the caller). Paged via `?limit=&offset=` (omit +/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/", + tag = "bank", + security(("session_cookie" = [])), + params(BankQuestionFilter, PageParams), + responses( + (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn list_questions( + State(st): State, + RequireTeacher(user): RequireTeacher, + Query(filter): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let mut questions = BankQuestion::list(&st.db).await?; + if let Some(ref subject) = filter.subject { + let subject = SubjectId::from_key(subject); + questions.retain(|question| question.get_subject() == &subject); + } + if let Some(ref owner) = filter.owner { + let owner = if owner == "me" { + user.get_id().clone() + } else { + UserId::from_key(owner) + }; + questions.retain(|question| question.get_owner() == &owner); + } + let total = questions.len() as i64; + // One image query for the whole bank, bucketed by template — no per-row + // fetch on the page. + let buckets = bank_images_by_question(&st.db).await?; + let empty: Vec = Vec::new(); + let items = paginate(&questions, limit, offset) + .iter() + .map(|question| { + let images = buckets.get(question.get_id().key()).unwrap_or(&empty); + BankQuestionResponse::new(question, images) + }) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// One template by id. School-wide — any teacher+ reads any template. +#[utoipa::path( + get, + path = "/{bid}", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + responses( + (status = 200, description = "The template", body = BankQuestionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such template", body = ErrorResponse), + ), +)] +async fn get_question( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path(bid): Path, +) -> Result, AppError> { + let question = question_or_404(&st, &bid).await?; + let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; + Ok(Json(BankQuestionResponse::new(&question, &images))) +} + +/// Edit a template. Owner only (admins aside — 403 otherwise). Omitted fields +/// keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so +/// a kind switch must bring the matching fields along. Replacing or clearing +/// `choices` drops the old options' pictures. Bank templates never freeze — +/// they have no exam tie. +#[utoipa::path( + patch, + path = "/{bid}", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + request_body = UpdateBankQuestion, + responses( + (status = 200, description = "Updated template", body = BankQuestionResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template", body = ErrorResponse), + ), +)] +async fn update_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(bid): Path, + Json(req): Json, +) -> Result, AppError> { + let question = owned_question(&st, &user, &bid).await?; + + // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a + // re-tag to a subject that's being deleted can't straddle the delete-guard. + let _guard = BANK_LOCK.read().await; + let subject = match req.subject_id { + Some(ref subject_id) => subject_must_exist(subject_id, &st.db).await?, + None => question.get_subject().clone(), + }; + let text = match req.text { + Some(ref text) => QuestionText::try_new(text)?, + None => question.get_text().clone(), + }; + let points = match req.points { + Some(points) => QuestionPoints::try_new(points)?, + None => question.get_points(), + }; + // Merge the kind-dependent fields (set / clear / keep per field), then + // re-validate them as a unit — a PATCH can't leave a half-question behind. + let kind = match req.kind { + Some(ref kind) => QuestionKind::try_new(kind)?, + None => question.get_kind().clone(), + }; + let choices_replaced = req.choices.is_some(); + let choices = match req.choices { + Some(update) => update, + None => question + .get_choices() + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), + }; + let correct = match req.correct { + Some(update) => update, + None => question.get_correct(), + }; + let spec = QuestionSpec::try_new(kind, choices, correct)?; + + let bid = question.get_id().clone(); + let updated = question.update(subject, text, points, spec, &st.db).await?; + // A replaced (or cleared) choice list orphans the old options' pictures — + // drop them all; the template's own illustration stays. + if choices_replaced { + for image in BankQuestionImage::delete_choices_for(&bid, &st.db).await? { + remove_blob(&st.files_path, image.get_file()).await; + } + } + let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?; + Ok(Json(BankQuestionResponse::new(&updated, &images))) +} + +/// Delete a template. Owner only (admins aside). Cascades its image rows and +/// takes their blobs off disk. +#[utoipa::path( + delete, + path = "/{bid}", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template", body = ErrorResponse), + ), +)] +async fn delete_question( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(bid): Path, +) -> Result { + let question = owned_question(&st, &user, &bid).await?; + // Rows go first (the delete cascades the image rows), blobs after — a crash + // in between strands at worst an unreachable blob. + let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; + question.delete(&st.db).await?; + for image in &images { + remove_blob(&st.files_path, image.get_file()).await; + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- template images -------------------------------------------------------- +// A template may carry one illustration (any kind) and, on choice templates, +// one picture per option — mirroring exam question images, minus the exam tie +// and the freeze. Mutations are owner-gated; reads are school-wide (teacher+). + +/// Attach (or replace) a template's illustration. Owner only (admins aside). +/// `multipart/form-data` with the image under a `file` field; the declared +/// content type must be `image/png`, `image/jpeg`, `image/webp`, or +/// `image/gif` (rasters only — no SVG), the bytes at most the school's +/// `max_file_bytes` (settings). +#[utoipa::path( + post, + path = "/{bid}/image", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = BankImageMeta), + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(bid): Path, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let question = owned_question(&st, &user, &bid).await?; + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + let stored = store_image(&st, question.get_id(), None, content_type, &upload.data).await?; + Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) +} + +/// A template's illustration bytes. School-wide — any teacher+ reads it. +#[utoipa::path( + get, + path = "/{bid}/image", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such template or image", body = ErrorResponse), + ), +)] +async fn get_question_image( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path(bid): Path, +) -> Result { + let question = question_or_404(&st, &bid).await?; + let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} + +/// Remove a template's illustration. Owner only (admins aside). +#[utoipa::path( + delete, + path = "/{bid}/image", + tag = "bank", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Bank question id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template or image", body = ErrorResponse), + ), +)] +async fn delete_question_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(bid): Path, +) -> Result { + let question = owned_question(&st, &user, &bid).await?; + let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + Ok(StatusCode::NO_CONTENT) +} + +/// Attach (or replace) one option's picture on a `choice` template. Owner only +/// (admins aside). Same form, limits, and rules as the illustration upload; +/// `index` is the option's zero-based position. Replacing the `choices` list +/// drops all its option pictures. +#[utoipa::path( + post, + path = "/{bid}/choices/{index}/image", + tag = "bank", + security(("session_cookie" = [])), + params( + ("bid" = String, Path, description = "Bank question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + request_body(content = UploadFileForm, content_type = "multipart/form-data"), + responses( + (status = 201, description = "Image stored", body = BankImageMeta), + (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text template, or an index past the choices", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template", body = ErrorResponse), + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), + ), +)] +async fn upload_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((bid, index)): Path<(String, i64)>, + mut multipart: Multipart, +) -> Result<(StatusCode, Json), AppError> { + let question = owned_question(&st, &user, &bid).await?; + let Some(choices) = question.get_choices() else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "index", + reason: "only choice questions take option pictures", + })); + }; + if !(0..choices.len() as i64).contains(&index) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "index", + reason: "must index one of the choices", + })); + } + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); + let upload = read_upload(&mut multipart, limit).await?; + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; + let stored = store_image( + &st, + question.get_id(), + Some(index), + content_type, + &upload.data, + ) + .await?; + Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) +} + +/// One option's picture bytes. School-wide — any teacher+ reads it. +#[utoipa::path( + get, + path = "/{bid}/choices/{index}/image", + tag = "bank", + security(("session_cookie" = [])), + params( + ("bid" = String, Path, description = "Bank question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + responses( + (status = 200, description = "The image bytes", content_type = "image/*"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such template or image", body = ErrorResponse), + ), +)] +async fn get_choice_image( + State(st): State, + RequireTeacher(_user): RequireTeacher, + Path((bid, index)): Path<(String, i64)>, +) -> Result { + let question = question_or_404(&st, &bid).await?; + let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) + .await? + .ok_or(AppError::NotFound)?; + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await +} + +/// Remove one option's picture. Owner only (admins aside). +#[utoipa::path( + delete, + path = "/{bid}/choices/{index}/image", + tag = "bank", + security(("session_cookie" = [])), + params( + ("bid" = String, Path, description = "Bank question id"), + ("index" = i64, Path, description = "Zero-based choice index"), + ), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), + (status = 404, description = "No such template or image", body = ErrorResponse), + ), +)] +async fn delete_choice_image( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((bid, index)): Path<(String, i64)>, +) -> Result { + let question = owned_question(&st, &user, &bid).await?; + let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let image = image.delete(&st.db).await?; + remove_blob(&st.files_path, image.get_file()).await; + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/exams.rs b/src/web/exams.rs index 205898b..2307839 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -12,6 +12,8 @@ use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; +use crate::domain::bank_question::{BankQuestion, BankQuestionId}; +use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ @@ -33,6 +35,7 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use super::bank_questions::BankQuestionResponse; use super::courses::{can_manage_course, can_view_course, visible_courses}; use super::subjects::subject_in_course; use super::{ @@ -76,6 +79,8 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(exam_live)) .routes(routes!(create_question, list_questions)) .routes(routes!(update_question, delete_question)) + .routes(routes!(question_from_bank)) + .routes(routes!(question_to_bank)) .routes(routes!(attempt_questions)) .routes(routes!(save_answer)) .routes(routes!(attempt_answers)) @@ -1427,6 +1432,8 @@ struct QuestionResponse { image: Option, /// Per-option pictures, aligned with `choices` (`choice` questions only). choice_images: Option>>, + /// The bank template this question was instantiated from, if any. + source_bank: Option, } impl QuestionResponse { @@ -1444,6 +1451,7 @@ impl QuestionResponse { correct: question.get_correct(), image: image_meta(images, None), choice_images: choice_image_metas(question, images), + source_bank: question.get_source_bank().map(|b| b.key().to_string()), } } } @@ -1731,6 +1739,227 @@ async fn delete_question( Ok(StatusCode::NO_CONTENT) } +// ---- question bank bridge --------------------------------------------------- +// Two copy funnels between an exam's questions and the school-wide bank +// (`web/bank_questions`): instantiate a template into this exam, or save one of +// this exam's questions back into the bank. Both COPY the row and every image +// blob to fresh ids/files — the source side is never touched or shared. + +#[derive(Deserialize, ToSchema)] +struct InstantiateFromBank { + /// The subject to file the new question under — one of the exam's course's + /// subjects (the same-course rule the bank row itself is exempt from). + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, +} + +/// Instantiate a bank template into this exam as a fresh question. Requires +/// teacher+ and management rights over the exam's course. `subject_id` must +/// name one of the course's subjects — the template's own subject is origin +/// metadata and does not carry over. The template (and its blobs) stay +/// untouched; a full copy — text, points, spec, illustration, and option +/// pictures — lands under a new question id. Locked once attempts exist. +#[utoipa::path( + post, + path = "/{id}/questions/from-bank/{bid}", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("bid" = String, Path, description = "Bank question id"), + ), + request_body = InstantiateFromBank, + responses( + (status = 201, description = "Question created from the template", body = QuestionResponse), + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such bank template", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + ), +)] +async fn question_from_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, bid)): Path<(String, String)>, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can author questions", + )); + } + // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and the + // create are one unit — same reasoning as `create_question`. + let _guard = EXAM_LOCK.write().await; + ensure_questions_editable(exam.get_id(), &st.db).await?; + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + + let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let question = ExamQuestion::create_from_bank( + exam.get_id(), + subject, + template.get_text().clone(), + template.get_points(), + template.spec(), + template.get_id().clone(), + &st.db, + ) + .await?; + + // Copy each of the template's image blobs to a fresh file under the new + // question + same slot (file before row, via `store_image`). A missing + // source blob is server-side damage, surfaced as a 500 — not silently lost. + // The copy is all-or-nothing: any mid-loop failure rolls back the fresh + // question row (its cascade drops the copied image rows) and the blobs + // written so far, leaving the source and destination untouched. + let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let mut copied: Vec = Vec::new(); + for source in &sources { + let step = async { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for bank image {}: {err}", + source.get_file() + )) + })?; + store_image( + &st, + &exam, + &question, + source.get_slot(), + source.get_content_type().clone(), + &bytes, + ) + .await + }; + match step.await { + Ok(image) => copied.push(image.get_file().to_string()), + Err(err) => { + for file in &copied { + remove_blob(&st.files_path, file).await; + } + let _ = question.delete(&st.db).await; + return Err(err); + } + } + } + let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(QuestionResponse::new(&question, &images)), + )) +} + +/// Save one of this exam's questions into the school-wide bank as a reusable +/// template. Requires teacher+ and management rights over the exam's course. +/// The caller becomes the template's owner; the question's subject rides along +/// as origin metadata. A full copy — text, points, spec, illustration, and +/// option pictures — lands under a new bank id; the exam question is untouched. +/// The origin exam is recorded on the template as `source_exam`. +#[utoipa::path( + post, + path = "/{id}/questions/{qid}/to-bank", + tag = "exams", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Exam id"), + ("qid" = String, Path, description = "Question id"), + ), + responses( + (status = 201, description = "Template saved to the bank", body = BankQuestionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), + ), +)] +async fn question_to_bank( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, qid)): Path<(String, String)>, +) -> Result<(StatusCode, Json), AppError> { + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", + )); + } + // Reader lease of [`BANK_LOCK`] across the question read and the insert: the + // template adopts the question's subject, and a re-tag/delete of this + // question could otherwise let that subject's delete-guard slip between the + // read and our insert (its `any_for_subject` check runs under BANK_LOCK's + // writer lease, so holding the reader lease forces it to see our new row). + let _bank_guard = super::bank_questions::BANK_LOCK.read().await; + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + + // `create_from_exam` mints its own id and insert (the funnel), fed the + // question's fields plus the origin exam it was saved off. + let template = BankQuestion::create_from_exam( + user.get_id().clone(), + question.get_subject().clone(), + question.get_text().clone(), + question.get_points(), + question.spec(), + exam.get_id().clone(), + &st.db, + ) + .await?; + + // Copy every image blob (illustration + option pictures) to a fresh file + // under the new bank row + same slot (file before row). All-or-nothing: a + // mid-loop failure rolls back the fresh bank row (cascade drops the copied + // image rows) and the blobs written so far; the source exam question stays + // untouched. + let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; + let mut copied: Vec = Vec::new(); + for source in &sources { + let step = async { + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) + .await + .map_err(|err| { + AppError::Internal(format!( + "missing blob for question image {}: {err}", + source.get_file() + )) + })?; + super::bank_questions::store_image( + &st, + template.get_id(), + source.get_slot(), + source.get_content_type().clone(), + &bytes, + ) + .await + }; + match step.await { + Ok(image) => copied.push(image.get_file().to_string()), + Err(err) => { + for file in &copied { + remove_blob(&st.files_path, file).await; + } + let _ = template.delete(&st.db).await; + return Err(err); + } + } + } + let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(BankQuestionResponse::new(&template, &images)), + )) +} + // ---- question images ---------------------------------------------------------- // A question may carry one illustration (any kind — the map above the prompt) // and, on choice questions, one picture per option (pick the right city off diff --git a/src/web/mod.rs b/src/web/mod.rs index bd87776..9883936 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -7,6 +7,7 @@ pub mod ai; pub mod appointments; pub mod attendance; pub mod auth; +pub mod bank_questions; pub mod chatbot; pub mod courses; pub mod events; diff --git a/src/web/subjects.rs b/src/web/subjects.rs index 00e3da4..aef4694 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; +use crate::domain::bank_question::BankQuestion; use crate::domain::course::{Course, CourseId}; use crate::domain::exam_question::ExamQuestion; use crate::domain::homework::Homework; @@ -15,6 +16,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course}; +use super::bank_questions::BANK_LOCK; use super::exams::EXAM_LOCK; use super::homework::HOMEWORK_LOCK; use super::{CurrentUser, RequireTeacher, SubjectResponse}; @@ -54,6 +56,21 @@ pub(crate) async fn subject_in_course( Ok(subject.get_id().clone()) } +/// Turn a request-supplied subject id into a validated reference, checking only +/// that the subject exists — no course tie. For the question bank, whose subject +/// is cross-course origin metadata: the same-course rule applies at instantiate +/// time, not here. An unknown subject is a `400` naming the field. +pub(crate) async fn subject_must_exist(id: &str, db: &Database) -> Result { + let subject = + Subject::read(&SubjectId::from_key(id), db) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }))?; + Ok(subject.get_id().clone()) +} + /// The subject plus its course, or a 404 — every handler here gates on the /// parent course, so they always travel together. async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { @@ -141,9 +158,9 @@ async fn update_subject( } /// Delete a subject. Requires teacher+ and management rights over its course. -/// Refused with a 409 while any exam question or homework still references it — -/// re-tag or delete those first, so nothing is left pointing at a subject that -/// no longer exists. +/// Refused with a 409 while any exam question, homework, or bank question still +/// references it — re-tag or delete those first, so nothing is left pointing at +/// a subject that no longer exists. #[utoipa::path( delete, path = "/{id}", @@ -155,7 +172,7 @@ async fn update_subject( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse), + (status = 409, description = "Exam questions, homework, or bank questions still reference this subject", body = ErrorResponse), ), )] async fn delete_subject( @@ -190,6 +207,18 @@ async fn delete_subject( "homework still references this subject — re-tag or delete it first", )); } + // Bank templates carry this subject as origin metadata; a deleted subject + // would leave them pointing at nothing. Writer lease of [`BANK_LOCK`], the + // bank twin of the two guards above: bank create/update validate their + // subject and insert under the reader lease, so the no-templates check and + // the delete can't straddle a template that just adopted this subject. Held + // last; the order is EXAM_LOCK, then HOMEWORK_LOCK, then BANK_LOCK. + let _bank_guard = BANK_LOCK.write().await; + if BankQuestion::any_for_subject(subject.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "bank questions still reference this subject — re-tag or delete them first", + )); + } subject.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/integration.rs b/tests/integration.rs index bd6a034..26908a6 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10626,6 +10626,17 @@ async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec>(0).unwrap() } +/// Every stored bank-question-image blob name, straight from the table. +async fn bank_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec { + let mut result = db + .query("SELECT VALUE file FROM bank_question_image") + .await + .unwrap() + .check() + .unwrap(); + result.take::>(0).unwrap() +} + /// Every stored answer-image (student drawing) blob name, straight from the table. async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec { let mut result = db @@ -16671,3 +16682,729 @@ async fn self_review_is_own_scoped_between_students() { assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer"); assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer"); } + +// --- question bank ----------------------------------------------------------- + +#[tokio::test] +async fn bank_question_create_get_list_and_instantiate() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bank_t", "teacher").await; + let course = create_course(&app, &teacher, "algebra").await; + let subject = create_subject(&app, &teacher, &course, "linear").await; + + // Create a template — subject is origin metadata, not held to a course. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", + "points": 10, "choices": ["3", "4", "5"], "correct": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["kind"], "choice"); + assert_eq!(res.body["correct"], 1); + assert_eq!(res.body["subject"], subject); + let bid = id_of(&res.body); + + // School-wide read + list. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["text"], "2 + 2?"); + let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await; + assert_eq!(common::items(&res.body).len(), 1); + + // `?subject=` matches, and a foreign id excludes. + let res = send(&app, "GET", &format!("/bank-questions?subject={subject}"), Some(&teacher), None).await; + assert_eq!(common::items(&res.body).len(), 1); + let res = send(&app, "GET", "/bank-questions?subject=nope", Some(&teacher), None).await; + assert_eq!(common::items(&res.body).len(), 0); + + // Instantiate into an exam under one of the course's subjects. + let now = Timestamp::now().as_millis(); + let exam = scheduled_exam( + &app, + &teacher, + &course, + json!({ "title": "midterm", "kind": "final", "mode": "sync", + "starts_at": now - 1_000, "ends_at": now + 600_000 }), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["exam"], exam); + assert_eq!(res.body["subject"], subject); + assert_eq!(res.body["correct"], 1); + assert_eq!(res.body["choices"][1], "4"); + + // The copy is independent — the template still stands. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); +} + +#[tokio::test] +async fn bank_question_owner_gate_cross_course_and_freeze() { + let (app, db) = app_and_db().await; + let owner = login_as(&app, &db, "bank_o", "teacher").await; + let other = login_as(&app, &db, "bank_x", "teacher").await; + let admin = login_as(&app, &db, "bank_a", "admin").await; + + let course = create_course(&app, &owner, "geo").await; + let subject = create_subject(&app, &owner, &course, "angles").await; + let res = send( + &app, + "POST", + "/bank-questions", + Some(&owner), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + let bid = id_of(&res.body); + + // A non-owner teacher reads it, but may not edit or delete. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::OK); + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&other), Some(json!({ "points": 7 }))).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&other), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + // Admin bypasses ownership. + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&admin), Some(json!({ "points": 7 }))).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["points"], 7); + + // Instantiate with a subject from ANOTHER course is a 400. + let course2 = create_course(&app, &owner, "chem").await; + let subject2 = create_subject(&app, &owner, &course2, "bonds").await; + let now = Timestamp::now().as_millis(); + let exam = scheduled_exam( + &app, + &owner, + &course, + json!({ "title": "t", "kind": "final", "mode": "sync", + "starts_at": now - 1_000, "ends_at": now + 600_000 }), + ) + .await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&owner), + Some(json!({ "subject_id": subject2 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // Once a student sits the exam, instantiate freezes (409). + let student = login(&app, "sinem").await; + let student_id = me_id(&app, &student).await; + enroll(&app, &owner, &course, &student_id).await; + let res = send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&owner), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); +} + +#[tokio::test] +async fn exam_question_saves_to_bank() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "s2b_t", "teacher").await; + let course = create_course(&app, &teacher, "phys").await; + let subject = create_subject(&app, &teacher, &course, "kinematics").await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), + ) + .await; + + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["text"], "v=?"); + assert_eq!(res.body["correct"], 0); + assert_eq!(res.body["subject"], subject); + assert_eq!(res.body["owner"], me_id(&app, &teacher).await); + let bid = id_of(&res.body); + + // It now lives in the school-wide bank. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); +} + +/// Instantiating a bank template copies its image blobs to fresh files under the +/// new exam question, byte-for-byte, and leaves the source template's images +/// untouched. +#[tokio::test] +async fn bank_instantiate_copies_images() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bimg_t", "teacher").await; + let course = create_course(&app, &teacher, "geo1").await; + let subject = create_subject(&app, &teacher, &course, "maps1").await; + + // A choice template with an illustration and one option picture. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice", + "points": 10, "choices": ["Ankara", "İzmir"], "correct": 0 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + + let illus = b"bank-illustration".as_slice(); + let choice = b"bank-choice-pic".as_slice(); + let (status, _) = + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", illus).await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/choices/0/image"), + "image/webp", + choice, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let src_bank_keys = bank_image_blob_keys(&db).await; + assert_eq!(src_bank_keys.len(), 2); + + // Instantiate into an exam. + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let qid = id_of(&res.body); + + // Both images retrievable on the new exam question, bytes equal to source. + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/exams/{exam}/questions/{qid}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, illus); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/exams/{exam}/questions/{qid}/choices/0/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, choice); + + // Copies are fresh files — new keys, none shared with the bank. + let exam_keys = image_blob_keys(&db).await; + assert_eq!(exam_keys.len(), 2); + for k in &exam_keys { + assert!(!src_bank_keys.contains(k), "copied blob reused a source file"); + } + + // Source bank images untouched — still 200 with the same bytes and keys. + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{bid}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, illus); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{bid}/choices/0/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, choice); + assert_eq!(bank_image_blob_keys(&db).await, src_bank_keys, "source keys changed"); +} + +/// Saving an exam question to the bank copies its image blobs to fresh files +/// under the new template, byte-for-byte, source exam images untouched. +#[tokio::test] +async fn bank_save_copies_images() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "simg_t", "teacher").await; + let course = create_course(&app, &teacher, "phys1").await; + let subject = create_subject(&app, &teacher, &course, "kin1").await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), + ) + .await; + + let illus = b"exam-illustration".as_slice(); + let choice = b"exam-choice-pic".as_slice(); + let (status, _) = post_image( + &app, + &teacher, + &format!("/exams/{exam}/questions/{qid}/image"), + "image/png", + illus, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &teacher, + &format!("/exams/{exam}/questions/{qid}/choices/0/image"), + "image/jpeg", + choice, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + let src_exam_keys = image_blob_keys(&db).await; + assert_eq!(src_exam_keys.len(), 2); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/{qid}/to-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + + // The new bank question carries both images, bytes equal. + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{bid}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, illus); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/bank-questions/{bid}/choices/0/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, choice); + + // Fresh keys; source exam images untouched. + let bank_keys = bank_image_blob_keys(&db).await; + assert_eq!(bank_keys.len(), 2); + for k in &bank_keys { + assert!(!src_exam_keys.contains(k), "copied blob reused a source file"); + } + assert_eq!(image_blob_keys(&db).await, src_exam_keys, "source keys changed"); + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/exams/{exam}/questions/{qid}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, illus); +} + +/// An image survives a full round trip: exam question -> bank -> a second exam, +/// with the bytes intact at the far end. +#[tokio::test] +async fn bank_round_trip_preserves_image_bytes() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rt_t", "teacher").await; + let course = create_course(&app, &teacher, "hist1").await; + let subject = create_subject(&app, &teacher, &course, "eras1").await; + let exam1 = create_exam(&app, &teacher, &course, "e1", "final").await; + let qid = create_question( + &app, + &teacher, + &exam1, + &subject, + json!({ "text": "When?", "kind": "text", "points": 10 }), + ) + .await; + let pic = b"round-trip-illustration".as_slice(); + let (status, _) = post_image( + &app, + &teacher, + &format!("/exams/{exam1}/questions/{qid}/image"), + "image/png", + pic, + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + // Hop one: exam -> bank. + let res = send( + &app, + "POST", + &format!("/exams/{exam1}/questions/{qid}/to-bank"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + + // Hop two: bank -> a second exam. + let exam2 = create_exam(&app, &teacher, &course, "e2", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam2}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let qid2 = id_of(&res.body); + + let (status, _, bytes) = common::send_raw( + &app, + "GET", + &format!("/exams/{exam2}/questions/{qid2}/image"), + Some(&teacher), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(bytes, pic, "bytes drifted across the round trip"); +} + +/// Gap-1 guard: a missing source blob mid-copy is all-or-nothing — the +/// instantiate 500s and leaves NO partial destination (no exam question row, no +/// exam image rows), while the source template survives intact. +#[tokio::test] +async fn bank_instantiate_rolls_back_on_missing_source_blob() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "rb_t", "teacher").await; + let course = create_course(&app, &teacher, "geo2").await; + let subject = create_subject(&app, &teacher, &course, "maps2").await; + + // Two images so the copy loop has multiple steps. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", + "points": 10, "choices": ["a", "b"], "correct": 0 })), + ) + .await; + let bid = id_of(&res.body); + let (status, _) = + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/choices/0/image"), + "image/png", + b"opt", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + // Corrupt the source on disk: delete one blob so the copy loop hits an + // unreadable source mid-flight. + let src_keys = bank_image_blob_keys(&db).await; + assert_eq!(src_keys.len(), 2); + tokio::fs::remove_file(common::files_dir().join(&src_keys[0])) + .await + .unwrap(); + + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body); + + // No partial destination: no question row, no exam image rows (isolated + // per-test DB is the race-safe source of truth; the shared parallel blob + // dir rules out an exact on-disk diff). + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert!( + common::items(&res.body).is_empty(), + "orphan question survived rollback" + ); + assert!( + image_blob_keys(&db).await.is_empty(), + "orphan exam image rows survived rollback" + ); + + // Source intact: the template still reads, and its surviving blob is still + // on disk. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(bank_image_blob_keys(&db).await, src_keys, "source bank rows changed"); + assert!( + common::files_dir().join(&src_keys[1]).exists(), + "surviving source blob vanished" + ); +} + +/// A bank template's subject is origin metadata, but it must still exist: +/// create and update both 400 on an unknown subject id. +#[tokio::test] +async fn bank_rejects_unknown_subject() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bsub_t", "teacher").await; + let course = create_course(&app, &teacher, "bsub_c").await; + let subject = create_subject(&app, &teacher, &course, "bsub_s").await; + + // Create with a bogus subject id — 400, not a stored row. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": "nope", "text": "q", "kind": "text", "points": 5 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // Create a real one, then PATCH its subject to a bogus id — also 400. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + let bid = id_of(&res.body); + let res = send( + &app, + "PATCH", + &format!("/bank-questions/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": "nope" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} + +/// A subject with bank templates referencing it can't be deleted (409) until +/// those templates are gone — mirrors the exam-question / homework guard. +#[tokio::test] +async fn subject_delete_blocked_by_bank_question() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bdel_t", "teacher").await; + let course = create_course(&app, &teacher, "bdel_c").await; + let subject = create_subject(&app, &teacher, &course, "bdel_s").await; + + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + let bid = id_of(&res.body); + + // Guarded while the template stands. + let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // Drop the template — the subject frees up. + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// `?owner=me` (and an explicit owner id) narrows the school-wide bank to one +/// owner's templates. +#[tokio::test] +async fn bank_owner_filter() { + let (app, db) = app_and_db().await; + let alice = login_as(&app, &db, "bown_a", "teacher").await; + let bob = login_as(&app, &db, "bown_b", "teacher").await; + let course = create_course(&app, &alice, "bown_c").await; + let subject = create_subject(&app, &alice, &course, "bown_s").await; + + for who in [&alice, &bob] { + send( + &app, + "POST", + "/bank-questions", + Some(who), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + } + let alice_id = me_id(&app, &alice).await; + let bob_id = me_id(&app, &bob).await; + + // Whole bank has both. + let res = send(&app, "GET", "/bank-questions", Some(&alice), None).await; + assert_eq!(common::items(&res.body).len(), 2); + + // `me` resolves to the caller. + let res = send(&app, "GET", "/bank-questions?owner=me", Some(&alice), None).await; + let items = common::items(&res.body); + assert_eq!(items.len(), 1); + assert_eq!(items[0]["owner"], alice_id); + + // An explicit id filters to that owner. + let res = send(&app, "GET", &format!("/bank-questions?owner={bob_id}"), Some(&alice), None).await; + let items = common::items(&res.body); + assert_eq!(items.len(), 1); + assert_eq!(items[0]["owner"], bob_id); +} + +/// A template's response carries its image metadata (illustration + per-choice +/// slots) once images are uploaded — the same shape the exam side returns. +#[tokio::test] +async fn bank_response_carries_image_metas() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bmeta_t", "teacher").await; + let course = create_course(&app, &teacher, "bmeta_c").await; + let subject = create_subject(&app, &teacher, &course, "bmeta_s").await; + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", + "points": 10, "choices": ["a", "b"], "correct": 0 })), + ) + .await; + let bid = id_of(&res.body); + + // No images yet: metas are null / all-empty. + assert!(res.body["image"].is_null()); + assert_eq!(res.body["choice_images"], json!([null, null])); + + let (status, _) = + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await; + assert_eq!(status, StatusCode::CREATED); + let (status, _) = post_image( + &app, + &teacher, + &format!("/bank-questions/{bid}/choices/0/image"), + "image/jpeg", + b"opt", + ) + .await; + assert_eq!(status, StatusCode::CREATED); + + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.body["image"]["content_type"], "image/png"); + assert_eq!(res.body["image"]["size"], 5); + assert_eq!(res.body["choice_images"][0]["content_type"], "image/jpeg"); + assert!(res.body["choice_images"][1].is_null()); + + // The list carries them too (batched, not per-row). + let res = send(&app, "GET", "/bank-questions?owner=me", Some(&teacher), None).await; + let items = common::items(&res.body); + assert_eq!(items[0]["image"]["content_type"], "image/png"); + assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg"); +} + +/// Provenance rides both directions: instantiate records `source_bank` on the +/// new exam question; save-to-bank records `source_exam` on the new template. +#[tokio::test] +async fn bank_provenance_both_directions() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bprov_t", "teacher").await; + let course = create_course(&app, &teacher, "bprov_c").await; + let subject = create_subject(&app, &teacher, &course, "bprov_s").await; + + // Bank -> exam: source_bank is the template id. + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + let bid = id_of(&res.body); + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions/from-bank/{bid}"), + Some(&teacher), + Some(json!({ "subject_id": subject })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["source_bank"], bid); + + // A directly authored exam question has no source_bank. + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "plain", "kind": "text", "points": 5 }), + ) + .await; + + // Exam -> bank: source_exam is the origin exam id. + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["source_exam"], exam); + + // A directly authored template has no source_exam. + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert!(res.body["source_exam"].is_null()); +}