From 022aaaa8174b3e1496b15d8c310055a67ec7ec5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 17 Jul 2026 20:18:17 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(subjects)!:=20course=20subject?= =?UTF-8?q?s,=20required=20on=20every=20exam=20question?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each course now owns its curriculum as subjects (name + optional description; course link fixed at creation). Every exam question must be tagged with a subject of its exam's own course, so exam content is attributable to a topic. - POST/GET /courses/{id}/subjects (manage / course-visibility, paged) - GET/PATCH/DELETE /subjects/{id}; delete is a 409 while any question still references the subject — re-tag or delete those questions first - course delete cascades its subjects BREAKING: question create/update payloads require subject_id, and questions written before subjects existed are destroyed on boot (answers first) — nothing truthful to backfill, pre-customer clean break. --- README.md | 39 +++- src/constant.rs | 3 + src/database.rs | 15 ++ src/domain/course.rs | 5 +- src/domain/exam_attempt.rs | 1 + src/domain/exam_question.rs | 26 ++- src/domain/mod.rs | 1 + src/domain/subject.rs | 159 ++++++++++++++ src/lib.rs | 4 +- src/web/courses.rs | 98 ++++++++- src/web/dto.rs | 26 +++ src/web/exams.rs | 37 +++- src/web/mod.rs | 6 +- src/web/subjects.rs | 174 ++++++++++++++++ tests/common/mod.rs | 15 ++ tests/e2e.rs | 39 +++- tests/integration.rs | 401 +++++++++++++++++++++++++++++++++--- tests/persistence.rs | 143 +++++++++++++ 18 files changed, 1137 insertions(+), 55 deletions(-) create mode 100644 src/domain/subject.rs create mode 100644 src/web/subjects.rs diff --git a/README.md b/README.md index 108f43e..d6fbf87 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,9 @@ closes the moment the event starts. Every event stays visible to everyone — the audience is a roster, not a wall. Marks are course-shaped (Google Classroom style): a teacher creates a course — kind **`course`** (a regular class) or **`study`** (a supervised study session — *etüt*; same -behavior, different label) — enrolls students, adds +behavior, different label) — lays out its **subjects** (curriculum topics — +every exam question must be tagged with one of its course's subjects, so +results can later be read per topic), enrolls students, adds exams inside it, and grades — enrolling, sitting exams, roll call, and marks are all student-only, staff never take part; students read a per-course weighted average and 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). | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | Read **own** attendance report | student | | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | -| View **visible** courses/exams; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | +| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | | 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 | | 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 | | Author an exam's questions (add/edit/delete) | teacher | Course-management rights; frozen once anyone has an attempt | | 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 | | Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | | Create courses | teacher | The creator manages the course | -| 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 | +| 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`) | | View a course's roster, an exam's result list / statistics | teacher | Course-management rights | | Read another user's mark report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | | 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* everywhere — enrollment, exams, sessions, marks — the kind is a label the UI renders differently, settable at creation and editable later. -Course data is walled per course. A course, its exams, and its sessions are +Course data is walled per course. A course, its exams, its sessions, and its +subjects are **visible** only to its enrolled users, its creator, and manager+ — a student sees just the classes they were added to, and the `/courses` / `/exams` catalogs are filtered accordingly. Teacher-level reads *inside* a course @@ -310,12 +313,17 @@ their existing shapes: the student exam-room reads | GET | `/courses/me` | student | The caller's **enrolled** courses · paged | | GET | `/courses/{id}` | student | Get course (enrolled, creator, or manager+) | | PATCH | `/courses/{id}` | teacher | Edit course (creator, or manager+ for any) | -| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments (creator, or manager+) | +| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects (creator, or manager+) | | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled) | | GET | `/courses/{id}/enrollments` | teacher | List the course roster (course manager) · paged | | DELETE | `/courses/{id}/enrollments/{user}` | teacher | Unenroll (keeps recorded results; course manager) | | POST | `/courses/{id}/sessions` | teacher | `{topic?, teacher_id?, starts_at, ends_at?}` — add a lesson (course manager; teacher defaults to the caller) | | GET | `/courses/{id}/sessions` | student | List the course's sessions, most recent first (enrolled, creator, or manager+) · paged | +| POST | `/courses/{id}/subjects` | teacher | `{name, description?}` — add a curriculum subject (course manager) | +| GET | `/courses/{id}/subjects` | student | List the course's subjects, creation order (enrolled, creator, or manager+) · paged | +| GET | `/subjects/{id}` | student | Get subject (enrolled, creator, or manager+) | +| PATCH | `/subjects/{id}` | teacher | Edit a subject's name/description (course manager; its course is fixed) | +| DELETE | `/subjects/{id}` | teacher | Delete a subject (course manager); `409` while exam questions reference it | | GET | `/sessions/{id}` | student | Get session (enrolled, session teacher, or course manager) | | PATCH | `/sessions/{id}` | teacher | Edit session (course manager; `null` clears `ends_at`) | | DELETE | `/sessions/{id}` | teacher | Delete session + its roll call (course manager) | @@ -336,7 +344,7 @@ their existing shapes: the student exam-room reads | 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 | | 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` | | POST | `/exams/{id}/attempt/finish` | student | Submit the attempt (`409` once the deadline passed); allowed even while locked out of the room | -| POST | `/exams/{id}/questions` | teacher | `{text, kind, points, choices?, correct?}` — add a question (course manager; frozen once attempted) | +| 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) | | GET | `/exams/{id}/questions` | teacher | The full question list, `correct` included (course manager) · paged | | PATCH | `/exams/{id}/questions/{qid}` | teacher | Edit a question — the kind bundle revalidates as a unit (course manager; frozen once attempted) | | DELETE | `/exams/{id}/questions/{qid}` | teacher | Delete a question + its answers (course manager; frozen once attempted) | @@ -385,7 +393,16 @@ exams in that course (`null` while nothing is graded — ungraded exams are skipped, not zeroed). The overall average is the plain mean of the non-null course averages. Unenrolling keeps result rows: the marks drop out of the report until re-enrollment, but stay visible on the exam itself. Deleting a -course cascades its exams, their results, and all enrollments. +course cascades its exams, their results, all enrollments, and its subjects. +A **subject** is one topic of a course's curriculum (`name` ≤ 200 chars, +optional `description` ≤ 2000): every exam question carries a mandatory +`subject_id` naming one of *its own course's* subjects (an unknown or +foreign-course subject is a `400`), so exam content is always attributable to +a topic. A subject's course link is fixed at creation, and a subject still +referenced by questions refuses deletion with a `409` — re-tag (PATCH the +questions' `subject_id`) or delete those questions first. Questions written +before subjects existed are **destroyed on boot** (answers first) — the clean +break instead of inventing a placeholder topic. Event `starts_at`/`ends_at` are optional **unix-millisecond** integers; if both are given, `ends_at` must not precede `starts_at`, and neither may be set in 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 the event's creator, and the audience becomes an uncapped registration list. Reading a child collection of a missing parent (`/events/{id}/attendance`, `/exams/{id}/results`, `/courses/{id}/enrollments`, `/courses/{id}/exams`, -`/courses/{id}/sessions`, `/sessions/{id}/attendance`) is a `404`, not an -empty list. +`/courses/{id}/sessions`, `/courses/{id}/subjects`, +`/sessions/{id}/attendance`) is a `404`, not an empty list. Personal info (`name`, `surname`, `email`, `phone`, `birth_date`) is the same optional set on every account, whatever the role, and is `null` until filled 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 `POST /exams/{id}/results`. **Questions** (`POST/GET/PATCH/DELETE /exams/{id}/questions[/{qid}]`, -course-management rights): each has `text` (≤ 2000 chars), `points` `1`–`100` +course-management rights): each has a mandatory `subject_id` (one of the +course's subjects, `GET /courses/{id}/subjects` — the topic the question +belongs to), `text` (≤ 2000 chars), `points` `1`–`100` (its share of the auto-score), and a `kind`: - `kind: "choice"` — carries `choices` (2–10 options, each ≤ 500 chars) and diff --git a/src/constant.rs b/src/constant.rs index c49ccc0..80b211f 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -64,6 +64,9 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; pub const MAX_COURSE_TITLE_LEN: usize = 200; pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; +pub const MAX_SUBJECT_NAME_LEN: usize = 200; +pub const MAX_SUBJECT_DESCRIPTION_LEN: usize = 2_000; + /// The default attendance states, and also the mandatory core: a school may /// add its own statuses via `PATCH /settings`, but these four can never be /// removed — the attendance rate's semantics are defined over them. diff --git a/src/database.rs b/src/database.rs index 7235a91..9eda9fc 100644 --- a/src/database.rs +++ b/src/database.rs @@ -27,6 +27,7 @@ pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; pub const WORK_ENTRY_TABLE: &str = "work_entry"; pub const SETTINGS_TABLE: &str = "settings"; pub const TERM_TABLE: &str = "term"; +pub const SUBJECT_TABLE: &str = "subject"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the @@ -110,6 +111,12 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS kind ON course TYPE string DEFAULT 'course'; DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; + DEFINE TABLE IF NOT EXISTS subject SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON subject TYPE record; + DEFINE FIELD IF NOT EXISTS name ON subject TYPE string; + DEFINE FIELD IF NOT EXISTS description ON subject TYPE string; + DEFINE INDEX IF NOT EXISTS subject_course ON subject FIELDS course; + DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record; @@ -173,7 +180,9 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS points ON exam_question TYPE int; DEFINE FIELD IF NOT EXISTS choices ON exam_question TYPE option>; DEFINE FIELD IF NOT EXISTS correct ON exam_question TYPE option; + DEFINE FIELD IF NOT EXISTS subject ON exam_question TYPE record; DEFINE INDEX IF NOT EXISTS exam_question_exam ON exam_question FIELDS exam; + DEFINE INDEX IF NOT EXISTS exam_question_subject ON exam_question FIELDS subject; DEFINE TABLE IF NOT EXISTS exam_answer SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON exam_answer TYPE record; @@ -215,6 +224,12 @@ const BACKFILL: &str = " UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {}; + -- Questions written before subjects existed (2026-07-17) are destroyed, not + -- backfilled: a subject is mandatory and there is nothing truthful to + -- assign. Their answers go first so no answer row outlives its question. + DELETE exam_answer WHERE question IN (SELECT VALUE id FROM exam_question WHERE subject = NONE); + DELETE exam_question WHERE subject = NONE; + -- The hand-picked `users` audience retired into `registration` (2026-07-16): -- each listed user becomes a signup row credited to the event's creator, and -- the event becomes an uncapped registration list. Runs once — converted diff --git a/src/domain/course.rs b/src/domain/course.rs index 077ca67..9c488f6 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -215,8 +215,8 @@ impl Course { /// Delete the course and cascade-remove everything inside it: results and /// attempts of its exams, its enrollments, its sessions with their roll - /// call, and the exams themselves. The children go in one transaction so a - /// crash can't leave an exam pointing at a deleted course. + /// call, its subjects, and the exams themselves. The children go in one + /// transaction so a crash can't leave an exam pointing at a deleted course. pub async fn delete(self, db: &Database) -> Result { db.query( "BEGIN TRANSACTION; @@ -227,6 +227,7 @@ impl Course { DELETE session_attendance WHERE course = $course; DELETE course_session WHERE course = $course; DELETE enrollment WHERE course = $course; + DELETE subject WHERE course = $course; DELETE exam WHERE course = $course; COMMIT TRANSACTION;", ) diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index 282bc2f..f6cabfd 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -370,6 +370,7 @@ mod tests { .unwrap(); let question = ExamQuestion::create( exam.get_id(), + crate::domain::subject::SubjectId::generate(), crate::domain::exam_question::QuestionText::try_new("3 + 3?").unwrap(), QuestionPoints::try_new(5).unwrap(), spec, diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index f7f3216..75fabd0 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -6,6 +6,7 @@ use crate::constant::{ }; use crate::database::{Database, EXAM_QUESTION_TABLE}; use crate::domain::exam::ExamId; +use crate::domain::subject::SubjectId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_question_kind, validate_question_points, validate_required}; @@ -161,11 +162,14 @@ impl QuestionSpec { /// One question of an exam. Order within the exam is the id's ULID order /// (creation order); the kind-dependent columns always satisfy the -/// [`QuestionSpec`] invariants because every write goes through one. +/// [`QuestionSpec`] invariants because every write goes through one. Every +/// question links to a subject of the exam's course — the handlers verify the +/// subject's course matches before any write. #[derive(Debug, Clone, SurrealValue)] pub struct ExamQuestion { id: ExamQuestionId, exam: ExamId, + subject: SubjectId, text: QuestionText, kind: QuestionKind, points: QuestionPoints, @@ -182,6 +186,10 @@ impl ExamQuestion { &self.exam } + pub fn get_subject(&self) -> &SubjectId { + &self.subject + } + pub fn get_text(&self) -> &QuestionText { &self.text } @@ -215,6 +223,7 @@ impl ExamQuestion { pub async fn create( exam: &ExamId, + subject: SubjectId, text: QuestionText, points: QuestionPoints, spec: QuestionSpec, @@ -223,6 +232,7 @@ impl ExamQuestion { let question = ExamQuestion { id: ExamQuestionId::generate(), exam: exam.clone(), + subject, text, points, kind: spec.kind, @@ -254,13 +264,26 @@ impl ExamQuestion { Ok(result.take::>(0)?) } + /// Whether any question anywhere references `subject` — the gate that + /// blocks deleting a subject still in use. + pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result { + let mut result = db + .query("SELECT VALUE id FROM exam_question WHERE subject = $subject LIMIT 1") + .bind(("subject", subject.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + pub async fn update( mut self, + subject: SubjectId, text: QuestionText, points: QuestionPoints, spec: QuestionSpec, db: &Database, ) -> Result { + self.subject = subject; self.text = text; self.points = points; self.kind = spec.kind; @@ -287,6 +310,7 @@ impl ExamQuestion { ExamQuestion { id: ExamQuestionId::generate(), exam: exam.clone(), + subject: SubjectId::generate(), text: QuestionText::try_new(text).unwrap(), points: QuestionPoints::try_new(points).unwrap(), kind: spec.kind, diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 7f231cb..4d0b021 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -21,6 +21,7 @@ pub mod role; pub mod session; pub mod session_attendance; pub mod settings; +pub mod subject; pub mod term; pub mod timestamp; pub mod user; diff --git a/src/domain/subject.rs b/src/domain/subject.rs new file mode 100644 index 0000000..8081935 --- /dev/null +++ b/src/domain/subject.rs @@ -0,0 +1,159 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_SUBJECT_DESCRIPTION_LEN, MAX_SUBJECT_NAME_LEN}; +use crate::database::{Database, SUBJECT_TABLE}; +use crate::domain::course::CourseId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SubjectId(RecordId); + +impl SubjectId { + pub fn generate() -> Self { + Self(RecordId::new(SUBJECT_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(SUBJECT_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SubjectName(String); + +impl SubjectName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_SUBJECT_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SubjectDescription(String); + +impl SubjectDescription { + pub fn try_new(value: &str) -> Result { + validate_optional("description", value, MAX_SUBJECT_DESCRIPTION_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A subject: one topic of a course's curriculum. Every exam question links to +/// a subject of its exam's course, so results can later be read per topic. The +/// course link is fixed at creation — a subject is course content, and moving +/// it would strand the questions tagged with it. +#[derive(Debug, Clone, SurrealValue)] +pub struct Subject { + id: SubjectId, + course: CourseId, + name: SubjectName, + description: SubjectDescription, +} + +impl Subject { + pub fn get_id(&self) -> &SubjectId { + &self.id + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_name(&self) -> &SubjectName { + &self.name + } + + pub fn get_description(&self) -> &SubjectDescription { + &self.description + } + + pub async fn create( + course: &CourseId, + name: SubjectName, + description: SubjectDescription, + db: &Database, + ) -> Result { + let subject = Subject { + id: SubjectId::generate(), + course: course.clone(), + name, + description, + }; + let created: Option = db.create(subject.id.record()).content(subject).await?; + created.ok_or_else(|| AppError::Internal("failed to create subject".into())) + } + + pub async fn read(id: &SubjectId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// The course's subjects in curriculum order (ULID ids sort by creation). + pub async fn list_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM subject WHERE course = $course ORDER BY id ASC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + name: SubjectName, + description: SubjectDescription, + db: &Database, + ) -> Result { + self.name = name; + self.description = description; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn name_is_required() { + assert!(SubjectName::try_new("Limits").is_ok()); + assert!(SubjectName::try_new("").is_err()); + assert!(SubjectName::try_new(" ").is_err()); + assert!(SubjectName::try_new(&"x".repeat(201)).is_err()); + } + + #[tokio::test] + async fn description_is_optional() { + assert!(SubjectDescription::try_new("").is_ok()); + assert!(SubjectDescription::try_new(&"x".repeat(2_001)).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 365a220..ccda239 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( @@ -48,6 +48,7 @@ use crate::state::AppState; (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"), (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)"), (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+"), + (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"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), ), )] @@ -88,6 +89,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/work", web::work::routes()) .nest("/attendance", web::attendance::routes()) .nest("/settings", web::settings::routes()) + .nest("/subjects", web::subjects::routes()) .nest("/terms", web::terms::routes()) .split_for_parts(); diff --git a/src/web/courses.rs b/src/web/courses.rs index 87e5e91..b297ba7 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -18,6 +18,7 @@ use crate::domain::exam::{ }; use crate::domain::role::Role; use crate::domain::settings::Settings; +use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -27,7 +28,8 @@ use super::sessions::resolve_session_teacher; use super::terms::resolve_term; use super::{ CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, - SessionResponse, check_not_past, check_time_range, paginate, person_map, set_or_clear, + SessionResponse, SubjectResponse, check_not_past, check_time_range, paginate, person_map, + set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -39,6 +41,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(unenroll)) .routes(routes!(create_exam_in_course, list_course_exams)) .routes(routes!(create_session_in_course, list_course_sessions)) + .routes(routes!(create_subject_in_course, list_course_subjects)) } #[derive(Deserialize, ToSchema)] @@ -655,6 +658,99 @@ async fn list_course_exams( Ok(Json(Page::new(items, total, limit, offset))) } +// ---- subjects in a course --------------------------------------------------- +// The course's curriculum topics. Every exam question links to one, so the +// list doubles as the tag picker when authoring questions. + +#[derive(Deserialize, ToSchema)] +struct CreateSubject { + #[schema(example = "Limits and continuity")] + name: String, + description: Option, +} + +/// Create a subject inside a course. Requires teacher+ and course management +/// rights. Subjects are the course's curriculum topics — every exam question +/// must be tagged with one of its course's subjects. +#[utoipa::path( + post, + path = "/{id}/subjects", + tag = "subjects", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = CreateSubject, + responses( + (status = 201, description = "Subject created", body = SubjectResponse), + (status = 400, description = "Invalid name or description", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn create_subject_in_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can add subjects to this course", + )); + } + + let name = SubjectName::try_new(&req.name)?; + let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; + let subject = Subject::create(course.get_id(), name, description, &st.db).await?; + Ok((StatusCode::CREATED, Json(SubjectResponse::new(&subject)))) +} + +/// List a course's subjects in creation order, paged via `?limit=&offset=` +/// (omit `limit` for all of them). Visible to the course's enrolled users, its +/// creator, and managers/admins. Returns a `{items, total, limit, offset}` +/// envelope. +#[utoipa::path( + get, + path = "/{id}/subjects", + tag = "subjects", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id"), PageParams), + responses( + (status = 200, description = "A page of the course's subjects (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the creator, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn list_course_subjects( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // Course must exist — a missing course is a 404, not an empty list. + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this course", + )); + } + let subjects = Subject::list_for_course(course.get_id(), &st.db).await?; + let total = subjects.len() as i64; + let items = paginate(&subjects, limit, offset) + .iter() + .map(SubjectResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + // ---- sessions in a course -------------------------------------------------- #[derive(Deserialize, ToSchema)] diff --git a/src/web/dto.rs b/src/web/dto.rs index babf1d2..33e02f4 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -10,6 +10,7 @@ use crate::domain::course::Course; use crate::domain::course_session::CourseSession; use crate::domain::exam::Exam; use crate::domain::role::Role as DomainRole; +use crate::domain::subject::Subject; use crate::domain::user::{User, UserId}; use crate::error::AppError; @@ -182,6 +183,31 @@ impl CourseResponse { } } +/// Public shape of a subject (one topic of a course's curriculum). Shared by +/// `courses` (in-course creation and listing) and `subjects` (lookup, edit, +/// delete). +#[derive(Serialize, ToSchema)] +pub struct SubjectResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + pub id: String, + /// The course whose curriculum this subject belongs to. + pub course: String, + #[schema(example = "Limits and continuity")] + pub name: String, + pub description: String, +} + +impl SubjectResponse { + pub fn new(subject: &Subject) -> Self { + Self { + id: subject.get_id().key().to_string(), + course: subject.get_course().key().to_string(), + name: subject.get_name().as_str().to_string(), + description: subject.get_description().as_str().to_string(), + } + } +} + /// Public shape of a course session (one lesson). Shared by `courses` /// (in-course creation and listing) and `sessions` (CRUD + roll call). #[derive(Serialize, ToSchema)] diff --git a/src/web/exams.rs b/src/web/exams.rs index 1ceef31..ceee1b6 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -34,6 +34,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::courses::{can_manage_course, can_view_course, visible_courses}; +use super::subjects::subject_in_course; use super::{ CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireTeacher, check_not_past, paginate, person_map, set_or_clear, @@ -1199,6 +1200,10 @@ async fn exam_live_stream( #[derive(Deserialize, ToSchema)] struct CreateQuestion { + /// The subject this question belongs to — one of the exam's course's + /// subjects (`GET /courses/{id}/subjects`). Required. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, /// The question itself. #[schema(example = "What is 2 + 2?")] text: String, @@ -1218,6 +1223,10 @@ struct CreateQuestion { #[derive(Deserialize, ToSchema)] struct UpdateQuestion { + /// Re-tag the question with another of the course's subjects. Omit to + /// keep the current one — a question always has a subject, so there is no + /// clearing it. + subject_id: Option, text: Option, points: Option, /// `choice` or `text`. Switching kinds needs the other fields to follow: @@ -1241,6 +1250,8 @@ struct UpdateQuestion { struct QuestionResponse { id: String, exam: String, + /// The subject this question belongs to (`GET /subjects/{id}`). + subject: String, text: String, /// `choice` or `text`. #[schema(example = "choice")] @@ -1256,6 +1267,7 @@ impl QuestionResponse { Self { id: question.get_id().key().to_string(), exam: question.get_exam().key().to_string(), + subject: question.get_subject().key().to_string(), text: question.get_text().as_str().to_string(), kind: question.get_kind().as_str().to_string(), points: question.get_points().as_i64(), @@ -1295,8 +1307,10 @@ async fn question_of_exam( } /// Add a question to an exam. Requires teacher+ and management rights over the -/// exam's course. `choice` questions carry 2–10 `choices` plus the `correct` -/// index; `text` questions carry neither. Locked once attempts exist. +/// exam's course. `subject_id` must name one of the course's subjects +/// (`GET /courses/{id}/subjects`) — every question belongs to a subject. +/// `choice` questions carry 2–10 `choices` plus the `correct` index; `text` +/// questions carry neither. Locked once attempts exist. #[utoipa::path( post, path = "/{id}/questions", @@ -1306,7 +1320,7 @@ async fn question_of_exam( request_body = CreateQuestion, responses( (status = 201, description = "Question created", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), @@ -1330,10 +1344,11 @@ async fn create_question( } ensure_questions_editable(exam.get_id(), &st.db).await?; + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; let text = QuestionText::try_new(&req.text)?; let points = QuestionPoints::try_new(req.points)?; let spec = QuestionSpec::try_new(QuestionKind::try_new(&req.kind)?, req.choices, req.correct)?; - let question = ExamQuestion::create(exam.get_id(), text, points, spec, &st.db).await?; + let question = ExamQuestion::create(exam.get_id(), subject, text, points, spec, &st.db).await?; Ok((StatusCode::CREATED, Json(QuestionResponse::new(&question)))) } @@ -1384,7 +1399,8 @@ async fn list_questions( /// Edit a question. Requires teacher+ and management rights over the exam's /// course. Omitted fields keep their value; `kind`/`choices`/`correct` are /// re-validated as a unit, so a kind switch must bring the matching fields -/// along. Locked once attempts exist. +/// along. `subject_id` re-tags within the course's subjects. Locked once +/// attempts exist. #[utoipa::path( patch, path = "/{id}/questions/{qid}", @@ -1397,7 +1413,7 @@ async fn list_questions( request_body = UpdateQuestion, responses( (status = 200, description = "Updated question", body = QuestionResponse), - (status = 400, description = "Invalid text, kind, points, choices, or correct", body = ErrorResponse), + (status = 400, description = "Invalid text, kind, points, choices, or correct — or an unknown subject, or one from another course", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), @@ -1422,6 +1438,10 @@ async fn update_question( ensure_questions_editable(exam.get_id(), &st.db).await?; let question = question_of_exam(exam.get_id(), &qid, &st.db).await?; + let subject = match req.subject_id { + Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, + None => question.get_subject().clone(), + }; let text = match req.text { Some(ref text) => QuestionText::try_new(text)?, None => question.get_text().clone(), @@ -1448,7 +1468,7 @@ async fn update_question( }; let spec = QuestionSpec::try_new(kind, choices, correct)?; - let updated = question.update(text, points, spec, &st.db).await?; + let updated = question.update(subject, text, points, spec, &st.db).await?; Ok(Json(QuestionResponse::new(&updated))) } @@ -1522,6 +1542,8 @@ impl AnswerStateResponse { #[derive(Serialize, ToSchema)] struct AttemptQuestionResponse { id: String, + /// The subject this question belongs to (`GET /subjects/{id}`). + subject: String, text: String, /// `choice` or `text`. #[schema(example = "choice")] @@ -1711,6 +1733,7 @@ async fn attempt_questions( .iter() .map(|question| AttemptQuestionResponse { id: question.get_id().key().to_string(), + subject: question.get_subject().key().to_string(), text: question.get_text().as_str().to_string(), kind: question.get_kind().as_str().to_string(), points: question.get_points().as_i64(), diff --git a/src/web/mod.rs b/src/web/mod.rs index 66cc335..a15a136 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -13,6 +13,7 @@ pub mod marks; pub mod notes; pub mod sessions; pub mod settings; +pub mod subjects; pub mod terms; pub mod users; pub mod work; @@ -21,7 +22,10 @@ mod dto; mod extractor; mod page; -pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map}; +pub use dto::{ + CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, + person_map, +}; pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; pub use page::{Page, PageParams, paginate}; diff --git a/src/web/subjects.rs b/src/web/subjects.rs new file mode 100644 index 0000000..ac8191b --- /dev/null +++ b/src/web/subjects.rs @@ -0,0 +1,174 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::Deserialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::course::{Course, CourseId}; +use crate::domain::exam_question::ExamQuestion; +use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::courses::{can_manage_course, can_view_course}; +use super::{CurrentUser, RequireTeacher, SubjectResponse}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(get_subject, update_subject, delete_subject)) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateSubject { + name: Option, + description: Option, +} + +/// Turn a request-supplied subject id into a validated reference, provided the +/// subject belongs to `course` — a question may only be tagged with a subject +/// of its own exam's course. Unknown or foreign subjects are a `400` naming +/// the field. Shared by the question create/update handlers. +pub(crate) async fn subject_in_course( + id: &str, + course: &CourseId, + db: &Database, +) -> Result { + let subject = + Subject::read(&SubjectId::from_key(id), db) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject does not exist", + }))?; + if subject.get_course() != course { + return Err(AppError::Validation(ValidationError::Invalid { + field: "subject_id", + reason: "subject belongs to a different course", + })); + } + Ok(subject.get_id().clone()) +} + +/// The subject plus its course, or a 404 — every handler here gates on the +/// parent course, so they always travel together. +async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course), AppError> { + let subject = Subject::read(&SubjectId::from_key(id), db) + .await? + .ok_or(AppError::NotFound)?; + let course = Course::read(subject.get_course(), db) + .await? + .ok_or(AppError::NotFound)?; + Ok((subject, course)) +} + +/// Fetch a single subject by id. Visible to whoever can view its course: the +/// course's enrolled users, its creator, and managers/admins. +#[utoipa::path( + get, + path = "/{id}", + tag = "subjects", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Subject id")), + responses( + (status = 200, description = "The subject", body = SubjectResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the course creator, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_subject( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let (subject, course) = subject_with_course(&id, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, or a manager/admin can view this subject", + )); + } + Ok(Json(SubjectResponse::new(&subject))) +} + +/// Update a subject's name or description. Requires teacher+ and management +/// rights over its course. Omitted fields keep their value; the course link is +/// fixed at creation. +#[utoipa::path( + patch, + path = "/{id}", + tag = "subjects", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Subject id")), + request_body = UpdateSubject, + responses( + (status = 200, description = "Updated subject", body = SubjectResponse), + (status = 400, description = "Invalid name or description", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_subject( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let (subject, course) = subject_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can edit this subject", + )); + } + + let name = match req.name { + Some(ref name) => SubjectName::try_new(name)?, + None => subject.get_name().clone(), + }; + let description = match req.description { + Some(ref description) => SubjectDescription::try_new(description)?, + None => subject.get_description().clone(), + }; + + let updated = subject.update(name, description, &st.db).await?; + Ok(Json(SubjectResponse::new(&updated))) +} + +/// Delete a subject. Requires teacher+ and management rights over its course. +/// Refused with a 409 while any exam question still references it — re-tag or +/// delete those questions first, so no question is left without a real subject. +#[utoipa::path( + delete, + path = "/{id}", + tag = "subjects", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Subject id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "Exam questions still reference this subject", body = ErrorResponse), + ), +)] +async fn delete_subject( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let (subject, course) = subject_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can delete this subject", + )); + } + if ExamQuestion::any_for_subject(subject.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "exam questions still reference this subject — re-tag or delete them first", + )); + } + subject.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 767237a..31afef2 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -254,6 +254,21 @@ pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String { id_of(&res.body) } +/// Create a subject inside `course` as `cookie` (asserts 201); returns its id. +/// Every exam question must be tagged with one of its course's subjects. +pub async fn create_subject(app: &Router, cookie: &str, course: &str, name: &str) -> String { + let res = send( + app, + "POST", + &format!("/courses/{course}/subjects"), + Some(cookie), + Some(json!({ "name": name })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create subject {name}"); + id_of(&res.body) +} + /// Create an exam inside `course` as `cookie` (asserts 201); returns its id. /// The exam's weight in the course average comes from its kind (settings). pub async fn create_exam( diff --git a/tests/e2e.rs b/tests/e2e.rs index d99a961..9c62b68 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -767,6 +767,7 @@ struct ExamRoom { student_id: String, cookie: String, course_id: String, + subject_id: String, exam_id: String, question_id: String, } @@ -810,6 +811,16 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { .await .unwrap(); let course_id = course["id"].as_str().unwrap().to_string(); + let subject: Value = teacher + .post(format!("{base}/courses/{course_id}/subjects")) + .json(&json!({ "name": "arithmetic" })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let subject_id = subject["id"].as_str().unwrap().to_string(); let res = teacher .post(format!("{base}/courses/{course_id}/enrollments")) .json(&json!({ "user_id": student_id })) @@ -832,8 +843,10 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { let exam_id = exam["id"].as_str().unwrap().to_string(); let question: Value = teacher .post(format!("{base}/exams/{exam_id}/questions")) - .json(&json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4"], "correct": 1 })) + .json( + &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", + "points": 10, "choices": ["3", "4"], "correct": 1 }), + ) .send() .await .unwrap() @@ -850,6 +863,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { student_id, cookie, course_id, + subject_id, exam_id, question_id, } @@ -875,7 +889,8 @@ async fn exam_room_websocket_round_trip() { // A second question so progress counts have something to be partial over. let res = teacher .post(format!("{base}/exams/{exam_id}/questions")) - .json(&json!({ "text": "Explain.", "kind": "text", "points": 20 })) + .json(&json!({ "subject_id": room.subject_id, "text": "Explain.", + "kind": "text", "points": 20 })) .send() .await .unwrap(); @@ -1438,8 +1453,10 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { let question: Value = room .teacher .post(format!("{}/exams/{exam_id}/questions", room.base)) - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, - "choices": ["5", "6"], "correct": 1 })) + .json( + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", + "points": 5, "choices": ["5", "6"], "correct": 1 }), + ) .send() .await .unwrap() @@ -1542,8 +1559,10 @@ async fn exam_room_messages_bind_to_their_own_sitting() { let question: Value = room .teacher .post(format!("{}/exams/{exam_id}/questions", room.base)) - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, - "choices": ["5", "6"], "correct": 1 })) + .json( + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", + "points": 5, "choices": ["5", "6"], "correct": 1 }), + ) .send() .await .unwrap() @@ -1727,8 +1746,10 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { let question: Value = room .teacher .post(format!("{}/exams/{exam_id}/questions", room.base)) - .json(&json!({ "text": "3 + 3?", "kind": "choice", "points": 5, - "choices": ["5", "6"], "correct": 1 })) + .json( + &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice", + "points": 5, "choices": ["5", "6"], "correct": 1 }), + ) .send() .await .unwrap() diff --git a/tests/integration.rs b/tests/integration.rs index 27fb5ff..317ff6f 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -6,8 +6,8 @@ mod common; use axum::body::Body; use axum::http::{Request, StatusCode}; use common::{ - app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, - login_as, me_id, mem_app, send, set_role, + app_and_db, create_course, create_exam, create_exam_with, create_session, create_subject, + enroll, id_of, login, login_as, me_id, mem_app, send, set_role, }; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; @@ -5792,6 +5792,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { let student = login(&app, "omer").await; let student_id = me_id(&app, &student).await; let course = create_course(&app, &teacher, "practice").await; + let subject = create_subject(&app, &teacher, &course, "drills").await; enroll(&app, &teacher, &course, &student_id).await; let exam = scheduled_exam( &app, @@ -5805,6 +5806,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -6143,16 +6145,283 @@ async fn live_stream_is_sse_and_teacher_scoped() { assert_eq!(res.status, StatusCode::NOT_FOUND); } +// --- subjects --------------------------------------------------------------- + +#[tokio::test] +async fn subject_crud_validation_and_rbac() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "sub_t", "teacher").await; + let other_teacher = login_as(&app, &db, "sub_t2", "teacher").await; + let boss = login_as(&app, &db, "sub_m", "manager").await; + let student = login(&app, "selin").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "calculus").await; + enroll(&app, &teacher, &course, &student_id).await; + + // Create echoes the full shape; description defaults to empty. + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&teacher), + Some(json!({ "name": "limits", "description": "epsilon-delta" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["course"], course); + assert_eq!(res.body["name"], "limits"); + assert_eq!(res.body["description"], "epsilon-delta"); + let subject = id_of(&res.body); + let second = create_subject(&app, &teacher, &course, "derivatives").await; + + // Validation: a blank name is a 400, a missing course a 404. + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&teacher), + Some(json!({ "name": " " })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + let res = send( + &app, + "POST", + "/courses/missing/subjects", + Some(&teacher), + Some(json!({ "name": "orphan" })), + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND); + + // Writes are management-gated: students lack the role, a rival teacher + // the rights; a manager passes everywhere. + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&student), + Some(json!({ "name": "nope" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&other_teacher), + Some(json!({ "name": "nope" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "PATCH", + &format!("/subjects/{subject}"), + Some(&other_teacher), + Some(json!({ "name": "hijack" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "DELETE", + &format!("/subjects/{second}"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // Reads follow course visibility: the enrolled student and a manager see + // the list and the subject, the rival teacher sees neither. + let res = send( + &app, + "GET", + &format!("/courses/{course}/subjects"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let listed = common::items(&res.body); + assert_eq!(listed.len(), 2, "creation order"); + assert_eq!(id_of(&listed[0]), subject); + assert_eq!(id_of(&listed[1]), second); + assert_eq!(common::total(&res.body), 2); + let res = send( + &app, + "GET", + &format!("/subjects/{subject}"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["name"], "limits"); + let res = send( + &app, + "GET", + &format!("/courses/{course}/subjects"), + Some(&other_teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "GET", + &format!("/subjects/{subject}"), + Some(&other_teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // PATCH keeps omitted fields; a manager may edit anyone's. + let res = send( + &app, + "PATCH", + &format!("/subjects/{subject}"), + Some(&boss), + Some(json!({ "name": "limits & continuity" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["name"], "limits & continuity"); + assert_eq!(res.body["description"], "epsilon-delta", "kept by omission"); + + // Unknown ids are 404s. + for (method, body) in [ + ("GET", None), + ("PATCH", Some(json!({ "name": "x" }))), + ("DELETE", None), + ] { + let res = send(&app, method, "/subjects/missing", Some(&teacher), body).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{method}"); + } + + // Delete works while nothing references the subject. + let res = send( + &app, + "DELETE", + &format!("/subjects/{second}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "GET", + &format!("/subjects/{second}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND); +} + +#[tokio::test] +async fn subject_delete_blocks_while_questions_reference_it() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "sdb_t", "teacher").await; + let course = create_course(&app, &teacher, "history").await; + let tagged = create_subject(&app, &teacher, &course, "antiquity").await; + let spare = create_subject(&app, &teacher, &course, "middle ages").await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; + let question = create_question( + &app, + &teacher, + &exam, + &tagged, + json!({ "text": "When?", "kind": "text", "points": 10 }), + ) + .await; + + // Referenced: the delete is a conflict, and the subject survives. + let res = send( + &app, + "DELETE", + &format!("/subjects/{tagged}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/subjects/{tagged}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + + // Re-tag the question elsewhere: the old subject frees up, the new one + // locks. + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{question}"), + Some(&teacher), + Some(json!({ "subject_id": spare })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/subjects/{tagged}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "DELETE", + &format!("/subjects/{spare}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + + // Deleting the question releases the last reference. + let res = send( + &app, + "DELETE", + &format!("/exams/{exam}/questions/{question}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "DELETE", + &format!("/subjects/{spare}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); +} + // --- exam questions + answers (taking an exam) ----------------------------- -/// Create a question via `POST /exams/{exam}/questions` (asserts 201); -/// returns its id. +/// Create a question tagged with `subject` via `POST /exams/{exam}/questions` +/// (asserts 201); returns its id. async fn create_question( app: &axum::Router, cookie: &str, exam: &str, - body: serde_json::Value, + subject: &str, + mut body: serde_json::Value, ) -> String { + body["subject_id"] = json!(subject); let res = send( app, "POST", @@ -6170,15 +6439,16 @@ async fn create_question( id_of(&res.body) } -/// A course with an open sync window and one enrolled student, the spine of -/// the question/answer tests. Returns (course, exam). +/// A course with an open sync window, one subject, and one enrolled student — +/// the spine of the question/answer tests. Returns (course, exam, subject). async fn open_exam_with_student( app: &axum::Router, teacher: &str, student_id: &str, course_title: &str, -) -> (String, String) { +) -> (String, String, String) { let course = create_course(app, teacher, course_title).await; + let subject = create_subject(app, teacher, &course, "general").await; enroll(app, teacher, &course, student_id).await; let now = Timestamp::now().as_millis(); let exam = scheduled_exam( @@ -6189,7 +6459,7 @@ async fn open_exam_with_student( "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; - (course, exam) + (course, exam, subject) } #[tokio::test] @@ -6199,6 +6469,7 @@ async fn question_crud_validation_and_rbac() { let other_teacher = login_as(&app, &db, "q_t2", "teacher").await; let student = login(&app, "quinn").await; let course = create_course(&app, &teacher, "logic").await; + let subject = create_subject(&app, &teacher, &course, "propositions").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; // A choice question echoes its full authoring view, correct included. @@ -6207,12 +6478,15 @@ async fn question_crud_validation_and_rbac() { "POST", &format!("/exams/{exam}/questions"), Some(&teacher), - Some(json!({ "text": "2 + 2?", "kind": "choice", "points": 10, - "choices": ["3", "4", "5"], "correct": 1 })), + Some( + json!({ "subject_id": subject, "text": "2 + 2?", "kind": "choice", "points": 10, + "choices": ["3", "4", "5"], "correct": 1 }), + ), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); assert_eq!(res.body["exam"], exam); + assert_eq!(res.body["subject"], subject); assert_eq!(res.body["kind"], "choice"); assert_eq!(res.body["points"], 10); assert_eq!(res.body["choices"][1], "4"); @@ -6225,7 +6499,7 @@ async fn question_crud_validation_and_rbac() { "POST", &format!("/exams/{exam}/questions"), Some(&teacher), - Some(json!({ "text": "Explain.", "kind": "text", "points": 20 })), + Some(json!({ "subject_id": subject, "text": "Explain.", "kind": "text", "points": 20 })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); @@ -6304,6 +6578,8 @@ async fn question_crud_validation_and_rbac() { json!({ "text": "x", "kind": "text", "points": 1, "correct": 0 }), ), ] { + let mut body = body; + body["subject_id"] = json!(subject); let res = send( &app, "POST", @@ -6315,8 +6591,26 @@ async fn question_crud_validation_and_rbac() { assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); } + // The subject must exist and belong to the exam's own course. + let other_course = create_course(&app, &teacher, "rhetoric").await; + let foreign_subject = create_subject(&app, &teacher, &other_course, "fallacies").await; + for (label, subject_id) in [ + ("unknown subject", "missing"), + ("foreign subject", foreign_subject.as_str()), + ] { + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&teacher), + Some(json!({ "subject_id": subject_id, "text": "x", "kind": "text", "points": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{label}: {}", res.body); + } + // Authoring needs management rights over the course; reading needs teacher+. - let question_body = json!({ "text": "x", "kind": "text", "points": 1 }); + let question_body = json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 }); let res = send( &app, "POST", @@ -6361,6 +6655,30 @@ async fn question_crud_validation_and_rbac() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); assert_eq!(res.body["points"], 15); assert_eq!(res.body["correct"], 1, "kind bundle kept"); + assert_eq!(res.body["subject"], subject, "subject kept by omission"); + + // Re-tagging stays inside the course: another of its subjects is fine, a + // foreign course's subject is a 400. + let second_subject = create_subject(&app, &teacher, &course, "predicates").await; + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{choice_q}"), + Some(&teacher), + Some(json!({ "subject_id": second_subject })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["subject"], second_subject); + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{choice_q}"), + Some(&teacher), + Some(json!({ "subject_id": foreign_subject })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); // Switching to text must clear the bundle explicitly... let res = send( @@ -6424,7 +6742,9 @@ async fn question_crud_validation_and_rbac() { ), ] { let body = match method { - "POST" => Some(json!({ "text": "x", "kind": "text", "points": 1 })), + "POST" => { + Some(json!({ "subject_id": subject, "text": "x", "kind": "text", "points": 1 })) + } "PATCH" => Some(json!({ "points": 2 })), _ => None, }; @@ -6468,11 +6788,13 @@ async fn questions_freeze_once_attempts_start() { let teacher = login_as(&app, &db, "frz_t", "teacher").await; let student = login(&app, "firat").await; let student_id = me_id(&app, &student).await; - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "algo").await; + let (_course, exam, subject) = + open_exam_with_student(&app, &teacher, &student_id, "algo").await; let question = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -6494,7 +6816,7 @@ async fn questions_freeze_once_attempts_start() { "POST", &format!("/exams/{exam}/questions"), Some(&teacher), - Some(json!({ "text": "late", "kind": "text", "points": 1 })), + Some(json!({ "subject_id": subject, "text": "late", "kind": "text", "points": 1 })), ) .await; assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); @@ -6524,11 +6846,12 @@ async fn student_question_view_hides_correct_and_embeds_answers() { let teacher = login_as(&app, &db, "sv_t", "teacher").await; let student = login(&app, "sona").await; let student_id = me_id(&app, &student).await; - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "art").await; + let (_course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "art").await; let choice_q = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -6537,6 +6860,7 @@ async fn student_question_view_hides_correct_and_embeds_answers() { &app, &teacher, &exam, + &subject, json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; @@ -6597,11 +6921,12 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { let teacher = login_as(&app, &db, "ans_t", "teacher").await; let student = login(&app, "arda").await; let student_id = me_id(&app, &student).await; - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "phys").await; + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "phys").await; let choice_q = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4", "5"], "correct": 1 }), ) @@ -6610,6 +6935,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { &app, &teacher, &exam, + &subject, json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; @@ -6731,6 +7057,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { &app, &teacher, &foreign_exam, + &subject, json!({ "text": "not yours", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": 0 }), ) @@ -6800,11 +7127,12 @@ async fn unenrollment_cuts_the_sittings_reads_and_writes() { let teacher = login_as(&app, &db, "cut_t", "teacher").await; let student = login(&app, "cansu").await; let student_id = me_id(&app, &student).await; - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; let question = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -6917,6 +7245,7 @@ async fn answer_saves_stop_at_the_deadline() { let student = login(&app, "dila").await; let student_id = me_id(&app, &student).await; let course = create_course(&app, &teacher, "geo").await; + let subject = create_subject(&app, &teacher, &course, "general").await; enroll(&app, &teacher, &course, &student_id).await; let now = Timestamp::now().as_millis(); @@ -6934,6 +7263,7 @@ async fn answer_saves_stop_at_the_deadline() { &app, &teacher, &exam, + &subject, json!({ "text": "quick", "kind": "choice", "points": 1, "choices": ["a", "b"], "correct": 0 }), ) @@ -6993,11 +7323,13 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { let teacher = login_as(&app, &db, "sc_t", "teacher").await; let student = login(&app, "sena").await; let student_id = me_id(&app, &student).await; - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "chem").await; + let (_course, exam, subject) = + open_exam_with_student(&app, &teacher, &student_id, "chem").await; let q1 = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -7006,6 +7338,7 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { &app, &teacher, &exam, + &subject, json!({ "text": "3 + 3?", "kind": "choice", "points": 20, "choices": ["6", "7"], "correct": 0 }), ) @@ -7014,6 +7347,7 @@ async fn teacher_answer_sheet_judges_choices_and_suggests_a_score() { &app, &teacher, &exam, + &subject, json!({ "text": "Explain.", "kind": "text", "points": 30 }), ) .await; @@ -7082,12 +7416,13 @@ async fn live_monitor_tracks_answer_progress() { let bora = login(&app, "bora").await; let ayla_id = me_id(&app, &ayla).await; let bora_id = me_id(&app, &bora).await; - let (course, exam) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await; + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &ayla_id, "stats").await; enroll(&app, &teacher, &course, &bora_id).await; let question = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -7096,6 +7431,7 @@ async fn live_monitor_tracks_answer_progress() { &app, &teacher, &exam, + &subject, json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; @@ -7153,11 +7489,12 @@ async fn questions_and_answers_cascade_with_deletes() { let teacher = login_as(&app, &db, "qc_t", "teacher").await; let student = login(&app, "cem").await; let student_id = me_id(&app, &student).await; - let (course, exam) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await; + let (course, exam, subject) = open_exam_with_student(&app, &teacher, &student_id, "geo2").await; let q1 = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -7166,6 +7503,7 @@ async fn questions_and_answers_cascade_with_deletes() { &app, &teacher, &exam, + &subject, json!({ "text": "Explain.", "kind": "text", "points": 20 }), ) .await; @@ -7271,6 +7609,7 @@ async fn questions_and_answers_cascade_with_deletes() { &app, &teacher, &exam2, + &subject, json!({ "text": "2 + 2?", "kind": "choice", "points": 10, "choices": ["3", "4"], "correct": 1 }), ) @@ -7316,6 +7655,16 @@ async fn questions_and_answers_cascade_with_deletes() { .unwrap() .is_empty() ); + // The course's subjects go down with it too. + let res = send( + &app, + "GET", + &format!("/subjects/{subject}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "subject cascaded"); } #[tokio::test] @@ -7323,11 +7672,13 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "rv_t", "teacher").await; let course = create_course(&app, &teacher, "sets").await; + let subject = create_subject(&app, &teacher, &course, "unions").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; let question = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "pick", "kind": "choice", "points": 10, "choices": ["a", "b", "c"], "correct": 2 }), ) @@ -7410,6 +7761,7 @@ async fn question_authoring_follows_course_management() { let teacher = login_as(&app, &db, "own_t", "teacher").await; let boss = login_as(&app, &db, "own_m", "manager").await; let course = create_course(&app, &teacher, "greek").await; + let subject = create_subject(&app, &boss, &course, "alphabet").await; let exam = create_exam(&app, &teacher, &course, "final", "final").await; // A manager+ authors questions in anyone's course, like every other @@ -7418,6 +7770,7 @@ async fn question_authoring_follows_course_management() { &app, &boss, &exam, + &subject, json!({ "text": "pick", "kind": "choice", "points": 10, "choices": ["a", "b"], "correct": 0 }), ) @@ -7448,11 +7801,13 @@ async fn concurrent_answer_saves_never_collide() { let teacher = login_as(&app, &db, "cc_t", "teacher").await; let student = login(&app, "cana").await; let student_id = me_id(&app, &student).await; - let (_course, exam) = open_exam_with_student(&app, &teacher, &student_id, "race").await; + let (_course, exam, subject) = + open_exam_with_student(&app, &teacher, &student_id, "race").await; let question = create_question( &app, &teacher, &exam, + &subject, json!({ "text": "pick", "kind": "choice", "points": 10, "choices": ["a", "b", "c"], "correct": 0 }), ) diff --git a/tests/persistence.rs b/tests/persistence.rs index d58fdf7..2e68d9e 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -700,3 +700,146 @@ async fn legacy_users_audiences_convert_to_registrations() { .await; assert_eq!(res.status, StatusCode::OK, "converted seat is markable"); } + +/// Exam-question rows written before subjects existed (2026-07) are destroyed +/// on the next boot, answers first — a subject is mandatory and there is +/// nothing truthful to backfill. The exam and the course's subjects survive. +#[tokio::test] +async fn legacy_subjectless_questions_are_destroyed_on_boot() { + let dir = tempfile::tempdir().unwrap(); + let cfg = config_at(&dir); + let creds = json!({ "username": "ali", "password": "secret1" }); + let exam_id; + let subject_id; + + // First boot: a full exam — course, subject, open exam, one answered + // question — then strip the question's subject the way an old binary's + // schema would have left it. + { + let db = database::init(&cfg).await.expect("first open"); + let app = build_router(state(db.clone(), &cfg)); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(creds.clone())) + .await + .status, + StatusCode::CREATED + ); + set_role(&db, "ali", "teacher").await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + let student = json!({ "username": "veli", "password": "secret1" }); + assert_eq!( + send(&app, "POST", "/auth/register", None, Some(student.clone())) + .await + .status, + StatusCode::CREATED + ); + let student_cookie = send(&app, "POST", "/auth/login", None, Some(student)) + .await + .cookie + .unwrap(); + let student_id = common::me_id(&app, &student_cookie).await; + + let course = create_course(&app, &cookie, "algebra").await; + enroll(&app, &cookie, &course, &student_id).await; + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&cookie), + Some(json!({ "name": "arithmetic" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + subject_id = common::id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/courses/{course}/exams"), + Some(&cookie), + Some(json!({ "title": "drill", "kind": "quiz", "mode": "open" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + exam_id = common::id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/questions"), + Some(&cookie), + Some( + json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", + "points": 10, "choices": ["3", "4"], "correct": 1 }), + ), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let question_id = common::id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/attempt"), + Some(&student_cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/exams/{exam_id}/attempt/answers"), + Some(&student_cookie), + Some(json!({ "question_id": question_id, "selected": 1 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + db.query( + "REMOVE FIELD IF EXISTS subject ON TABLE exam_question; + UPDATE exam_question SET subject = NONE;", + ) + .await + .expect("strip subject") + .check() + .expect("strip subject check"); + } + + // Second boot re-runs the migration and the destroy-backfill: the + // subjectless question and its answer are gone, the exam and subject + // still stand. + let db = reopen(&cfg).await; + let app = build_router(state(db.clone(), &cfg)); + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let res = send( + &app, + "GET", + &format!("/exams/{exam_id}/questions"), + Some(&cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 0, "legacy questions destroyed"); + let res = send( + &app, + "GET", + &format!("/subjects/{subject_id}"), + Some(&cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "the subject itself survives"); + let mut result = db + .query("SELECT VALUE id FROM exam_answer") + .await + .expect("count answers") + .check() + .expect("count answers check"); + let answers: Vec = result.take(0).expect("answer rows"); + assert!(answers.is_empty(), "orphaned answers destroyed"); +}