Course subjects, required on every exam question
Browse files at this commit022aaaa8174b3e1496b15d8c310055a67ec7ec5aParent: f29537c- feat
- course subjects, required on every exam question
18 changed files +1137 -55
- README.md +29 -10
- src/constant.rs +3 -0
- src/database.rs +15 -0
- src/domain/course.rs +3 -2
- src/domain/exam_attempt.rs +1 -0
- src/domain/exam_question.rs +25 -1
- src/domain/mod.rs +1 -0
- src/domain/subject.rs +159 -0
- src/lib.rs +3 -1
- src/web/courses.rs +97 -1
- src/web/dto.rs +26 -0
- src/web/exams.rs +30 -7
- src/web/mod.rs +5 -1
- src/web/subjects.rs +174 -0
- tests/common/mod.rs +15 -0
- tests/e2e.rs +30 -9
- tests/integration.rs +378 -23
- tests/persistence.rs +143 -0
README.mdmodified+29 -10
| @@ -17,7 +17,9 @@ closes the moment the event starts. Every event stays visible to everyone — | |||
| 17 | the audience is a roster, not a wall. Marks are course-shaped | 17 | the audience is a roster, not a wall. Marks are course-shaped |
| 18 | (Google Classroom style): a teacher creates a course — kind **`course`** (a | 18 | (Google Classroom style): a teacher creates a course — kind **`course`** (a |
| 19 | regular class) or **`study`** (a supervised study session — *etüt*; same | 19 | regular class) or **`study`** (a supervised study session — *etüt*; same |
| 20 | -behavior, different label) — enrolls students, adds | 20 | +behavior, different label) — lays out its **subjects** (curriculum topics — |
| 21 | +every exam question must be tagged with one of its course's subjects, so | ||
| 22 | +results can later be read per topic), enrolls students, adds | ||
| 21 | exams inside it, and grades — enrolling, sitting exams, roll call, and marks are | 23 | exams inside it, and grades — enrolling, sitting exams, roll call, and marks are |
| 22 | all student-only, staff never take part; students read a per-course weighted average and | 24 | all student-only, staff never take part; students read a per-course weighted average and |
| 23 | an overall average from their mark report — each exam weighted by its **kind** | 25 | an overall average from their mark report — each exam weighted by its **kind** |
| @@ -187,14 +189,14 @@ effect on the user's very next call (no re-login). | |||
| 187 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | 189 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | |
| 188 | | Read **own** attendance report | student | | | 190 | | Read **own** attendance report | student | | |
| 189 | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | | 191 | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | |
| 190 | -| View **visible** courses/exams; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | | 192 | +| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | |
| 191 | | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server | | 193 | | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server | |
| 192 | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | | 194 | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | |
| 193 | | Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | | 195 | | Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | |
| 194 | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | | 196 | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | |
| 195 | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | | 197 | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | |
| 196 | | Create courses | teacher | The creator manages the course | | 198 | | Create courses | teacher | The creator manages the course | |
| 197 | -| Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled | | 199 | +| Manage inside a course: edit/delete it, enroll/unenroll **students**, add/edit/delete its exams and **subjects**, grade, remove results | teacher | Only the **course creator**, or a `manager`+ for any course; only students can be enrolled; a subject still referenced by exam questions won't delete (`409`) | |
| 198 | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | | 200 | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | |
| 199 | | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | | 201 | | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | |
| 200 | | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | | 202 | | Grade students | teacher | Target must be an **enrolled student**; grading never targets oneself | |
| @@ -244,7 +246,8 @@ A course is either a regular class (kind `course`, the default) or an *etüt* | |||
| 244 | everywhere — enrollment, exams, sessions, marks — the kind is a label the UI | 246 | everywhere — enrollment, exams, sessions, marks — the kind is a label the UI |
| 245 | renders differently, settable at creation and editable later. | 247 | renders differently, settable at creation and editable later. |
| 246 | 248 | ||
| 247 | -Course data is walled per course. A course, its exams, and its sessions are | 249 | +Course data is walled per course. A course, its exams, its sessions, and its |
| 250 | +subjects are | ||
| 248 | **visible** only to its enrolled users, its creator, and manager+ — a student | 251 | **visible** only to its enrolled users, its creator, and manager+ — a student |
| 249 | sees just the classes they were added to, and the `/courses` / `/exams` | 252 | sees just the classes they were added to, and the `/courses` / `/exams` |
| 250 | catalogs are filtered accordingly. Teacher-level reads *inside* a course | 253 | catalogs are filtered accordingly. Teacher-level reads *inside* a course |
| @@ -310,12 +313,17 @@ their existing shapes: the student exam-room reads | |||
| 310 | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | | 313 | | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | |
| 311 | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | | 314 | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | |
| 312 | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | | 315 | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | |
| 313 | -| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) | | 316 | +| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) | |
| 314 | | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | | 317 | | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | |
| 315 | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | 318 | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | |
| 316 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | 319 | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | |
| 317 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | 320 | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | |
| 318 | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged | | 321 | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged | |
| 322 | +| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` — add a curriculum subject (course manager) | | ||
| 323 | +| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, or manager+) · paged | | ||
| 324 | +| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) | | ||
| 325 | +| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) | | ||
| 326 | +| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions reference it | | ||
| 319 | | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | | 327 | | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | |
| 320 | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | | 328 | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | |
| 321 | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | | 329 | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | |
| @@ -336,7 +344,7 @@ their existing shapes: the student exam-room reads | |||
| 336 | | POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — students only; enrolled; window open where one exists; `409` once `max_attempts` is spent | | 344 | | POST | `/exams/{id}/attempt` | student | Start (`201`), resume (`200`), or retake (`201`, blank sheet) the caller's attempt — students only; enrolled; window open where one exists; `409` once `max_attempts` is spent | |
| 337 | | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` | | 345 | | GET | `/exams/{id}/attempt` | student | Own latest attempt: status, `attempt`/`attempts_used`/`max_attempts`, deadline, `remaining_ms`, `left_at`, mark, progress (`answered`/`question_count`), server `now` | |
| 338 | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | | 346 | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | |
| 339 | -| POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) | | 347 | +| POST | `/exams/{id}/questions` | teacher | `{subject_id, text, kind, points, choices?, correct?}` — add a question tagged with one of the course's subjects (course manager; frozen once attempted) | |
| 340 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | 348 | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | |
| 341 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | 349 | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | |
| 342 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | | 350 | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | |
| @@ -385,7 +393,16 @@ exams in that course (`null` while nothing is graded — ungraded exams are | |||
| 385 | skipped, not zeroed). The overall average is the plain mean of the non-null | 393 | skipped, not zeroed). The overall average is the plain mean of the non-null |
| 386 | course averages. Unenrolling keeps result rows: the marks drop out of the | 394 | course averages. Unenrolling keeps result rows: the marks drop out of the |
| 387 | report until re-enrollment, but stay visible on the exam itself. Deleting a | 395 | report until re-enrollment, but stay visible on the exam itself. Deleting a |
| 388 | -course cascades its exams, their results, and all enrollments. | 396 | +course cascades its exams, their results, all enrollments, and its subjects. |
| 397 | +A **subject** is one topic of a course's curriculum (`name` ≤ 200 chars, | ||
| 398 | +optional `description` ≤ 2000): every exam question carries a mandatory | ||
| 399 | +`subject_id` naming one of *its own course's* subjects (an unknown or | ||
| 400 | +foreign-course subject is a `400`), so exam content is always attributable to | ||
| 401 | +a topic. A subject's course link is fixed at creation, and a subject still | ||
| 402 | +referenced by questions refuses deletion with a `409` — re-tag (PATCH the | ||
| 403 | +questions' `subject_id`) or delete those questions first. Questions written | ||
| 404 | +before subjects existed are **destroyed on boot** (answers first) — the clean | ||
| 405 | +break instead of inventing a placeholder topic. | ||
| 389 | Event `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both | 406 | Event `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both |
| 390 | are given, `ends_at` must not precede `starts_at`, and neither may be set in | 407 | are given, `ends_at` must not precede `starts_at`, and neither may be set in |
| 391 | the past (else `400`). On `PATCH`, an omitted time keeps its value and an | 408 | the past (else `400`). On `PATCH`, an omitted time keeps its value and an |
| @@ -413,8 +430,8 @@ audiences convert on boot: each listed user becomes a signup row credited to | |||
| 413 | the event's creator, and the audience becomes an uncapped registration list. | 430 | the event's creator, and the audience becomes an uncapped registration list. |
| 414 | Reading a child collection of a missing parent (`/events/{id}/attendance`, | 431 | Reading a child collection of a missing parent (`/events/{id}/attendance`, |
| 415 | `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`, | 432 | `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`, |
| 416 | -`/courses/{id}/sessions`, `/sessions/{id}/attendance`) is a `404`, not an | 433 | +`/courses/{id}/sessions`, `/courses/{id}/subjects`, |
| 417 | -empty list. | 434 | +`/sessions/{id}/attendance`) is a `404`, not an empty list. |
| 418 | Personal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same | 435 | Personal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same |
| 419 | optional set on every account, whatever the role, and is `null` until filled | 436 | optional set on every account, whatever the role, and is `null` until filled |
| 420 | in. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field | 437 | in. On `PATCH /users/me` (or the admin `PATCH /users/{id}/profile`) each field |
| @@ -598,7 +615,9 @@ attempt, autosaved as they go; choice questions are machine-checked as a | |||
| 598 | `POST /exams/{id}/results`. | 615 | `POST /exams/{id}/results`. |
| 599 | 616 | ||
| 600 | **Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`, | 617 | **Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`, |
| 601 | -course-management rights): each has `text` (≤ 2000 chars), `points` `1`–`100` | 618 | +course-management rights): each has a mandatory `subject_id` (one of the |
| 619 | +course's subjects, `GET /courses/{id}/subjects` — the topic the question | ||
| 620 | +belongs to), `text` (≤ 2000 chars), `points` `1`–`100` | ||
| 602 | (its share of the auto-score), and a `kind`: | 621 | (its share of the auto-score), and a `kind`: |
| 603 | 622 | ||
| 604 | - `kind: "choice"` — carries `choices` (2–10 options, each ≤ 500 chars) and | 623 | - `kind: "choice"` — carries `choices` (2–10 options, each ≤ 500 chars) and |
src/constant.rsmodified+3 -0
| @@ -64,6 +64,9 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; | |||
| 64 | pub const MAX_COURSE_TITLE_LEN: usize = 200; | 64 | pub const MAX_COURSE_TITLE_LEN: usize = 200; |
| 65 | pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; | 65 | pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; |
| 66 | 66 | ||
| 67 | +pub const MAX_SUBJECT_NAME_LEN: usize = 200; | ||
| 68 | +pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000; | ||
| 69 | + | ||
| 67 | /// The default attendance states, and also the mandatory core: a school may | 70 | /// The default attendance states, and also the mandatory core: a school may |
| 68 | /// add its own statuses via `PATCH /settings`, but these four can never be | 71 | /// add its own statuses via `PATCH /settings`, but these four can never be |
| 69 | /// removed — the attendance rate's semantics are defined over them. | 72 | /// removed — the attendance rate's semantics are defined over them. |
src/database.rsmodified+15 -0
| @@ -27,6 +27,7 @@ pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; | |||
| 27 | pub const WORK_ENTRY_TABLE: &str = "work_entry"; | 27 | pub const WORK_ENTRY_TABLE: &str = "work_entry"; |
| 28 | pub const SETTINGS_TABLE: &str = "settings"; | 28 | pub const SETTINGS_TABLE: &str = "settings"; |
| 29 | pub const TERM_TABLE: &str = "term"; | 29 | pub const TERM_TABLE: &str = "term"; |
| 30 | +pub const SUBJECT_TABLE: &str = "subject"; | ||
| 30 | 31 | ||
| 31 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. | 32 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 32 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the | 33 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the |
| @@ -110,6 +111,12 @@ const MIGRATION: &str = " | |||
| 110 | DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; | 111 | DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; |
| 111 | DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; | 112 | DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; |
| 112 | 113 | ||
| 114 | + DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; | ||
| 115 | + DEFINE FIELD IF NOT EXISTS course ON subject TYPE record<course>; | ||
| 116 | + DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; | ||
| 117 | + DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; | ||
| 118 | + DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; | ||
| 119 | + | ||
| 113 | DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; | 120 | DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; |
| 114 | DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>; | 121 | DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>; |
| 115 | DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>; | 122 | DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>; |
| @@ -173,7 +180,9 @@ const MIGRATION: &str = " | |||
| 173 | DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; | 180 | DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; |
| 174 | DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>; | 181 | DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option<array<string>>; |
| 175 | DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>; | 182 | DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option<int>; |
| 183 | + DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record<subject>; | ||
| 176 | DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; | 184 | DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; |
| 185 | + DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; | ||
| 177 | 186 | ||
| 178 | DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; | 187 | DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; |
| 179 | DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>; | 188 | DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record<exam>; |
| @@ -215,6 +224,12 @@ const BACKFILL: &str = " | |||
| 215 | 224 | ||
| 216 | UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; | 225 | UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; |
| 217 | 226 | ||
| 227 | + -- Questions written before subjects existed (2026-07-17) are destroyed, not | ||
| 228 | + -- backfilled: a subject is mandatory and there is nothing truthful to | ||
| 229 | + -- assign. Their answers go first so no answer row outlives its question. | ||
| 230 | + DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); | ||
| 231 | + DELETE exam_question WHERE subject = NONE; | ||
| 232 | + | ||
| 218 | -- The hand-picked `users` audience retired into `registration` (2026-07-16): | 233 | -- The hand-picked `users` audience retired into `registration` (2026-07-16): |
| 219 | -- each listed user becomes a signup row credited to the event's creator, and | 234 | -- each listed user becomes a signup row credited to the event's creator, and |
| 220 | -- the event becomes an uncapped registration list. Runs once — converted | 235 | -- the event becomes an uncapped registration list. Runs once — converted |
src/domain/course.rsmodified+3 -2
| @@ -215,8 +215,8 @@ impl Course { | |||
| 215 | 215 | ||
| 216 | /// Delete the course and cascade-remove everything inside it: results and | 216 | /// Delete the course and cascade-remove everything inside it: results and |
| 217 | /// attempts of its exams, its enrollments, its sessions with their roll | 217 | /// attempts of its exams, its enrollments, its sessions with their roll |
| 218 | - /// call, and the exams themselves. The children go in one transaction so a | 218 | + /// call, its subjects, and the exams themselves. The children go in one |
| 219 | - /// crash can't leave an exam pointing at a deleted course. | 219 | + /// transaction so a crash can't leave an exam pointing at a deleted course. |
| 220 | pub async fn delete(self, db: &Database) -> Result<Course, AppError> { | 220 | pub async fn delete(self, db: &Database) -> Result<Course, AppError> { |
| 221 | db.query( | 221 | db.query( |
| 222 | "BEGIN TRANSACTION; | 222 | "BEGIN TRANSACTION; |
| @@ -227,6 +227,7 @@ impl Course { | |||
| 227 | DELETE session_attendance WHERE course = $course; | 227 | DELETE session_attendance WHERE course = $course; |
| 228 | DELETE course_session WHERE course = $course; | 228 | DELETE course_session WHERE course = $course; |
| 229 | DELETE enrollment WHERE course = $course; | 229 | DELETE enrollment WHERE course = $course; |
| 230 | + DELETE subject WHERE course = $course; | ||
| 230 | DELETE exam WHERE course = $course; | 231 | DELETE exam WHERE course = $course; |
| 231 | COMMIT TRANSACTION;", | 232 | COMMIT TRANSACTION;", |
| 232 | ) | 233 | ) |
src/domain/exam_attempt.rsmodified+1 -0
| @@ -370,6 +370,7 @@ mod tests { | |||
| 370 | .unwrap(); | 370 | .unwrap(); |
| 371 | let question = ExamQuestion::create( | 371 | let question = ExamQuestion::create( |
| 372 | exam.get_id(), | 372 | exam.get_id(), |
| 373 | + crate::domain::subject::SubjectId::generate(), | ||
| 373 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), | 374 | crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), |
| 374 | QuestionPoints::try_new(5).unwrap(), | 375 | QuestionPoints::try_new(5).unwrap(), |
| 375 | spec, | 376 | spec, |
src/domain/exam_question.rsmodified+25 -1
| @@ -6,6 +6,7 @@ use crate::constant::{ | |||
| 6 | }; | 6 | }; |
| 7 | use crate::database::{Database, EXAM_QUESTION_TABLE}; | 7 | use crate::database::{Database, EXAM_QUESTION_TABLE}; |
| 8 | use crate::domain::exam::ExamId; | 8 | use crate::domain::exam::ExamId; |
| 9 | +use crate::domain::subject::SubjectId; | ||
| 9 | use crate::error::{AppError, ValidationError}; | 10 | use crate::error::{AppError, ValidationError}; |
| 10 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; | 11 | use crate::validate::{validate_question_kind, validate_question_points, validate_required}; |
| 11 | 12 | ||
| @@ -161,11 +162,14 @@ impl QuestionSpec { | |||
| 161 | 162 | ||
| 162 | /// One question of an exam. Order within the exam is the id's ULID order | 163 | /// One question of an exam. Order within the exam is the id's ULID order |
| 163 | /// (creation order); the kind-dependent columns always satisfy the | 164 | /// (creation order); the kind-dependent columns always satisfy the |
| 164 | -/// [`QuestionSpec`] invariants because every write goes through one. | 165 | +/// [`QuestionSpec`] invariants because every write goes through one. Every |
| 166 | +/// question links to a subject of the exam's course — the handlers verify the | ||
| 167 | +/// subject's course matches before any write. | ||
| 165 | #[derive(Debug, Clone, SurrealValue)] | 168 | #[derive(Debug, Clone, SurrealValue)] |
| 166 | pub struct ExamQuestion { | 169 | pub struct ExamQuestion { |
| 167 | id: ExamQuestionId, | 170 | id: ExamQuestionId, |
| 168 | exam: ExamId, | 171 | exam: ExamId, |
| 172 | + subject: SubjectId, | ||
| 169 | text: QuestionText, | 173 | text: QuestionText, |
| 170 | kind: QuestionKind, | 174 | kind: QuestionKind, |
| 171 | points: QuestionPoints, | 175 | points: QuestionPoints, |
| @@ -182,6 +186,10 @@ impl ExamQuestion { | |||
| 182 | &self.exam | 186 | &self.exam |
| 183 | } | 187 | } |
| 184 | 188 | ||
| 189 | + pub fn get_subject(&self) -> &SubjectId { | ||
| 190 | + &self.subject | ||
| 191 | + } | ||
| 192 | + | ||
| 185 | pub fn get_text(&self) -> &QuestionText { | 193 | pub fn get_text(&self) -> &QuestionText { |
| 186 | &self.text | 194 | &self.text |
| 187 | } | 195 | } |
| @@ -215,6 +223,7 @@ impl ExamQuestion { | |||
| 215 | 223 | ||
| 216 | pub async fn create( | 224 | pub async fn create( |
| 217 | exam: &ExamId, | 225 | exam: &ExamId, |
| 226 | + subject: SubjectId, | ||
| 218 | text: QuestionText, | 227 | text: QuestionText, |
| 219 | points: QuestionPoints, | 228 | points: QuestionPoints, |
| 220 | spec: QuestionSpec, | 229 | spec: QuestionSpec, |
| @@ -223,6 +232,7 @@ impl ExamQuestion { | |||
| 223 | let question = ExamQuestion { | 232 | let question = ExamQuestion { |
| 224 | id: ExamQuestionId::generate(), | 233 | id: ExamQuestionId::generate(), |
| 225 | exam: exam.clone(), | 234 | exam: exam.clone(), |
| 235 | + subject, | ||
| 226 | text, | 236 | text, |
| 227 | points, | 237 | points, |
| 228 | kind: spec.kind, | 238 | kind: spec.kind, |
| @@ -254,13 +264,26 @@ impl ExamQuestion { | |||
| 254 | Ok(result.take::<Vec<ExamQuestion>>(0)?) | 264 | Ok(result.take::<Vec<ExamQuestion>>(0)?) |
| 255 | } | 265 | } |
| 256 | 266 | ||
| 267 | + /// Whether any question anywhere references `subject` — the gate that | ||
| 268 | + /// blocks deleting a subject still in use. | ||
| 269 | + pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> { | ||
| 270 | + let mut result = db | ||
| 271 | + .query("SELECT VALUE id FROM exam_question WHERE subject = $subject LIMIT 1") | ||
| 272 | + .bind(("subject", subject.record())) | ||
| 273 | + .await? | ||
| 274 | + .check()?; | ||
| 275 | + Ok(!result.take::<Vec<RecordId>>(0)?.is_empty()) | ||
| 276 | + } | ||
| 277 | + | ||
| 257 | pub async fn update( | 278 | pub async fn update( |
| 258 | mut self, | 279 | mut self, |
| 280 | + subject: SubjectId, | ||
| 259 | text: QuestionText, | 281 | text: QuestionText, |
| 260 | points: QuestionPoints, | 282 | points: QuestionPoints, |
| 261 | spec: QuestionSpec, | 283 | spec: QuestionSpec, |
| 262 | db: &Database, | 284 | db: &Database, |
| 263 | ) -> Result<ExamQuestion, AppError> { | 285 | ) -> Result<ExamQuestion, AppError> { |
| 286 | + self.subject = subject; | ||
| 264 | self.text = text; | 287 | self.text = text; |
| 265 | self.points = points; | 288 | self.points = points; |
| 266 | self.kind = spec.kind; | 289 | self.kind = spec.kind; |
| @@ -287,6 +310,7 @@ impl ExamQuestion { | |||
| 287 | ExamQuestion { | 310 | ExamQuestion { |
| 288 | id: ExamQuestionId::generate(), | 311 | id: ExamQuestionId::generate(), |
| 289 | exam: exam.clone(), | 312 | exam: exam.clone(), |
| 313 | + subject: SubjectId::generate(), | ||
| 290 | text: QuestionText::try_new(text).unwrap(), | 314 | text: QuestionText::try_new(text).unwrap(), |
| 291 | points: QuestionPoints::try_new(points).unwrap(), | 315 | points: QuestionPoints::try_new(points).unwrap(), |
| 292 | kind: spec.kind, | 316 | kind: spec.kind, |
src/domain/mod.rsmodified+1 -0
| @@ -21,6 +21,7 @@ pub mod role; | |||
| 21 | pub mod session; | 21 | pub mod session; |
| 22 | pub mod session_attendance; | 22 | pub mod session_attendance; |
| 23 | pub mod settings; | 23 | pub mod settings; |
| 24 | +pub mod subject; | ||
| 24 | pub mod term; | 25 | pub mod term; |
| 25 | pub mod timestamp; | 26 | pub mod timestamp; |
| 26 | pub mod user; | 27 | pub mod user; |
src/domain/subject.rsadded+159 -0
| @@ -0,0 +1,159 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN}; | ||
| 5 | +use crate::database::{Database, SUBJECT_TABLE}; | ||
| 6 | +use crate::domain::course::CourseId; | ||
| 7 | +use crate::error::{AppError, ValidationError}; | ||
| 8 | +use crate::validate::{validate_optional, validate_required}; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct SubjectId(RecordId); | ||
| 12 | + | ||
| 13 | +impl SubjectId { | ||
| 14 | + pub fn generate() -> Self { | ||
| 15 | + Self(RecordId::new(SUBJECT_TABLE, Ulid::new().to_string())) | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + pub fn from_key(key: &str) -> Self { | ||
| 19 | + Self(RecordId::new(SUBJECT_TABLE, key)) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + pub fn record(&self) -> RecordId { | ||
| 23 | + self.0.clone() | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + pub fn key(&self) -> &str { | ||
| 27 | + match &self.0.key { | ||
| 28 | + RecordIdKey::String(key) => key, | ||
| 29 | + _ => "", | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 35 | +pub struct SubjectName(String); | ||
| 36 | + | ||
| 37 | +impl SubjectName { | ||
| 38 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 39 | + validate_required("name", value, MAX_SUBJECT_NAME_LEN)?; | ||
| 40 | + Ok(Self(value.to_string())) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + pub fn as_str(&self) -> &str { | ||
| 44 | + &self.0 | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 49 | +pub struct SubjectDescription(String); | ||
| 50 | + | ||
| 51 | +impl SubjectDescription { | ||
| 52 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 53 | + validate_optional("description", value, MAX_SUBJECT_DESCRIPTION_LEN)?; | ||
| 54 | + Ok(Self(value.to_string())) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub fn as_str(&self) -> &str { | ||
| 58 | + &self.0 | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// A subject: one topic of a course's curriculum. Every exam question links to | ||
| 63 | +/// a subject of its exam's course, so results can later be read per topic. The | ||
| 64 | +/// course link is fixed at creation — a subject is course content, and moving | ||
| 65 | +/// it would strand the questions tagged with it. | ||
| 66 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 67 | +pub struct Subject { | ||
| 68 | + id: SubjectId, | ||
| 69 | + course: CourseId, | ||
| 70 | + name: SubjectName, | ||
| 71 | + description: SubjectDescription, | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +impl Subject { | ||
| 75 | + pub fn get_id(&self) -> &SubjectId { | ||
| 76 | + &self.id | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + pub fn get_course(&self) -> &CourseId { | ||
| 80 | + &self.course | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + pub fn get_name(&self) -> &SubjectName { | ||
| 84 | + &self.name | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + pub fn get_description(&self) -> &SubjectDescription { | ||
| 88 | + &self.description | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + pub async fn create( | ||
| 92 | + course: &CourseId, | ||
| 93 | + name: SubjectName, | ||
| 94 | + description: SubjectDescription, | ||
| 95 | + db: &Database, | ||
| 96 | + ) -> Result<Subject, AppError> { | ||
| 97 | + let subject = Subject { | ||
| 98 | + id: SubjectId::generate(), | ||
| 99 | + course: course.clone(), | ||
| 100 | + name, | ||
| 101 | + description, | ||
| 102 | + }; | ||
| 103 | + let created: Option<Subject> = db.create(subject.id.record()).content(subject).await?; | ||
| 104 | + created.ok_or_else(|| AppError::Internal("failed to create subject".into())) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + pub async fn read(id: &SubjectId, db: &Database) -> Result<Option<Subject>, AppError> { | ||
| 108 | + Ok(db.select(id.record()).await?) | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + /// The course's subjects in curriculum order (ULID ids sort by creation). | ||
| 112 | + pub async fn list_for_course( | ||
| 113 | + course: &CourseId, | ||
| 114 | + db: &Database, | ||
| 115 | + ) -> Result<Vec<Subject>, AppError> { | ||
| 116 | + let mut result = db | ||
| 117 | + .query("SELECT * FROM subject WHERE course = $course ORDER BY id ASC") | ||
| 118 | + .bind(("course", course.record())) | ||
| 119 | + .await? | ||
| 120 | + .check()?; | ||
| 121 | + Ok(result.take::<Vec<Subject>>(0)?) | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + pub async fn update( | ||
| 125 | + mut self, | ||
| 126 | + name: SubjectName, | ||
| 127 | + description: SubjectDescription, | ||
| 128 | + db: &Database, | ||
| 129 | + ) -> Result<Subject, AppError> { | ||
| 130 | + self.name = name; | ||
| 131 | + self.description = description; | ||
| 132 | + let updated: Option<Subject> = db.update(self.id.record()).content(self).await?; | ||
| 133 | + updated.ok_or(AppError::NotFound) | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + pub async fn delete(self, db: &Database) -> Result<Subject, AppError> { | ||
| 137 | + let deleted: Option<Subject> = db.delete(self.id.record()).await?; | ||
| 138 | + deleted.ok_or(AppError::NotFound) | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +#[cfg(test)] | ||
| 143 | +mod tests { | ||
| 144 | + use super::*; | ||
| 145 | + | ||
| 146 | + #[tokio::test] | ||
| 147 | + async fn name_is_required() { | ||
| 148 | + assert!(SubjectName::try_new("Limits").is_ok()); | ||
| 149 | + assert!(SubjectName::try_new("").is_err()); | ||
| 150 | + assert!(SubjectName::try_new(" ").is_err()); | ||
| 151 | + assert!(SubjectName::try_new(&"x".repeat(201)).is_err()); | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + #[tokio::test] | ||
| 155 | + async fn description_is_optional() { | ||
| 156 | + assert!(SubjectDescription::try_new("").is_ok()); | ||
| 157 | + assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err()); | ||
| 158 | + } | ||
| 159 | +} | ||
src/lib.rsmodified+3 -1
| @@ -32,7 +32,7 @@ use crate::state::AppState; | |||
| 32 | info( | 32 | info( |
| 33 | title = "Hezarfen Backend API", | 33 | title = "Hezarfen Backend API", |
| 34 | version = env!("CARGO_PKG_VERSION"), | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", | 35 | + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", |
| 36 | ), | 36 | ), |
| 37 | modifiers(&SecurityAddon), | 37 | modifiers(&SecurityAddon), |
| 38 | tags( | 38 | tags( |
| @@ -48,6 +48,7 @@ use crate::state::AppState; | |||
| 48 | (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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), | 48 | (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). A modeless exam is an offline-graded draft — attempts on it are a 409. 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"), |
| 49 | (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)"), | 49 | (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)"), |
| 50 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file note-upload size limit (`max_file_bytes`). Read: any authenticated user; edit: manager+"), | 50 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file note-upload size limit (`max_file_bytes`). Read: any authenticated user; edit: manager+"), |
| 51 | + (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"), | ||
| 51 | (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), | 52 | (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), |
| 52 | ), | 53 | ), |
| 53 | )] | 54 | )] |
| @@ -88,6 +89,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 88 | .nest("/work", web::work::routes()) | 89 | .nest("/work", web::work::routes()) |
| 89 | .nest("/attendance", web::attendance::routes()) | 90 | .nest("/attendance", web::attendance::routes()) |
| 90 | .nest("/settings", web::settings::routes()) | 91 | .nest("/settings", web::settings::routes()) |
| 92 | + .nest("/subjects", web::subjects::routes()) | ||
| 91 | .nest("/terms", web::terms::routes()) | 93 | .nest("/terms", web::terms::routes()) |
| 92 | .split_for_parts(); | 94 | .split_for_parts(); |
| 93 | 95 | ||
src/web/courses.rsmodified+97 -1
| @@ -18,6 +18,7 @@ use crate::domain::exam::{ | |||
| 18 | }; | 18 | }; |
| 19 | use crate::domain::role::Role; | 19 | use crate::domain::role::Role; |
| 20 | use crate::domain::settings::Settings; | 20 | use crate::domain::settings::Settings; |
| 21 | +use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 21 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| 22 | use crate::domain::user::{User, UserId}; | 23 | use crate::domain::user::{User, UserId}; |
| 23 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 24 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -27,7 +28,8 @@ use super::sessions::resolve_session_teacher; | |||
| 27 | use super::terms::resolve_term; | 28 | use super::terms::resolve_term; |
| 28 | use super::{ | 29 | use super::{ |
| 29 | CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, | 30 | CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, |
| 30 | - SessionResponse, check_not_past, check_time_range, paginate, person_map, set_or_clear, | 31 | + SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map, |
| 32 | + set_or_clear, | ||
| 31 | }; | 33 | }; |
| 32 | 34 | ||
| 33 | pub fn routes() -> OpenApiRouter<AppState> { | 35 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -39,6 +41,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 39 | .routes(routes!(unenroll)) | 41 | .routes(routes!(unenroll)) |
| 40 | .routes(routes!(create_exam_in_course, list_course_exams)) | 42 | .routes(routes!(create_exam_in_course, list_course_exams)) |
| 41 | .routes(routes!(create_session_in_course, list_course_sessions)) | 43 | .routes(routes!(create_session_in_course, list_course_sessions)) |
| 44 | + .routes(routes!(create_subject_in_course, list_course_subjects)) | ||
| 42 | } | 45 | } |
| 43 | 46 | ||
| 44 | #[derive(Deserialize, ToSchema)] | 47 | #[derive(Deserialize, ToSchema)] |
| @@ -655,6 +658,99 @@ async fn list_course_exams( | |||
| 655 | Ok(Json(Page::new(items, total, limit, offset))) | 658 | Ok(Json(Page::new(items, total, limit, offset))) |
| 656 | } | 659 | } |
| 657 | 660 | ||
| 661 | +// ---- subjects in a course --------------------------------------------------- | ||
| 662 | +// The course's curriculum topics. Every exam question links to one, so the | ||
| 663 | +// list doubles as the tag picker when authoring questions. | ||
| 664 | + | ||
| 665 | +#[derive(Deserialize, ToSchema)] | ||
| 666 | +struct CreateSubject { | ||
| 667 | + #[schema(example = "Limits and continuity")] | ||
| 668 | + name: String, | ||
| 669 | + description: Option<String>, | ||
| 670 | +} | ||
| 671 | + | ||
| 672 | +/// Create a subject inside a course. Requires teacher+ and course management | ||
| 673 | +/// rights. Subjects are the course's curriculum topics — every exam question | ||
| 674 | +/// must be tagged with one of its course's subjects. | ||
| 675 | +#[utoipa::path( | ||
| 676 | + post, | ||
| 677 | + path = "/{id}/subjects", | ||
| 678 | + tag = "subjects", | ||
| 679 | + security(("session_cookie" = [])), | ||
| 680 | + params(("id" = String, Path, description = "Course id")), | ||
| 681 | + request_body = CreateSubject, | ||
| 682 | + responses( | ||
| 683 | + (status = 201, description = "Subject created", body = SubjectResponse), | ||
| 684 | + (status = 400, description = "Invalid name or description", body = ErrorResponse), | ||
| 685 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 686 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 687 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 688 | + ), | ||
| 689 | +)] | ||
| 690 | +async fn create_subject_in_course( | ||
| 691 | + State(st): State<AppState>, | ||
| 692 | + RequireTeacher(user): RequireTeacher, | ||
| 693 | + Path(id): Path<String>, | ||
| 694 | + Json(req): Json<CreateSubject>, | ||
| 695 | +) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { | ||
| 696 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 697 | + .await? | ||
| 698 | + .ok_or(AppError::NotFound)?; | ||
| 699 | + if !can_manage_course(&course, &user) { | ||
| 700 | + return Err(AppError::Forbidden( | ||
| 701 | + "only the course creator or a manager/admin can add subjects to this course", | ||
| 702 | + )); | ||
| 703 | + } | ||
| 704 | + | ||
| 705 | + let name = SubjectName::try_new(&req.name)?; | ||
| 706 | + let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; | ||
| 707 | + let subject = Subject::create(course.get_id(), name, description, &st.db).await?; | ||
| 708 | + Ok((StatusCode::CREATED, Json(SubjectResponse::new(&subject)))) | ||
| 709 | +} | ||
| 710 | + | ||
| 711 | +/// List a course's subjects in creation order, paged via `?limit=&offset=` | ||
| 712 | +/// (omit `limit` for all of them). Visible to the course's enrolled users, its | ||
| 713 | +/// creator, and managers/admins. Returns a `{items, total, limit, offset}` | ||
| 714 | +/// envelope. | ||
| 715 | +#[utoipa::path( | ||
| 716 | + get, | ||
| 717 | + path = "/{id}/subjects", | ||
| 718 | + tag = "subjects", | ||
| 719 | + security(("session_cookie" = [])), | ||
| 720 | + params(("id" = String, Path, description = "Course id"), PageParams), | ||
| 721 | + responses( | ||
| 722 | + (status = 200, description = "A page of the course's subjects (all of them when unpaged)", body = Page<SubjectResponse>), | ||
| 723 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 724 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 725 | + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), | ||
| 726 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 727 | + ), | ||
| 728 | +)] | ||
| 729 | +async fn list_course_subjects( | ||
| 730 | + State(st): State<AppState>, | ||
| 731 | + CurrentUser(user): CurrentUser, | ||
| 732 | + Path(id): Path<String>, | ||
| 733 | + Query(page): Query<PageParams>, | ||
| 734 | +) -> Result<Json<Page<SubjectResponse>>, AppError> { | ||
| 735 | + let (limit, offset) = page.resolve()?; | ||
| 736 | + // Course must exist — a missing course is a 404, not an empty list. | ||
| 737 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 738 | + .await? | ||
| 739 | + .ok_or(AppError::NotFound)?; | ||
| 740 | + if !can_view_course(&course, &user, &st.db).await? { | ||
| 741 | + return Err(AppError::Forbidden( | ||
| 742 | + "only enrolled users, the course creator, or a manager/admin can view this course", | ||
| 743 | + )); | ||
| 744 | + } | ||
| 745 | + let subjects = Subject::list_for_course(course.get_id(), &st.db).await?; | ||
| 746 | + let total = subjects.len() as i64; | ||
| 747 | + let items = paginate(&subjects, limit, offset) | ||
| 748 | + .iter() | ||
| 749 | + .map(SubjectResponse::new) | ||
| 750 | + .collect(); | ||
| 751 | + Ok(Json(Page::new(items, total, limit, offset))) | ||
| 752 | +} | ||
| 753 | + | ||
| 658 | // ---- sessions in a course -------------------------------------------------- | 754 | // ---- sessions in a course -------------------------------------------------- |
| 659 | 755 | ||
| 660 | #[derive(Deserialize, ToSchema)] | 756 | #[derive(Deserialize, ToSchema)] |
src/web/dto.rsmodified+26 -0
| @@ -10,6 +10,7 @@ use crate::domain::course::Course; | |||
| 10 | use crate::domain::course_session::CourseSession; | 10 | use crate::domain::course_session::CourseSession; |
| 11 | use crate::domain::exam::Exam; | 11 | use crate::domain::exam::Exam; |
| 12 | use crate::domain::role::Role as DomainRole; | 12 | use crate::domain::role::Role as DomainRole; |
| 13 | +use crate::domain::subject::Subject; | ||
| 13 | use crate::domain::user::{User, UserId}; | 14 | use crate::domain::user::{User, UserId}; |
| 14 | use crate::error::AppError; | 15 | use crate::error::AppError; |
| 15 | 16 | ||
| @@ -182,6 +183,31 @@ impl CourseResponse { | |||
| 182 | } | 183 | } |
| 183 | } | 184 | } |
| 184 | 185 | ||
| 186 | +/// Public shape of a subject (one topic of a course's curriculum). Shared by | ||
| 187 | +/// `courses` (in-course creation and listing) and `subjects` (lookup, edit, | ||
| 188 | +/// delete). | ||
| 189 | +#[derive(Serialize, ToSchema)] | ||
| 190 | +pub struct SubjectResponse { | ||
| 191 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 192 | + pub id: String, | ||
| 193 | + /// The course whose curriculum this subject belongs to. | ||
| 194 | + pub course: String, | ||
| 195 | + #[schema(example = "Limits and continuity")] | ||
| 196 | + pub name: String, | ||
| 197 | + pub description: String, | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +impl SubjectResponse { | ||
| 201 | + pub fn new(subject: &Subject) -> Self { | ||
| 202 | + Self { | ||
| 203 | + id: subject.get_id().key().to_string(), | ||
| 204 | + course: subject.get_course().key().to_string(), | ||
| 205 | + name: subject.get_name().as_str().to_string(), | ||
| 206 | + description: subject.get_description().as_str().to_string(), | ||
| 207 | + } | ||
| 208 | + } | ||
| 209 | +} | ||
| 210 | + | ||
| 185 | /// Public shape of a course session (one lesson). Shared by `courses` | 211 | /// Public shape of a course session (one lesson). Shared by `courses` |
| 186 | /// (in-course creation and listing) and `sessions` (CRUD + roll call). | 212 | /// (in-course creation and listing) and `sessions` (CRUD + roll call). |
| 187 | #[derive(Serialize, ToSchema)] | 213 | #[derive(Serialize, ToSchema)] |
src/web/exams.rsmodified+30 -7
| @@ -34,6 +34,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; | |||
| 34 | use crate::state::AppState; | 34 | use crate::state::AppState; |
| 35 | 35 | ||
| 36 | use super::courses::{can_manage_course, can_view_course, visible_courses}; | 36 | use super::courses::{can_manage_course, can_view_course, visible_courses}; |
| 37 | +use super::subjects::subject_in_course; | ||
| 37 | use super::{ | 38 | use super::{ |
| 38 | CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past, | 39 | CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past, |
| 39 | paginate, person_map, set_or_clear, | 40 | paginate, person_map, set_or_clear, |
| @@ -1199,6 +1200,10 @@ async fn exam_live_stream( | |||
| 1199 | 1200 | ||
| 1200 | #[derive(Deserialize, ToSchema)] | 1201 | #[derive(Deserialize, ToSchema)] |
| 1201 | struct CreateQuestion { | 1202 | struct CreateQuestion { |
| 1203 | + /// The subject this question belongs to — one of the exam's course's | ||
| 1204 | + /// subjects (`GET /courses/{id}/subjects`). Required. | ||
| 1205 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 1206 | + subject_id: String, | ||
| 1202 | /// The question itself. | 1207 | /// The question itself. |
| 1203 | #[schema(example = "What is 2 + 2?")] | 1208 | #[schema(example = "What is 2 + 2?")] |
| 1204 | text: String, | 1209 | text: String, |
| @@ -1218,6 +1223,10 @@ struct CreateQuestion { | |||
| 1218 | 1223 | ||
| 1219 | #[derive(Deserialize, ToSchema)] | 1224 | #[derive(Deserialize, ToSchema)] |
| 1220 | struct UpdateQuestion { | 1225 | struct UpdateQuestion { |
| 1226 | + /// Re-tag the question with another of the course's subjects. Omit to | ||
| 1227 | + /// keep the current one — a question always has a subject, so there is no | ||
| 1228 | + /// clearing it. | ||
| 1229 | + subject_id: Option<String>, | ||
| 1221 | text: Option<String>, | 1230 | text: Option<String>, |
| 1222 | points: Option<i64>, | 1231 | points: Option<i64>, |
| 1223 | /// `choice` or `text`. Switching kinds needs the other fields to follow: | 1232 | /// `choice` or `text`. Switching kinds needs the other fields to follow: |
| @@ -1241,6 +1250,8 @@ struct UpdateQuestion { | |||
| 1241 | struct QuestionResponse { | 1250 | struct QuestionResponse { |
| 1242 | id: String, | 1251 | id: String, |
| 1243 | exam: String, | 1252 | exam: String, |
| 1253 | + /// The subject this question belongs to (`GET /subjects/{id}`). | ||
| 1254 | + subject: String, | ||
| 1244 | text: String, | 1255 | text: String, |
| 1245 | /// `choice` or `text`. | 1256 | /// `choice` or `text`. |
| 1246 | #[schema(example = "choice")] | 1257 | #[schema(example = "choice")] |
| @@ -1256,6 +1267,7 @@ impl QuestionResponse { | |||
| 1256 | Self { | 1267 | Self { |
| 1257 | id: question.get_id().key().to_string(), | 1268 | id: question.get_id().key().to_string(), |
| 1258 | exam: question.get_exam().key().to_string(), | 1269 | exam: question.get_exam().key().to_string(), |
| 1270 | + subject: question.get_subject().key().to_string(), | ||
| 1259 | text: question.get_text().as_str().to_string(), | 1271 | text: question.get_text().as_str().to_string(), |
| 1260 | kind: question.get_kind().as_str().to_string(), | 1272 | kind: question.get_kind().as_str().to_string(), |
| 1261 | points: question.get_points().as_i64(), | 1273 | points: question.get_points().as_i64(), |
| @@ -1295,8 +1307,10 @@ async fn question_of_exam( | |||
| 1295 | } | 1307 | } |
| 1296 | 1308 | ||
| 1297 | /// Add a question to an exam. Requires teacher+ and management rights over the | 1309 | /// Add a question to an exam. Requires teacher+ and management rights over the |
| 1298 | -/// exam's course. `choice` questions carry 2–10 `choices` plus the `correct` | 1310 | +/// exam's course. `subject_id` must name one of the course's subjects |
| 1299 | -/// index; `text` questions carry neither. Locked once attempts exist. | 1311 | +/// (`GET /courses/{id}/subjects`) — every question belongs to a subject. |
| 1312 | +/// `choice` questions carry 2–10 `choices` plus the `correct` index; `text` | ||
| 1313 | +/// questions carry neither. Locked once attempts exist. | ||
| 1300 | #[utoipa::path( | 1314 | #[utoipa::path( |
| 1301 | post, | 1315 | post, |
| 1302 | path = "/{id}/questions", | 1316 | path = "/{id}/questions", |
| @@ -1306,7 +1320,7 @@ async fn question_of_exam( | |||
| 1306 | request_body = CreateQuestion, | 1320 | request_body = CreateQuestion, |
| 1307 | responses( | 1321 | responses( |
| 1308 | (status = 201, description = "Question created", body = QuestionResponse), | 1322 | (status = 201, description = "Question created", body = QuestionResponse), |
| 1309 | - (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse), | 1323 | + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), |
| 1310 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1324 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1311 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | 1325 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 1312 | (status = 404, description = "Exam not found", body = ErrorResponse), | 1326 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| @@ -1330,10 +1344,11 @@ async fn create_question( | |||
| 1330 | } | 1344 | } |
| 1331 | ensure_questions_editable(exam.get_id(), &st.db).await?; | 1345 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 1332 | 1346 | ||
| 1347 | + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | ||
| 1333 | let text = QuestionText::try_new(&req.text)?; | 1348 | let text = QuestionText::try_new(&req.text)?; |
| 1334 | let points = QuestionPoints::try_new(req.points)?; | 1349 | let points = QuestionPoints::try_new(req.points)?; |
| 1335 | let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; | 1350 | let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; |
| 1336 | - let question = ExamQuestion::create(exam.get_id(), text, points, spec, &st.db).await?; | 1351 | + let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; |
| 1337 | Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) | 1352 | Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) |
| 1338 | } | 1353 | } |
| 1339 | 1354 | ||
| @@ -1384,7 +1399,8 @@ async fn list_questions( | |||
| 1384 | /// Edit a question. Requires teacher+ and management rights over the exam's | 1399 | /// Edit a question. Requires teacher+ and management rights over the exam's |
| 1385 | /// course. Omitted fields keep their value; `kind`/`choices`/`correct` are | 1400 | /// course. Omitted fields keep their value; `kind`/`choices`/`correct` are |
| 1386 | /// re-validated as a unit, so a kind switch must bring the matching fields | 1401 | /// re-validated as a unit, so a kind switch must bring the matching fields |
| 1387 | -/// along. Locked once attempts exist. | 1402 | +/// along. `subject_id` re-tags within the course's subjects. Locked once |
| 1403 | +/// attempts exist. | ||
| 1388 | #[utoipa::path( | 1404 | #[utoipa::path( |
| 1389 | patch, | 1405 | patch, |
| 1390 | path = "/{id}/questions/{qid}", | 1406 | path = "/{id}/questions/{qid}", |
| @@ -1397,7 +1413,7 @@ async fn list_questions( | |||
| 1397 | request_body = UpdateQuestion, | 1413 | request_body = UpdateQuestion, |
| 1398 | responses( | 1414 | responses( |
| 1399 | (status = 200, description = "Updated question", body = QuestionResponse), | 1415 | (status = 200, description = "Updated question", body = QuestionResponse), |
| 1400 | - (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse), | 1416 | + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), |
| 1401 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 1417 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1402 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | 1418 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 1403 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), | 1419 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| @@ -1422,6 +1438,10 @@ async fn update_question( | |||
| 1422 | ensure_questions_editable(exam.get_id(), &st.db).await?; | 1438 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 1423 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; | 1439 | let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; |
| 1424 | 1440 | ||
| 1441 | + let subject = match req.subject_id { | ||
| 1442 | + Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, | ||
| 1443 | + None => question.get_subject().clone(), | ||
| 1444 | + }; | ||
| 1425 | let text = match req.text { | 1445 | let text = match req.text { |
| 1426 | Some(ref text) => QuestionText::try_new(text)?, | 1446 | Some(ref text) => QuestionText::try_new(text)?, |
| 1427 | None => question.get_text().clone(), | 1447 | None => question.get_text().clone(), |
| @@ -1448,7 +1468,7 @@ async fn update_question( | |||
| 1448 | }; | 1468 | }; |
| 1449 | let spec = QuestionSpec::try_new(kind, choices, correct)?; | 1469 | let spec = QuestionSpec::try_new(kind, choices, correct)?; |
| 1450 | 1470 | ||
| 1451 | - let updated = question.update(text, points, spec, &st.db).await?; | 1471 | + let updated = question.update(subject, text, points, spec, &st.db).await?; |
| 1452 | Ok(Json(QuestionResponse::new(&updated))) | 1472 | Ok(Json(QuestionResponse::new(&updated))) |
| 1453 | } | 1473 | } |
| 1454 | 1474 | ||
| @@ -1522,6 +1542,8 @@ impl AnswerStateResponse { | |||
| 1522 | #[derive(Serialize, ToSchema)] | 1542 | #[derive(Serialize, ToSchema)] |
| 1523 | struct AttemptQuestionResponse { | 1543 | struct AttemptQuestionResponse { |
| 1524 | id: String, | 1544 | id: String, |
| 1545 | + /// The subject this question belongs to (`GET /subjects/{id}`). | ||
| 1546 | + subject: String, | ||
| 1525 | text: String, | 1547 | text: String, |
| 1526 | /// `choice` or `text`. | 1548 | /// `choice` or `text`. |
| 1527 | #[schema(example = "choice")] | 1549 | #[schema(example = "choice")] |
| @@ -1711,6 +1733,7 @@ async fn attempt_questions( | |||
| 1711 | .iter() | 1733 | .iter() |
| 1712 | .map(|question| AttemptQuestionResponse { | 1734 | .map(|question| AttemptQuestionResponse { |
| 1713 | id: question.get_id().key().to_string(), | 1735 | id: question.get_id().key().to_string(), |
| 1736 | + subject: question.get_subject().key().to_string(), | ||
| 1714 | text: question.get_text().as_str().to_string(), | 1737 | text: question.get_text().as_str().to_string(), |
| 1715 | kind: question.get_kind().as_str().to_string(), | 1738 | kind: question.get_kind().as_str().to_string(), |
| 1716 | points: question.get_points().as_i64(), | 1739 | points: question.get_points().as_i64(), |
src/web/mod.rsmodified+5 -1
| @@ -13,6 +13,7 @@ pub mod marks; | |||
| 13 | pub mod notes; | 13 | pub mod notes; |
| 14 | pub mod sessions; | 14 | pub mod sessions; |
| 15 | pub mod settings; | 15 | pub mod settings; |
| 16 | +pub mod subjects; | ||
| 16 | pub mod terms; | 17 | pub mod terms; |
| 17 | pub mod users; | 18 | pub mod users; |
| 18 | pub mod work; | 19 | pub mod work; |
| @@ -21,7 +22,10 @@ mod dto; | |||
| 21 | mod extractor; | 22 | mod extractor; |
| 22 | mod page; | 23 | mod page; |
| 23 | 24 | ||
| 24 | -pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map}; | 25 | +pub use dto::{ |
| 26 | + CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, | ||
| 27 | + person_map, | ||
| 28 | +}; | ||
| 25 | pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; | 29 | pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; |
| 26 | pub use page::{Page, PageParams, paginate}; | 30 | pub use page::{Page, PageParams, paginate}; |
| 27 | 31 | ||
src/web/subjects.rsadded+174 -0
| @@ -0,0 +1,174 @@ | |||
| 1 | +use axum::Json; | ||
| 2 | +use axum::extract::{Path, State}; | ||
| 3 | +use axum::http::StatusCode; | ||
| 4 | +use serde::Deserialize; | ||
| 5 | +use utoipa::ToSchema; | ||
| 6 | +use utoipa_axum::router::OpenApiRouter; | ||
| 7 | +use utoipa_axum::routes; | ||
| 8 | + | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::domain::course::{Course, CourseId}; | ||
| 11 | +use crate::domain::exam_question::ExamQuestion; | ||
| 12 | +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; | ||
| 13 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 14 | +use crate::state::AppState; | ||
| 15 | + | ||
| 16 | +use super::courses::{can_manage_course, can_view_course}; | ||
| 17 | +use super::{CurrentUser, RequireTeacher, SubjectResponse}; | ||
| 18 | + | ||
| 19 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 20 | + OpenApiRouter::new().routes(routes!(get_subject, update_subject, delete_subject)) | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +#[derive(Deserialize, ToSchema)] | ||
| 24 | +struct UpdateSubject { | ||
| 25 | + name: Option<String>, | ||
| 26 | + description: Option<String>, | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Turn a request-supplied subject id into a validated reference, provided the | ||
| 30 | +/// subject belongs to `course` — a question may only be tagged with a subject | ||
| 31 | +/// of its own exam's course. Unknown or foreign subjects are a `400` naming | ||
| 32 | +/// the field. Shared by the question create/update handlers. | ||
| 33 | +pub(crate) async fn subject_in_course( | ||
| 34 | + id: &str, | ||
| 35 | + course: &CourseId, | ||
| 36 | + db: &Database, | ||
| 37 | +) -> Result<SubjectId, AppError> { | ||
| 38 | + let subject = | ||
| 39 | + Subject::read(&SubjectId::from_key(id), db) | ||
| 40 | + .await? | ||
| 41 | + .ok_or(AppError::Validation(ValidationError::Invalid { | ||
| 42 | + field: "subject_id", | ||
| 43 | + reason: "subject does not exist", | ||
| 44 | + }))?; | ||
| 45 | + if subject.get_course() != course { | ||
| 46 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 47 | + field: "subject_id", | ||
| 48 | + reason: "subject belongs to a different course", | ||
| 49 | + })); | ||
| 50 | + } | ||
| 51 | + Ok(subject.get_id().clone()) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The subject plus its course, or a 404 — every handler here gates on the | ||
| 55 | +/// parent course, so they always travel together. | ||
| 56 | +async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { | ||
| 57 | + let subject = Subject::read(&SubjectId::from_key(id), db) | ||
| 58 | + .await? | ||
| 59 | + .ok_or(AppError::NotFound)?; | ||
| 60 | + let course = Course::read(subject.get_course(), db) | ||
| 61 | + .await? | ||
| 62 | + .ok_or(AppError::NotFound)?; | ||
| 63 | + Ok((subject, course)) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Fetch a single subject by id. Visible to whoever can view its course: the | ||
| 67 | +/// course's enrolled users, its creator, and managers/admins. | ||
| 68 | +#[utoipa::path( | ||
| 69 | + get, | ||
| 70 | + path = "/{id}", | ||
| 71 | + tag = "subjects", | ||
| 72 | + security(("session_cookie" = [])), | ||
| 73 | + params(("id" = String, Path, description = "Subject id")), | ||
| 74 | + responses( | ||
| 75 | + (status = 200, description = "The subject", body = SubjectResponse), | ||
| 76 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 77 | + (status = 403, description = "Not enrolled, not the course creator, and not a manager/admin", body = ErrorResponse), | ||
| 78 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 79 | + ), | ||
| 80 | +)] | ||
| 81 | +async fn get_subject( | ||
| 82 | + State(st): State<AppState>, | ||
| 83 | + CurrentUser(user): CurrentUser, | ||
| 84 | + Path(id): Path<String>, | ||
| 85 | +) -> Result<Json<SubjectResponse>, AppError> { | ||
| 86 | + let (subject, course) = subject_with_course(&id, &st.db).await?; | ||
| 87 | + if !can_view_course(&course, &user, &st.db).await? { | ||
| 88 | + return Err(AppError::Forbidden( | ||
| 89 | + "only enrolled users, the course creator, or a manager/admin can view this subject", | ||
| 90 | + )); | ||
| 91 | + } | ||
| 92 | + Ok(Json(SubjectResponse::new(&subject))) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Update a subject's name or description. Requires teacher+ and management | ||
| 96 | +/// rights over its course. Omitted fields keep their value; the course link is | ||
| 97 | +/// fixed at creation. | ||
| 98 | +#[utoipa::path( | ||
| 99 | + patch, | ||
| 100 | + path = "/{id}", | ||
| 101 | + tag = "subjects", | ||
| 102 | + security(("session_cookie" = [])), | ||
| 103 | + params(("id" = String, Path, description = "Subject id")), | ||
| 104 | + request_body = UpdateSubject, | ||
| 105 | + responses( | ||
| 106 | + (status = 200, description = "Updated subject", body = SubjectResponse), | ||
| 107 | + (status = 400, description = "Invalid name or description", body = ErrorResponse), | ||
| 108 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 109 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 110 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 111 | + ), | ||
| 112 | +)] | ||
| 113 | +async fn update_subject( | ||
| 114 | + State(st): State<AppState>, | ||
| 115 | + RequireTeacher(user): RequireTeacher, | ||
| 116 | + Path(id): Path<String>, | ||
| 117 | + Json(req): Json<UpdateSubject>, | ||
| 118 | +) -> Result<Json<SubjectResponse>, AppError> { | ||
| 119 | + let (subject, course) = subject_with_course(&id, &st.db).await?; | ||
| 120 | + if !can_manage_course(&course, &user) { | ||
| 121 | + return Err(AppError::Forbidden( | ||
| 122 | + "only the course creator or a manager/admin can edit this subject", | ||
| 123 | + )); | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + let name = match req.name { | ||
| 127 | + Some(ref name) => SubjectName::try_new(name)?, | ||
| 128 | + None => subject.get_name().clone(), | ||
| 129 | + }; | ||
| 130 | + let description = match req.description { | ||
| 131 | + Some(ref description) => SubjectDescription::try_new(description)?, | ||
| 132 | + None => subject.get_description().clone(), | ||
| 133 | + }; | ||
| 134 | + | ||
| 135 | + let updated = subject.update(name, description, &st.db).await?; | ||
| 136 | + Ok(Json(SubjectResponse::new(&updated))) | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +/// Delete a subject. Requires teacher+ and management rights over its course. | ||
| 140 | +/// Refused with a 409 while any exam question still references it — re-tag or | ||
| 141 | +/// delete those questions first, so no question is left without a real subject. | ||
| 142 | +#[utoipa::path( | ||
| 143 | + delete, | ||
| 144 | + path = "/{id}", | ||
| 145 | + tag = "subjects", | ||
| 146 | + security(("session_cookie" = [])), | ||
| 147 | + params(("id" = String, Path, description = "Subject id")), | ||
| 148 | + responses( | ||
| 149 | + (status = 204, description = "Deleted"), | ||
| 150 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 151 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 152 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 153 | + (status = 409, description = "Exam questions still reference this subject", body = ErrorResponse), | ||
| 154 | + ), | ||
| 155 | +)] | ||
| 156 | +async fn delete_subject( | ||
| 157 | + State(st): State<AppState>, | ||
| 158 | + RequireTeacher(user): RequireTeacher, | ||
| 159 | + Path(id): Path<String>, | ||
| 160 | +) -> Result<StatusCode, AppError> { | ||
| 161 | + let (subject, course) = subject_with_course(&id, &st.db).await?; | ||
| 162 | + if !can_manage_course(&course, &user) { | ||
| 163 | + return Err(AppError::Forbidden( | ||
| 164 | + "only the course creator or a manager/admin can delete this subject", | ||
| 165 | + )); | ||
| 166 | + } | ||
| 167 | + if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? { | ||
| 168 | + return Err(AppError::Conflict( | ||
| 169 | + "exam questions still reference this subject — re-tag or delete them first", | ||
| 170 | + )); | ||
| 171 | + } | ||
| 172 | + subject.delete(&st.db).await?; | ||
| 173 | + Ok(StatusCode::NO_CONTENT) | ||
| 174 | +} | ||
tests/common/mod.rsmodified+15 -0
| @@ -254,6 +254,21 @@ pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String { | |||
| 254 | id_of(&res.body) | 254 | id_of(&res.body) |
| 255 | } | 255 | } |
| 256 | 256 | ||
| 257 | +/// Create a subject inside `course` as `cookie` (asserts 201); returns its id. | ||
| 258 | +/// Every exam question must be tagged with one of its course's subjects. | ||
| 259 | +pub async fn create_subject(app: &Router, cookie: &str, course: &str, name: &str) -> String { | ||
| 260 | + let res = send( | ||
| 261 | + app, | ||
| 262 | + "POST", | ||
| 263 | + &format!("/courses/{course}/subjects"), | ||
| 264 | + Some(cookie), | ||
| 265 | + Some(json!({ "name": name })), | ||
| 266 | + ) | ||
| 267 | + .await; | ||
| 268 | + assert_eq!(res.status, StatusCode::CREATED, "create subject {name}"); | ||
| 269 | + id_of(&res.body) | ||
| 270 | +} | ||
| 271 | + | ||
| 257 | /// Create an exam inside `course` as `cookie` (asserts 201); returns its id. | 272 | /// Create an exam inside `course` as `cookie` (asserts 201); returns its id. |
| 258 | /// The exam's weight in the course average comes from its kind (settings). | 273 | /// The exam's weight in the course average comes from its kind (settings). |
| 259 | pub async fn create_exam( | 274 | pub async fn create_exam( |
tests/e2e.rsmodified+30 -9
| @@ -767,6 +767,7 @@ struct ExamRoom { | |||
| 767 | student_id: String, | 767 | student_id: String, |
| 768 | cookie: String, | 768 | cookie: String, |
| 769 | course_id: String, | 769 | course_id: String, |
| 770 | + subject_id: String, | ||
| 770 | exam_id: String, | 771 | exam_id: String, |
| 771 | question_id: String, | 772 | question_id: String, |
| 772 | } | 773 | } |
| @@ -810,6 +811,16 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | |||
| 810 | .await | 811 | .await |
| 811 | .unwrap(); | 812 | .unwrap(); |
| 812 | let course_id = course["id"].as_str().unwrap().to_string(); | 813 | let course_id = course["id"].as_str().unwrap().to_string(); |
| 814 | + let subject: Value = teacher | ||
| 815 | + .post(format!("{base}/courses/{course_id}/subjects")) | ||
| 816 | + .json(&json!({ "name": "arithmetic" })) | ||
| 817 | + .send() | ||
| 818 | + .await | ||
| 819 | + .unwrap() | ||
| 820 | + .json() | ||
| 821 | + .await | ||
| 822 | + .unwrap(); | ||
| 823 | + let subject_id = subject["id"].as_str().unwrap().to_string(); | ||
| 813 | let res = teacher | 824 | let res = teacher |
| 814 | .post(format!("{base}/courses/{course_id}/enrollments")) | 825 | .post(format!("{base}/courses/{course_id}/enrollments")) |
| 815 | .json(&json!({ "user_id": student_id })) | 826 | .json(&json!({ "user_id": student_id })) |
| @@ -832,8 +843,10 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | |||
| 832 | let exam_id = exam["id"].as_str().unwrap().to_string(); | 843 | let exam_id = exam["id"].as_str().unwrap().to_string(); |
| 833 | let question: Value = teacher | 844 | let question: Value = teacher |
| 834 | .post(format!("{base}/exams/{exam_id}/questions")) | 845 | .post(format!("{base}/exams/{exam_id}/questions")) |
| 835 | - .json(&json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 846 | + .json( |
| 836 | - "choices": ["3", "4"], "correct": 1 })) | 847 | + &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", |
| 848 | + "points": 10, "choices": ["3", "4"], "correct": 1 }), | ||
| 849 | + ) | ||
| 837 | .send() | 850 | .send() |
| 838 | .await | 851 | .await |
| 839 | .unwrap() | 852 | .unwrap() |
| @@ -850,6 +863,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { | |||
| 850 | student_id, | 863 | student_id, |
| 851 | cookie, | 864 | cookie, |
| 852 | course_id, | 865 | course_id, |
| 866 | + subject_id, | ||
| 853 | exam_id, | 867 | exam_id, |
| 854 | question_id, | 868 | question_id, |
| 855 | } | 869 | } |
| @@ -875,7 +889,8 @@ async fn exam_room_websocket_round_trip() { | |||
| 875 | // A second question so progress counts have something to be partial over. | 889 | // A second question so progress counts have something to be partial over. |
| 876 | let res = teacher | 890 | let res = teacher |
| 877 | .post(format!("{base}/exams/{exam_id}/questions")) | 891 | .post(format!("{base}/exams/{exam_id}/questions")) |
| 878 | - .json(&json!({ "text": "Explain.", "kind": "text", "points": 20 })) | 892 | + .json(&json!({ "subject_id": room.subject_id, "text": "Explain.", |
| 893 | + "kind": "text", "points": 20 })) | ||
| 879 | .send() | 894 | .send() |
| 880 | .await | 895 | .await |
| 881 | .unwrap(); | 896 | .unwrap(); |
| @@ -1438,8 +1453,10 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { | |||
| 1438 | let question: Value = room | 1453 | let question: Value = room |
| 1439 | .teacher | 1454 | .teacher |
| 1440 | .post(format!("{}/exams/{exam_id}/questions", room.base)) | 1455 | .post(format!("{}/exams/{exam_id}/questions", room.base)) |
| 1441 | - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, | 1456 | + .json( |
| 1442 | - "choices": ["5", "6"], "correct": 1 })) | 1457 | + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", |
| 1458 | + "points": 5, "choices": ["5", "6"], "correct": 1 }), | ||
| 1459 | + ) | ||
| 1443 | .send() | 1460 | .send() |
| 1444 | .await | 1461 | .await |
| 1445 | .unwrap() | 1462 | .unwrap() |
| @@ -1542,8 +1559,10 @@ async fn exam_room_messages_bind_to_their_own_sitting() { | |||
| 1542 | let question: Value = room | 1559 | let question: Value = room |
| 1543 | .teacher | 1560 | .teacher |
| 1544 | .post(format!("{}/exams/{exam_id}/questions", room.base)) | 1561 | .post(format!("{}/exams/{exam_id}/questions", room.base)) |
| 1545 | - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, | 1562 | + .json( |
| 1546 | - "choices": ["5", "6"], "correct": 1 })) | 1563 | + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", |
| 1564 | + "points": 5, "choices": ["5", "6"], "correct": 1 }), | ||
| 1565 | + ) | ||
| 1547 | .send() | 1566 | .send() |
| 1548 | .await | 1567 | .await |
| 1549 | .unwrap() | 1568 | .unwrap() |
| @@ -1727,8 +1746,10 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { | |||
| 1727 | let question: Value = room | 1746 | let question: Value = room |
| 1728 | .teacher | 1747 | .teacher |
| 1729 | .post(format!("{}/exams/{exam_id}/questions", room.base)) | 1748 | .post(format!("{}/exams/{exam_id}/questions", room.base)) |
| 1730 | - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, | 1749 | + .json( |
| 1731 | - "choices": ["5", "6"], "correct": 1 })) | 1750 | + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", |
| 1751 | + "points": 5, "choices": ["5", "6"], "correct": 1 }), | ||
| 1752 | + ) | ||
| 1732 | .send() | 1753 | .send() |
| 1733 | .await | 1754 | .await |
| 1734 | .unwrap() | 1755 | .unwrap() |
tests/integration.rsmodified+378 -23
| @@ -6,8 +6,8 @@ mod common; | |||
| 6 | use axum::body::Body; | 6 | use axum::body::Body; |
| 7 | use axum::http::{Request, StatusCode}; | 7 | use axum::http::{Request, StatusCode}; |
| 8 | use common::{ | 8 | use common::{ |
| 9 | - app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, | 9 | + app_and_db, create_course, create_exam, create_exam_with, create_session, create_subject, |
| 10 | - login_as, me_id, mem_app, send, set_role, | 10 | + enroll, id_of, login, login_as, me_id, mem_app, send, set_role, |
| 11 | }; | 11 | }; |
| 12 | use hezarfen_backend::domain::exam::ExamId; | 12 | use hezarfen_backend::domain::exam::ExamId; |
| 13 | use hezarfen_backend::domain::exam_attempt::ExamAttempt; | 13 | use hezarfen_backend::domain::exam_attempt::ExamAttempt; |
| @@ -5792,6 +5792,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { | |||
| 5792 | let student = login(&app, "omer").await; | 5792 | let student = login(&app, "omer").await; |
| 5793 | let student_id = me_id(&app, &student).await; | 5793 | let student_id = me_id(&app, &student).await; |
| 5794 | let course = create_course(&app, &teacher, "practice").await; | 5794 | let course = create_course(&app, &teacher, "practice").await; |
| 5795 | + let subject = create_subject(&app, &teacher, &course, "drills").await; | ||
| 5795 | enroll(&app, &teacher, &course, &student_id).await; | 5796 | enroll(&app, &teacher, &course, &student_id).await; |
| 5796 | let exam = scheduled_exam( | 5797 | let exam = scheduled_exam( |
| 5797 | &app, | 5798 | &app, |
| @@ -5805,6 +5806,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { | |||
| 5805 | &app, | 5806 | &app, |
| 5806 | &teacher, | 5807 | &teacher, |
| 5807 | &exam, | 5808 | &exam, |
| 5809 | + &subject, | ||
| 5808 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 5810 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 5809 | "choices": ["3", "4"], "correct": 1 }), | 5811 | "choices": ["3", "4"], "correct": 1 }), |
| 5810 | ) | 5812 | ) |
| @@ -6143,16 +6145,283 @@ async fn live_stream_is_sse_and_teacher_scoped() { | |||
| 6143 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 6145 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 6144 | } | 6146 | } |
| 6145 | 6147 | ||
| 6148 | +// --- subjects --------------------------------------------------------------- | ||
| 6149 | + | ||
| 6150 | +#[tokio::test] | ||
| 6151 | +async fn subject_crud_validation_and_rbac() { | ||
| 6152 | + let (app, db) = app_and_db().await; | ||
| 6153 | + let teacher = login_as(&app, &db, "sub_t", "teacher").await; | ||
| 6154 | + let other_teacher = login_as(&app, &db, "sub_t2", "teacher").await; | ||
| 6155 | + let boss = login_as(&app, &db, "sub_m", "manager").await; | ||
| 6156 | + let student = login(&app, "selin").await; | ||
| 6157 | + let student_id = me_id(&app, &student).await; | ||
| 6158 | + let course = create_course(&app, &teacher, "calculus").await; | ||
| 6159 | + enroll(&app, &teacher, &course, &student_id).await; | ||
| 6160 | + | ||
| 6161 | + // Create echoes the full shape; description defaults to empty. | ||
| 6162 | + let res = send( | ||
| 6163 | + &app, | ||
| 6164 | + "POST", | ||
| 6165 | + &format!("/courses/{course}/subjects"), | ||
| 6166 | + Some(&teacher), | ||
| 6167 | + Some(json!({ "name": "limits", "description": "epsilon-delta" })), | ||
| 6168 | + ) | ||
| 6169 | + .await; | ||
| 6170 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 6171 | + assert_eq!(res.body["course"], course); | ||
| 6172 | + assert_eq!(res.body["name"], "limits"); | ||
| 6173 | + assert_eq!(res.body["description"], "epsilon-delta"); | ||
| 6174 | + let subject = id_of(&res.body); | ||
| 6175 | + let second = create_subject(&app, &teacher, &course, "derivatives").await; | ||
| 6176 | + | ||
| 6177 | + // Validation: a blank name is a 400, a missing course a 404. | ||
| 6178 | + let res = send( | ||
| 6179 | + &app, | ||
| 6180 | + "POST", | ||
| 6181 | + &format!("/courses/{course}/subjects"), | ||
| 6182 | + Some(&teacher), | ||
| 6183 | + Some(json!({ "name": " " })), | ||
| 6184 | + ) | ||
| 6185 | + .await; | ||
| 6186 | + assert_eq!(res.status, StatusCode::BAD_REQUEST); | ||
| 6187 | + let res = send( | ||
| 6188 | + &app, | ||
| 6189 | + "POST", | ||
| 6190 | + "/courses/missing/subjects", | ||
| 6191 | + Some(&teacher), | ||
| 6192 | + Some(json!({ "name": "orphan" })), | ||
| 6193 | + ) | ||
| 6194 | + .await; | ||
| 6195 | + assert_eq!(res.status, StatusCode::NOT_FOUND); | ||
| 6196 | + | ||
| 6197 | + // Writes are management-gated: students lack the role, a rival teacher | ||
| 6198 | + // the rights; a manager passes everywhere. | ||
| 6199 | + let res = send( | ||
| 6200 | + &app, | ||
| 6201 | + "POST", | ||
| 6202 | + &format!("/courses/{course}/subjects"), | ||
| 6203 | + Some(&student), | ||
| 6204 | + Some(json!({ "name": "nope" })), | ||
| 6205 | + ) | ||
| 6206 | + .await; | ||
| 6207 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6208 | + let res = send( | ||
| 6209 | + &app, | ||
| 6210 | + "POST", | ||
| 6211 | + &format!("/courses/{course}/subjects"), | ||
| 6212 | + Some(&other_teacher), | ||
| 6213 | + Some(json!({ "name": "nope" })), | ||
| 6214 | + ) | ||
| 6215 | + .await; | ||
| 6216 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6217 | + let res = send( | ||
| 6218 | + &app, | ||
| 6219 | + "PATCH", | ||
| 6220 | + &format!("/subjects/{subject}"), | ||
| 6221 | + Some(&other_teacher), | ||
| 6222 | + Some(json!({ "name": "hijack" })), | ||
| 6223 | + ) | ||
| 6224 | + .await; | ||
| 6225 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6226 | + let res = send( | ||
| 6227 | + &app, | ||
| 6228 | + "DELETE", | ||
| 6229 | + &format!("/subjects/{second}"), | ||
| 6230 | + Some(&student), | ||
| 6231 | + None, | ||
| 6232 | + ) | ||
| 6233 | + .await; | ||
| 6234 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6235 | + | ||
| 6236 | + // Reads follow course visibility: the enrolled student and a manager see | ||
| 6237 | + // the list and the subject, the rival teacher sees neither. | ||
| 6238 | + let res = send( | ||
| 6239 | + &app, | ||
| 6240 | + "GET", | ||
| 6241 | + &format!("/courses/{course}/subjects"), | ||
| 6242 | + Some(&student), | ||
| 6243 | + None, | ||
| 6244 | + ) | ||
| 6245 | + .await; | ||
| 6246 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6247 | + let listed = common::items(&res.body); | ||
| 6248 | + assert_eq!(listed.len(), 2, "creation order"); | ||
| 6249 | + assert_eq!(id_of(&listed[0]), subject); | ||
| 6250 | + assert_eq!(id_of(&listed[1]), second); | ||
| 6251 | + assert_eq!(common::total(&res.body), 2); | ||
| 6252 | + let res = send( | ||
| 6253 | + &app, | ||
| 6254 | + "GET", | ||
| 6255 | + &format!("/subjects/{subject}"), | ||
| 6256 | + Some(&student), | ||
| 6257 | + None, | ||
| 6258 | + ) | ||
| 6259 | + .await; | ||
| 6260 | + assert_eq!(res.status, StatusCode::OK); | ||
| 6261 | + assert_eq!(res.body["name"], "limits"); | ||
| 6262 | + let res = send( | ||
| 6263 | + &app, | ||
| 6264 | + "GET", | ||
| 6265 | + &format!("/courses/{course}/subjects"), | ||
| 6266 | + Some(&other_teacher), | ||
| 6267 | + None, | ||
| 6268 | + ) | ||
| 6269 | + .await; | ||
| 6270 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6271 | + let res = send( | ||
| 6272 | + &app, | ||
| 6273 | + "GET", | ||
| 6274 | + &format!("/subjects/{subject}"), | ||
| 6275 | + Some(&other_teacher), | ||
| 6276 | + None, | ||
| 6277 | + ) | ||
| 6278 | + .await; | ||
| 6279 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6280 | + | ||
| 6281 | + // PATCH keeps omitted fields; a manager may edit anyone's. | ||
| 6282 | + let res = send( | ||
| 6283 | + &app, | ||
| 6284 | + "PATCH", | ||
| 6285 | + &format!("/subjects/{subject}"), | ||
| 6286 | + Some(&boss), | ||
| 6287 | + Some(json!({ "name": "limits & continuity" })), | ||
| 6288 | + ) | ||
| 6289 | + .await; | ||
| 6290 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6291 | + assert_eq!(res.body["name"], "limits & continuity"); | ||
| 6292 | + assert_eq!(res.body["description"], "epsilon-delta", "kept by omission"); | ||
| 6293 | + | ||
| 6294 | + // Unknown ids are 404s. | ||
| 6295 | + for (method, body) in [ | ||
| 6296 | + ("GET", None), | ||
| 6297 | + ("PATCH", Some(json!({ "name": "x" }))), | ||
| 6298 | + ("DELETE", None), | ||
| 6299 | + ] { | ||
| 6300 | + let res = send(&app, method, "/subjects/missing", Some(&teacher), body).await; | ||
| 6301 | + assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}"); | ||
| 6302 | + } | ||
| 6303 | + | ||
| 6304 | + // Delete works while nothing references the subject. | ||
| 6305 | + let res = send( | ||
| 6306 | + &app, | ||
| 6307 | + "DELETE", | ||
| 6308 | + &format!("/subjects/{second}"), | ||
| 6309 | + Some(&teacher), | ||
| 6310 | + None, | ||
| 6311 | + ) | ||
| 6312 | + .await; | ||
| 6313 | + assert_eq!(res.status, StatusCode::NO_CONTENT); | ||
| 6314 | + let res = send( | ||
| 6315 | + &app, | ||
| 6316 | + "GET", | ||
| 6317 | + &format!("/subjects/{second}"), | ||
| 6318 | + Some(&teacher), | ||
| 6319 | + None, | ||
| 6320 | + ) | ||
| 6321 | + .await; | ||
| 6322 | + assert_eq!(res.status, StatusCode::NOT_FOUND); | ||
| 6323 | +} | ||
| 6324 | + | ||
| 6325 | +#[tokio::test] | ||
| 6326 | +async fn subject_delete_blocks_while_questions_reference_it() { | ||
| 6327 | + let (app, db) = app_and_db().await; | ||
| 6328 | + let teacher = login_as(&app, &db, "sdb_t", "teacher").await; | ||
| 6329 | + let course = create_course(&app, &teacher, "history").await; | ||
| 6330 | + let tagged = create_subject(&app, &teacher, &course, "antiquity").await; | ||
| 6331 | + let spare = create_subject(&app, &teacher, &course, "middle ages").await; | ||
| 6332 | + let exam = create_exam(&app, &teacher, &course, "final", "final").await; | ||
| 6333 | + let question = create_question( | ||
| 6334 | + &app, | ||
| 6335 | + &teacher, | ||
| 6336 | + &exam, | ||
| 6337 | + &tagged, | ||
| 6338 | + json!({ "text": "When?", "kind": "text", "points": 10 }), | ||
| 6339 | + ) | ||
| 6340 | + .await; | ||
| 6341 | + | ||
| 6342 | + // Referenced: the delete is a conflict, and the subject survives. | ||
| 6343 | + let res = send( | ||
| 6344 | + &app, | ||
| 6345 | + "DELETE", | ||
| 6346 | + &format!("/subjects/{tagged}"), | ||
| 6347 | + Some(&teacher), | ||
| 6348 | + None, | ||
| 6349 | + ) | ||
| 6350 | + .await; | ||
| 6351 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | ||
| 6352 | + let res = send( | ||
| 6353 | + &app, | ||
| 6354 | + "GET", | ||
| 6355 | + &format!("/subjects/{tagged}"), | ||
| 6356 | + Some(&teacher), | ||
| 6357 | + None, | ||
| 6358 | + ) | ||
| 6359 | + .await; | ||
| 6360 | + assert_eq!(res.status, StatusCode::OK); | ||
| 6361 | + | ||
| 6362 | + // Re-tag the question elsewhere: the old subject frees up, the new one | ||
| 6363 | + // locks. | ||
| 6364 | + let res = send( | ||
| 6365 | + &app, | ||
| 6366 | + "PATCH", | ||
| 6367 | + &format!("/exams/{exam}/questions/{question}"), | ||
| 6368 | + Some(&teacher), | ||
| 6369 | + Some(json!({ "subject_id": spare })), | ||
| 6370 | + ) | ||
| 6371 | + .await; | ||
| 6372 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6373 | + let res = send( | ||
| 6374 | + &app, | ||
| 6375 | + "DELETE", | ||
| 6376 | + &format!("/subjects/{tagged}"), | ||
| 6377 | + Some(&teacher), | ||
| 6378 | + None, | ||
| 6379 | + ) | ||
| 6380 | + .await; | ||
| 6381 | + assert_eq!(res.status, StatusCode::NO_CONTENT); | ||
| 6382 | + let res = send( | ||
| 6383 | + &app, | ||
| 6384 | + "DELETE", | ||
| 6385 | + &format!("/subjects/{spare}"), | ||
| 6386 | + Some(&teacher), | ||
| 6387 | + None, | ||
| 6388 | + ) | ||
| 6389 | + .await; | ||
| 6390 | + assert_eq!(res.status, StatusCode::CONFLICT); | ||
| 6391 | + | ||
| 6392 | + // Deleting the question releases the last reference. | ||
| 6393 | + let res = send( | ||
| 6394 | + &app, | ||
| 6395 | + "DELETE", | ||
| 6396 | + &format!("/exams/{exam}/questions/{question}"), | ||
| 6397 | + Some(&teacher), | ||
| 6398 | + None, | ||
| 6399 | + ) | ||
| 6400 | + .await; | ||
| 6401 | + assert_eq!(res.status, StatusCode::NO_CONTENT); | ||
| 6402 | + let res = send( | ||
| 6403 | + &app, | ||
| 6404 | + "DELETE", | ||
| 6405 | + &format!("/subjects/{spare}"), | ||
| 6406 | + Some(&teacher), | ||
| 6407 | + None, | ||
| 6408 | + ) | ||
| 6409 | + .await; | ||
| 6410 | + assert_eq!(res.status, StatusCode::NO_CONTENT); | ||
| 6411 | +} | ||
| 6412 | + | ||
| 6146 | // --- exam questions + answers (taking an exam) ----------------------------- | 6413 | // --- exam questions + answers (taking an exam) ----------------------------- |
| 6147 | 6414 | ||
| 6148 | -/// Create a question via `POST /exams/{exam}/questions` (asserts 201); | 6415 | +/// Create a question tagged with `subject` via `POST /exams/{exam}/questions` |
| 6149 | -/// returns its id. | 6416 | +/// (asserts 201); returns its id. |
| 6150 | async fn create_question( | 6417 | async fn create_question( |
| 6151 | app: &axum::Router, | 6418 | app: &axum::Router, |
| 6152 | cookie: &str, | 6419 | cookie: &str, |
| 6153 | exam: &str, | 6420 | exam: &str, |
| 6154 | - body: serde_json::Value, | 6421 | + subject: &str, |
| 6422 | + mut body: serde_json::Value, | ||
| 6155 | ) -> String { | 6423 | ) -> String { |
| 6424 | + body["subject_id"] = json!(subject); | ||
| 6156 | let res = send( | 6425 | let res = send( |
| 6157 | app, | 6426 | app, |
| 6158 | "POST", | 6427 | "POST", |
| @@ -6170,15 +6439,16 @@ async fn create_question( | |||
| 6170 | id_of(&res.body) | 6439 | id_of(&res.body) |
| 6171 | } | 6440 | } |
| 6172 | 6441 | ||
| 6173 | -/// A course with an open sync window and one enrolled student, the spine of | 6442 | +/// A course with an open sync window, one subject, and one enrolled student — |
| 6174 | -/// the question/answer tests. Returns (course, exam). | 6443 | +/// the spine of the question/answer tests. Returns (course, exam, subject). |
| 6175 | async fn open_exam_with_student( | 6444 | async fn open_exam_with_student( |
| 6176 | app: &axum::Router, | 6445 | app: &axum::Router, |
| 6177 | teacher: &str, | 6446 | teacher: &str, |
| 6178 | student_id: &str, | 6447 | student_id: &str, |
| 6179 | course_title: &str, | 6448 | course_title: &str, |
| 6180 | -) -> (String, String) { | 6449 | +) -> (String, String, String) { |
| 6181 | let course = create_course(app, teacher, course_title).await; | 6450 | let course = create_course(app, teacher, course_title).await; |
| 6451 | + let subject = create_subject(app, teacher, &course, "general").await; | ||
| 6182 | enroll(app, teacher, &course, student_id).await; | 6452 | enroll(app, teacher, &course, student_id).await; |
| 6183 | let now = Timestamp::now().as_millis(); | 6453 | let now = Timestamp::now().as_millis(); |
| 6184 | let exam = scheduled_exam( | 6454 | let exam = scheduled_exam( |
| @@ -6189,7 +6459,7 @@ async fn open_exam_with_student( | |||
| 6189 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), | 6459 | "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), |
| 6190 | ) | 6460 | ) |
| 6191 | .await; | 6461 | .await; |
| 6192 | - (course, exam) | 6462 | + (course, exam, subject) |
| 6193 | } | 6463 | } |
| 6194 | 6464 | ||
| 6195 | #[tokio::test] | 6465 | #[tokio::test] |
| @@ -6199,6 +6469,7 @@ async fn question_crud_validation_and_rbac() { | |||
| 6199 | let other_teacher = login_as(&app, &db, "q_t2", "teacher").await; | 6469 | let other_teacher = login_as(&app, &db, "q_t2", "teacher").await; |
| 6200 | let student = login(&app, "quinn").await; | 6470 | let student = login(&app, "quinn").await; |
| 6201 | let course = create_course(&app, &teacher, "logic").await; | 6471 | let course = create_course(&app, &teacher, "logic").await; |
| 6472 | + let subject = create_subject(&app, &teacher, &course, "propositions").await; | ||
| 6202 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; | 6473 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; |
| 6203 | 6474 | ||
| 6204 | // A choice question echoes its full authoring view, correct included. | 6475 | // A choice question echoes its full authoring view, correct included. |
| @@ -6207,12 +6478,15 @@ async fn question_crud_validation_and_rbac() { | |||
| 6207 | "POST", | 6478 | "POST", |
| 6208 | &format!("/exams/{exam}/questions"), | 6479 | &format!("/exams/{exam}/questions"), |
| 6209 | Some(&teacher), | 6480 | Some(&teacher), |
| 6210 | - Some(json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 6481 | + Some( |
| 6211 | - "choices": ["3", "4", "5"], "correct": 1 })), | 6482 | + json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10, |
| 6483 | + "choices": ["3", "4", "5"], "correct": 1 }), | ||
| 6484 | + ), | ||
| 6212 | ) | 6485 | ) |
| 6213 | .await; | 6486 | .await; |
| 6214 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 6487 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 6215 | assert_eq!(res.body["exam"], exam); | 6488 | assert_eq!(res.body["exam"], exam); |
| 6489 | + assert_eq!(res.body["subject"], subject); | ||
| 6216 | assert_eq!(res.body["kind"], "choice"); | 6490 | assert_eq!(res.body["kind"], "choice"); |
| 6217 | assert_eq!(res.body["points"], 10); | 6491 | assert_eq!(res.body["points"], 10); |
| 6218 | assert_eq!(res.body["choices"][1], "4"); | 6492 | assert_eq!(res.body["choices"][1], "4"); |
| @@ -6225,7 +6499,7 @@ async fn question_crud_validation_and_rbac() { | |||
| 6225 | "POST", | 6499 | "POST", |
| 6226 | &format!("/exams/{exam}/questions"), | 6500 | &format!("/exams/{exam}/questions"), |
| 6227 | Some(&teacher), | 6501 | Some(&teacher), |
| 6228 | - Some(json!({ "text": "Explain.", "kind": "text", "points": 20 })), | 6502 | + Some(json!({ "subject_id": subject, "text": "Explain.", "kind": "text", "points": 20 })), |
| 6229 | ) | 6503 | ) |
| 6230 | .await; | 6504 | .await; |
| 6231 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | 6505 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| @@ -6304,6 +6578,8 @@ async fn question_crud_validation_and_rbac() { | |||
| 6304 | json!({ "text": "x", "kind": "text", "points": 1, "correct": 0 }), | 6578 | json!({ "text": "x", "kind": "text", "points": 1, "correct": 0 }), |
| 6305 | ), | 6579 | ), |
| 6306 | ] { | 6580 | ] { |
| 6581 | + let mut body = body; | ||
| 6582 | + body["subject_id"] = json!(subject); | ||
| 6307 | let res = send( | 6583 | let res = send( |
| 6308 | &app, | 6584 | &app, |
| 6309 | "POST", | 6585 | "POST", |
| @@ -6315,8 +6591,26 @@ async fn question_crud_validation_and_rbac() { | |||
| 6315 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); | 6591 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); |
| 6316 | } | 6592 | } |
| 6317 | 6593 | ||
| 6594 | + // The subject must exist and belong to the exam's own course. | ||
| 6595 | + let other_course = create_course(&app, &teacher, "rhetoric").await; | ||
| 6596 | + let foreign_subject = create_subject(&app, &teacher, &other_course, "fallacies").await; | ||
| 6597 | + for (label, subject_id) in [ | ||
| 6598 | + ("unknown subject", "missing"), | ||
| 6599 | + ("foreign subject", foreign_subject.as_str()), | ||
| 6600 | + ] { | ||
| 6601 | + let res = send( | ||
| 6602 | + &app, | ||
| 6603 | + "POST", | ||
| 6604 | + &format!("/exams/{exam}/questions"), | ||
| 6605 | + Some(&teacher), | ||
| 6606 | + Some(json!({ "subject_id": subject_id, "text": "x", "kind": "text", "points": 1 })), | ||
| 6607 | + ) | ||
| 6608 | + .await; | ||
| 6609 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); | ||
| 6610 | + } | ||
| 6611 | + | ||
| 6318 | // Authoring needs management rights over the course; reading needs teacher+. | 6612 | // Authoring needs management rights over the course; reading needs teacher+. |
| 6319 | - let question_body = json!({ "text": "x", "kind": "text", "points": 1 }); | 6613 | + let question_body = json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 }); |
| 6320 | let res = send( | 6614 | let res = send( |
| 6321 | &app, | 6615 | &app, |
| 6322 | "POST", | 6616 | "POST", |
| @@ -6361,6 +6655,30 @@ async fn question_crud_validation_and_rbac() { | |||
| 6361 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 6655 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 6362 | assert_eq!(res.body["points"], 15); | 6656 | assert_eq!(res.body["points"], 15); |
| 6363 | assert_eq!(res.body["correct"], 1, "kind bundle kept"); | 6657 | assert_eq!(res.body["correct"], 1, "kind bundle kept"); |
| 6658 | + assert_eq!(res.body["subject"], subject, "subject kept by omission"); | ||
| 6659 | + | ||
| 6660 | + // Re-tagging stays inside the course: another of its subjects is fine, a | ||
| 6661 | + // foreign course's subject is a 400. | ||
| 6662 | + let second_subject = create_subject(&app, &teacher, &course, "predicates").await; | ||
| 6663 | + let res = send( | ||
| 6664 | + &app, | ||
| 6665 | + "PATCH", | ||
| 6666 | + &format!("/exams/{exam}/questions/{choice_q}"), | ||
| 6667 | + Some(&teacher), | ||
| 6668 | + Some(json!({ "subject_id": second_subject })), | ||
| 6669 | + ) | ||
| 6670 | + .await; | ||
| 6671 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 6672 | + assert_eq!(res.body["subject"], second_subject); | ||
| 6673 | + let res = send( | ||
| 6674 | + &app, | ||
| 6675 | + "PATCH", | ||
| 6676 | + &format!("/exams/{exam}/questions/{choice_q}"), | ||
| 6677 | + Some(&teacher), | ||
| 6678 | + Some(json!({ "subject_id": foreign_subject })), | ||
| 6679 | + ) | ||
| 6680 | + .await; | ||
| 6681 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 6364 | 6682 | ||
| 6365 | // Switching to text must clear the bundle explicitly... | 6683 | // Switching to text must clear the bundle explicitly... |
| 6366 | let res = send( | 6684 | let res = send( |
| @@ -6424,7 +6742,9 @@ async fn question_crud_validation_and_rbac() { | |||
| 6424 | ), | 6742 | ), |
| 6425 | ] { | 6743 | ] { |
| 6426 | let body = match method { | 6744 | let body = match method { |
| 6427 | - "POST" => Some(json!({ "text": "x", "kind": "text", "points": 1 })), | 6745 | + "POST" => { |
| 6746 | + Some(json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 })) | ||
| 6747 | + } | ||
| 6428 | "PATCH" => Some(json!({ "points": 2 })), | 6748 | "PATCH" => Some(json!({ "points": 2 })), |
| 6429 | _ => None, | 6749 | _ => None, |
| 6430 | }; | 6750 | }; |
| @@ -6468,11 +6788,13 @@ async fn questions_freeze_once_attempts_start() { | |||
| 6468 | let teacher = login_as(&app, &db, "frz_t", "teacher").await; | 6788 | let teacher = login_as(&app, &db, "frz_t", "teacher").await; |
| 6469 | let student = login(&app, "firat").await; | 6789 | let student = login(&app, "firat").await; |
| 6470 | let student_id = me_id(&app, &student).await; | 6790 | let student_id = me_id(&app, &student).await; |
| 6471 | - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "algo").await; | 6791 | + let (_course, exam, subject) = |
| 6792 | + open_exam_with_student(&app, &teacher, &student_id, "algo").await; | ||
| 6472 | let question = create_question( | 6793 | let question = create_question( |
| 6473 | &app, | 6794 | &app, |
| 6474 | &teacher, | 6795 | &teacher, |
| 6475 | &exam, | 6796 | &exam, |
| 6797 | + &subject, | ||
| 6476 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 6798 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 6477 | "choices": ["3", "4"], "correct": 1 }), | 6799 | "choices": ["3", "4"], "correct": 1 }), |
| 6478 | ) | 6800 | ) |
| @@ -6494,7 +6816,7 @@ async fn questions_freeze_once_attempts_start() { | |||
| 6494 | "POST", | 6816 | "POST", |
| 6495 | &format!("/exams/{exam}/questions"), | 6817 | &format!("/exams/{exam}/questions"), |
| 6496 | Some(&teacher), | 6818 | Some(&teacher), |
| 6497 | - Some(json!({ "text": "late", "kind": "text", "points": 1 })), | 6819 | + Some(json!({ "subject_id": subject, "text": "late", "kind": "text", "points": 1 })), |
| 6498 | ) | 6820 | ) |
| 6499 | .await; | 6821 | .await; |
| 6500 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 6822 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| @@ -6524,11 +6846,12 @@ async fn student_question_view_hides_correct_and_embeds_answers() { | |||
| 6524 | let teacher = login_as(&app, &db, "sv_t", "teacher").await; | 6846 | let teacher = login_as(&app, &db, "sv_t", "teacher").await; |
| 6525 | let student = login(&app, "sona").await; | 6847 | let student = login(&app, "sona").await; |
| 6526 | let student_id = me_id(&app, &student).await; | 6848 | let student_id = me_id(&app, &student).await; |
| 6527 | - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "art").await; | 6849 | + let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "art").await; |
| 6528 | let choice_q = create_question( | 6850 | let choice_q = create_question( |
| 6529 | &app, | 6851 | &app, |
| 6530 | &teacher, | 6852 | &teacher, |
| 6531 | &exam, | 6853 | &exam, |
| 6854 | + &subject, | ||
| 6532 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 6855 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 6533 | "choices": ["3", "4"], "correct": 1 }), | 6856 | "choices": ["3", "4"], "correct": 1 }), |
| 6534 | ) | 6857 | ) |
| @@ -6537,6 +6860,7 @@ async fn student_question_view_hides_correct_and_embeds_answers() { | |||
| 6537 | &app, | 6860 | &app, |
| 6538 | &teacher, | 6861 | &teacher, |
| 6539 | &exam, | 6862 | &exam, |
| 6863 | + &subject, | ||
| 6540 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), | 6864 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 6541 | ) | 6865 | ) |
| 6542 | .await; | 6866 | .await; |
| @@ -6597,11 +6921,12 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { | |||
| 6597 | let teacher = login_as(&app, &db, "ans_t", "teacher").await; | 6921 | let teacher = login_as(&app, &db, "ans_t", "teacher").await; |
| 6598 | let student = login(&app, "arda").await; | 6922 | let student = login(&app, "arda").await; |
| 6599 | let student_id = me_id(&app, &student).await; | 6923 | let student_id = me_id(&app, &student).await; |
| 6600 | - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "phys").await; | 6924 | + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "phys").await; |
| 6601 | let choice_q = create_question( | 6925 | let choice_q = create_question( |
| 6602 | &app, | 6926 | &app, |
| 6603 | &teacher, | 6927 | &teacher, |
| 6604 | &exam, | 6928 | &exam, |
| 6929 | + &subject, | ||
| 6605 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 6930 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 6606 | "choices": ["3", "4", "5"], "correct": 1 }), | 6931 | "choices": ["3", "4", "5"], "correct": 1 }), |
| 6607 | ) | 6932 | ) |
| @@ -6610,6 +6935,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { | |||
| 6610 | &app, | 6935 | &app, |
| 6611 | &teacher, | 6936 | &teacher, |
| 6612 | &exam, | 6937 | &exam, |
| 6938 | + &subject, | ||
| 6613 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), | 6939 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 6614 | ) | 6940 | ) |
| 6615 | .await; | 6941 | .await; |
| @@ -6731,6 +7057,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { | |||
| 6731 | &app, | 7057 | &app, |
| 6732 | &teacher, | 7058 | &teacher, |
| 6733 | &foreign_exam, | 7059 | &foreign_exam, |
| 7060 | + &subject, | ||
| 6734 | json!({ "text": "not yours", "kind": "choice", "points": 1, | 7061 | json!({ "text": "not yours", "kind": "choice", "points": 1, |
| 6735 | "choices": ["a", "b"], "correct": 0 }), | 7062 | "choices": ["a", "b"], "correct": 0 }), |
| 6736 | ) | 7063 | ) |
| @@ -6800,11 +7127,12 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() { | |||
| 6800 | let teacher = login_as(&app, &db, "cut_t", "teacher").await; | 7127 | let teacher = login_as(&app, &db, "cut_t", "teacher").await; |
| 6801 | let student = login(&app, "cansu").await; | 7128 | let student = login(&app, "cansu").await; |
| 6802 | let student_id = me_id(&app, &student).await; | 7129 | let student_id = me_id(&app, &student).await; |
| 6803 | - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; | 7130 | + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; |
| 6804 | let question = create_question( | 7131 | let question = create_question( |
| 6805 | &app, | 7132 | &app, |
| 6806 | &teacher, | 7133 | &teacher, |
| 6807 | &exam, | 7134 | &exam, |
| 7135 | + &subject, | ||
| 6808 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 7136 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 6809 | "choices": ["3", "4"], "correct": 1 }), | 7137 | "choices": ["3", "4"], "correct": 1 }), |
| 6810 | ) | 7138 | ) |
| @@ -6917,6 +7245,7 @@ async fn answer_saves_stop_at_the_deadline() { | |||
| 6917 | let student = login(&app, "dila").await; | 7245 | let student = login(&app, "dila").await; |
| 6918 | let student_id = me_id(&app, &student).await; | 7246 | let student_id = me_id(&app, &student).await; |
| 6919 | let course = create_course(&app, &teacher, "geo").await; | 7247 | let course = create_course(&app, &teacher, "geo").await; |
| 7248 | + let subject = create_subject(&app, &teacher, &course, "general").await; | ||
| 6920 | enroll(&app, &teacher, &course, &student_id).await; | 7249 | enroll(&app, &teacher, &course, &student_id).await; |
| 6921 | let now = Timestamp::now().as_millis(); | 7250 | let now = Timestamp::now().as_millis(); |
| 6922 | 7251 | ||
| @@ -6934,6 +7263,7 @@ async fn answer_saves_stop_at_the_deadline() { | |||
| 6934 | &app, | 7263 | &app, |
| 6935 | &teacher, | 7264 | &teacher, |
| 6936 | &exam, | 7265 | &exam, |
| 7266 | + &subject, | ||
| 6937 | json!({ "text": "quick", "kind": "choice", "points": 1, | 7267 | json!({ "text": "quick", "kind": "choice", "points": 1, |
| 6938 | "choices": ["a", "b"], "correct": 0 }), | 7268 | "choices": ["a", "b"], "correct": 0 }), |
| 6939 | ) | 7269 | ) |
| @@ -6993,11 +7323,13 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { | |||
| 6993 | let teacher = login_as(&app, &db, "sc_t", "teacher").await; | 7323 | let teacher = login_as(&app, &db, "sc_t", "teacher").await; |
| 6994 | let student = login(&app, "sena").await; | 7324 | let student = login(&app, "sena").await; |
| 6995 | let student_id = me_id(&app, &student).await; | 7325 | let student_id = me_id(&app, &student).await; |
| 6996 | - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; | 7326 | + let (_course, exam, subject) = |
| 7327 | + open_exam_with_student(&app, &teacher, &student_id, "chem").await; | ||
| 6997 | let q1 = create_question( | 7328 | let q1 = create_question( |
| 6998 | &app, | 7329 | &app, |
| 6999 | &teacher, | 7330 | &teacher, |
| 7000 | &exam, | 7331 | &exam, |
| 7332 | + &subject, | ||
| 7001 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 7333 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 7002 | "choices": ["3", "4"], "correct": 1 }), | 7334 | "choices": ["3", "4"], "correct": 1 }), |
| 7003 | ) | 7335 | ) |
| @@ -7006,6 +7338,7 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { | |||
| 7006 | &app, | 7338 | &app, |
| 7007 | &teacher, | 7339 | &teacher, |
| 7008 | &exam, | 7340 | &exam, |
| 7341 | + &subject, | ||
| 7009 | json!({ "text": "3 + 3?", "kind": "choice", "points": 20, | 7342 | json!({ "text": "3 + 3?", "kind": "choice", "points": 20, |
| 7010 | "choices": ["6", "7"], "correct": 0 }), | 7343 | "choices": ["6", "7"], "correct": 0 }), |
| 7011 | ) | 7344 | ) |
| @@ -7014,6 +7347,7 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { | |||
| 7014 | &app, | 7347 | &app, |
| 7015 | &teacher, | 7348 | &teacher, |
| 7016 | &exam, | 7349 | &exam, |
| 7350 | + &subject, | ||
| 7017 | json!({ "text": "Explain.", "kind": "text", "points": 30 }), | 7351 | json!({ "text": "Explain.", "kind": "text", "points": 30 }), |
| 7018 | ) | 7352 | ) |
| 7019 | .await; | 7353 | .await; |
| @@ -7082,12 +7416,13 @@ async fn live_monitor_tracks_answer_progress() { | |||
| 7082 | let bora = login(&app, "bora").await; | 7416 | let bora = login(&app, "bora").await; |
| 7083 | let ayla_id = me_id(&app, &ayla).await; | 7417 | let ayla_id = me_id(&app, &ayla).await; |
| 7084 | let bora_id = me_id(&app, &bora).await; | 7418 | let bora_id = me_id(&app, &bora).await; |
| 7085 | - let (course, exam) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await; | 7419 | + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await; |
| 7086 | enroll(&app, &teacher, &course, &bora_id).await; | 7420 | enroll(&app, &teacher, &course, &bora_id).await; |
| 7087 | let question = create_question( | 7421 | let question = create_question( |
| 7088 | &app, | 7422 | &app, |
| 7089 | &teacher, | 7423 | &teacher, |
| 7090 | &exam, | 7424 | &exam, |
| 7425 | + &subject, | ||
| 7091 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 7426 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 7092 | "choices": ["3", "4"], "correct": 1 }), | 7427 | "choices": ["3", "4"], "correct": 1 }), |
| 7093 | ) | 7428 | ) |
| @@ -7096,6 +7431,7 @@ async fn live_monitor_tracks_answer_progress() { | |||
| 7096 | &app, | 7431 | &app, |
| 7097 | &teacher, | 7432 | &teacher, |
| 7098 | &exam, | 7433 | &exam, |
| 7434 | + &subject, | ||
| 7099 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), | 7435 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 7100 | ) | 7436 | ) |
| 7101 | .await; | 7437 | .await; |
| @@ -7153,11 +7489,12 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 7153 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; | 7489 | let teacher = login_as(&app, &db, "qc_t", "teacher").await; |
| 7154 | let student = login(&app, "cem").await; | 7490 | let student = login(&app, "cem").await; |
| 7155 | let student_id = me_id(&app, &student).await; | 7491 | let student_id = me_id(&app, &student).await; |
| 7156 | - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await; | 7492 | + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await; |
| 7157 | let q1 = create_question( | 7493 | let q1 = create_question( |
| 7158 | &app, | 7494 | &app, |
| 7159 | &teacher, | 7495 | &teacher, |
| 7160 | &exam, | 7496 | &exam, |
| 7497 | + &subject, | ||
| 7161 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 7498 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 7162 | "choices": ["3", "4"], "correct": 1 }), | 7499 | "choices": ["3", "4"], "correct": 1 }), |
| 7163 | ) | 7500 | ) |
| @@ -7166,6 +7503,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 7166 | &app, | 7503 | &app, |
| 7167 | &teacher, | 7504 | &teacher, |
| 7168 | &exam, | 7505 | &exam, |
| 7506 | + &subject, | ||
| 7169 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), | 7507 | json!({ "text": "Explain.", "kind": "text", "points": 20 }), |
| 7170 | ) | 7508 | ) |
| 7171 | .await; | 7509 | .await; |
| @@ -7271,6 +7609,7 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 7271 | &app, | 7609 | &app, |
| 7272 | &teacher, | 7610 | &teacher, |
| 7273 | &exam2, | 7611 | &exam2, |
| 7612 | + &subject, | ||
| 7274 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, | 7613 | json!({ "text": "2 + 2?", "kind": "choice", "points": 10, |
| 7275 | "choices": ["3", "4"], "correct": 1 }), | 7614 | "choices": ["3", "4"], "correct": 1 }), |
| 7276 | ) | 7615 | ) |
| @@ -7316,6 +7655,16 @@ async fn questions_and_answers_cascade_with_deletes() { | |||
| 7316 | .unwrap() | 7655 | .unwrap() |
| 7317 | .is_empty() | 7656 | .is_empty() |
| 7318 | ); | 7657 | ); |
| 7658 | + // The course's subjects go down with it too. | ||
| 7659 | + let res = send( | ||
| 7660 | + &app, | ||
| 7661 | + "GET", | ||
| 7662 | + &format!("/subjects/{subject}"), | ||
| 7663 | + Some(&teacher), | ||
| 7664 | + None, | ||
| 7665 | + ) | ||
| 7666 | + .await; | ||
| 7667 | + assert_eq!(res.status, StatusCode::NOT_FOUND, "subject cascaded"); | ||
| 7319 | } | 7668 | } |
| 7320 | 7669 | ||
| 7321 | #[tokio::test] | 7670 | #[tokio::test] |
| @@ -7323,11 +7672,13 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { | |||
| 7323 | let (app, db) = app_and_db().await; | 7672 | let (app, db) = app_and_db().await; |
| 7324 | let teacher = login_as(&app, &db, "rv_t", "teacher").await; | 7673 | let teacher = login_as(&app, &db, "rv_t", "teacher").await; |
| 7325 | let course = create_course(&app, &teacher, "sets").await; | 7674 | let course = create_course(&app, &teacher, "sets").await; |
| 7675 | + let subject = create_subject(&app, &teacher, &course, "unions").await; | ||
| 7326 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; | 7676 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; |
| 7327 | let question = create_question( | 7677 | let question = create_question( |
| 7328 | &app, | 7678 | &app, |
| 7329 | &teacher, | 7679 | &teacher, |
| 7330 | &exam, | 7680 | &exam, |
| 7681 | + &subject, | ||
| 7331 | json!({ "text": "pick", "kind": "choice", "points": 10, | 7682 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 7332 | "choices": ["a", "b", "c"], "correct": 2 }), | 7683 | "choices": ["a", "b", "c"], "correct": 2 }), |
| 7333 | ) | 7684 | ) |
| @@ -7410,6 +7761,7 @@ async fn question_authoring_follows_course_management() { | |||
| 7410 | let teacher = login_as(&app, &db, "own_t", "teacher").await; | 7761 | let teacher = login_as(&app, &db, "own_t", "teacher").await; |
| 7411 | let boss = login_as(&app, &db, "own_m", "manager").await; | 7762 | let boss = login_as(&app, &db, "own_m", "manager").await; |
| 7412 | let course = create_course(&app, &teacher, "greek").await; | 7763 | let course = create_course(&app, &teacher, "greek").await; |
| 7764 | + let subject = create_subject(&app, &boss, &course, "alphabet").await; | ||
| 7413 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; | 7765 | let exam = create_exam(&app, &teacher, &course, "final", "final").await; |
| 7414 | 7766 | ||
| 7415 | // A manager+ authors questions in anyone's course, like every other | 7767 | // A manager+ authors questions in anyone's course, like every other |
| @@ -7418,6 +7770,7 @@ async fn question_authoring_follows_course_management() { | |||
| 7418 | &app, | 7770 | &app, |
| 7419 | &boss, | 7771 | &boss, |
| 7420 | &exam, | 7772 | &exam, |
| 7773 | + &subject, | ||
| 7421 | json!({ "text": "pick", "kind": "choice", "points": 10, | 7774 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 7422 | "choices": ["a", "b"], "correct": 0 }), | 7775 | "choices": ["a", "b"], "correct": 0 }), |
| 7423 | ) | 7776 | ) |
| @@ -7448,11 +7801,13 @@ async fn concurrent_answer_saves_never_collide() { | |||
| 7448 | let teacher = login_as(&app, &db, "cc_t", "teacher").await; | 7801 | let teacher = login_as(&app, &db, "cc_t", "teacher").await; |
| 7449 | let student = login(&app, "cana").await; | 7802 | let student = login(&app, "cana").await; |
| 7450 | let student_id = me_id(&app, &student).await; | 7803 | let student_id = me_id(&app, &student).await; |
| 7451 | - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "race").await; | 7804 | + let (_course, exam, subject) = |
| 7805 | + open_exam_with_student(&app, &teacher, &student_id, "race").await; | ||
| 7452 | let question = create_question( | 7806 | let question = create_question( |
| 7453 | &app, | 7807 | &app, |
| 7454 | &teacher, | 7808 | &teacher, |
| 7455 | &exam, | 7809 | &exam, |
| 7810 | + &subject, | ||
| 7456 | json!({ "text": "pick", "kind": "choice", "points": 10, | 7811 | json!({ "text": "pick", "kind": "choice", "points": 10, |
| 7457 | "choices": ["a", "b", "c"], "correct": 0 }), | 7812 | "choices": ["a", "b", "c"], "correct": 0 }), |
| 7458 | ) | 7813 | ) |
tests/persistence.rsmodified+143 -0
| @@ -700,3 +700,146 @@ async fn legacy_users_audiences_convert_to_registrations() { | |||
| 700 | .await; | 700 | .await; |
| 701 | assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); | 701 | assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); |
| 702 | } | 702 | } |
| 703 | + | ||
| 704 | +/// Exam-question rows written before subjects existed (2026-07) are destroyed | ||
| 705 | +/// on the next boot, answers first — a subject is mandatory and there is | ||
| 706 | +/// nothing truthful to backfill. The exam and the course's subjects survive. | ||
| 707 | +#[tokio::test] | ||
| 708 | +async fn legacy_subjectless_questions_are_destroyed_on_boot() { | ||
| 709 | + let dir = tempfile::tempdir().unwrap(); | ||
| 710 | + let cfg = config_at(&dir); | ||
| 711 | + let creds = json!({ "username": "ali", "password": "secret1" }); | ||
| 712 | + let exam_id; | ||
| 713 | + let subject_id; | ||
| 714 | + | ||
| 715 | + // First boot: a full exam — course, subject, open exam, one answered | ||
| 716 | + // question — then strip the question's subject the way an old binary's | ||
| 717 | + // schema would have left it. | ||
| 718 | + { | ||
| 719 | + let db = database::init(&cfg).await.expect("first open"); | ||
| 720 | + let app = build_router(state(db.clone(), &cfg)); | ||
| 721 | + assert_eq!( | ||
| 722 | + send(&app, "POST", "/auth/register", None, Some(creds.clone())) | ||
| 723 | + .await | ||
| 724 | + .status, | ||
| 725 | + StatusCode::CREATED | ||
| 726 | + ); | ||
| 727 | + set_role(&db, "ali", "teacher").await; | ||
| 728 | + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) | ||
| 729 | + .await | ||
| 730 | + .cookie | ||
| 731 | + .unwrap(); | ||
| 732 | + let student = json!({ "username": "veli", "password": "secret1" }); | ||
| 733 | + assert_eq!( | ||
| 734 | + send(&app, "POST", "/auth/register", None, Some(student.clone())) | ||
| 735 | + .await | ||
| 736 | + .status, | ||
| 737 | + StatusCode::CREATED | ||
| 738 | + ); | ||
| 739 | + let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) | ||
| 740 | + .await | ||
| 741 | + .cookie | ||
| 742 | + .unwrap(); | ||
| 743 | + let student_id = common::me_id(&app, &student_cookie).await; | ||
| 744 | + | ||
| 745 | + let course = create_course(&app, &cookie, "algebra").await; | ||
| 746 | + enroll(&app, &cookie, &course, &student_id).await; | ||
| 747 | + let res = send( | ||
| 748 | + &app, | ||
| 749 | + "POST", | ||
| 750 | + &format!("/courses/{course}/subjects"), | ||
| 751 | + Some(&cookie), | ||
| 752 | + Some(json!({ "name": "arithmetic" })), | ||
| 753 | + ) | ||
| 754 | + .await; | ||
| 755 | + assert_eq!(res.status, StatusCode::CREATED); | ||
| 756 | + subject_id = common::id_of(&res.body); | ||
| 757 | + let res = send( | ||
| 758 | + &app, | ||
| 759 | + "POST", | ||
| 760 | + &format!("/courses/{course}/exams"), | ||
| 761 | + Some(&cookie), | ||
| 762 | + Some(json!({ "title": "drill", "kind": "quiz", "mode": "open" })), | ||
| 763 | + ) | ||
| 764 | + .await; | ||
| 765 | + assert_eq!(res.status, StatusCode::CREATED); | ||
| 766 | + exam_id = common::id_of(&res.body); | ||
| 767 | + let res = send( | ||
| 768 | + &app, | ||
| 769 | + "POST", | ||
| 770 | + &format!("/exams/{exam_id}/questions"), | ||
| 771 | + Some(&cookie), | ||
| 772 | + Some( | ||
| 773 | + json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", | ||
| 774 | + "points": 10, "choices": ["3", "4"], "correct": 1 }), | ||
| 775 | + ), | ||
| 776 | + ) | ||
| 777 | + .await; | ||
| 778 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 779 | + let question_id = common::id_of(&res.body); | ||
| 780 | + let res = send( | ||
| 781 | + &app, | ||
| 782 | + "POST", | ||
| 783 | + &format!("/exams/{exam_id}/attempt"), | ||
| 784 | + Some(&student_cookie), | ||
| 785 | + None, | ||
| 786 | + ) | ||
| 787 | + .await; | ||
| 788 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | ||
| 789 | + let res = send( | ||
| 790 | + &app, | ||
| 791 | + "POST", | ||
| 792 | + &format!("/exams/{exam_id}/attempt/answers"), | ||
| 793 | + Some(&student_cookie), | ||
| 794 | + Some(json!({ "question_id": question_id, "selected": 1 })), | ||
| 795 | + ) | ||
| 796 | + .await; | ||
| 797 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 798 | + | ||
| 799 | + db.query( | ||
| 800 | + "REMOVE FIELD IF EXISTS subject ON TABLE exam_question; | ||
| 801 | + UPDATE exam_question SET subject = NONE;", | ||
| 802 | + ) | ||
| 803 | + .await | ||
| 804 | + .expect("strip subject") | ||
| 805 | + .check() | ||
| 806 | + .expect("strip subject check"); | ||
| 807 | + } | ||
| 808 | + | ||
| 809 | + // Second boot re-runs the migration and the destroy-backfill: the | ||
| 810 | + // subjectless question and its answer are gone, the exam and subject | ||
| 811 | + // still stand. | ||
| 812 | + let db = reopen(&cfg).await; | ||
| 813 | + let app = build_router(state(db.clone(), &cfg)); | ||
| 814 | + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) | ||
| 815 | + .await | ||
| 816 | + .cookie | ||
| 817 | + .unwrap(); | ||
| 818 | + let res = send( | ||
| 819 | + &app, | ||
| 820 | + "GET", | ||
| 821 | + &format!("/exams/{exam_id}/questions"), | ||
| 822 | + Some(&cookie), | ||
| 823 | + None, | ||
| 824 | + ) | ||
| 825 | + .await; | ||
| 826 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 827 | + assert_eq!(common::total(&res.body), 0, "legacy questions destroyed"); | ||
| 828 | + let res = send( | ||
| 829 | + &app, | ||
| 830 | + "GET", | ||
| 831 | + &format!("/subjects/{subject_id}"), | ||
| 832 | + Some(&cookie), | ||
| 833 | + None, | ||
| 834 | + ) | ||
| 835 | + .await; | ||
| 836 | + assert_eq!(res.status, StatusCode::OK, "the subject itself survives"); | ||
| 837 | + let mut result = db | ||
| 838 | + .query("SELECT VALUE id FROM exam_answer") | ||
| 839 | + .await | ||
| 840 | + .expect("count answers") | ||
| 841 | + .check() | ||
| 842 | + .expect("count answers check"); | ||
| 843 | + let answers: Vec<surrealdb::types::RecordId> = result.take(0).expect("answer rows"); | ||
| 844 | + assert!(answers.is_empty(), "orphaned answers destroyed"); | ||
| 845 | +} | ||