Add a reusable school-wide question bank
Browse files at this commit8b07cfad172238d521da62c144afe847bcaa792bParent: 5d48a8d- feat
- add a reusable school-wide question bank
12 changed files +2386 -7
- README.md +73 -3
- src/database.rs +24 -0
- src/domain/bank_question.rs +287 -0
- src/domain/bank_question_image.rs +233 -0
- src/domain/exam_question.rs +42 -0
- src/domain/mod.rs +2 -0
- src/lib.rs +2 -0
- src/web/bank_questions.rs +723 -0
- src/web/exams.rs +229 -0
- src/web/mod.rs +1 -0
- src/web/subjects.rs +33 -4
- tests/integration.rs +737 -0
README.mdmodified+73 -3
| @@ -47,7 +47,11 @@ governed by a teacher-controlled rejoin door. Writing an exam takes a while, so | |||
| 47 | when it's ready. Questions can carry **images**: any question may hold one | 47 | when it's ready. Questions can carry **images**: any question may hold one |
| 48 | illustration (a map above the prompt), and each option of a choice question | 48 | illustration (a map above the prompt), and each option of a choice question |
| 49 | may be a picture of its own (pick the right city off the map) — raster | 49 | may be a picture of its own (pick the right city off the map) — raster |
| 50 | -uploads capped by the same `max_file_bytes` policy as note files. Teachers | 50 | +uploads capped by the same `max_file_bytes` policy as note files. Good |
| 51 | +questions get reused, so a teacher+ can bank one in a school-wide **question | ||
| 52 | +bank** — detached templates (with their own images) that any teacher copies | ||
| 53 | +into a fresh exam question across years, editable and deletable only by | ||
| 54 | +whoever saved them. Teachers | ||
| 51 | watch attendance, per-student remaining time, | 55 | watch attendance, per-student remaining time, |
| 52 | sittings, walk-outs, no-shows (`absent` once the window closes), submissions, | 56 | sittings, walk-outs, no-shows (`absent` once the window closes), submissions, |
| 53 | and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out | 57 | and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out |
| @@ -305,6 +309,8 @@ course enrollments. | |||
| 305 | | 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 | | 309 | | 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 | |
| 306 | | 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 | | 310 | | 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 | |
| 307 | | 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 | | 311 | | 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 | |
| 312 | +| 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 | | ||
| 313 | +| Edit / delete a bank question (and its images) | teacher | **Owner only** (admin bypass); bank rows carry no exam link, so they never freeze | | ||
| 308 | | Read **own** attendance report | student | | | 314 | | Read **own** attendance report | student | | |
| 309 | | 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 | | 315 | | 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 | |
| 310 | | 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 | | 316 | | 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 | |||
| 515 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | 521 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | |
| 516 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | 522 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | |
| 517 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | | 523 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | |
| 524 | +| 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) | | ||
| 525 | +| 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) | | ||
| 518 | | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) | | 526 | | GET | `/exams/{id}/attempt/questions` | student | The sitting view: no `correct`, own answers embedded, image metadata included (requires enrollment + an attempt) | |
| 519 | | 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) | | 527 | | 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) | |
| 520 | | GET | `/exams/{id}/questions/{qid}/image` | student | The illustration bytes (course manager anytime; students enrolled + attempt started) | | 528 | | 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 | |||
| 538 | | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | | 546 | | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | |
| 539 | | 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") | | 547 | | 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") | |
| 540 | | 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 | | 548 | | 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 | |
| 549 | +| GET | `/bank-questions` | teacher | The school-wide question bank — `?subject=<id>` filters by origin subject, `?owner=<id>` (or `?owner=me`) by owner; reusable templates any teacher+ can read, each with its image metas (`image`, `choice_images`) · paged | | ||
| 550 | +| 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) | | ||
| 551 | +| GET | `/bank-questions/{bid}` | teacher | Get one bank question, `correct` + image metas (`image`, `choice_images`) included (any teacher+) | | ||
| 552 | +| PATCH | `/bank-questions/{bid}` | teacher | Edit a bank question — the kind bundle revalidates as a unit (**owner only**, admin bypass; bank rows never freeze) | | ||
| 553 | +| DELETE | `/bank-questions/{bid}` | teacher | Delete a bank question + its images (**owner only**, admin bypass) | | ||
| 554 | +| 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) | | ||
| 555 | +| GET | `/bank-questions/{bid}/image` | teacher | The illustration bytes (any teacher+) | | ||
| 556 | +| DELETE | `/bank-questions/{bid}/image` | teacher | Remove the illustration (**owner only**, admin bypass) | | ||
| 557 | +| 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) | | ||
| 558 | +| GET | `/bank-questions/{bid}/choices/{index}/image` | teacher | The option picture's bytes (any teacher+) | | ||
| 559 | +| DELETE | `/bank-questions/{bid}/choices/{index}/image` | teacher | Remove one option picture (**owner only**, admin bypass) | | ||
| 541 | | 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) | | 560 | | 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) | |
| 542 | | 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 | | 561 | | 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 | |
| 543 | | GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) · paged | | 562 | | 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 | |||
| 1222 | The student's own `GET /exams/{id}/attempt` echoes the same | 1241 | The student's own `GET /exams/{id}/attempt` echoes the same |
| 1223 | `answered`/`question_count` pair. | 1242 | `answered`/`question_count` pair. |
| 1224 | 1243 | ||
| 1244 | +## Question bank | ||
| 1245 | + | ||
| 1246 | +Writing good questions is slow, and the same one gets asked year after year, so | ||
| 1247 | +the school keeps a reusable **question bank**. A bank question is an | ||
| 1248 | +`ExamQuestion` cut loose from any exam: it has the same shape (`subject_id`, | ||
| 1249 | +`text`, `kind`, `points`, and — for a `choice` — `choices` + `correct`), the | ||
| 1250 | +same image slots (one illustration, plus a picture per option), and the same | ||
| 1251 | +newtype validation, but it carries **no exam link**. Because nothing sits it, | ||
| 1252 | +a bank row **never freezes** — its owner can edit or delete it forever. | ||
| 1253 | + | ||
| 1254 | +`POST /bank-questions` (teacher+) saves one, stamping the caller as its | ||
| 1255 | +**owner**. `subject_id` is origin metadata, but it must **exist** — an unknown | ||
| 1256 | +subject is a `400` (create and PATCH alike); the reverse guard holds too, so | ||
| 1257 | +deleting a subject a template still references is a `409` (same as exam | ||
| 1258 | +questions and homework). Reads are school-wide: `GET /bank-questions` lists the | ||
| 1259 | +whole bank (paged, `?subject=<id>` narrows by origin subject, `?owner=<id>` — or | ||
| 1260 | +`?owner=me` — by owner) and `GET /bank-questions/{bid}` fetches one with | ||
| 1261 | +`correct` included — any teacher+ can browse and reuse what any colleague | ||
| 1262 | +banked. Each response carries its **image metadata** — an `image` meta for the | ||
| 1263 | +illustration and a `choice_images` array aligned with `choices` (per-slot | ||
| 1264 | +`{content_type, size}`, `null` where a slot has no picture) — the same shape an | ||
| 1265 | +exam question's response uses; the bytes still come from the image endpoints. | ||
| 1266 | +Mutation is **owner-only** (an `admin` bypasses): `PATCH /bank-questions/{bid}` | ||
| 1267 | +revalidates the kind bundle as a unit, `DELETE /bank-questions/{bid}` drops the | ||
| 1268 | +row and its image blobs. The illustration and option pictures work exactly like | ||
| 1269 | +an exam question's — `POST|GET|DELETE /bank-questions/{bid}/image` and | ||
| 1270 | +`…/choices/{index}/image`, `multipart/form-data` with one `file` part, raster | ||
| 1271 | +only (`png`/`jpeg`/`webp`/`gif`), ≤ `max_file_bytes` — reads school-wide, | ||
| 1272 | +writes owner-only. | ||
| 1273 | + | ||
| 1274 | +The bank feeds exams by **copying**, never linking. `POST | ||
| 1275 | +/exams/{id}/questions/from-bank/{bid}` instantiates a bank question into the | ||
| 1276 | +exam: it mints a **fresh** exam-scoped question (new id, its own answer rows, | ||
| 1277 | +its image blobs copied to new files), so later edits on either side never | ||
| 1278 | +touch the other. The subject on the bank row is origin metadata only — the | ||
| 1279 | +call takes its own `{subject_id}`, re-checked against the target course's | ||
| 1280 | +subjects (`400` on a cross-course subject), and instantiating into an exam | ||
| 1281 | +that already has attempts is a `409`, the same freeze that guards hand-authored | ||
| 1282 | +questions. The instantiated question records the template it came from in | ||
| 1283 | +`source_bank`. The reverse, `POST /exams/{id}/questions/{qid}/to-bank`, copies | ||
| 1284 | +an existing exam question **into** the bank (new detached row, images copied to | ||
| 1285 | +new files, owner = caller); the source question is left untouched, and the new | ||
| 1286 | +template records the origin exam in `source_exam`. Both provenance fields are | ||
| 1287 | +nullable — a hand-authored question or template carries `null` — and one-way | ||
| 1288 | +metadata (the copies stay fully detached). All bank routes are course-agnostic | ||
| 1289 | +and require teacher+. | ||
| 1290 | + | ||
| 1225 | ## Homework | 1291 | ## Homework |
| 1226 | 1292 | ||
| 1227 | A course hands out **homework**: `POST /courses/{id}/homework` with a title, | 1293 | A course hands out **homework**: `POST /courses/{id}/homework` with a title, |
| @@ -1782,6 +1848,10 @@ src/ | |||
| 1782 | metadata; bytes on disk under FILES_PATH) | 1848 | metadata; bytes on disk under FILES_PATH) |
| 1783 | answer_image.rs AnswerImageId · AnswerImage (student answer-drawing | 1849 | answer_image.rs AnswerImageId · AnswerImage (student answer-drawing |
| 1784 | metadata; bytes on disk under FILES_PATH) | 1850 | metadata; bytes on disk under FILES_PATH) |
| 1851 | + bank_question.rs BankQuestionId · BankQuestion (school-wide reusable | ||
| 1852 | + question template, copied into exams; no exam FK) | ||
| 1853 | + bank_question_image.rs BankQuestionImageId · BankQuestionImage (bank | ||
| 1854 | + question/choice picture metadata; bytes on disk under FILES_PATH) | ||
| 1785 | profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) | 1855 | profile.rs PersonName · Email · Phone · BirthDate (personal-info newtypes) |
| 1786 | preferences.rs Theme · Language (own UI preferences) | 1856 | preferences.rs Theme · Language (own UI preferences) |
| 1787 | message.rs MessageId · MessageSubject · MessageBody · MessageLabel · | 1857 | message.rs MessageId · MessageSubject · MessageBody · MessageLabel · |
| @@ -1827,8 +1897,8 @@ src/ | |||
| 1827 | page.rs PageParams · Page<T> (shared pagination) | 1897 | page.rs PageParams · Page<T> (shared pagination) |
| 1828 | auth.rs users.rs notes.rs messages.rs events.rs appointments.rs | 1898 | auth.rs users.rs notes.rs messages.rs events.rs appointments.rs |
| 1829 | courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs | 1899 | courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs |
| 1830 | - marks.rs work.rs pomodoro.rs attendance.rs settings.rs terms.rs | 1900 | + bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs |
| 1831 | - ai.rs chatbot.rs | 1901 | + settings.rs terms.rs ai.rs chatbot.rs |
| 1832 | ``` | 1902 | ``` |
| 1833 | 1903 | ||
| 1834 | Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory | 1904 | Tests: `cargo test` — unit (in-source), integration (`tower::oneshot` + in-memory |
src/database.rsmodified+24 -0
| @@ -38,6 +38,8 @@ pub const EXAM_QUESTION_TABLE: &str = "exam_question"; | |||
| 38 | pub const QUESTION_IMAGE_TABLE: &str = "question_image"; | 38 | pub const QUESTION_IMAGE_TABLE: &str = "question_image"; |
| 39 | pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; | 39 | pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; |
| 40 | pub const ANSWER_IMAGE_TABLE: &str = "answer_image"; | 40 | pub const ANSWER_IMAGE_TABLE: &str = "answer_image"; |
| 41 | +pub const BANK_QUESTION_TABLE: &str = "bank_question"; | ||
| 42 | +pub const BANK_QUESTION_IMAGE_TABLE: &str = "bank_question_image"; | ||
| 41 | pub const COURSE_TABLE: &str = "course"; | 43 | pub const COURSE_TABLE: &str = "course"; |
| 42 | pub const ENROLLMENT_TABLE: &str = "enrollment"; | 44 | pub const ENROLLMENT_TABLE: &str = "enrollment"; |
| 43 | pub const PARENT_LINK_TABLE: &str = "parent_link"; | 45 | pub const PARENT_LINK_TABLE: &str = "parent_link"; |
| @@ -274,6 +276,7 @@ const MIGRATION: &str = " | |||
| 274 | DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>; | 276 | DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>; |
| 275 | DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>; | 277 | DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>; |
| 276 | DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>; | 278 | DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>; |
| 279 | + DEFINE FIELD IF NOT EXISTS source_bank ON exam_question TYPE option<record<bank_question>>; | ||
| 277 | DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; | 280 | DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; |
| 278 | DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; | 281 | DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; |
| 279 | 282 | ||
| @@ -287,6 +290,27 @@ const MIGRATION: &str = " | |||
| 287 | DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; | 290 | DEFINE INDEX IF NOT EXISTS question_image_exam ON question_image FIELDS exam; |
| 288 | DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; | 291 | DEFINE INDEX IF NOT EXISTS question_image_question ON question_image FIELDS question; |
| 289 | 292 | ||
| 293 | + DEFINE TABLE IF NOT EXISTS bank_question SCHEMAFULL; | ||
| 294 | + DEFINE FIELD IF NOT EXISTS owner ON bank_question TYPE record<user>; | ||
| 295 | + DEFINE FIELD IF NOT EXISTS subject ON bank_question TYPE record<subject>; | ||
| 296 | + DEFINE FIELD IF NOT EXISTS text ON bank_question TYPE string; | ||
| 297 | + DEFINE FIELD IF NOT EXISTS kind ON bank_question TYPE string; | ||
| 298 | + DEFINE FIELD IF NOT EXISTS points ON bank_question TYPE int; | ||
| 299 | + DEFINE FIELD IF NOT EXISTS choices ON bank_question TYPE option<array<string>>; | ||
| 300 | + DEFINE FIELD IF NOT EXISTS correct ON bank_question TYPE option<int>; | ||
| 301 | + DEFINE FIELD IF NOT EXISTS source_exam ON bank_question TYPE option<record<exam>>; | ||
| 302 | + DEFINE FIELD IF NOT EXISTS created_at ON bank_question TYPE int READONLY; | ||
| 303 | + DEFINE INDEX IF NOT EXISTS bank_question_owner ON bank_question FIELDS owner; | ||
| 304 | + DEFINE INDEX IF NOT EXISTS bank_question_subject ON bank_question FIELDS subject; | ||
| 305 | + | ||
| 306 | + DEFINE TABLE IF NOT EXISTS bank_question_image SCHEMAFULL; | ||
| 307 | + DEFINE FIELD IF NOT EXISTS bank_question ON bank_question_image TYPE record<bank_question>; | ||
| 308 | + DEFINE FIELD IF NOT EXISTS slot ON bank_question_image TYPE option<int>; | ||
| 309 | + DEFINE FIELD IF NOT EXISTS file ON bank_question_image TYPE string; | ||
| 310 | + DEFINE FIELD IF NOT EXISTS content_type ON bank_question_image TYPE string; | ||
| 311 | + DEFINE FIELD IF NOT EXISTS size ON bank_question_image TYPE int; | ||
| 312 | + DEFINE INDEX IF NOT EXISTS bank_question_image_question ON bank_question_image FIELDS bank_question; | ||
| 313 | + | ||
| 290 | DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; | 314 | DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; |
| 291 | DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>; | 315 | DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>; |
| 292 | DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>; | 316 | DEFINE FIELD IF NOT EXISTS question ON exam_answer TYPE record<exam_question>; |
src/domain/bank_question.rsadded+287 -0
| @@ -0,0 +1,287 @@ | |||
| 1 | +//! A reusable question template in the school-wide question bank. Unlike an | ||
| 2 | +//! [`crate::domain::exam_question::ExamQuestion`], a bank row is fully detached | ||
| 3 | +//! from any exam: no exam FK, so no attempt ever freezes it, and its images | ||
| 4 | +//! live in their own [`crate::domain::bank_question_image`] slot table. Teachers | ||
| 5 | +//! save templates here and later *copy* them into an exam — the copy is a fresh | ||
| 6 | +//! `ExamQuestion` with its own id, images, and answers; the two never share a | ||
| 7 | +//! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants | ||
| 8 | +//! because every write goes through one. | ||
| 9 | + | ||
| 10 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 11 | +use ulid::Ulid; | ||
| 12 | + | ||
| 13 | +use crate::database::{BANK_QUESTION_TABLE, Database}; | ||
| 14 | +use crate::domain::exam::ExamId; | ||
| 15 | +use crate::domain::exam_question::{ | ||
| 16 | + ChoiceText, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | ||
| 17 | +}; | ||
| 18 | +use crate::domain::subject::SubjectId; | ||
| 19 | +use crate::domain::timestamp::Timestamp; | ||
| 20 | +use crate::domain::user::UserId; | ||
| 21 | +use crate::error::AppError; | ||
| 22 | + | ||
| 23 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 24 | +pub struct BankQuestionId(RecordId); | ||
| 25 | + | ||
| 26 | +impl BankQuestionId { | ||
| 27 | + pub fn generate() -> Self { | ||
| 28 | + Self(RecordId::new(BANK_QUESTION_TABLE, Ulid::new().to_string())) | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + pub fn from_key(key: &str) -> Self { | ||
| 32 | + Self(RecordId::new(BANK_QUESTION_TABLE, key)) | ||
| 33 | + } | ||
| 34 | + | ||
| 35 | + pub fn record(&self) -> RecordId { | ||
| 36 | + self.0.clone() | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + pub fn key(&self) -> &str { | ||
| 40 | + match &self.0.key { | ||
| 41 | + RecordIdKey::String(key) => key, | ||
| 42 | + _ => "", | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// One template in the shared question bank. `owner` is the teacher who saved | ||
| 48 | +/// it (the only one who may edit or delete it, admins aside); `subject` is | ||
| 49 | +/// origin metadata only — the same-course rule is checked against the caller's | ||
| 50 | +/// subject when a template is copied into an exam, not here. | ||
| 51 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 52 | +pub struct BankQuestion { | ||
| 53 | + id: BankQuestionId, | ||
| 54 | + owner: UserId, | ||
| 55 | + subject: SubjectId, | ||
| 56 | + text: QuestionText, | ||
| 57 | + kind: QuestionKind, | ||
| 58 | + points: QuestionPoints, | ||
| 59 | + choices: Option<Vec<ChoiceText>>, | ||
| 60 | + correct: Option<i64>, | ||
| 61 | + /// The exam question this template was saved from, if any. | ||
| 62 | + source_exam: Option<ExamId>, | ||
| 63 | + created_at: Timestamp, | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +impl BankQuestion { | ||
| 67 | + pub fn get_id(&self) -> &BankQuestionId { | ||
| 68 | + &self.id | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + pub fn get_owner(&self) -> &UserId { | ||
| 72 | + &self.owner | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + pub fn get_subject(&self) -> &SubjectId { | ||
| 76 | + &self.subject | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub fn get_text(&self) -> &QuestionText { | ||
| 80 | + &self.text | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + pub fn get_kind(&self) -> &QuestionKind { | ||
| 84 | + &self.kind | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + pub fn get_points(&self) -> QuestionPoints { | ||
| 88 | + self.points | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + pub fn get_choices(&self) -> Option<&[ChoiceText]> { | ||
| 92 | + self.choices.as_deref() | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + pub fn get_correct(&self) -> Option<i64> { | ||
| 96 | + self.correct | ||
| 97 | + } | ||
| 98 | + | ||
| 99 | + pub fn get_source_exam(&self) -> Option<&ExamId> { | ||
| 100 | + self.source_exam.as_ref() | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + pub fn get_created_at(&self) -> Timestamp { | ||
| 104 | + self.created_at | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + /// The stored kind-dependent fields as the validated bundle (for | ||
| 108 | + /// merge-on-update). Bypasses `try_new`: the fields were written through a | ||
| 109 | + /// `QuestionSpec`, so the invariants already hold. | ||
| 110 | + pub fn spec(&self) -> QuestionSpec { | ||
| 111 | + // `QuestionSpec` fields are private; rebuild through `try_new`, which | ||
| 112 | + // the stored values are guaranteed to satisfy. | ||
| 113 | + QuestionSpec::try_new( | ||
| 114 | + self.kind.clone(), | ||
| 115 | + self.choices | ||
| 116 | + .as_ref() | ||
| 117 | + .map(|cs| cs.iter().map(|c| c.as_str().to_string()).collect()), | ||
| 118 | + self.correct, | ||
| 119 | + ) | ||
| 120 | + .expect("stored bank question fields satisfy the spec invariants") | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + pub async fn create( | ||
| 124 | + owner: UserId, | ||
| 125 | + subject: SubjectId, | ||
| 126 | + text: QuestionText, | ||
| 127 | + points: QuestionPoints, | ||
| 128 | + spec: QuestionSpec, | ||
| 129 | + db: &Database, | ||
| 130 | + ) -> Result<BankQuestion, AppError> { | ||
| 131 | + Self::insert(owner, subject, text, points, spec, None, db).await | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + /// Like [`Self::create`], but records the origin exam the template was | ||
| 135 | + /// saved from (`POST …/questions/{qid}/to-bank`). | ||
| 136 | + pub async fn create_from_exam( | ||
| 137 | + owner: UserId, | ||
| 138 | + subject: SubjectId, | ||
| 139 | + text: QuestionText, | ||
| 140 | + points: QuestionPoints, | ||
| 141 | + spec: QuestionSpec, | ||
| 142 | + source: ExamId, | ||
| 143 | + db: &Database, | ||
| 144 | + ) -> Result<BankQuestion, AppError> { | ||
| 145 | + Self::insert(owner, subject, text, points, spec, Some(source), db).await | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + #[allow(clippy::too_many_arguments)] | ||
| 149 | + async fn insert( | ||
| 150 | + owner: UserId, | ||
| 151 | + subject: SubjectId, | ||
| 152 | + text: QuestionText, | ||
| 153 | + points: QuestionPoints, | ||
| 154 | + spec: QuestionSpec, | ||
| 155 | + source_exam: Option<ExamId>, | ||
| 156 | + db: &Database, | ||
| 157 | + ) -> Result<BankQuestion, AppError> { | ||
| 158 | + let question = BankQuestion::from_parts( | ||
| 159 | + BankQuestionId::generate(), | ||
| 160 | + owner, | ||
| 161 | + subject, | ||
| 162 | + text, | ||
| 163 | + points, | ||
| 164 | + spec, | ||
| 165 | + source_exam, | ||
| 166 | + Timestamp::now(), | ||
| 167 | + ); | ||
| 168 | + let created: Option<BankQuestion> = | ||
| 169 | + db.create(question.id.record()).content(question).await?; | ||
| 170 | + created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) | ||
| 171 | + } | ||
| 172 | + | ||
| 173 | + /// Whether any bank template references `subject` as its origin — the gate | ||
| 174 | + /// that blocks deleting a subject still used by a template. | ||
| 175 | + pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> { | ||
| 176 | + let mut result = db | ||
| 177 | + .query("SELECT VALUE id FROM bank_question WHERE subject = $subject LIMIT 1") | ||
| 178 | + .bind(("subject", subject.record())) | ||
| 179 | + .await? | ||
| 180 | + .check()?; | ||
| 181 | + Ok(!result.take::<Vec<RecordId>>(0)?.is_empty()) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + pub async fn read(id: &BankQuestionId, db: &Database) -> Result<Option<BankQuestion>, AppError> { | ||
| 185 | + Ok(db.select(id.record()).await?) | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + /// Every template in the bank, school-wide (no owner filter), in creation | ||
| 189 | + /// order (ULID ids sort by creation). | ||
| 190 | + pub async fn list(db: &Database) -> Result<Vec<BankQuestion>, AppError> { | ||
| 191 | + let mut result = db | ||
| 192 | + .query("SELECT * FROM bank_question ORDER BY id ASC") | ||
| 193 | + .await? | ||
| 194 | + .check()?; | ||
| 195 | + Ok(result.take::<Vec<BankQuestion>>(0)?) | ||
| 196 | + } | ||
| 197 | + | ||
| 198 | + pub async fn update( | ||
| 199 | + mut self, | ||
| 200 | + subject: SubjectId, | ||
| 201 | + text: QuestionText, | ||
| 202 | + points: QuestionPoints, | ||
| 203 | + spec: QuestionSpec, | ||
| 204 | + db: &Database, | ||
| 205 | + ) -> Result<BankQuestion, AppError> { | ||
| 206 | + self.subject = subject; | ||
| 207 | + self.text = text; | ||
| 208 | + self.points = points; | ||
| 209 | + let (kind, choices, correct) = spec.into_parts(); | ||
| 210 | + self.kind = kind; | ||
| 211 | + self.choices = choices; | ||
| 212 | + self.correct = correct; | ||
| 213 | + let updated: Option<BankQuestion> = db.update(self.id.record()).content(self).await?; | ||
| 214 | + updated.ok_or(AppError::NotFound) | ||
| 215 | + } | ||
| 216 | + | ||
| 217 | + /// Delete the template and cascade-remove its bank images, so none points | ||
| 218 | + /// at a missing template. Bank rows have no answers. The image *blobs* are | ||
| 219 | + /// the web layer's to remove — it collects their names before calling this. | ||
| 220 | + pub async fn delete(self, db: &Database) -> Result<BankQuestion, AppError> { | ||
| 221 | + db.query("DELETE bank_question_image WHERE bank_question = $b;") | ||
| 222 | + .bind(("b", self.id.record())) | ||
| 223 | + .await? | ||
| 224 | + .check()?; | ||
| 225 | + let deleted: Option<BankQuestion> = db.delete(self.id.record()).await?; | ||
| 226 | + deleted.ok_or(AppError::NotFound) | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + #[allow(clippy::too_many_arguments)] | ||
| 230 | + fn from_parts( | ||
| 231 | + id: BankQuestionId, | ||
| 232 | + owner: UserId, | ||
| 233 | + subject: SubjectId, | ||
| 234 | + text: QuestionText, | ||
| 235 | + points: QuestionPoints, | ||
| 236 | + spec: QuestionSpec, | ||
| 237 | + source_exam: Option<ExamId>, | ||
| 238 | + created_at: Timestamp, | ||
| 239 | + ) -> BankQuestion { | ||
| 240 | + let (kind, choices, correct) = spec.into_parts(); | ||
| 241 | + BankQuestion { | ||
| 242 | + id, | ||
| 243 | + owner, | ||
| 244 | + subject, | ||
| 245 | + text, | ||
| 246 | + kind, | ||
| 247 | + points, | ||
| 248 | + choices, | ||
| 249 | + correct, | ||
| 250 | + source_exam, | ||
| 251 | + created_at, | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +#[cfg(test)] | ||
| 257 | +mod tests { | ||
| 258 | + use super::*; | ||
| 259 | + | ||
| 260 | + fn spec() -> QuestionSpec { | ||
| 261 | + QuestionSpec::try_new( | ||
| 262 | + QuestionKind::try_new("choice").unwrap(), | ||
| 263 | + Some(vec!["yes".into(), "no".into()]), | ||
| 264 | + Some(1), | ||
| 265 | + ) | ||
| 266 | + .unwrap() | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + #[tokio::test] | ||
| 270 | + async fn list_is_school_wide() { | ||
| 271 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 272 | + for _ in 0..2 { | ||
| 273 | + BankQuestion::create( | ||
| 274 | + UserId::generate(), | ||
| 275 | + SubjectId::generate(), | ||
| 276 | + QuestionText::try_new("q").unwrap(), | ||
| 277 | + QuestionPoints::try_new(1).unwrap(), | ||
| 278 | + spec(), | ||
| 279 | + &db, | ||
| 280 | + ) | ||
| 281 | + .await | ||
| 282 | + .unwrap(); | ||
| 283 | + } | ||
| 284 | + // Different owners, yet both listed. | ||
| 285 | + assert_eq!(BankQuestion::list(&db).await.unwrap().len(), 2); | ||
| 286 | + } | ||
| 287 | +} | ||
src/domain/bank_question_image.rsadded+233 -0
| @@ -0,0 +1,233 @@ | |||
| 1 | +//! An image pinned to a bank question — the question's own illustration | ||
| 2 | +//! (`slot = NONE`) or one choice's picture (`slot = i`, choice questions only). | ||
| 3 | +//! A structural copy of [`crate::domain::question_image`] with the exam FK | ||
| 4 | +//! dropped: a bank template belongs to no exam, and its owner is reachable | ||
| 5 | +//! through the `bank_question` row. The row carries metadata; the bytes live | ||
| 6 | +//! on disk under [`crate::config::Config::files_path`] in a file named by | ||
| 7 | +//! `file` — a fresh server-generated ULID per upload. The row id is | ||
| 8 | +//! *deterministic* per (question, slot), so "one image per slot" holds by | ||
| 9 | +//! construction and a replace is a plain UPSERT. The web layer owns the blob | ||
| 10 | +//! I/O and its ordering; this module owns the rows. | ||
| 11 | + | ||
| 12 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 13 | +use ulid::Ulid; | ||
| 14 | + | ||
| 15 | +use crate::database::{BANK_QUESTION_IMAGE_TABLE, Database}; | ||
| 16 | +use crate::domain::bank_question::BankQuestionId; | ||
| 17 | +use crate::domain::note_file::FileContentType; | ||
| 18 | +use crate::error::AppError; | ||
| 19 | + | ||
| 20 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 21 | +pub struct BankQuestionImageId(RecordId); | ||
| 22 | + | ||
| 23 | +impl BankQuestionImageId { | ||
| 24 | + /// The one id a (question, slot) pair can have: `{bid}_q` for the | ||
| 25 | + /// question's own image, `{bid}_{i}` for choice `i` — uniqueness per slot | ||
| 26 | + /// needs no index this way. | ||
| 27 | + pub fn for_slot(question: &BankQuestionId, slot: Option<i64>) -> Self { | ||
| 28 | + let suffix = match slot { | ||
| 29 | + None => "q".to_string(), | ||
| 30 | + Some(index) => index.to_string(), | ||
| 31 | + }; | ||
| 32 | + Self(RecordId::new( | ||
| 33 | + BANK_QUESTION_IMAGE_TABLE, | ||
| 34 | + format!("{}_{suffix}", question.key()), | ||
| 35 | + )) | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + pub fn record(&self) -> RecordId { | ||
| 39 | + self.0.clone() | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + pub fn key(&self) -> &str { | ||
| 43 | + match &self.0.key { | ||
| 44 | + RecordIdKey::String(key) => key, | ||
| 45 | + _ => "", | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 51 | +pub struct BankQuestionImage { | ||
| 52 | + id: BankQuestionImageId, | ||
| 53 | + bank_question: BankQuestionId, | ||
| 54 | + /// `NONE` = the question's illustration; `i` = the picture of choice `i`. | ||
| 55 | + slot: Option<i64>, | ||
| 56 | + /// The blob's on-disk name — a fresh ULID every upload. | ||
| 57 | + file: String, | ||
| 58 | + content_type: FileContentType, | ||
| 59 | + size: i64, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl BankQuestionImage { | ||
| 63 | + /// Assemble a row (fresh blob name generated here) without persisting it. | ||
| 64 | + /// The caller writes the blob under [`Self::get_file`] first, then calls | ||
| 65 | + /// [`Self::upsert`] — so a stored row always points at a real blob. | ||
| 66 | + pub fn new( | ||
| 67 | + question: &BankQuestionId, | ||
| 68 | + slot: Option<i64>, | ||
| 69 | + content_type: FileContentType, | ||
| 70 | + size: i64, | ||
| 71 | + ) -> Self { | ||
| 72 | + Self { | ||
| 73 | + id: BankQuestionImageId::for_slot(question, slot), | ||
| 74 | + bank_question: question.clone(), | ||
| 75 | + slot, | ||
| 76 | + file: Ulid::new().to_string(), | ||
| 77 | + content_type, | ||
| 78 | + size, | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + pub fn get_bank_question(&self) -> &BankQuestionId { | ||
| 83 | + &self.bank_question | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + pub fn get_slot(&self) -> Option<i64> { | ||
| 87 | + self.slot | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + pub fn get_file(&self) -> &str { | ||
| 91 | + &self.file | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + pub fn get_content_type(&self) -> &FileContentType { | ||
| 95 | + &self.content_type | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + pub fn get_size(&self) -> i64 { | ||
| 99 | + self.size | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + /// Create or replace the slot's image row — the deterministic id makes | ||
| 103 | + /// this the whole "one image per slot" story. | ||
| 104 | + pub async fn upsert(self, db: &Database) -> Result<BankQuestionImage, AppError> { | ||
| 105 | + let written: Option<BankQuestionImage> = db.upsert(self.id.record()).content(self).await?; | ||
| 106 | + written.ok_or_else(|| AppError::Internal("failed to store bank question image".into())) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub async fn read_slot( | ||
| 110 | + question: &BankQuestionId, | ||
| 111 | + slot: Option<i64>, | ||
| 112 | + db: &Database, | ||
| 113 | + ) -> Result<Option<BankQuestionImage>, AppError> { | ||
| 114 | + Ok(db | ||
| 115 | + .select(BankQuestionImageId::for_slot(question, slot).record()) | ||
| 116 | + .await?) | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + pub async fn list_for_question( | ||
| 120 | + question: &BankQuestionId, | ||
| 121 | + db: &Database, | ||
| 122 | + ) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 123 | + let mut result = db | ||
| 124 | + .query("SELECT * FROM bank_question_image WHERE bank_question = $b") | ||
| 125 | + .bind(("b", question.record())) | ||
| 126 | + .await? | ||
| 127 | + .check()?; | ||
| 128 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// Every bank image row, school-wide — for bucketing onto a whole template | ||
| 132 | + /// list in one query (the bank list is itself school-wide). | ||
| 133 | + pub async fn list_all(db: &Database) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 134 | + let mut result = db | ||
| 135 | + .query("SELECT * FROM bank_question_image") | ||
| 136 | + .await? | ||
| 137 | + .check()?; | ||
| 138 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 139 | + } | ||
| 140 | + | ||
| 141 | + /// Drop every *choice* image of the question (the question's own | ||
| 142 | + /// illustration stays), returning the removed rows so the caller can take | ||
| 143 | + /// their blobs off disk. Runs when a PATCH replaces the choice list — the | ||
| 144 | + /// old pictures belong to the old options. | ||
| 145 | + pub async fn delete_choices_for( | ||
| 146 | + question: &BankQuestionId, | ||
| 147 | + db: &Database, | ||
| 148 | + ) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 149 | + let mut result = db | ||
| 150 | + .query("DELETE bank_question_image WHERE bank_question = $b AND slot != NONE RETURN BEFORE") | ||
| 151 | + .bind(("b", question.record())) | ||
| 152 | + .await? | ||
| 153 | + .check()?; | ||
| 154 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + pub async fn delete(self, db: &Database) -> Result<BankQuestionImage, AppError> { | ||
| 158 | + let deleted: Option<BankQuestionImage> = db.delete(self.id.record()).await?; | ||
| 159 | + deleted.ok_or(AppError::NotFound) | ||
| 160 | + } | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +#[cfg(test)] | ||
| 164 | +mod tests { | ||
| 165 | + use super::*; | ||
| 166 | + | ||
| 167 | + fn png() -> FileContentType { | ||
| 168 | + FileContentType::try_new("image/png").unwrap() | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + #[tokio::test] | ||
| 172 | + async fn for_slot_keys_by_question_and_slot() { | ||
| 173 | + let question = BankQuestionId::from_key("abc"); | ||
| 174 | + assert_eq!( | ||
| 175 | + BankQuestionImageId::for_slot(&question, None).key(), | ||
| 176 | + "abc_q" | ||
| 177 | + ); | ||
| 178 | + assert_eq!( | ||
| 179 | + BankQuestionImageId::for_slot(&question, Some(0)).key(), | ||
| 180 | + "abc_0" | ||
| 181 | + ); | ||
| 182 | + assert_eq!( | ||
| 183 | + BankQuestionImageId::for_slot(&question, Some(3)).key(), | ||
| 184 | + "abc_3" | ||
| 185 | + ); | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + #[tokio::test] | ||
| 189 | + async fn upsert_replaces_per_slot() { | ||
| 190 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 191 | + let question = BankQuestionId::generate(); | ||
| 192 | + | ||
| 193 | + let first = BankQuestionImage::new(&question, None, png(), 3) | ||
| 194 | + .upsert(&db) | ||
| 195 | + .await | ||
| 196 | + .unwrap(); | ||
| 197 | + let second = BankQuestionImage::new(&question, None, png(), 5) | ||
| 198 | + .upsert(&db) | ||
| 199 | + .await | ||
| 200 | + .unwrap(); | ||
| 201 | + // Same slot, same row — the replace swapped the blob pointer. | ||
| 202 | + assert_ne!(first.get_file(), second.get_file()); | ||
| 203 | + let rows = BankQuestionImage::list_for_question(&question, &db) | ||
| 204 | + .await | ||
| 205 | + .unwrap(); | ||
| 206 | + assert_eq!(rows.len(), 1); | ||
| 207 | + assert_eq!(rows[0].get_size(), 5); | ||
| 208 | + } | ||
| 209 | + | ||
| 210 | + #[tokio::test] | ||
| 211 | + async fn choice_wipe_spares_the_question_image() { | ||
| 212 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 213 | + let question = BankQuestionId::generate(); | ||
| 214 | + for slot in [None, Some(0), Some(1)] { | ||
| 215 | + BankQuestionImage::new(&question, slot, png(), 1) | ||
| 216 | + .upsert(&db) | ||
| 217 | + .await | ||
| 218 | + .unwrap(); | ||
| 219 | + } | ||
| 220 | + | ||
| 221 | + let dropped = BankQuestionImage::delete_choices_for(&question, &db) | ||
| 222 | + .await | ||
| 223 | + .unwrap(); | ||
| 224 | + assert_eq!(dropped.len(), 2); | ||
| 225 | + assert!(dropped.iter().all(|image| image.get_slot().is_some())); | ||
| 226 | + | ||
| 227 | + let left = BankQuestionImage::list_for_question(&question, &db) | ||
| 228 | + .await | ||
| 229 | + .unwrap(); | ||
| 230 | + assert_eq!(left.len(), 1); | ||
| 231 | + assert_eq!(left[0].get_slot(), None); | ||
| 232 | + } | ||
| 233 | +} | ||
src/domain/exam_question.rsmodified+42 -0
| @@ -5,6 +5,7 @@ use crate::constant::{ | |||
| 5 | MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, | 5 | MAX_CHOICE_TEXT_LEN, MAX_QUESTION_CHOICES, MAX_QUESTION_TEXT_LEN, MIN_QUESTION_CHOICES, |
| 6 | }; | 6 | }; |
| 7 | use crate::database::{Database, EXAM_QUESTION_TABLE}; | 7 | use crate::database::{Database, EXAM_QUESTION_TABLE}; |
| 8 | +use crate::domain::bank_question::BankQuestionId; | ||
| 8 | use crate::domain::exam::ExamId; | 9 | use crate::domain::exam::ExamId; |
| 9 | use crate::domain::subject::SubjectId; | 10 | use crate::domain::subject::SubjectId; |
| 10 | use crate::error::{AppError, ValidationError}; | 11 | use crate::error::{AppError, ValidationError}; |
| @@ -158,6 +159,12 @@ impl QuestionSpec { | |||
| 158 | pub fn get_kind(&self) -> &QuestionKind { | 159 | pub fn get_kind(&self) -> &QuestionKind { |
| 159 | &self.kind | 160 | &self.kind |
| 160 | } | 161 | } |
| 162 | + | ||
| 163 | + /// The validated fields, consumed — for a writer in another module (the | ||
| 164 | + /// question bank) that stores the same three columns. | ||
| 165 | + pub fn into_parts(self) -> (QuestionKind, Option<Vec<ChoiceText>>, Option<i64>) { | ||
| 166 | + (self.kind, self.choices, self.correct) | ||
| 167 | + } | ||
| 161 | } | 168 | } |
| 162 | 169 | ||
| 163 | /// One question of an exam. Order within the exam is the id's ULID order | 170 | /// One question of an exam. Order within the exam is the id's ULID order |
| @@ -175,6 +182,8 @@ pub struct ExamQuestion { | |||
| 175 | points: QuestionPoints, | 182 | points: QuestionPoints, |
| 176 | choices: Option<Vec<ChoiceText>>, | 183 | choices: Option<Vec<ChoiceText>>, |
| 177 | correct: Option<i64>, | 184 | correct: Option<i64>, |
| 185 | + /// The bank template this question was instantiated from, if any. | ||
| 186 | + source_bank: Option<BankQuestionId>, | ||
| 178 | } | 187 | } |
| 179 | 188 | ||
| 180 | impl ExamQuestion { | 189 | impl ExamQuestion { |
| @@ -210,6 +219,10 @@ impl ExamQuestion { | |||
| 210 | self.correct | 219 | self.correct |
| 211 | } | 220 | } |
| 212 | 221 | ||
| 222 | + pub fn get_source_bank(&self) -> Option<&BankQuestionId> { | ||
| 223 | + self.source_bank.as_ref() | ||
| 224 | + } | ||
| 225 | + | ||
| 213 | /// The stored kind-dependent fields as the validated bundle (for | 226 | /// The stored kind-dependent fields as the validated bundle (for |
| 214 | /// merge-on-update). Bypasses `try_new`: the fields were written through a | 227 | /// merge-on-update). Bypasses `try_new`: the fields were written through a |
| 215 | /// `QuestionSpec`, so the invariants already hold. | 228 | /// `QuestionSpec`, so the invariants already hold. |
| @@ -228,6 +241,33 @@ impl ExamQuestion { | |||
| 228 | points: QuestionPoints, | 241 | points: QuestionPoints, |
| 229 | spec: QuestionSpec, | 242 | spec: QuestionSpec, |
| 230 | db: &Database, | 243 | db: &Database, |
| 244 | + ) -> Result<ExamQuestion, AppError> { | ||
| 245 | + Self::insert(exam, subject, text, points, spec, None, db).await | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + /// Like [`Self::create`], but records the bank template this question was | ||
| 249 | + /// instantiated from (`POST …/questions/from-bank/{bid}`). | ||
| 250 | + pub async fn create_from_bank( | ||
| 251 | + exam: &ExamId, | ||
| 252 | + subject: SubjectId, | ||
| 253 | + text: QuestionText, | ||
| 254 | + points: QuestionPoints, | ||
| 255 | + spec: QuestionSpec, | ||
| 256 | + source: BankQuestionId, | ||
| 257 | + db: &Database, | ||
| 258 | + ) -> Result<ExamQuestion, AppError> { | ||
| 259 | + Self::insert(exam, subject, text, points, spec, Some(source), db).await | ||
| 260 | + } | ||
| 261 | + | ||
| 262 | + #[allow(clippy::too_many_arguments)] | ||
| 263 | + async fn insert( | ||
| 264 | + exam: &ExamId, | ||
| 265 | + subject: SubjectId, | ||
| 266 | + text: QuestionText, | ||
| 267 | + points: QuestionPoints, | ||
| 268 | + spec: QuestionSpec, | ||
| 269 | + source_bank: Option<BankQuestionId>, | ||
| 270 | + db: &Database, | ||
| 231 | ) -> Result<ExamQuestion, AppError> { | 271 | ) -> Result<ExamQuestion, AppError> { |
| 232 | let question = ExamQuestion { | 272 | let question = ExamQuestion { |
| 233 | id: ExamQuestionId::generate(), | 273 | id: ExamQuestionId::generate(), |
| @@ -238,6 +278,7 @@ impl ExamQuestion { | |||
| 238 | kind: spec.kind, | 278 | kind: spec.kind, |
| 239 | choices: spec.choices, | 279 | choices: spec.choices, |
| 240 | correct: spec.correct, | 280 | correct: spec.correct, |
| 281 | + source_bank, | ||
| 241 | }; | 282 | }; |
| 242 | let created: Option<ExamQuestion> = | 283 | let created: Option<ExamQuestion> = |
| 243 | db.create(question.id.record()).content(question).await?; | 284 | db.create(question.id.record()).content(question).await?; |
| @@ -320,6 +361,7 @@ impl ExamQuestion { | |||
| 320 | kind: spec.kind, | 361 | kind: spec.kind, |
| 321 | choices: spec.choices, | 362 | choices: spec.choices, |
| 322 | correct: spec.correct, | 363 | correct: spec.correct, |
| 364 | + source_bank: None, | ||
| 323 | } | 365 | } |
| 324 | } | 366 | } |
| 325 | } | 367 | } |
src/domain/mod.rsmodified+2 -0
| @@ -6,6 +6,8 @@ pub mod answer_image; | |||
| 6 | pub mod appointment; | 6 | pub mod appointment; |
| 7 | pub mod appointment_slot; | 7 | pub mod appointment_slot; |
| 8 | pub mod attendance; | 8 | pub mod attendance; |
| 9 | +pub mod bank_question; | ||
| 10 | +pub mod bank_question_image; | ||
| 9 | pub mod chatbot_message; | 11 | pub mod chatbot_message; |
| 10 | pub mod chatbot_thread; | 12 | pub mod chatbot_thread; |
| 11 | pub mod course; | 13 | pub mod course; |
src/lib.rsmodified+2 -0
| @@ -53,6 +53,7 @@ use crate::state::AppState; | |||
| 53 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | 53 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 54 | (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), | 54 | (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), |
| 55 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), | 55 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), |
| 56 | + (name = "bank", description = "The school-wide question bank: a shared library of reusable question templates. Any teacher+ reads the whole bank (`GET /bank-questions`, optional `?subject=` origin filter) and instantiates any template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Reads and instantiate are school-wide, but editing or deleting a template needs ownership (its owner, or an admin — 403 otherwise); templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and school-wide to read"), | ||
| 56 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 57 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 57 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), | 58 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), |
| 58 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 59 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| @@ -103,6 +104,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 103 | .nest("/work", web::work::routes()) | 104 | .nest("/work", web::work::routes()) |
| 104 | .nest("/pomodoro", web::pomodoro::routes()) | 105 | .nest("/pomodoro", web::pomodoro::routes()) |
| 105 | .nest("/questions", web::questions::routes()) | 106 | .nest("/questions", web::questions::routes()) |
| 107 | + .nest("/bank-questions", web::bank_questions::routes()) | ||
| 106 | .nest("/attendance", web::attendance::routes()) | 108 | .nest("/attendance", web::attendance::routes()) |
| 107 | .nest("/settings", web::settings::routes()) | 109 | .nest("/settings", web::settings::routes()) |
| 108 | .nest("/subjects", web::subjects::routes()) | 110 | .nest("/subjects", web::subjects::routes()) |
src/web/bank_questions.rsadded+723 -0
| @@ -0,0 +1,723 @@ | |||
| 1 | +//! The school-wide question bank: a shared library of reusable question | ||
| 2 | +//! templates. Any teacher+ reads the whole bank and instantiates any template | ||
| 3 | +//! into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, in | ||
| 4 | +//! `web/exams`), but only a template's owner (admins aside) may edit or delete | ||
| 5 | +//! it. A template carries the same content an exam question does — text, | ||
| 6 | +//! points, a `choice`/`text` spec, an optional illustration, and per-option | ||
| 7 | +//! pictures — minus any exam tie: its `subject` is origin metadata only (the | ||
| 8 | +//! same-course rule is checked at instantiate time against the target exam's | ||
| 9 | +//! course, never here, since the bank spans courses). Instantiate and | ||
| 10 | +//! save-to-bank both *copy* rows and blobs; the two sides never share one. | ||
| 11 | + | ||
| 12 | +use std::collections::HashMap; | ||
| 13 | + | ||
| 14 | +use axum::Json; | ||
| 15 | +use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | ||
| 16 | +use axum::http::StatusCode; | ||
| 17 | +use axum::response::Response; | ||
| 18 | +use serde::{Deserialize, Serialize}; | ||
| 19 | +use utoipa::{IntoParams, ToSchema}; | ||
| 20 | +use utoipa_axum::router::OpenApiRouter; | ||
| 21 | +use utoipa_axum::routes; | ||
| 22 | + | ||
| 23 | +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | ||
| 24 | +use crate::domain::bank_question::{BankQuestion, BankQuestionId}; | ||
| 25 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 26 | +use crate::domain::exam_question::{QuestionKind, QuestionPoints, QuestionSpec, QuestionText}; | ||
| 27 | +use crate::domain::note_file::FileContentType; | ||
| 28 | +use crate::domain::role::Role; | ||
| 29 | +use crate::domain::settings::Settings; | ||
| 30 | +use crate::domain::subject::SubjectId; | ||
| 31 | +use crate::domain::user::{User, UserId}; | ||
| 32 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 33 | +use crate::state::AppState; | ||
| 34 | + | ||
| 35 | +use super::subjects::subject_must_exist; | ||
| 36 | +use super::{ | ||
| 37 | + Page, PageParams, RequireTeacher, UploadFileForm, blob_path, image_content_type, | ||
| 38 | + paginate, read_upload, remove_blob, serve_inline_blob, set_or_clear, | ||
| 39 | +}; | ||
| 40 | + | ||
| 41 | +/// Serializes bank writes that adopt a `subject` against a concurrent subject | ||
| 42 | +/// delete. Bank create/update take the reader lease across their | ||
| 43 | +/// subject-exists check and the insert; the subject delete-guard takes the | ||
| 44 | +/// writer lease across its `any_for_subject` check and the delete, so a | ||
| 45 | +/// template can't land on a subject that vanished mid-flight — the bank twin | ||
| 46 | +/// of the [`super::exams::EXAM_LOCK`]/[`super::homework::HOMEWORK_LOCK`] guards. | ||
| 47 | +/// Save-to-bank (`question_to_bank`) takes the same reader lease across its | ||
| 48 | +/// question read and insert: the source question can be re-tagged/deleted, so | ||
| 49 | +/// its subject isn't otherwise pinned. Held after EXAM_LOCK/HOMEWORK_LOCK in | ||
| 50 | +/// the delete path; bank writers take only this one, so no cycle. | ||
| 51 | +pub(crate) static BANK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); | ||
| 52 | + | ||
| 53 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 54 | + OpenApiRouter::new() | ||
| 55 | + .routes(routes!(create_question, list_questions)) | ||
| 56 | + .routes(routes!(get_question, update_question, delete_question)) | ||
| 57 | + // The image routes get their own HTTP body cap, like the exam and | ||
| 58 | + // note-file ones: the server-wide hard ceiling plus multipart framing. | ||
| 59 | + .merge( | ||
| 60 | + OpenApiRouter::new() | ||
| 61 | + .routes(routes!( | ||
| 62 | + upload_question_image, | ||
| 63 | + get_question_image, | ||
| 64 | + delete_question_image | ||
| 65 | + )) | ||
| 66 | + .routes(routes!( | ||
| 67 | + upload_choice_image, | ||
| 68 | + get_choice_image, | ||
| 69 | + delete_choice_image | ||
| 70 | + )) | ||
| 71 | + .layer(DefaultBodyLimit::max( | ||
| 72 | + MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 73 | + )), | ||
| 74 | + ) | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +#[derive(Deserialize, ToSchema)] | ||
| 78 | +struct CreateBankQuestion { | ||
| 79 | + /// The subject this template came from — origin metadata only. Any of the | ||
| 80 | + /// school's subjects; it is *not* held to a course here (the bank spans | ||
| 81 | + /// courses), only checked against the target exam's course when the | ||
| 82 | + /// template is instantiated. | ||
| 83 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 84 | + subject_id: String, | ||
| 85 | + #[schema(example = "What is 2 + 2?")] | ||
| 86 | + text: String, | ||
| 87 | + /// `choice` or `text`. | ||
| 88 | + #[schema(example = "choice")] | ||
| 89 | + kind: String, | ||
| 90 | + /// This template's default point value, `1`–`100`. | ||
| 91 | + #[schema(example = 10)] | ||
| 92 | + points: i64, | ||
| 93 | + /// The options of a `choice` question (2–10 of them); omit for `text`. | ||
| 94 | + choices: Option<Vec<String>>, | ||
| 95 | + /// Zero-based index of the right option; required for `choice`, absent | ||
| 96 | + /// for `text`. | ||
| 97 | + #[schema(example = 1)] | ||
| 98 | + correct: Option<i64>, | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +#[derive(Deserialize, ToSchema)] | ||
| 102 | +struct UpdateBankQuestion { | ||
| 103 | + /// Re-tag the template's origin subject. Omit to keep the current one. | ||
| 104 | + subject_id: Option<String>, | ||
| 105 | + text: Option<String>, | ||
| 106 | + points: Option<i64>, | ||
| 107 | + /// `choice` or `text`. Switching kinds needs the other fields to follow: | ||
| 108 | + /// send `choices` + `correct` when moving to `choice`, explicit `null`s | ||
| 109 | + /// when moving to `text`. | ||
| 110 | + kind: Option<String>, | ||
| 111 | + /// Omit to keep the stored options; send `null` to drop them (text | ||
| 112 | + /// questions only). Replacing or clearing the list also drops every option | ||
| 113 | + /// picture — the old images belong to the old options. | ||
| 114 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 115 | + #[schema(value_type = Option<Vec<String>>)] | ||
| 116 | + choices: Option<Option<Vec<String>>>, | ||
| 117 | + /// Omit to keep; `null` to clear (text questions only). | ||
| 118 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 119 | + #[schema(value_type = Option<i64>)] | ||
| 120 | + correct: Option<Option<i64>>, | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Filters for the bank list. | ||
| 124 | +#[derive(Deserialize, IntoParams)] | ||
| 125 | +struct BankQuestionFilter { | ||
| 126 | + /// Narrow to templates whose origin `subject` matches this id. Omit for | ||
| 127 | + /// the whole bank. | ||
| 128 | + subject: Option<String>, | ||
| 129 | + /// Narrow to templates owned by this user (a user id, or `me` for the | ||
| 130 | + /// caller). Omit for every owner's templates. | ||
| 131 | + owner: Option<String>, | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// A bank template as its readers see it — `correct` included (teacher+ only, | ||
| 135 | +/// so the answer key is theirs to see). Its images, if any, are fetched | ||
| 136 | +/// through the image endpoints. | ||
| 137 | +#[derive(Serialize, ToSchema)] | ||
| 138 | +pub(crate) struct BankQuestionResponse { | ||
| 139 | + id: String, | ||
| 140 | + /// The teacher who owns the template (only they, or an admin, may edit it). | ||
| 141 | + owner: String, | ||
| 142 | + /// The origin subject (metadata only — not enforced against a course). | ||
| 143 | + subject: String, | ||
| 144 | + text: String, | ||
| 145 | + /// `choice` or `text`. | ||
| 146 | + #[schema(example = "choice")] | ||
| 147 | + kind: String, | ||
| 148 | + points: i64, | ||
| 149 | + choices: Option<Vec<String>>, | ||
| 150 | + /// Zero-based index of the right option (`choice` templates only). | ||
| 151 | + correct: Option<i64>, | ||
| 152 | + /// The template's illustration, if one was uploaded (any kind). | ||
| 153 | + image: Option<BankImageMeta>, | ||
| 154 | + /// Per-option pictures, aligned with `choices` (`choice` templates only). | ||
| 155 | + choice_images: Option<Vec<Option<BankImageMeta>>>, | ||
| 156 | + /// The exam this template was saved off, if any (a direct-authored | ||
| 157 | + /// template has none). | ||
| 158 | + source_exam: Option<String>, | ||
| 159 | + /// When the template was saved, UTC unix-milliseconds. | ||
| 160 | + created_at: i64, | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +impl BankQuestionResponse { | ||
| 164 | + pub(crate) fn new(question: &BankQuestion, images: &[BankQuestionImage]) -> Self { | ||
| 165 | + Self { | ||
| 166 | + id: question.get_id().key().to_string(), | ||
| 167 | + owner: question.get_owner().key().to_string(), | ||
| 168 | + subject: question.get_subject().key().to_string(), | ||
| 169 | + text: question.get_text().as_str().to_string(), | ||
| 170 | + kind: question.get_kind().as_str().to_string(), | ||
| 171 | + points: question.get_points().as_i64(), | ||
| 172 | + choices: question | ||
| 173 | + .get_choices() | ||
| 174 | + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), | ||
| 175 | + correct: question.get_correct(), | ||
| 176 | + image: bank_image_meta(images, None), | ||
| 177 | + choice_images: bank_choice_image_metas(question, images), | ||
| 178 | + source_exam: question.get_source_exam().map(|e| e.key().to_string()), | ||
| 179 | + created_at: question.get_created_at().as_millis(), | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +/// The template's slot out of its image rows. | ||
| 185 | +fn bank_image_meta(images: &[BankQuestionImage], slot: Option<i64>) -> Option<BankImageMeta> { | ||
| 186 | + images | ||
| 187 | + .iter() | ||
| 188 | + .find(|image| image.get_slot() == slot) | ||
| 189 | + .map(BankImageMeta::new) | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +/// The per-choice metas, aligned index-for-index with `choices` (`None` | ||
| 193 | +/// entries = that option has no picture); `None` whole for text templates. | ||
| 194 | +fn bank_choice_image_metas( | ||
| 195 | + question: &BankQuestion, | ||
| 196 | + images: &[BankQuestionImage], | ||
| 197 | +) -> Option<Vec<Option<BankImageMeta>>> { | ||
| 198 | + question.get_choices().map(|choices| { | ||
| 199 | + (0..choices.len() as i64) | ||
| 200 | + .map(|index| bank_image_meta(images, Some(index))) | ||
| 201 | + .collect() | ||
| 202 | + }) | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// Every bank image row bucketed by template key — one query feeding a whole | ||
| 206 | +/// template list (avoids an image query per row). | ||
| 207 | +async fn bank_images_by_question( | ||
| 208 | + db: &crate::database::Database, | ||
| 209 | +) -> Result<HashMap<String, Vec<BankQuestionImage>>, AppError> { | ||
| 210 | + let mut buckets: HashMap<String, Vec<BankQuestionImage>> = HashMap::new(); | ||
| 211 | + for image in BankQuestionImage::list_all(db).await? { | ||
| 212 | + buckets | ||
| 213 | + .entry(image.get_bank_question().key().to_string()) | ||
| 214 | + .or_default() | ||
| 215 | + .push(image); | ||
| 216 | + } | ||
| 217 | + Ok(buckets) | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +/// A stored bank image's metadata; the bytes come from the image endpoints. | ||
| 221 | +#[derive(Serialize, ToSchema)] | ||
| 222 | +struct BankImageMeta { | ||
| 223 | + #[schema(example = "image/png")] | ||
| 224 | + content_type: String, | ||
| 225 | + #[schema(example = 24_576)] | ||
| 226 | + size: i64, | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +impl BankImageMeta { | ||
| 230 | + fn new(image: &BankQuestionImage) -> Self { | ||
| 231 | + Self { | ||
| 232 | + content_type: image.get_content_type().as_str().to_string(), | ||
| 233 | + size: image.get_size(), | ||
| 234 | + } | ||
| 235 | + } | ||
| 236 | +} | ||
| 237 | + | ||
| 238 | +/// The template, or a 404. | ||
| 239 | +async fn question_or_404(st: &AppState, bid: &str) -> Result<BankQuestion, AppError> { | ||
| 240 | + BankQuestion::read(&BankQuestionId::from_key(bid), &st.db) | ||
| 241 | + .await? | ||
| 242 | + .ok_or(AppError::NotFound) | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +/// Reads are school-wide, but a mutation needs ownership: the caller owns the | ||
| 246 | +/// template, or is an admin. Everyone else gets a 403. | ||
| 247 | +fn ensure_owner(question: &BankQuestion, user: &User) -> Result<(), AppError> { | ||
| 248 | + if question.get_owner() == user.get_id() || user.get_role().at_least(Role::Admin) { | ||
| 249 | + return Ok(()); | ||
| 250 | + } | ||
| 251 | + Err(AppError::Forbidden( | ||
| 252 | + "only the template's owner or an admin can change it", | ||
| 253 | + )) | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +/// The template, provided the caller may edit it — the shared front half of | ||
| 257 | +/// every owner-gated write (PATCH, delete, image writes). | ||
| 258 | +async fn owned_question(st: &AppState, user: &User, bid: &str) -> Result<BankQuestion, AppError> { | ||
| 259 | + let question = question_or_404(st, bid).await?; | ||
| 260 | + ensure_owner(&question, user)?; | ||
| 261 | + Ok(question) | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +/// The whole bank-image write tail: new blob to disk, row UPSERT (the | ||
| 265 | +/// deterministic per-slot id makes it a replace), then the replaced blob off | ||
| 266 | +/// disk. A failed row write takes the fresh blob back out. | ||
| 267 | +pub(crate) async fn store_image( | ||
| 268 | + st: &AppState, | ||
| 269 | + question: &BankQuestionId, | ||
| 270 | + slot: Option<i64>, | ||
| 271 | + content_type: FileContentType, | ||
| 272 | + data: &[u8], | ||
| 273 | +) -> Result<BankQuestionImage, AppError> { | ||
| 274 | + let replaced = BankQuestionImage::read_slot(question, slot, &st.db).await?; | ||
| 275 | + let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); | ||
| 276 | + let path = blob_path(&st.files_path, image.get_file()); | ||
| 277 | + tokio::fs::write(&path, data) | ||
| 278 | + .await | ||
| 279 | + .map_err(|err| AppError::Internal(format!("failed to store the image blob: {err}")))?; | ||
| 280 | + match image.upsert(&st.db).await { | ||
| 281 | + Ok(stored) => { | ||
| 282 | + if let Some(replaced) = replaced { | ||
| 283 | + remove_blob(&st.files_path, replaced.get_file()).await; | ||
| 284 | + } | ||
| 285 | + Ok(stored) | ||
| 286 | + } | ||
| 287 | + Err(err) => { | ||
| 288 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 289 | + Err(err) | ||
| 290 | + } | ||
| 291 | + } | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +/// Add a template to the bank. Requires teacher+. `subject_id` is origin | ||
| 295 | +/// metadata (any subject — the same-course rule lives at instantiate time), | ||
| 296 | +/// so it need only exist (an unknown subject is a `400`). `choice` templates | ||
| 297 | +/// carry 2–10 `choices` plus the `correct` index; `text` templates carry | ||
| 298 | +/// neither. The caller becomes the owner. | ||
| 299 | +#[utoipa::path( | ||
| 300 | + post, | ||
| 301 | + path = "/", | ||
| 302 | + tag = "bank", | ||
| 303 | + security(("session_cookie" = [])), | ||
| 304 | + request_body = CreateBankQuestion, | ||
| 305 | + responses( | ||
| 306 | + (status = 201, description = "Template created", body = BankQuestionResponse), | ||
| 307 | + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject", body = ErrorResponse), | ||
| 308 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 309 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 310 | + ), | ||
| 311 | +)] | ||
| 312 | +async fn create_question( | ||
| 313 | + State(st): State<AppState>, | ||
| 314 | + RequireTeacher(user): RequireTeacher, | ||
| 315 | + Json(req): Json<CreateBankQuestion>, | ||
| 316 | +) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> { | ||
| 317 | + // Reader lease of [`BANK_LOCK`]: the exists-check and the insert are one | ||
| 318 | + // unit, so a subject delete can't slip between them (see the lock's doc). | ||
| 319 | + let _guard = BANK_LOCK.read().await; | ||
| 320 | + // Origin metadata only — no course to check it against, but it must exist. | ||
| 321 | + let subject = subject_must_exist(&req.subject_id, &st.db).await?; | ||
| 322 | + let text = QuestionText::try_new(&req.text)?; | ||
| 323 | + let points = QuestionPoints::try_new(req.points)?; | ||
| 324 | + let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; | ||
| 325 | + let question = | ||
| 326 | + BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?; | ||
| 327 | + Ok(( | ||
| 328 | + StatusCode::CREATED, | ||
| 329 | + Json(BankQuestionResponse::new(&question, &[])), | ||
| 330 | + )) | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +/// The whole bank, school-wide, in creation order — every teacher+ reads every | ||
| 334 | +/// template. `?subject=` narrows to one origin subject; `?owner=` to one owner | ||
| 335 | +/// (a user id, or `me` for the caller). Paged via `?limit=&offset=` (omit | ||
| 336 | +/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope. | ||
| 337 | +#[utoipa::path( | ||
| 338 | + get, | ||
| 339 | + path = "/", | ||
| 340 | + tag = "bank", | ||
| 341 | + security(("session_cookie" = [])), | ||
| 342 | + params(BankQuestionFilter, PageParams), | ||
| 343 | + responses( | ||
| 344 | + (status = 200, description = "A page of the bank's templates (all of them when unpaged)", body = Page<BankQuestionResponse>), | ||
| 345 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 346 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 347 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 348 | + ), | ||
| 349 | +)] | ||
| 350 | +async fn list_questions( | ||
| 351 | + State(st): State<AppState>, | ||
| 352 | + RequireTeacher(user): RequireTeacher, | ||
| 353 | + Query(filter): Query<BankQuestionFilter>, | ||
| 354 | + Query(page): Query<PageParams>, | ||
| 355 | +) -> Result<Json<Page<BankQuestionResponse>>, AppError> { | ||
| 356 | + let (limit, offset) = page.resolve()?; | ||
| 357 | + let mut questions = BankQuestion::list(&st.db).await?; | ||
| 358 | + if let Some(ref subject) = filter.subject { | ||
| 359 | + let subject = SubjectId::from_key(subject); | ||
| 360 | + questions.retain(|question| question.get_subject() == &subject); | ||
| 361 | + } | ||
| 362 | + if let Some(ref owner) = filter.owner { | ||
| 363 | + let owner = if owner == "me" { | ||
| 364 | + user.get_id().clone() | ||
| 365 | + } else { | ||
| 366 | + UserId::from_key(owner) | ||
| 367 | + }; | ||
| 368 | + questions.retain(|question| question.get_owner() == &owner); | ||
| 369 | + } | ||
| 370 | + let total = questions.len() as i64; | ||
| 371 | + // One image query for the whole bank, bucketed by template — no per-row | ||
| 372 | + // fetch on the page. | ||
| 373 | + let buckets = bank_images_by_question(&st.db).await?; | ||
| 374 | + let empty: Vec<BankQuestionImage> = Vec::new(); | ||
| 375 | + let items = paginate(&questions, limit, offset) | ||
| 376 | + .iter() | ||
| 377 | + .map(|question| { | ||
| 378 | + let images = buckets.get(question.get_id().key()).unwrap_or(&empty); | ||
| 379 | + BankQuestionResponse::new(question, images) | ||
| 380 | + }) | ||
| 381 | + .collect(); | ||
| 382 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +/// One template by id. School-wide — any teacher+ reads any template. | ||
| 386 | +#[utoipa::path( | ||
| 387 | + get, | ||
| 388 | + path = "/{bid}", | ||
| 389 | + tag = "bank", | ||
| 390 | + security(("session_cookie" = [])), | ||
| 391 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 392 | + responses( | ||
| 393 | + (status = 200, description = "The template", body = BankQuestionResponse), | ||
| 394 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 395 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 396 | + (status = 404, description = "No such template", body = ErrorResponse), | ||
| 397 | + ), | ||
| 398 | +)] | ||
| 399 | +async fn get_question( | ||
| 400 | + State(st): State<AppState>, | ||
| 401 | + RequireTeacher(_user): RequireTeacher, | ||
| 402 | + Path(bid): Path<String>, | ||
| 403 | +) -> Result<Json<BankQuestionResponse>, AppError> { | ||
| 404 | + let question = question_or_404(&st, &bid).await?; | ||
| 405 | + let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; | ||
| 406 | + Ok(Json(BankQuestionResponse::new(&question, &images))) | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +/// Edit a template. Owner only (admins aside — 403 otherwise). Omitted fields | ||
| 410 | +/// keep their value; `kind`/`choices`/`correct` are re-validated as a unit, so | ||
| 411 | +/// a kind switch must bring the matching fields along. Replacing or clearing | ||
| 412 | +/// `choices` drops the old options' pictures. Bank templates never freeze — | ||
| 413 | +/// they have no exam tie. | ||
| 414 | +#[utoipa::path( | ||
| 415 | + patch, | ||
| 416 | + path = "/{bid}", | ||
| 417 | + tag = "bank", | ||
| 418 | + security(("session_cookie" = [])), | ||
| 419 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 420 | + request_body = UpdateBankQuestion, | ||
| 421 | + responses( | ||
| 422 | + (status = 200, description = "Updated template", body = BankQuestionResponse), | ||
| 423 | + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject", body = ErrorResponse), | ||
| 424 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 425 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 426 | + (status = 404, description = "No such template", body = ErrorResponse), | ||
| 427 | + ), | ||
| 428 | +)] | ||
| 429 | +async fn update_question( | ||
| 430 | + State(st): State<AppState>, | ||
| 431 | + RequireTeacher(user): RequireTeacher, | ||
| 432 | + Path(bid): Path<String>, | ||
| 433 | + Json(req): Json<UpdateBankQuestion>, | ||
| 434 | +) -> Result<Json<BankQuestionResponse>, AppError> { | ||
| 435 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 436 | + | ||
| 437 | + // Reader lease of [`BANK_LOCK`] across the exists-check and the update, so a | ||
| 438 | + // re-tag to a subject that's being deleted can't straddle the delete-guard. | ||
| 439 | + let _guard = BANK_LOCK.read().await; | ||
| 440 | + let subject = match req.subject_id { | ||
| 441 | + Some(ref subject_id) => subject_must_exist(subject_id, &st.db).await?, | ||
| 442 | + None => question.get_subject().clone(), | ||
| 443 | + }; | ||
| 444 | + let text = match req.text { | ||
| 445 | + Some(ref text) => QuestionText::try_new(text)?, | ||
| 446 | + None => question.get_text().clone(), | ||
| 447 | + }; | ||
| 448 | + let points = match req.points { | ||
| 449 | + Some(points) => QuestionPoints::try_new(points)?, | ||
| 450 | + None => question.get_points(), | ||
| 451 | + }; | ||
| 452 | + // Merge the kind-dependent fields (set / clear / keep per field), then | ||
| 453 | + // re-validate them as a unit — a PATCH can't leave a half-question behind. | ||
| 454 | + let kind = match req.kind { | ||
| 455 | + Some(ref kind) => QuestionKind::try_new(kind)?, | ||
| 456 | + None => question.get_kind().clone(), | ||
| 457 | + }; | ||
| 458 | + let choices_replaced = req.choices.is_some(); | ||
| 459 | + let choices = match req.choices { | ||
| 460 | + Some(update) => update, | ||
| 461 | + None => question | ||
| 462 | + .get_choices() | ||
| 463 | + .map(|choices| choices.iter().map(|c| c.as_str().to_string()).collect()), | ||
| 464 | + }; | ||
| 465 | + let correct = match req.correct { | ||
| 466 | + Some(update) => update, | ||
| 467 | + None => question.get_correct(), | ||
| 468 | + }; | ||
| 469 | + let spec = QuestionSpec::try_new(kind, choices, correct)?; | ||
| 470 | + | ||
| 471 | + let bid = question.get_id().clone(); | ||
| 472 | + let updated = question.update(subject, text, points, spec, &st.db).await?; | ||
| 473 | + // A replaced (or cleared) choice list orphans the old options' pictures — | ||
| 474 | + // drop them all; the template's own illustration stays. | ||
| 475 | + if choices_replaced { | ||
| 476 | + for image in BankQuestionImage::delete_choices_for(&bid, &st.db).await? { | ||
| 477 | + remove_blob(&st.files_path, image.get_file()).await; | ||
| 478 | + } | ||
| 479 | + } | ||
| 480 | + let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?; | ||
| 481 | + Ok(Json(BankQuestionResponse::new(&updated, &images))) | ||
| 482 | +} | ||
| 483 | + | ||
| 484 | +/// Delete a template. Owner only (admins aside). Cascades its image rows and | ||
| 485 | +/// takes their blobs off disk. | ||
| 486 | +#[utoipa::path( | ||
| 487 | + delete, | ||
| 488 | + path = "/{bid}", | ||
| 489 | + tag = "bank", | ||
| 490 | + security(("session_cookie" = [])), | ||
| 491 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 492 | + responses( | ||
| 493 | + (status = 204, description = "Deleted"), | ||
| 494 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 495 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 496 | + (status = 404, description = "No such template", body = ErrorResponse), | ||
| 497 | + ), | ||
| 498 | +)] | ||
| 499 | +async fn delete_question( | ||
| 500 | + State(st): State<AppState>, | ||
| 501 | + RequireTeacher(user): RequireTeacher, | ||
| 502 | + Path(bid): Path<String>, | ||
| 503 | +) -> Result<StatusCode, AppError> { | ||
| 504 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 505 | + // Rows go first (the delete cascades the image rows), blobs after — a crash | ||
| 506 | + // in between strands at worst an unreachable blob. | ||
| 507 | + let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; | ||
| 508 | + question.delete(&st.db).await?; | ||
| 509 | + for image in &images { | ||
| 510 | + remove_blob(&st.files_path, image.get_file()).await; | ||
| 511 | + } | ||
| 512 | + Ok(StatusCode::NO_CONTENT) | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +// ---- template images -------------------------------------------------------- | ||
| 516 | +// A template may carry one illustration (any kind) and, on choice templates, | ||
| 517 | +// one picture per option — mirroring exam question images, minus the exam tie | ||
| 518 | +// and the freeze. Mutations are owner-gated; reads are school-wide (teacher+). | ||
| 519 | + | ||
| 520 | +/// Attach (or replace) a template's illustration. Owner only (admins aside). | ||
| 521 | +/// `multipart/form-data` with the image under a `file` field; the declared | ||
| 522 | +/// content type must be `image/png`, `image/jpeg`, `image/webp`, or | ||
| 523 | +/// `image/gif` (rasters only — no SVG), the bytes at most the school's | ||
| 524 | +/// `max_file_bytes` (settings). | ||
| 525 | +#[utoipa::path( | ||
| 526 | + post, | ||
| 527 | + path = "/{bid}/image", | ||
| 528 | + tag = "bank", | ||
| 529 | + security(("session_cookie" = [])), | ||
| 530 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 531 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 532 | + responses( | ||
| 533 | + (status = 201, description = "Image stored", body = BankImageMeta), | ||
| 534 | + (status = 400, description = "Missing file field, empty file, or a content type outside the image allowlist", body = ErrorResponse), | ||
| 535 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 536 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 537 | + (status = 404, description = "No such template", body = ErrorResponse), | ||
| 538 | + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), | ||
| 539 | + ), | ||
| 540 | +)] | ||
| 541 | +async fn upload_question_image( | ||
| 542 | + State(st): State<AppState>, | ||
| 543 | + RequireTeacher(user): RequireTeacher, | ||
| 544 | + Path(bid): Path<String>, | ||
| 545 | + mut multipart: Multipart, | ||
| 546 | +) -> Result<(StatusCode, Json<BankImageMeta>), AppError> { | ||
| 547 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 548 | + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | ||
| 549 | + let upload = read_upload(&mut multipart, limit).await?; | ||
| 550 | + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; | ||
| 551 | + let stored = store_image(&st, question.get_id(), None, content_type, &upload.data).await?; | ||
| 552 | + Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) | ||
| 553 | +} | ||
| 554 | + | ||
| 555 | +/// A template's illustration bytes. School-wide — any teacher+ reads it. | ||
| 556 | +#[utoipa::path( | ||
| 557 | + get, | ||
| 558 | + path = "/{bid}/image", | ||
| 559 | + tag = "bank", | ||
| 560 | + security(("session_cookie" = [])), | ||
| 561 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 562 | + responses( | ||
| 563 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 564 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 565 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 566 | + (status = 404, description = "No such template or image", body = ErrorResponse), | ||
| 567 | + ), | ||
| 568 | +)] | ||
| 569 | +async fn get_question_image( | ||
| 570 | + State(st): State<AppState>, | ||
| 571 | + RequireTeacher(_user): RequireTeacher, | ||
| 572 | + Path(bid): Path<String>, | ||
| 573 | +) -> Result<Response, AppError> { | ||
| 574 | + let question = question_or_404(&st, &bid).await?; | ||
| 575 | + let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) | ||
| 576 | + .await? | ||
| 577 | + .ok_or(AppError::NotFound)?; | ||
| 578 | + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await | ||
| 579 | +} | ||
| 580 | + | ||
| 581 | +/// Remove a template's illustration. Owner only (admins aside). | ||
| 582 | +#[utoipa::path( | ||
| 583 | + delete, | ||
| 584 | + path = "/{bid}/image", | ||
| 585 | + tag = "bank", | ||
| 586 | + security(("session_cookie" = [])), | ||
| 587 | + params(("bid" = String, Path, description = "Bank question id")), | ||
| 588 | + responses( | ||
| 589 | + (status = 204, description = "Deleted"), | ||
| 590 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 591 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 592 | + (status = 404, description = "No such template or image", body = ErrorResponse), | ||
| 593 | + ), | ||
| 594 | +)] | ||
| 595 | +async fn delete_question_image( | ||
| 596 | + State(st): State<AppState>, | ||
| 597 | + RequireTeacher(user): RequireTeacher, | ||
| 598 | + Path(bid): Path<String>, | ||
| 599 | +) -> Result<StatusCode, AppError> { | ||
| 600 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 601 | + let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) | ||
| 602 | + .await? | ||
| 603 | + .ok_or(AppError::NotFound)?; | ||
| 604 | + let image = image.delete(&st.db).await?; | ||
| 605 | + remove_blob(&st.files_path, image.get_file()).await; | ||
| 606 | + Ok(StatusCode::NO_CONTENT) | ||
| 607 | +} | ||
| 608 | + | ||
| 609 | +/// Attach (or replace) one option's picture on a `choice` template. Owner only | ||
| 610 | +/// (admins aside). Same form, limits, and rules as the illustration upload; | ||
| 611 | +/// `index` is the option's zero-based position. Replacing the `choices` list | ||
| 612 | +/// drops all its option pictures. | ||
| 613 | +#[utoipa::path( | ||
| 614 | + post, | ||
| 615 | + path = "/{bid}/choices/{index}/image", | ||
| 616 | + tag = "bank", | ||
| 617 | + security(("session_cookie" = [])), | ||
| 618 | + params( | ||
| 619 | + ("bid" = String, Path, description = "Bank question id"), | ||
| 620 | + ("index" = i64, Path, description = "Zero-based choice index"), | ||
| 621 | + ), | ||
| 622 | + request_body(content = UploadFileForm, content_type = "multipart/form-data"), | ||
| 623 | + responses( | ||
| 624 | + (status = 201, description = "Image stored", body = BankImageMeta), | ||
| 625 | + (status = 400, description = "Missing file field, empty file, a content type outside the image allowlist, a text template, or an index past the choices", body = ErrorResponse), | ||
| 626 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 627 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 628 | + (status = 404, description = "No such template", body = ErrorResponse), | ||
| 629 | + (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), | ||
| 630 | + ), | ||
| 631 | +)] | ||
| 632 | +async fn upload_choice_image( | ||
| 633 | + State(st): State<AppState>, | ||
| 634 | + RequireTeacher(user): RequireTeacher, | ||
| 635 | + Path((bid, index)): Path<(String, i64)>, | ||
| 636 | + mut multipart: Multipart, | ||
| 637 | +) -> Result<(StatusCode, Json<BankImageMeta>), AppError> { | ||
| 638 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 639 | + let Some(choices) = question.get_choices() else { | ||
| 640 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 641 | + field: "index", | ||
| 642 | + reason: "only choice questions take option pictures", | ||
| 643 | + })); | ||
| 644 | + }; | ||
| 645 | + if !(0..choices.len() as i64).contains(&index) { | ||
| 646 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 647 | + field: "index", | ||
| 648 | + reason: "must index one of the choices", | ||
| 649 | + })); | ||
| 650 | + } | ||
| 651 | + let limit = Settings::load(&st.db).await?.get_max_file_bytes(); | ||
| 652 | + let upload = read_upload(&mut multipart, limit).await?; | ||
| 653 | + let content_type = image_content_type(&upload.content_type.unwrap_or_default())?; | ||
| 654 | + let stored = store_image( | ||
| 655 | + &st, | ||
| 656 | + question.get_id(), | ||
| 657 | + Some(index), | ||
| 658 | + content_type, | ||
| 659 | + &upload.data, | ||
| 660 | + ) | ||
| 661 | + .await?; | ||
| 662 | + Ok((StatusCode::CREATED, Json(BankImageMeta::new(&stored)))) | ||
| 663 | +} | ||
| 664 | + | ||
| 665 | +/// One option's picture bytes. School-wide — any teacher+ reads it. | ||
| 666 | +#[utoipa::path( | ||
| 667 | + get, | ||
| 668 | + path = "/{bid}/choices/{index}/image", | ||
| 669 | + tag = "bank", | ||
| 670 | + security(("session_cookie" = [])), | ||
| 671 | + params( | ||
| 672 | + ("bid" = String, Path, description = "Bank question id"), | ||
| 673 | + ("index" = i64, Path, description = "Zero-based choice index"), | ||
| 674 | + ), | ||
| 675 | + responses( | ||
| 676 | + (status = 200, description = "The image bytes", content_type = "image/*"), | ||
| 677 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 678 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 679 | + (status = 404, description = "No such template or image", body = ErrorResponse), | ||
| 680 | + ), | ||
| 681 | +)] | ||
| 682 | +async fn get_choice_image( | ||
| 683 | + State(st): State<AppState>, | ||
| 684 | + RequireTeacher(_user): RequireTeacher, | ||
| 685 | + Path((bid, index)): Path<(String, i64)>, | ||
| 686 | +) -> Result<Response, AppError> { | ||
| 687 | + let question = question_or_404(&st, &bid).await?; | ||
| 688 | + let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) | ||
| 689 | + .await? | ||
| 690 | + .ok_or(AppError::NotFound)?; | ||
| 691 | + serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await | ||
| 692 | +} | ||
| 693 | + | ||
| 694 | +/// Remove one option's picture. Owner only (admins aside). | ||
| 695 | +#[utoipa::path( | ||
| 696 | + delete, | ||
| 697 | + path = "/{bid}/choices/{index}/image", | ||
| 698 | + tag = "bank", | ||
| 699 | + security(("session_cookie" = [])), | ||
| 700 | + params( | ||
| 701 | + ("bid" = String, Path, description = "Bank question id"), | ||
| 702 | + ("index" = i64, Path, description = "Zero-based choice index"), | ||
| 703 | + ), | ||
| 704 | + responses( | ||
| 705 | + (status = 204, description = "Deleted"), | ||
| 706 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 707 | + (status = 403, description = "Not the template's owner (and not an admin)", body = ErrorResponse), | ||
| 708 | + (status = 404, description = "No such template or image", body = ErrorResponse), | ||
| 709 | + ), | ||
| 710 | +)] | ||
| 711 | +async fn delete_choice_image( | ||
| 712 | + State(st): State<AppState>, | ||
| 713 | + RequireTeacher(user): RequireTeacher, | ||
| 714 | + Path((bid, index)): Path<(String, i64)>, | ||
| 715 | +) -> Result<StatusCode, AppError> { | ||
| 716 | + let question = owned_question(&st, &user, &bid).await?; | ||
| 717 | + let image = BankQuestionImage::read_slot(question.get_id(), Some(index), &st.db) | ||
| 718 | + .await? | ||
| 719 | + .ok_or(AppError::NotFound)?; | ||
| 720 | + let image = image.delete(&st.db).await?; | ||
| 721 | + remove_blob(&st.files_path, image.get_file()).await; | ||
| 722 | + Ok(StatusCode::NO_CONTENT) | ||
| 723 | +} | ||
src/web/exams.rsmodified+229 -0
| @@ -12,6 +12,8 @@ use utoipa_axum::routes; | |||
| 12 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | 12 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 13 | use crate::database::Database; | 13 | use crate::database::Database; |
| 14 | use crate::domain::answer_image::AnswerImage; | 14 | use crate::domain::answer_image::AnswerImage; |
| 15 | +use crate::domain::bank_question::{BankQuestion, BankQuestionId}; | ||
| 16 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 15 | use crate::domain::course::Course; | 17 | use crate::domain::course::Course; |
| 16 | use crate::domain::enrollment::Enrollment; | 18 | use crate::domain::enrollment::Enrollment; |
| 17 | use crate::domain::exam::{ | 19 | use crate::domain::exam::{ |
| @@ -33,6 +35,7 @@ use crate::domain::user::{User, UserId}; | |||
| 33 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 35 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 34 | use crate::state::AppState; | 36 | use crate::state::AppState; |
| 35 | 37 | ||
| 38 | +use super::bank_questions::BankQuestionResponse; | ||
| 36 | use super::courses::{can_manage_course, can_view_course, visible_courses}; | 39 | use super::courses::{can_manage_course, can_view_course, visible_courses}; |
| 37 | use super::subjects::subject_in_course; | 40 | use super::subjects::subject_in_course; |
| 38 | use super::{ | 41 | use super::{ |
| @@ -76,6 +79,8 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 76 | .routes(routes!(exam_live)) | 79 | .routes(routes!(exam_live)) |
| 77 | .routes(routes!(create_question, list_questions)) | 80 | .routes(routes!(create_question, list_questions)) |
| 78 | .routes(routes!(update_question, delete_question)) | 81 | .routes(routes!(update_question, delete_question)) |
| 82 | + .routes(routes!(question_from_bank)) | ||
| 83 | + .routes(routes!(question_to_bank)) | ||
| 79 | .routes(routes!(attempt_questions)) | 84 | .routes(routes!(attempt_questions)) |
| 80 | .routes(routes!(save_answer)) | 85 | .routes(routes!(save_answer)) |
| 81 | .routes(routes!(attempt_answers)) | 86 | .routes(routes!(attempt_answers)) |
| @@ -1427,6 +1432,8 @@ struct QuestionResponse { | |||
| 1427 | image: Option<ImageMetaResponse>, | 1432 | image: Option<ImageMetaResponse>, |
| 1428 | /// Per-option pictures, aligned with `choices` (`choice` questions only). | 1433 | /// Per-option pictures, aligned with `choices` (`choice` questions only). |
| 1429 | choice_images: Option<Vec<Option<ImageMetaResponse>>>, | 1434 | choice_images: Option<Vec<Option<ImageMetaResponse>>>, |
| 1435 | + /// The bank template this question was instantiated from, if any. | ||
| 1436 | + source_bank: Option<String>, | ||
| 1430 | } | 1437 | } |
| 1431 | 1438 | ||
| 1432 | impl QuestionResponse { | 1439 | impl QuestionResponse { |
| @@ -1444,6 +1451,7 @@ impl QuestionResponse { | |||
| 1444 | correct: question.get_correct(), | 1451 | correct: question.get_correct(), |
| 1445 | image: image_meta(images, None), | 1452 | image: image_meta(images, None), |
| 1446 | choice_images: choice_image_metas(question, images), | 1453 | choice_images: choice_image_metas(question, images), |
| 1454 | + source_bank: question.get_source_bank().map(|b| b.key().to_string()), | ||
| 1447 | } | 1455 | } |
| 1448 | } | 1456 | } |
| 1449 | } | 1457 | } |
| @@ -1731,6 +1739,227 @@ async fn delete_question( | |||
| 1731 | Ok(StatusCode::NO_CONTENT) | 1739 | Ok(StatusCode::NO_CONTENT) |
| 1732 | } | 1740 | } |
| 1733 | 1741 | ||
| 1742 | +// ---- question bank bridge --------------------------------------------------- | ||
| 1743 | +// Two copy funnels between an exam's questions and the school-wide bank | ||
| 1744 | +// (`web/bank_questions`): instantiate a template into this exam, or save one of | ||
| 1745 | +// this exam's questions back into the bank. Both COPY the row and every image | ||
| 1746 | +// blob to fresh ids/files — the source side is never touched or shared. | ||
| 1747 | + | ||
| 1748 | +#[derive(Deserialize, ToSchema)] | ||
| 1749 | +struct InstantiateFromBank { | ||
| 1750 | + /// The subject to file the new question under — one of the exam's course's | ||
| 1751 | + /// subjects (the same-course rule the bank row itself is exempt from). | ||
| 1752 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 1753 | + subject_id: String, | ||
| 1754 | +} | ||
| 1755 | + | ||
| 1756 | +/// Instantiate a bank template into this exam as a fresh question. Requires | ||
| 1757 | +/// teacher+ and management rights over the exam's course. `subject_id` must | ||
| 1758 | +/// name one of the course's subjects — the template's own subject is origin | ||
| 1759 | +/// metadata and does not carry over. The template (and its blobs) stay | ||
| 1760 | +/// untouched; a full copy — text, points, spec, illustration, and option | ||
| 1761 | +/// pictures — lands under a new question id. Locked once attempts exist. | ||
| 1762 | +#[utoipa::path( | ||
| 1763 | + post, | ||
| 1764 | + path = "/{id}/questions/from-bank/{bid}", | ||
| 1765 | + tag = "exams", | ||
| 1766 | + security(("session_cookie" = [])), | ||
| 1767 | + params( | ||
| 1768 | + ("id" = String, Path, description = "Exam id"), | ||
| 1769 | + ("bid" = String, Path, description = "Bank question id"), | ||
| 1770 | + ), | ||
| 1771 | + request_body = InstantiateFromBank, | ||
| 1772 | + responses( | ||
| 1773 | + (status = 201, description = "Question created from the template", body = QuestionResponse), | ||
| 1774 | + (status = 400, description = "Unknown subject, or one from another course", body = ErrorResponse), | ||
| 1775 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1776 | + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | ||
| 1777 | + (status = 404, description = "No such exam, or no such bank template", body = ErrorResponse), | ||
| 1778 | + (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | ||
| 1779 | + ), | ||
| 1780 | +)] | ||
| 1781 | +async fn question_from_bank( | ||
| 1782 | + State(st): State<AppState>, | ||
| 1783 | + RequireTeacher(user): RequireTeacher, | ||
| 1784 | + Path((id, bid)): Path<(String, String)>, | ||
| 1785 | + Json(req): Json<InstantiateFromBank>, | ||
| 1786 | +) -> Result<(StatusCode, Json<QuestionResponse>), AppError> { | ||
| 1787 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) | ||
| 1788 | + .await? | ||
| 1789 | + .ok_or(AppError::NotFound)?; | ||
| 1790 | + let course = course_of(&exam, &st.db).await?; | ||
| 1791 | + if !can_manage_course(&course, &user) { | ||
| 1792 | + return Err(AppError::Forbidden( | ||
| 1793 | + "only the course creator, an assigned teacher, or a manager/admin can author questions", | ||
| 1794 | + )); | ||
| 1795 | + } | ||
| 1796 | + // Writer lease of [`EXAM_LOCK`]: the freeze gate, the subject check, and the | ||
| 1797 | + // create are one unit — same reasoning as `create_question`. | ||
| 1798 | + let _guard = EXAM_LOCK.write().await; | ||
| 1799 | + ensure_questions_editable(exam.get_id(), &st.db).await?; | ||
| 1800 | + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | ||
| 1801 | + | ||
| 1802 | + let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) | ||
| 1803 | + .await? | ||
| 1804 | + .ok_or(AppError::NotFound)?; | ||
| 1805 | + let question = ExamQuestion::create_from_bank( | ||
| 1806 | + exam.get_id(), | ||
| 1807 | + subject, | ||
| 1808 | + template.get_text().clone(), | ||
| 1809 | + template.get_points(), | ||
| 1810 | + template.spec(), | ||
| 1811 | + template.get_id().clone(), | ||
| 1812 | + &st.db, | ||
| 1813 | + ) | ||
| 1814 | + .await?; | ||
| 1815 | + | ||
| 1816 | + // Copy each of the template's image blobs to a fresh file under the new | ||
| 1817 | + // question + same slot (file before row, via `store_image`). A missing | ||
| 1818 | + // source blob is server-side damage, surfaced as a 500 — not silently lost. | ||
| 1819 | + // The copy is all-or-nothing: any mid-loop failure rolls back the fresh | ||
| 1820 | + // question row (its cascade drops the copied image rows) and the blobs | ||
| 1821 | + // written so far, leaving the source and destination untouched. | ||
| 1822 | + let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | ||
| 1823 | + let mut copied: Vec<String> = Vec::new(); | ||
| 1824 | + for source in &sources { | ||
| 1825 | + let step = async { | ||
| 1826 | + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) | ||
| 1827 | + .await | ||
| 1828 | + .map_err(|err| { | ||
| 1829 | + AppError::Internal(format!( | ||
| 1830 | + "missing blob for bank image {}: {err}", | ||
| 1831 | + source.get_file() | ||
| 1832 | + )) | ||
| 1833 | + })?; | ||
| 1834 | + store_image( | ||
| 1835 | + &st, | ||
| 1836 | + &exam, | ||
| 1837 | + &question, | ||
| 1838 | + source.get_slot(), | ||
| 1839 | + source.get_content_type().clone(), | ||
| 1840 | + &bytes, | ||
| 1841 | + ) | ||
| 1842 | + .await | ||
| 1843 | + }; | ||
| 1844 | + match step.await { | ||
| 1845 | + Ok(image) => copied.push(image.get_file().to_string()), | ||
| 1846 | + Err(err) => { | ||
| 1847 | + for file in &copied { | ||
| 1848 | + remove_blob(&st.files_path, file).await; | ||
| 1849 | + } | ||
| 1850 | + let _ = question.delete(&st.db).await; | ||
| 1851 | + return Err(err); | ||
| 1852 | + } | ||
| 1853 | + } | ||
| 1854 | + } | ||
| 1855 | + let images = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | ||
| 1856 | + Ok(( | ||
| 1857 | + StatusCode::CREATED, | ||
| 1858 | + Json(QuestionResponse::new(&question, &images)), | ||
| 1859 | + )) | ||
| 1860 | +} | ||
| 1861 | + | ||
| 1862 | +/// Save one of this exam's questions into the school-wide bank as a reusable | ||
| 1863 | +/// template. Requires teacher+ and management rights over the exam's course. | ||
| 1864 | +/// The caller becomes the template's owner; the question's subject rides along | ||
| 1865 | +/// as origin metadata. A full copy — text, points, spec, illustration, and | ||
| 1866 | +/// option pictures — lands under a new bank id; the exam question is untouched. | ||
| 1867 | +/// The origin exam is recorded on the template as `source_exam`. | ||
| 1868 | +#[utoipa::path( | ||
| 1869 | + post, | ||
| 1870 | + path = "/{id}/questions/{qid}/to-bank", | ||
| 1871 | + tag = "exams", | ||
| 1872 | + security(("session_cookie" = [])), | ||
| 1873 | + params( | ||
| 1874 | + ("id" = String, Path, description = "Exam id"), | ||
| 1875 | + ("qid" = String, Path, description = "Question id"), | ||
| 1876 | + ), | ||
| 1877 | + responses( | ||
| 1878 | + (status = 201, description = "Template saved to the bank", body = BankQuestionResponse), | ||
| 1879 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1880 | + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | ||
| 1881 | + (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), | ||
| 1882 | + ), | ||
| 1883 | +)] | ||
| 1884 | +async fn question_to_bank( | ||
| 1885 | + State(st): State<AppState>, | ||
| 1886 | + RequireTeacher(user): RequireTeacher, | ||
| 1887 | + Path((id, qid)): Path<(String, String)>, | ||
| 1888 | +) -> Result<(StatusCode, Json<BankQuestionResponse>), AppError> { | ||
| 1889 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) | ||
| 1890 | + .await? | ||
| 1891 | + .ok_or(AppError::NotFound)?; | ||
| 1892 | + let course = course_of(&exam, &st.db).await?; | ||
| 1893 | + if !can_manage_course(&course, &user) { | ||
| 1894 | + return Err(AppError::Forbidden( | ||
| 1895 | + "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", | ||
| 1896 | + )); | ||
| 1897 | + } | ||
| 1898 | + // Reader lease of [`BANK_LOCK`] across the question read and the insert: the | ||
| 1899 | + // template adopts the question's subject, and a re-tag/delete of this | ||
| 1900 | + // question could otherwise let that subject's delete-guard slip between the | ||
| 1901 | + // read and our insert (its `any_for_subject` check runs under BANK_LOCK's | ||
| 1902 | + // writer lease, so holding the reader lease forces it to see our new row). | ||
| 1903 | + let _bank_guard = super::bank_questions::BANK_LOCK.read().await; | ||
| 1904 | + let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | ||
| 1905 | + | ||
| 1906 | + // `create_from_exam` mints its own id and insert (the funnel), fed the | ||
| 1907 | + // question's fields plus the origin exam it was saved off. | ||
| 1908 | + let template = BankQuestion::create_from_exam( | ||
| 1909 | + user.get_id().clone(), | ||
| 1910 | + question.get_subject().clone(), | ||
| 1911 | + question.get_text().clone(), | ||
| 1912 | + question.get_points(), | ||
| 1913 | + question.spec(), | ||
| 1914 | + exam.get_id().clone(), | ||
| 1915 | + &st.db, | ||
| 1916 | + ) | ||
| 1917 | + .await?; | ||
| 1918 | + | ||
| 1919 | + // Copy every image blob (illustration + option pictures) to a fresh file | ||
| 1920 | + // under the new bank row + same slot (file before row). All-or-nothing: a | ||
| 1921 | + // mid-loop failure rolls back the fresh bank row (cascade drops the copied | ||
| 1922 | + // image rows) and the blobs written so far; the source exam question stays | ||
| 1923 | + // untouched. | ||
| 1924 | + let sources = QuestionImage::list_for_question(question.get_id(), &st.db).await?; | ||
| 1925 | + let mut copied: Vec<String> = Vec::new(); | ||
| 1926 | + for source in &sources { | ||
| 1927 | + let step = async { | ||
| 1928 | + let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) | ||
| 1929 | + .await | ||
| 1930 | + .map_err(|err| { | ||
| 1931 | + AppError::Internal(format!( | ||
| 1932 | + "missing blob for question image {}: {err}", | ||
| 1933 | + source.get_file() | ||
| 1934 | + )) | ||
| 1935 | + })?; | ||
| 1936 | + super::bank_questions::store_image( | ||
| 1937 | + &st, | ||
| 1938 | + template.get_id(), | ||
| 1939 | + source.get_slot(), | ||
| 1940 | + source.get_content_type().clone(), | ||
| 1941 | + &bytes, | ||
| 1942 | + ) | ||
| 1943 | + .await | ||
| 1944 | + }; | ||
| 1945 | + match step.await { | ||
| 1946 | + Ok(image) => copied.push(image.get_file().to_string()), | ||
| 1947 | + Err(err) => { | ||
| 1948 | + for file in &copied { | ||
| 1949 | + remove_blob(&st.files_path, file).await; | ||
| 1950 | + } | ||
| 1951 | + let _ = template.delete(&st.db).await; | ||
| 1952 | + return Err(err); | ||
| 1953 | + } | ||
| 1954 | + } | ||
| 1955 | + } | ||
| 1956 | + let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | ||
| 1957 | + Ok(( | ||
| 1958 | + StatusCode::CREATED, | ||
| 1959 | + Json(BankQuestionResponse::new(&template, &images)), | ||
| 1960 | + )) | ||
| 1961 | +} | ||
| 1962 | + | ||
| 1734 | // ---- question images ---------------------------------------------------------- | 1963 | // ---- question images ---------------------------------------------------------- |
| 1735 | // A question may carry one illustration (any kind — the map above the prompt) | 1964 | // A question may carry one illustration (any kind — the map above the prompt) |
| 1736 | // and, on choice questions, one picture per option (pick the right city off | 1965 | // and, on choice questions, one picture per option (pick the right city off |
src/web/mod.rsmodified+1 -0
| @@ -7,6 +7,7 @@ pub mod ai; | |||
| 7 | pub mod appointments; | 7 | pub mod appointments; |
| 8 | pub mod attendance; | 8 | pub mod attendance; |
| 9 | pub mod auth; | 9 | pub mod auth; |
| 10 | +pub mod bank_questions; | ||
| 10 | pub mod chatbot; | 11 | pub mod chatbot; |
| 11 | pub mod courses; | 12 | pub mod courses; |
| 12 | pub mod events; | 13 | pub mod events; |
src/web/subjects.rsmodified+33 -4
| @@ -7,6 +7,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 7 | use utoipa_axum::routes; | 7 | use utoipa_axum::routes; |
| 8 | 8 | ||
| 9 | use crate::database::Database; | 9 | use crate::database::Database; |
| 10 | +use crate::domain::bank_question::BankQuestion; | ||
| 10 | use crate::domain::course::{Course, CourseId}; | 11 | use crate::domain::course::{Course, CourseId}; |
| 11 | use crate::domain::exam_question::ExamQuestion; | 12 | use crate::domain::exam_question::ExamQuestion; |
| 12 | use crate::domain::homework::Homework; | 13 | use crate::domain::homework::Homework; |
| @@ -15,6 +16,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; | |||
| 15 | use crate::state::AppState; | 16 | use crate::state::AppState; |
| 16 | 17 | ||
| 17 | use super::courses::{can_manage_course, can_view_course}; | 18 | use super::courses::{can_manage_course, can_view_course}; |
| 19 | +use super::bank_questions::BANK_LOCK; | ||
| 18 | use super::exams::EXAM_LOCK; | 20 | use super::exams::EXAM_LOCK; |
| 19 | use super::homework::HOMEWORK_LOCK; | 21 | use super::homework::HOMEWORK_LOCK; |
| 20 | use super::{CurrentUser, RequireTeacher, SubjectResponse}; | 22 | use super::{CurrentUser, RequireTeacher, SubjectResponse}; |
| @@ -54,6 +56,21 @@ pub(crate) async fn subject_in_course( | |||
| 54 | Ok(subject.get_id().clone()) | 56 | Ok(subject.get_id().clone()) |
| 55 | } | 57 | } |
| 56 | 58 | ||
| 59 | +/// Turn a request-supplied subject id into a validated reference, checking only | ||
| 60 | +/// that the subject exists — no course tie. For the question bank, whose subject | ||
| 61 | +/// is cross-course origin metadata: the same-course rule applies at instantiate | ||
| 62 | +/// time, not here. An unknown subject is a `400` naming the field. | ||
| 63 | +pub(crate) async fn subject_must_exist(id: &str, db: &Database) -> Result<SubjectId, AppError> { | ||
| 64 | + let subject = | ||
| 65 | + Subject::read(&SubjectId::from_key(id), db) | ||
| 66 | + .await? | ||
| 67 | + .ok_or(AppError::Validation(ValidationError::Invalid { | ||
| 68 | + field: "subject_id", | ||
| 69 | + reason: "subject does not exist", | ||
| 70 | + }))?; | ||
| 71 | + Ok(subject.get_id().clone()) | ||
| 72 | +} | ||
| 73 | + | ||
| 57 | /// The subject plus its course, or a 404 — every handler here gates on the | 74 | /// The subject plus its course, or a 404 — every handler here gates on the |
| 58 | /// parent course, so they always travel together. | 75 | /// parent course, so they always travel together. |
| 59 | async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { | 76 | async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { |
| @@ -141,9 +158,9 @@ async fn update_subject( | |||
| 141 | } | 158 | } |
| 142 | 159 | ||
| 143 | /// Delete a subject. Requires teacher+ and management rights over its course. | 160 | /// Delete a subject. Requires teacher+ and management rights over its course. |
| 144 | -/// Refused with a 409 while any exam question or homework still references it — | 161 | +/// Refused with a 409 while any exam question, homework, or bank question still |
| 145 | -/// re-tag or delete those first, so nothing is left pointing at a subject that | 162 | +/// references it — re-tag or delete those first, so nothing is left pointing at |
| 146 | -/// no longer exists. | 163 | +/// a subject that no longer exists. |
| 147 | #[utoipa::path( | 164 | #[utoipa::path( |
| 148 | delete, | 165 | delete, |
| 149 | path = "/{id}", | 166 | path = "/{id}", |
| @@ -155,7 +172,7 @@ async fn update_subject( | |||
| 155 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 172 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 156 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | 173 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 157 | (status = 404, description = "Not found", body = ErrorResponse), | 174 | (status = 404, description = "Not found", body = ErrorResponse), |
| 158 | - (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse), | 175 | + (status = 409, description = "Exam questions, homework, or bank questions still reference this subject", body = ErrorResponse), |
| 159 | ), | 176 | ), |
| 160 | )] | 177 | )] |
| 161 | async fn delete_subject( | 178 | async fn delete_subject( |
| @@ -190,6 +207,18 @@ async fn delete_subject( | |||
| 190 | "homework still references this subject — re-tag or delete it first", | 207 | "homework still references this subject — re-tag or delete it first", |
| 191 | )); | 208 | )); |
| 192 | } | 209 | } |
| 210 | + // Bank templates carry this subject as origin metadata; a deleted subject | ||
| 211 | + // would leave them pointing at nothing. Writer lease of [`BANK_LOCK`], the | ||
| 212 | + // bank twin of the two guards above: bank create/update validate their | ||
| 213 | + // subject and insert under the reader lease, so the no-templates check and | ||
| 214 | + // the delete can't straddle a template that just adopted this subject. Held | ||
| 215 | + // last; the order is EXAM_LOCK, then HOMEWORK_LOCK, then BANK_LOCK. | ||
| 216 | + let _bank_guard = BANK_LOCK.write().await; | ||
| 217 | + if BankQuestion::any_for_subject(subject.get_id(), &st.db).await? { | ||
| 218 | + return Err(AppError::Conflict( | ||
| 219 | + "bank questions still reference this subject — re-tag or delete them first", | ||
| 220 | + )); | ||
| 221 | + } | ||
| 193 | subject.delete(&st.db).await?; | 222 | subject.delete(&st.db).await?; |
| 194 | Ok(StatusCode::NO_CONTENT) | 223 | Ok(StatusCode::NO_CONTENT) |
| 195 | } | 224 | } |
tests/integration.rsmodified+737 -0
| @@ -10626,6 +10626,17 @@ async fn image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<Strin | |||
| 10626 | result.take::<Vec<String>>(0).unwrap() | 10626 | result.take::<Vec<String>>(0).unwrap() |
| 10627 | } | 10627 | } |
| 10628 | 10628 | ||
| 10629 | +/// Every stored bank-question-image blob name, straight from the table. | ||
| 10630 | +async fn bank_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | ||
| 10631 | + let mut result = db | ||
| 10632 | + .query("SELECT VALUE file FROM bank_question_image") | ||
| 10633 | + .await | ||
| 10634 | + .unwrap() | ||
| 10635 | + .check() | ||
| 10636 | + .unwrap(); | ||
| 10637 | + result.take::<Vec<String>>(0).unwrap() | ||
| 10638 | +} | ||
| 10639 | + | ||
| 10629 | /// Every stored answer-image (student drawing) blob name, straight from the table. | 10640 | /// Every stored answer-image (student drawing) blob name, straight from the table. |
| 10630 | async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { | 10641 | async fn answer_image_blob_keys(db: &hezarfen_backend::database::Database) -> Vec<String> { |
| 10631 | let mut result = db | 10642 | let mut result = db |
| @@ -16671,3 +16682,729 @@ async fn self_review_is_own_scoped_between_students() { | |||
| 16671 | assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer"); | 16682 | assert_eq!(sheet.body["answers"][0]["text"], "cicero", "A sees her own answer"); |
| 16672 | assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer"); | 16683 | assert_ne!(sheet.body["answers"][0]["text"], "cato", "never B's answer"); |
| 16673 | } | 16684 | } |
| 16685 | + | ||
| 16686 | +// --- question bank ----------------------------------------------------------- | ||
| 16687 | + | ||
| 16688 | +#[tokio::test] | ||
| 16689 | +async fn bank_question_create_get_list_and_instantiate() { | ||
| 16690 | + let (app, db) = app_and_db().await; | ||
| 16691 | + let teacher = login_as(&app, &db, "bank_t", "teacher").await; | ||
| 16692 | + let course = create_course(&app, &teacher, "algebra").await; | ||
| 16693 | + let subject = create_subject(&app, &teacher, &course, "linear").await; | ||
| 16694 | + | ||
| 16695 | + // Create a template — subject is origin metadata, not held to a course. | ||
| 16696 | + let res = send( | ||
| 16697 | + &app, | ||
| 16698 | + "POST", | ||
| 16699 | + "/bank-questions", | ||
| 16700 | + Some(&teacher), | ||
| 16701 | + Some(json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", | ||
| 16702 | + "points": 10, "choices": ["3", "4", "5"], "correct": 1 })), | ||
| 16703 | + ) | ||
| 16704 | + .await; | ||
| 16705 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16706 | + assert_eq!(res.body["kind"], "choice"); | ||
| 16707 | + assert_eq!(res.body["correct"], 1); | ||
| 16708 | + assert_eq!(res.body["subject"], subject); | ||
| 16709 | + let bid = id_of(&res.body); | ||
| 16710 | + | ||
| 16711 | + // School-wide read + list. | ||
| 16712 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 16713 | + assert_eq!(res.status, StatusCode::OK); | ||
| 16714 | + assert_eq!(res.body["text"], "2 + 2?"); | ||
| 16715 | + let res = send(&app, "GET", "/bank-questions", Some(&teacher), None).await; | ||
| 16716 | + assert_eq!(common::items(&res.body).len(), 1); | ||
| 16717 | + | ||
| 16718 | + // `?subject=` matches, and a foreign id excludes. | ||
| 16719 | + let res = send(&app, "GET", &format!("/bank-questions?subject={subject}"), Some(&teacher), None).await; | ||
| 16720 | + assert_eq!(common::items(&res.body).len(), 1); | ||
| 16721 | + let res = send(&app, "GET", "/bank-questions?subject=nope", Some(&teacher), None).await; | ||
| 16722 | + assert_eq!(common::items(&res.body).len(), 0); | ||
| 16723 | + | ||
| 16724 | + // Instantiate into an exam under one of the course's subjects. | ||
| 16725 | + let now = Timestamp::now().as_millis(); | ||
| 16726 | + let exam = scheduled_exam( | ||
| 16727 | + &app, | ||
| 16728 | + &teacher, | ||
| 16729 | + &course, | ||
| 16730 | + json!({ "title": "midterm", "kind": "final", "mode": "sync", | ||
| 16731 | + "starts_at": now - 1_000, "ends_at": now + 600_000 }), | ||
| 16732 | + ) | ||
| 16733 | + .await; | ||
| 16734 | + let res = send( | ||
| 16735 | + &app, | ||
| 16736 | + "POST", | ||
| 16737 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 16738 | + Some(&teacher), | ||
| 16739 | + Some(json!({ "subject_id": subject })), | ||
| 16740 | + ) | ||
| 16741 | + .await; | ||
| 16742 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16743 | + assert_eq!(res.body["exam"], exam); | ||
| 16744 | + assert_eq!(res.body["subject"], subject); | ||
| 16745 | + assert_eq!(res.body["correct"], 1); | ||
| 16746 | + assert_eq!(res.body["choices"][1], "4"); | ||
| 16747 | + | ||
| 16748 | + // The copy is independent — the template still stands. | ||
| 16749 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 16750 | + assert_eq!(res.status, StatusCode::OK); | ||
| 16751 | +} | ||
| 16752 | + | ||
| 16753 | +#[tokio::test] | ||
| 16754 | +async fn bank_question_owner_gate_cross_course_and_freeze() { | ||
| 16755 | + let (app, db) = app_and_db().await; | ||
| 16756 | + let owner = login_as(&app, &db, "bank_o", "teacher").await; | ||
| 16757 | + let other = login_as(&app, &db, "bank_x", "teacher").await; | ||
| 16758 | + let admin = login_as(&app, &db, "bank_a", "admin").await; | ||
| 16759 | + | ||
| 16760 | + let course = create_course(&app, &owner, "geo").await; | ||
| 16761 | + let subject = create_subject(&app, &owner, &course, "angles").await; | ||
| 16762 | + let res = send( | ||
| 16763 | + &app, | ||
| 16764 | + "POST", | ||
| 16765 | + "/bank-questions", | ||
| 16766 | + Some(&owner), | ||
| 16767 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 16768 | + ) | ||
| 16769 | + .await; | ||
| 16770 | + let bid = id_of(&res.body); | ||
| 16771 | + | ||
| 16772 | + // A non-owner teacher reads it, but may not edit or delete. | ||
| 16773 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&other), None).await; | ||
| 16774 | + assert_eq!(res.status, StatusCode::OK); | ||
| 16775 | + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&other), Some(json!({ "points": 7 }))).await; | ||
| 16776 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | ||
| 16777 | + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&other), None).await; | ||
| 16778 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 16779 | + // Admin bypasses ownership. | ||
| 16780 | + let res = send(&app, "PATCH", &format!("/bank-questions/{bid}"), Some(&admin), Some(json!({ "points": 7 }))).await; | ||
| 16781 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 16782 | + assert_eq!(res.body["points"], 7); | ||
| 16783 | + | ||
| 16784 | + // Instantiate with a subject from ANOTHER course is a 400. | ||
| 16785 | + let course2 = create_course(&app, &owner, "chem").await; | ||
| 16786 | + let subject2 = create_subject(&app, &owner, &course2, "bonds").await; | ||
| 16787 | + let now = Timestamp::now().as_millis(); | ||
| 16788 | + let exam = scheduled_exam( | ||
| 16789 | + &app, | ||
| 16790 | + &owner, | ||
| 16791 | + &course, | ||
| 16792 | + json!({ "title": "t", "kind": "final", "mode": "sync", | ||
| 16793 | + "starts_at": now - 1_000, "ends_at": now + 600_000 }), | ||
| 16794 | + ) | ||
| 16795 | + .await; | ||
| 16796 | + let res = send( | ||
| 16797 | + &app, | ||
| 16798 | + "POST", | ||
| 16799 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 16800 | + Some(&owner), | ||
| 16801 | + Some(json!({ "subject_id": subject2 })), | ||
| 16802 | + ) | ||
| 16803 | + .await; | ||
| 16804 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 16805 | + | ||
| 16806 | + // Once a student sits the exam, instantiate freezes (409). | ||
| 16807 | + let student = login(&app, "sinem").await; | ||
| 16808 | + let student_id = me_id(&app, &student).await; | ||
| 16809 | + enroll(&app, &owner, &course, &student_id).await; | ||
| 16810 | + let res = send(&app, "POST", &format!("/exams/{exam}/attempt"), Some(&student), None).await; | ||
| 16811 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16812 | + let res = send( | ||
| 16813 | + &app, | ||
| 16814 | + "POST", | ||
| 16815 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 16816 | + Some(&owner), | ||
| 16817 | + Some(json!({ "subject_id": subject })), | ||
| 16818 | + ) | ||
| 16819 | + .await; | ||
| 16820 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 16821 | +} | ||
| 16822 | + | ||
| 16823 | +#[tokio::test] | ||
| 16824 | +async fn exam_question_saves_to_bank() { | ||
| 16825 | + let (app, db) = app_and_db().await; | ||
| 16826 | + let teacher = login_as(&app, &db, "s2b_t", "teacher").await; | ||
| 16827 | + let course = create_course(&app, &teacher, "phys").await; | ||
| 16828 | + let subject = create_subject(&app, &teacher, &course, "kinematics").await; | ||
| 16829 | + let exam = create_exam(&app, &teacher, &course, "final", "final").await; | ||
| 16830 | + let qid = create_question( | ||
| 16831 | + &app, | ||
| 16832 | + &teacher, | ||
| 16833 | + &exam, | ||
| 16834 | + &subject, | ||
| 16835 | + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), | ||
| 16836 | + ) | ||
| 16837 | + .await; | ||
| 16838 | + | ||
| 16839 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 16840 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16841 | + assert_eq!(res.body["text"], "v=?"); | ||
| 16842 | + assert_eq!(res.body["correct"], 0); | ||
| 16843 | + assert_eq!(res.body["subject"], subject); | ||
| 16844 | + assert_eq!(res.body["owner"], me_id(&app, &teacher).await); | ||
| 16845 | + let bid = id_of(&res.body); | ||
| 16846 | + | ||
| 16847 | + // It now lives in the school-wide bank. | ||
| 16848 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 16849 | + assert_eq!(res.status, StatusCode::OK); | ||
| 16850 | +} | ||
| 16851 | + | ||
| 16852 | +/// Instantiating a bank template copies its image blobs to fresh files under the | ||
| 16853 | +/// new exam question, byte-for-byte, and leaves the source template's images | ||
| 16854 | +/// untouched. | ||
| 16855 | +#[tokio::test] | ||
| 16856 | +async fn bank_instantiate_copies_images() { | ||
| 16857 | + let (app, db) = app_and_db().await; | ||
| 16858 | + let teacher = login_as(&app, &db, "bimg_t", "teacher").await; | ||
| 16859 | + let course = create_course(&app, &teacher, "geo1").await; | ||
| 16860 | + let subject = create_subject(&app, &teacher, &course, "maps1").await; | ||
| 16861 | + | ||
| 16862 | + // A choice template with an illustration and one option picture. | ||
| 16863 | + let res = send( | ||
| 16864 | + &app, | ||
| 16865 | + "POST", | ||
| 16866 | + "/bank-questions", | ||
| 16867 | + Some(&teacher), | ||
| 16868 | + Some(json!({ "subject_id": subject, "text": "Which city?", "kind": "choice", | ||
| 16869 | + "points": 10, "choices": ["Ankara", "İzmir"], "correct": 0 })), | ||
| 16870 | + ) | ||
| 16871 | + .await; | ||
| 16872 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16873 | + let bid = id_of(&res.body); | ||
| 16874 | + | ||
| 16875 | + let illus = b"bank-illustration".as_slice(); | ||
| 16876 | + let choice = b"bank-choice-pic".as_slice(); | ||
| 16877 | + let (status, _) = | ||
| 16878 | + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", illus).await; | ||
| 16879 | + assert_eq!(status, StatusCode::CREATED); | ||
| 16880 | + let (status, _) = post_image( | ||
| 16881 | + &app, | ||
| 16882 | + &teacher, | ||
| 16883 | + &format!("/bank-questions/{bid}/choices/0/image"), | ||
| 16884 | + "image/webp", | ||
| 16885 | + choice, | ||
| 16886 | + ) | ||
| 16887 | + .await; | ||
| 16888 | + assert_eq!(status, StatusCode::CREATED); | ||
| 16889 | + let src_bank_keys = bank_image_blob_keys(&db).await; | ||
| 16890 | + assert_eq!(src_bank_keys.len(), 2); | ||
| 16891 | + | ||
| 16892 | + // Instantiate into an exam. | ||
| 16893 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 16894 | + let res = send( | ||
| 16895 | + &app, | ||
| 16896 | + "POST", | ||
| 16897 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 16898 | + Some(&teacher), | ||
| 16899 | + Some(json!({ "subject_id": subject })), | ||
| 16900 | + ) | ||
| 16901 | + .await; | ||
| 16902 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 16903 | + let qid = id_of(&res.body); | ||
| 16904 | + | ||
| 16905 | + // Both images retrievable on the new exam question, bytes equal to source. | ||
| 16906 | + let (status, _, bytes) = common::send_raw( | ||
| 16907 | + &app, | ||
| 16908 | + "GET", | ||
| 16909 | + &format!("/exams/{exam}/questions/{qid}/image"), | ||
| 16910 | + Some(&teacher), | ||
| 16911 | + None, | ||
| 16912 | + Vec::new(), | ||
| 16913 | + ) | ||
| 16914 | + .await; | ||
| 16915 | + assert_eq!(status, StatusCode::OK); | ||
| 16916 | + assert_eq!(bytes, illus); | ||
| 16917 | + let (status, _, bytes) = common::send_raw( | ||
| 16918 | + &app, | ||
| 16919 | + "GET", | ||
| 16920 | + &format!("/exams/{exam}/questions/{qid}/choices/0/image"), | ||
| 16921 | + Some(&teacher), | ||
| 16922 | + None, | ||
| 16923 | + Vec::new(), | ||
| 16924 | + ) | ||
| 16925 | + .await; | ||
| 16926 | + assert_eq!(status, StatusCode::OK); | ||
| 16927 | + assert_eq!(bytes, choice); | ||
| 16928 | + | ||
| 16929 | + // Copies are fresh files — new keys, none shared with the bank. | ||
| 16930 | + let exam_keys = image_blob_keys(&db).await; | ||
| 16931 | + assert_eq!(exam_keys.len(), 2); | ||
| 16932 | + for k in &exam_keys { | ||
| 16933 | + assert!(!src_bank_keys.contains(k), "copied blob reused a source file"); | ||
| 16934 | + } | ||
| 16935 | + | ||
| 16936 | + // Source bank images untouched — still 200 with the same bytes and keys. | ||
| 16937 | + let (status, _, bytes) = common::send_raw( | ||
| 16938 | + &app, | ||
| 16939 | + "GET", | ||
| 16940 | + &format!("/bank-questions/{bid}/image"), | ||
| 16941 | + Some(&teacher), | ||
| 16942 | + None, | ||
| 16943 | + Vec::new(), | ||
| 16944 | + ) | ||
| 16945 | + .await; | ||
| 16946 | + assert_eq!(status, StatusCode::OK); | ||
| 16947 | + assert_eq!(bytes, illus); | ||
| 16948 | + let (status, _, bytes) = common::send_raw( | ||
| 16949 | + &app, | ||
| 16950 | + "GET", | ||
| 16951 | + &format!("/bank-questions/{bid}/choices/0/image"), | ||
| 16952 | + Some(&teacher), | ||
| 16953 | + None, | ||
| 16954 | + Vec::new(), | ||
| 16955 | + ) | ||
| 16956 | + .await; | ||
| 16957 | + assert_eq!(status, StatusCode::OK); | ||
| 16958 | + assert_eq!(bytes, choice); | ||
| 16959 | + assert_eq!(bank_image_blob_keys(&db).await, src_bank_keys, "source keys changed"); | ||
| 16960 | +} | ||
| 16961 | + | ||
| 16962 | +/// Saving an exam question to the bank copies its image blobs to fresh files | ||
| 16963 | +/// under the new template, byte-for-byte, source exam images untouched. | ||
| 16964 | +#[tokio::test] | ||
| 16965 | +async fn bank_save_copies_images() { | ||
| 16966 | + let (app, db) = app_and_db().await; | ||
| 16967 | + let teacher = login_as(&app, &db, "simg_t", "teacher").await; | ||
| 16968 | + let course = create_course(&app, &teacher, "phys1").await; | ||
| 16969 | + let subject = create_subject(&app, &teacher, &course, "kin1").await; | ||
| 16970 | + let exam = create_exam(&app, &teacher, &course, "final", "final").await; | ||
| 16971 | + let qid = create_question( | ||
| 16972 | + &app, | ||
| 16973 | + &teacher, | ||
| 16974 | + &exam, | ||
| 16975 | + &subject, | ||
| 16976 | + json!({ "text": "v=?", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), | ||
| 16977 | + ) | ||
| 16978 | + .await; | ||
| 16979 | + | ||
| 16980 | + let illus = b"exam-illustration".as_slice(); | ||
| 16981 | + let choice = b"exam-choice-pic".as_slice(); | ||
| 16982 | + let (status, _) = post_image( | ||
| 16983 | + &app, | ||
| 16984 | + &teacher, | ||
| 16985 | + &format!("/exams/{exam}/questions/{qid}/image"), | ||
| 16986 | + "image/png", | ||
| 16987 | + illus, | ||
| 16988 | + ) | ||
| 16989 | + .await; | ||
| 16990 | + assert_eq!(status, StatusCode::CREATED); | ||
| 16991 | + let (status, _) = post_image( | ||
| 16992 | + &app, | ||
| 16993 | + &teacher, | ||
| 16994 | + &format!("/exams/{exam}/questions/{qid}/choices/0/image"), | ||
| 16995 | + "image/jpeg", | ||
| 16996 | + choice, | ||
| 16997 | + ) | ||
| 16998 | + .await; | ||
| 16999 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17000 | + let src_exam_keys = image_blob_keys(&db).await; | ||
| 17001 | + assert_eq!(src_exam_keys.len(), 2); | ||
| 17002 | + | ||
| 17003 | + let res = send( | ||
| 17004 | + &app, | ||
| 17005 | + "POST", | ||
| 17006 | + &format!("/exams/{exam}/questions/{qid}/to-bank"), | ||
| 17007 | + Some(&teacher), | ||
| 17008 | + None, | ||
| 17009 | + ) | ||
| 17010 | + .await; | ||
| 17011 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17012 | + let bid = id_of(&res.body); | ||
| 17013 | + | ||
| 17014 | + // The new bank question carries both images, bytes equal. | ||
| 17015 | + let (status, _, bytes) = common::send_raw( | ||
| 17016 | + &app, | ||
| 17017 | + "GET", | ||
| 17018 | + &format!("/bank-questions/{bid}/image"), | ||
| 17019 | + Some(&teacher), | ||
| 17020 | + None, | ||
| 17021 | + Vec::new(), | ||
| 17022 | + ) | ||
| 17023 | + .await; | ||
| 17024 | + assert_eq!(status, StatusCode::OK); | ||
| 17025 | + assert_eq!(bytes, illus); | ||
| 17026 | + let (status, _, bytes) = common::send_raw( | ||
| 17027 | + &app, | ||
| 17028 | + "GET", | ||
| 17029 | + &format!("/bank-questions/{bid}/choices/0/image"), | ||
| 17030 | + Some(&teacher), | ||
| 17031 | + None, | ||
| 17032 | + Vec::new(), | ||
| 17033 | + ) | ||
| 17034 | + .await; | ||
| 17035 | + assert_eq!(status, StatusCode::OK); | ||
| 17036 | + assert_eq!(bytes, choice); | ||
| 17037 | + | ||
| 17038 | + // Fresh keys; source exam images untouched. | ||
| 17039 | + let bank_keys = bank_image_blob_keys(&db).await; | ||
| 17040 | + assert_eq!(bank_keys.len(), 2); | ||
| 17041 | + for k in &bank_keys { | ||
| 17042 | + assert!(!src_exam_keys.contains(k), "copied blob reused a source file"); | ||
| 17043 | + } | ||
| 17044 | + assert_eq!(image_blob_keys(&db).await, src_exam_keys, "source keys changed"); | ||
| 17045 | + let (status, _, bytes) = common::send_raw( | ||
| 17046 | + &app, | ||
| 17047 | + "GET", | ||
| 17048 | + &format!("/exams/{exam}/questions/{qid}/image"), | ||
| 17049 | + Some(&teacher), | ||
| 17050 | + None, | ||
| 17051 | + Vec::new(), | ||
| 17052 | + ) | ||
| 17053 | + .await; | ||
| 17054 | + assert_eq!(status, StatusCode::OK); | ||
| 17055 | + assert_eq!(bytes, illus); | ||
| 17056 | +} | ||
| 17057 | + | ||
| 17058 | +/// An image survives a full round trip: exam question -> bank -> a second exam, | ||
| 17059 | +/// with the bytes intact at the far end. | ||
| 17060 | +#[tokio::test] | ||
| 17061 | +async fn bank_round_trip_preserves_image_bytes() { | ||
| 17062 | + let (app, db) = app_and_db().await; | ||
| 17063 | + let teacher = login_as(&app, &db, "rt_t", "teacher").await; | ||
| 17064 | + let course = create_course(&app, &teacher, "hist1").await; | ||
| 17065 | + let subject = create_subject(&app, &teacher, &course, "eras1").await; | ||
| 17066 | + let exam1 = create_exam(&app, &teacher, &course, "e1", "final").await; | ||
| 17067 | + let qid = create_question( | ||
| 17068 | + &app, | ||
| 17069 | + &teacher, | ||
| 17070 | + &exam1, | ||
| 17071 | + &subject, | ||
| 17072 | + json!({ "text": "When?", "kind": "text", "points": 10 }), | ||
| 17073 | + ) | ||
| 17074 | + .await; | ||
| 17075 | + let pic = b"round-trip-illustration".as_slice(); | ||
| 17076 | + let (status, _) = post_image( | ||
| 17077 | + &app, | ||
| 17078 | + &teacher, | ||
| 17079 | + &format!("/exams/{exam1}/questions/{qid}/image"), | ||
| 17080 | + "image/png", | ||
| 17081 | + pic, | ||
| 17082 | + ) | ||
| 17083 | + .await; | ||
| 17084 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17085 | + | ||
| 17086 | + // Hop one: exam -> bank. | ||
| 17087 | + let res = send( | ||
| 17088 | + &app, | ||
| 17089 | + "POST", | ||
| 17090 | + &format!("/exams/{exam1}/questions/{qid}/to-bank"), | ||
| 17091 | + Some(&teacher), | ||
| 17092 | + None, | ||
| 17093 | + ) | ||
| 17094 | + .await; | ||
| 17095 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17096 | + let bid = id_of(&res.body); | ||
| 17097 | + | ||
| 17098 | + // Hop two: bank -> a second exam. | ||
| 17099 | + let exam2 = create_exam(&app, &teacher, &course, "e2", "final").await; | ||
| 17100 | + let res = send( | ||
| 17101 | + &app, | ||
| 17102 | + "POST", | ||
| 17103 | + &format!("/exams/{exam2}/questions/from-bank/{bid}"), | ||
| 17104 | + Some(&teacher), | ||
| 17105 | + Some(json!({ "subject_id": subject })), | ||
| 17106 | + ) | ||
| 17107 | + .await; | ||
| 17108 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17109 | + let qid2 = id_of(&res.body); | ||
| 17110 | + | ||
| 17111 | + let (status, _, bytes) = common::send_raw( | ||
| 17112 | + &app, | ||
| 17113 | + "GET", | ||
| 17114 | + &format!("/exams/{exam2}/questions/{qid2}/image"), | ||
| 17115 | + Some(&teacher), | ||
| 17116 | + None, | ||
| 17117 | + Vec::new(), | ||
| 17118 | + ) | ||
| 17119 | + .await; | ||
| 17120 | + assert_eq!(status, StatusCode::OK); | ||
| 17121 | + assert_eq!(bytes, pic, "bytes drifted across the round trip"); | ||
| 17122 | +} | ||
| 17123 | + | ||
| 17124 | +/// Gap-1 guard: a missing source blob mid-copy is all-or-nothing — the | ||
| 17125 | +/// instantiate 500s and leaves NO partial destination (no exam question row, no | ||
| 17126 | +/// exam image rows), while the source template survives intact. | ||
| 17127 | +#[tokio::test] | ||
| 17128 | +async fn bank_instantiate_rolls_back_on_missing_source_blob() { | ||
| 17129 | + let (app, db) = app_and_db().await; | ||
| 17130 | + let teacher = login_as(&app, &db, "rb_t", "teacher").await; | ||
| 17131 | + let course = create_course(&app, &teacher, "geo2").await; | ||
| 17132 | + let subject = create_subject(&app, &teacher, &course, "maps2").await; | ||
| 17133 | + | ||
| 17134 | + // Two images so the copy loop has multiple steps. | ||
| 17135 | + let res = send( | ||
| 17136 | + &app, | ||
| 17137 | + "POST", | ||
| 17138 | + "/bank-questions", | ||
| 17139 | + Some(&teacher), | ||
| 17140 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", | ||
| 17141 | + "points": 10, "choices": ["a", "b"], "correct": 0 })), | ||
| 17142 | + ) | ||
| 17143 | + .await; | ||
| 17144 | + let bid = id_of(&res.body); | ||
| 17145 | + let (status, _) = | ||
| 17146 | + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await; | ||
| 17147 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17148 | + let (status, _) = post_image( | ||
| 17149 | + &app, | ||
| 17150 | + &teacher, | ||
| 17151 | + &format!("/bank-questions/{bid}/choices/0/image"), | ||
| 17152 | + "image/png", | ||
| 17153 | + b"opt", | ||
| 17154 | + ) | ||
| 17155 | + .await; | ||
| 17156 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17157 | + | ||
| 17158 | + // Corrupt the source on disk: delete one blob so the copy loop hits an | ||
| 17159 | + // unreadable source mid-flight. | ||
| 17160 | + let src_keys = bank_image_blob_keys(&db).await; | ||
| 17161 | + assert_eq!(src_keys.len(), 2); | ||
| 17162 | + tokio::fs::remove_file(common::files_dir().join(&src_keys[0])) | ||
| 17163 | + .await | ||
| 17164 | + .unwrap(); | ||
| 17165 | + | ||
| 17166 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17167 | + let res = send( | ||
| 17168 | + &app, | ||
| 17169 | + "POST", | ||
| 17170 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 17171 | + Some(&teacher), | ||
| 17172 | + Some(json!({ "subject_id": subject })), | ||
| 17173 | + ) | ||
| 17174 | + .await; | ||
| 17175 | + assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR, "{}", res.body); | ||
| 17176 | + | ||
| 17177 | + // No partial destination: no question row, no exam image rows (isolated | ||
| 17178 | + // per-test DB is the race-safe source of truth; the shared parallel blob | ||
| 17179 | + // dir rules out an exact on-disk diff). | ||
| 17180 | + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; | ||
| 17181 | + assert!( | ||
| 17182 | + common::items(&res.body).is_empty(), | ||
| 17183 | + "orphan question survived rollback" | ||
| 17184 | + ); | ||
| 17185 | + assert!( | ||
| 17186 | + image_blob_keys(&db).await.is_empty(), | ||
| 17187 | + "orphan exam image rows survived rollback" | ||
| 17188 | + ); | ||
| 17189 | + | ||
| 17190 | + // Source intact: the template still reads, and its surviving blob is still | ||
| 17191 | + // on disk. | ||
| 17192 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17193 | + assert_eq!(res.status, StatusCode::OK); | ||
| 17194 | + assert_eq!(bank_image_blob_keys(&db).await, src_keys, "source bank rows changed"); | ||
| 17195 | + assert!( | ||
| 17196 | + common::files_dir().join(&src_keys[1]).exists(), | ||
| 17197 | + "surviving source blob vanished" | ||
| 17198 | + ); | ||
| 17199 | +} | ||
| 17200 | + | ||
| 17201 | +/// A bank template's subject is origin metadata, but it must still exist: | ||
| 17202 | +/// create and update both 400 on an unknown subject id. | ||
| 17203 | +#[tokio::test] | ||
| 17204 | +async fn bank_rejects_unknown_subject() { | ||
| 17205 | + let (app, db) = app_and_db().await; | ||
| 17206 | + let teacher = login_as(&app, &db, "bsub_t", "teacher").await; | ||
| 17207 | + let course = create_course(&app, &teacher, "bsub_c").await; | ||
| 17208 | + let subject = create_subject(&app, &teacher, &course, "bsub_s").await; | ||
| 17209 | + | ||
| 17210 | + // Create with a bogus subject id — 400, not a stored row. | ||
| 17211 | + let res = send( | ||
| 17212 | + &app, | ||
| 17213 | + "POST", | ||
| 17214 | + "/bank-questions", | ||
| 17215 | + Some(&teacher), | ||
| 17216 | + Some(json!({ "subject_id": "nope", "text": "q", "kind": "text", "points": 5 })), | ||
| 17217 | + ) | ||
| 17218 | + .await; | ||
| 17219 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 17220 | + | ||
| 17221 | + // Create a real one, then PATCH its subject to a bogus id — also 400. | ||
| 17222 | + let res = send( | ||
| 17223 | + &app, | ||
| 17224 | + "POST", | ||
| 17225 | + "/bank-questions", | ||
| 17226 | + Some(&teacher), | ||
| 17227 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 17228 | + ) | ||
| 17229 | + .await; | ||
| 17230 | + let bid = id_of(&res.body); | ||
| 17231 | + let res = send( | ||
| 17232 | + &app, | ||
| 17233 | + "PATCH", | ||
| 17234 | + &format!("/bank-questions/{bid}"), | ||
| 17235 | + Some(&teacher), | ||
| 17236 | + Some(json!({ "subject_id": "nope" })), | ||
| 17237 | + ) | ||
| 17238 | + .await; | ||
| 17239 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 17240 | +} | ||
| 17241 | + | ||
| 17242 | +/// A subject with bank templates referencing it can't be deleted (409) until | ||
| 17243 | +/// those templates are gone — mirrors the exam-question / homework guard. | ||
| 17244 | +#[tokio::test] | ||
| 17245 | +async fn subject_delete_blocked_by_bank_question() { | ||
| 17246 | + let (app, db) = app_and_db().await; | ||
| 17247 | + let teacher = login_as(&app, &db, "bdel_t", "teacher").await; | ||
| 17248 | + let course = create_course(&app, &teacher, "bdel_c").await; | ||
| 17249 | + let subject = create_subject(&app, &teacher, &course, "bdel_s").await; | ||
| 17250 | + | ||
| 17251 | + let res = send( | ||
| 17252 | + &app, | ||
| 17253 | + "POST", | ||
| 17254 | + "/bank-questions", | ||
| 17255 | + Some(&teacher), | ||
| 17256 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 17257 | + ) | ||
| 17258 | + .await; | ||
| 17259 | + let bid = id_of(&res.body); | ||
| 17260 | + | ||
| 17261 | + // Guarded while the template stands. | ||
| 17262 | + let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; | ||
| 17263 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 17264 | + | ||
| 17265 | + // Drop the template — the subject frees up. | ||
| 17266 | + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17267 | + assert_eq!(res.status, StatusCode::NO_CONTENT); | ||
| 17268 | + let res = send(&app, "DELETE", &format!("/subjects/{subject}"), Some(&teacher), None).await; | ||
| 17269 | + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | ||
| 17270 | +} | ||
| 17271 | + | ||
| 17272 | +/// `?owner=me` (and an explicit owner id) narrows the school-wide bank to one | ||
| 17273 | +/// owner's templates. | ||
| 17274 | +#[tokio::test] | ||
| 17275 | +async fn bank_owner_filter() { | ||
| 17276 | + let (app, db) = app_and_db().await; | ||
| 17277 | + let alice = login_as(&app, &db, "bown_a", "teacher").await; | ||
| 17278 | + let bob = login_as(&app, &db, "bown_b", "teacher").await; | ||
| 17279 | + let course = create_course(&app, &alice, "bown_c").await; | ||
| 17280 | + let subject = create_subject(&app, &alice, &course, "bown_s").await; | ||
| 17281 | + | ||
| 17282 | + for who in [&alice, &bob] { | ||
| 17283 | + send( | ||
| 17284 | + &app, | ||
| 17285 | + "POST", | ||
| 17286 | + "/bank-questions", | ||
| 17287 | + Some(who), | ||
| 17288 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 17289 | + ) | ||
| 17290 | + .await; | ||
| 17291 | + } | ||
| 17292 | + let alice_id = me_id(&app, &alice).await; | ||
| 17293 | + let bob_id = me_id(&app, &bob).await; | ||
| 17294 | + | ||
| 17295 | + // Whole bank has both. | ||
| 17296 | + let res = send(&app, "GET", "/bank-questions", Some(&alice), None).await; | ||
| 17297 | + assert_eq!(common::items(&res.body).len(), 2); | ||
| 17298 | + | ||
| 17299 | + // `me` resolves to the caller. | ||
| 17300 | + let res = send(&app, "GET", "/bank-questions?owner=me", Some(&alice), None).await; | ||
| 17301 | + let items = common::items(&res.body); | ||
| 17302 | + assert_eq!(items.len(), 1); | ||
| 17303 | + assert_eq!(items[0]["owner"], alice_id); | ||
| 17304 | + | ||
| 17305 | + // An explicit id filters to that owner. | ||
| 17306 | + let res = send(&app, "GET", &format!("/bank-questions?owner={bob_id}"), Some(&alice), None).await; | ||
| 17307 | + let items = common::items(&res.body); | ||
| 17308 | + assert_eq!(items.len(), 1); | ||
| 17309 | + assert_eq!(items[0]["owner"], bob_id); | ||
| 17310 | +} | ||
| 17311 | + | ||
| 17312 | +/// A template's response carries its image metadata (illustration + per-choice | ||
| 17313 | +/// slots) once images are uploaded — the same shape the exam side returns. | ||
| 17314 | +#[tokio::test] | ||
| 17315 | +async fn bank_response_carries_image_metas() { | ||
| 17316 | + let (app, db) = app_and_db().await; | ||
| 17317 | + let teacher = login_as(&app, &db, "bmeta_t", "teacher").await; | ||
| 17318 | + let course = create_course(&app, &teacher, "bmeta_c").await; | ||
| 17319 | + let subject = create_subject(&app, &teacher, &course, "bmeta_s").await; | ||
| 17320 | + let res = send( | ||
| 17321 | + &app, | ||
| 17322 | + "POST", | ||
| 17323 | + "/bank-questions", | ||
| 17324 | + Some(&teacher), | ||
| 17325 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "choice", | ||
| 17326 | + "points": 10, "choices": ["a", "b"], "correct": 0 })), | ||
| 17327 | + ) | ||
| 17328 | + .await; | ||
| 17329 | + let bid = id_of(&res.body); | ||
| 17330 | + | ||
| 17331 | + // No images yet: metas are null / all-empty. | ||
| 17332 | + assert!(res.body["image"].is_null()); | ||
| 17333 | + assert_eq!(res.body["choice_images"], json!([null, null])); | ||
| 17334 | + | ||
| 17335 | + let (status, _) = | ||
| 17336 | + post_image(&app, &teacher, &format!("/bank-questions/{bid}/image"), "image/png", b"illus").await; | ||
| 17337 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17338 | + let (status, _) = post_image( | ||
| 17339 | + &app, | ||
| 17340 | + &teacher, | ||
| 17341 | + &format!("/bank-questions/{bid}/choices/0/image"), | ||
| 17342 | + "image/jpeg", | ||
| 17343 | + b"opt", | ||
| 17344 | + ) | ||
| 17345 | + .await; | ||
| 17346 | + assert_eq!(status, StatusCode::CREATED); | ||
| 17347 | + | ||
| 17348 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17349 | + assert_eq!(res.body["image"]["content_type"], "image/png"); | ||
| 17350 | + assert_eq!(res.body["image"]["size"], 5); | ||
| 17351 | + assert_eq!(res.body["choice_images"][0]["content_type"], "image/jpeg"); | ||
| 17352 | + assert!(res.body["choice_images"][1].is_null()); | ||
| 17353 | + | ||
| 17354 | + // The list carries them too (batched, not per-row). | ||
| 17355 | + let res = send(&app, "GET", "/bank-questions?owner=me", Some(&teacher), None).await; | ||
| 17356 | + let items = common::items(&res.body); | ||
| 17357 | + assert_eq!(items[0]["image"]["content_type"], "image/png"); | ||
| 17358 | + assert_eq!(items[0]["choice_images"][0]["content_type"], "image/jpeg"); | ||
| 17359 | +} | ||
| 17360 | + | ||
| 17361 | +/// Provenance rides both directions: instantiate records `source_bank` on the | ||
| 17362 | +/// new exam question; save-to-bank records `source_exam` on the new template. | ||
| 17363 | +#[tokio::test] | ||
| 17364 | +async fn bank_provenance_both_directions() { | ||
| 17365 | + let (app, db) = app_and_db().await; | ||
| 17366 | + let teacher = login_as(&app, &db, "bprov_t", "teacher").await; | ||
| 17367 | + let course = create_course(&app, &teacher, "bprov_c").await; | ||
| 17368 | + let subject = create_subject(&app, &teacher, &course, "bprov_s").await; | ||
| 17369 | + | ||
| 17370 | + // Bank -> exam: source_bank is the template id. | ||
| 17371 | + let res = send( | ||
| 17372 | + &app, | ||
| 17373 | + "POST", | ||
| 17374 | + "/bank-questions", | ||
| 17375 | + Some(&teacher), | ||
| 17376 | + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), | ||
| 17377 | + ) | ||
| 17378 | + .await; | ||
| 17379 | + let bid = id_of(&res.body); | ||
| 17380 | + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; | ||
| 17381 | + let res = send( | ||
| 17382 | + &app, | ||
| 17383 | + "POST", | ||
| 17384 | + &format!("/exams/{exam}/questions/from-bank/{bid}"), | ||
| 17385 | + Some(&teacher), | ||
| 17386 | + Some(json!({ "subject_id": subject })), | ||
| 17387 | + ) | ||
| 17388 | + .await; | ||
| 17389 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17390 | + assert_eq!(res.body["source_bank"], bid); | ||
| 17391 | + | ||
| 17392 | + // A directly authored exam question has no source_bank. | ||
| 17393 | + let qid = create_question( | ||
| 17394 | + &app, | ||
| 17395 | + &teacher, | ||
| 17396 | + &exam, | ||
| 17397 | + &subject, | ||
| 17398 | + json!({ "text": "plain", "kind": "text", "points": 5 }), | ||
| 17399 | + ) | ||
| 17400 | + .await; | ||
| 17401 | + | ||
| 17402 | + // Exam -> bank: source_exam is the origin exam id. | ||
| 17403 | + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; | ||
| 17404 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 17405 | + assert_eq!(res.body["source_exam"], exam); | ||
| 17406 | + | ||
| 17407 | + // A directly authored template has no source_exam. | ||
| 17408 | + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; | ||
| 17409 | + assert!(res.body["source_exam"].is_null()); | ||
| 17410 | +} | ||