forge
Explore
Log in

Don't you dare go Hollow

Guard course, exam-kind, and term removal

Browse files at this commit

91917114dd8b9d602bc2ccbbd9a0643ef7bf1820Ahmet Kaan GümüşParent: 1b82dab
  • feat
    • guard course, exam-kind, and term removal
Show full message
✨ feat(deletes): guard course, exam-kind, and term removal

Three referential-integrity guards, all 409 instead of silently taking
dependent data with them:

- DELETE /courses/{id} refuses while anyone is enrolled. The cascade
  used to delete the enrollments along with the course, so a roster
  could vanish on a misclick; the check and the delete are held under
  ENROLL_LOCK so a concurrent enroll cannot slip in behind it.
- PATCH /settings refuses to drop an exam kind whose exams already
  carry marks. Weights resolve live, so removing the kind would
  re-weight every one of those marks to 1 without touching a row. The
  check is re-run per CAS retry against the snapshot the save is
  conditioned on, under an EXAM_LOCK writer lease so grading cannot
  land the first mark mid-flight. An unmarked kind still leaves freely.
- DELETE /terms/{id} refuses while any course links it, rather than
  unlinking those courses. Guarded by a new TERM_LOCK, taken by the
  course writes that assign a term. Lock order: never held together
  with ENROLL_LOCK; if a path ever needs both, ENROLL_LOCK first.

No rows change; existing courses with a roster and terms with linked
courses simply need emptying before deletion. Frontend must surface
the new 409 on all three.
README.mdmodified+14 -8
@@ -435,7 +435,7 @@ their existing shapes: the student exam-room reads
435 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |435 | GET | `/courses/me` | student | The caller's **enrolled** courses · paged |
436 | GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |436 | GET | `/courses/{id}` | student | Get course (enrolled, creator, assigned teacher, or manager+) |
437 | PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |437 | PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) |
438-| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, enrollments, subjects, and homework (submissions, files, and grades included) (creator, or manager+ — **not** an assigned teacher) |438+| DELETE | `/courses/{id}` | teacher | Delete course + its exams, results, subjects, sessions, and homework (submissions, files, and grades included) (creator, or manager+ — **not** an assigned teacher; `409` while anyone is still enrolled) |
439 | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) |439 | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) |
440 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |440 | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) |
441 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |441 | POST | `/courses/{id}/enrollments` | teacher | `{user_id}` — enroll a **student** (idempotent upsert; course manager; only students can be enrolled; `409` once a capped course is full) |
@@ -535,12 +535,12 @@ their existing shapes: the student exam-room reads
535 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |535 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
536 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |536 | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full |
537 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` |537 | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` |
538-| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other (see "Per-school policy") |538+| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other; `409` when a removed exam kind still has graded exams (see "Per-school policy") |
539 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |539 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
540 | GET | `/terms` | student | List terms, newest first · paged |540 | GET | `/terms` | student | List terms, newest first · paged |
541 | GET | `/terms/{id}` | student | Get one term |541 | GET | `/terms/{id}` | student | Get one term |
542 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |542 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
543-| DELETE | `/terms/{id}` | manager | Delete a term — linked courses are unlinked, never deleted |543+| DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it |
544 544
545 `status` must be one of the school's attendance statuses (`GET /settings`);545 `status` must be one of the school's attendance statuses (`GET /settings`);
546 the core four `present | absent | late | excused` always exist, plus whatever546 the core four `present | absent | late | excused` always exist, plus whatever
@@ -565,8 +565,10 @@ A course average is `Σ(mark×weight) / Σ(weight)` over the student's **graded*
565 exams in that course (`null` while nothing is graded — ungraded exams are565 exams in that course (`null` while nothing is graded — ungraded exams are
566 skipped, not zeroed). The overall average is the plain mean of the non-null566 skipped, not zeroed). The overall average is the plain mean of the non-null
567 course averages. Unenrolling keeps result rows: the marks drop out of the567 course averages. Unenrolling keeps result rows: the marks drop out of the
568-report until re-enrollment, but stay visible on the exam itself. Deleting a568+report until re-enrollment, but stay visible on the exam itself. A course
569-course cascades its exams, their results, all enrollments, and its subjects.569+with anyone still on its roster refuses deletion (`409`) — empty the roster
570+first; once empty, deleting it cascades its exams, their results, its
571+sessions and roll call, and its subjects.
570 A **subject** is one topic of a course's curriculum (`name` ≤ 200 chars,572 A **subject** is one topic of a course's curriculum (`name` ≤ 200 chars,
571 optional `description` ≤ 2000): every exam question carries a mandatory573 optional `description` ≤ 2000): every exam question carries a mandatory
572 `subject_id` naming one of *its own course's* subjects (an unknown or574 `subject_id` naming one of *its own course's* subjects (an unknown or
@@ -702,8 +704,10 @@ editable `settings` singleton (`GET /settings` for any signed-in user,
702 final, project, oral`, all weighing `1` (a plain average); replace the704 final, project, oral`, all weighing `1` (a plain average); replace the
703 list with whatever the school grades and weighs (`{"name": "final",705 list with whatever the school grades and weighs (`{"name": "final",
704 "weight": 3}`, …). Reports resolve weights live: editing a weight706 "weight": 3}`, …). Reports resolve weights live: editing a weight
705- re-weights every exam of that kind at once, and an exam keeping a707+ re-weights every exam of that kind at once. For the same reason a kind
706- since-removed kind counts with weight `1`.708+ whose exams already carry marks cannot be removed from the list (`409`):
709+ those marks would silently re-weight. An unmarked kind leaves freely, and
710+ an exam keeping a since-removed kind counts with weight `1`.
707 - **`attendance_statuses`** — what attendance marking accepts. The core four711 - **`attendance_statuses`** — what attendance marking accepts. The core four
708 (`present`, `absent`, `late`, `excused`) are mandatory because the712 (`present`, `absent`, `late`, `excused`) are mandatory because the
709 attendance rate is defined over them (`(present+late) /713 attendance rate is defined over them (`(present+late) /
@@ -731,7 +735,9 @@ retired status — only **new writes** are held to the current lists.
731 Academic structure is data too. **Terms** (`/terms`) model whatever calendar735 Academic structure is data too. **Terms** (`/terms`) model whatever calendar
732 the school runs — semester, trimester, quarter systems are just rows with a736 the school runs — semester, trimester, quarter systems are just rows with a
733 name and a date range. Courses may link to one via `term_id` (nullable), and737 name and a date range. Courses may link to one via `term_id` (nullable), and
734-deleting a term only unlinks its courses. Term dates may lie in the past,738+deleting a term is refused with a `409` while any course still links to it —
739+unlink those courses (`PATCH /courses/{id}` with `"term_id": null`) or delete
740+them first, so the calendar never disappears under them. Term dates may lie in the past,
735 deliberately: a school adopting the app mid-year backfills its calendar —741 deliberately: a school adopting the app mid-year backfills its calendar —
736 unlike exam/lesson/event times, which reject backdating.742 unlike exam/lesson/event times, which reject backdating.
737 743
src/domain/enrollment.rsmodified+13 -1
@@ -9,7 +9,9 @@ use crate::error::AppError;
9 /// Serializes enrolls so the capacity check (count, then write) can't9 /// Serializes enrolls so the capacity check (count, then write) can't
10 /// over-admit under concurrency — the database's optimistic transactions10 /// over-admit under concurrency — the database's optimistic transactions
11 /// don't serialize cross-record counts against concurrent inserts.11 /// don't serialize cross-record counts against concurrent inserts.
12-static ENROLL_LOCK: Mutex<()> = Mutex::const_new(());12+/// It also serializes the roster check of a course delete against a concurrent
13+/// enroll, so a student can't join a course that is already on its way out.
14+pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(());
13 15
14 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]16 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
15 pub struct EnrollmentId(RecordId);17 pub struct EnrollmentId(RecordId);
@@ -121,6 +123,16 @@ impl Enrollment {
121 Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())123 Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next())
122 }124 }
123 125
126+ /// True iff anyone is still on the course's roster — the delete guard.
127+ pub async fn any_for_course(course: &CourseId, db: &Database) -> Result<bool, AppError> {
128+ let mut result = db
129+ .query("SELECT VALUE id FROM enrollment WHERE course = $course LIMIT 1")
130+ .bind(("course", course.record()))
131+ .await?
132+ .check()?;
133+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
134+ }
135+
124 pub async fn list_for_course(136 pub async fn list_for_course(
125 course: &CourseId,137 course: &CourseId,
126 db: &Database,138 db: &Database,
src/domain/exam_result.rsmodified+16 -0
@@ -145,6 +145,22 @@ impl ExamResult {
145 Ok(result.take::<Vec<ExamResult>>(0)?)145 Ok(result.take::<Vec<ExamResult>>(0)?)
146 }146 }
147 147
148+ /// True iff any exam of `kind` has produced a mark — the settings guard
149+ /// against removing an exam kind that grades already depend on (weights are
150+ /// read live from settings, so dropping the kind would silently re-weight
151+ /// those marks).
152+ pub async fn any_for_kind(kind: &str, db: &Database) -> Result<bool, AppError> {
153+ let mut result = db
154+ .query(
155+ "SELECT VALUE id FROM exam_result
156+ WHERE exam IN (SELECT VALUE id FROM exam WHERE kind = $kind) LIMIT 1",
157+ )
158+ .bind(("kind", kind.to_string()))
159+ .await?
160+ .check()?;
161+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
162+ }
163+
148 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {164 pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result<Vec<ExamResult>, AppError> {
149 let mut result = db165 let mut result = db
150 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")166 .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC")
src/domain/term.rsmodified+24 -5
@@ -7,6 +7,7 @@
7 //! rule that guards exams/lessons/events deliberately does not apply here.7 //! rule that guards exams/lessons/events deliberately does not apply here.
8 8
9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
10+use tokio::sync::Mutex;
10 use ulid::Ulid;11 use ulid::Ulid;
11 12
12 use crate::constant::MAX_TERM_NAME_LEN;13 use crate::constant::MAX_TERM_NAME_LEN;
@@ -15,6 +16,17 @@ use crate::domain::timestamp::Timestamp;
15 use crate::error::{AppError, ValidationError};16 use crate::error::{AppError, ValidationError};
16 use crate::validate::validate_required;17 use crate::validate::validate_required;
17 18
19+/// Serializes the term delete guard (does any course still link it?) against
20+/// the course writes that assign a term, so a course can't land on a term that
21+/// is already on its way out. Course writes take it only when they actually
22+/// link a term.
23+///
24+/// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the
25+/// course writes that take this one touch no roster, and the course delete that
26+/// takes `ENROLL_LOCK` touches no term — so the two cannot deadlock. Should a
27+/// future path need both, take `ENROLL_LOCK` first.
28+pub(crate) static TERM_LOCK: Mutex<()> = Mutex::const_new(());
29+
18 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]30 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
19 pub struct TermId(RecordId);31 pub struct TermId(RecordId);
20 32
@@ -123,13 +135,20 @@ impl Term {
123 updated.ok_or(AppError::NotFound)135 updated.ok_or(AppError::NotFound)
124 }136 }
125 137
126- /// Delete the term. Courses keep existing — they just lose the link, so138+ /// True iff any course still links to this term — the delete guard.
127- /// deleting a term can never take a course (or its marks) with it.139+ pub async fn any_course(id: &TermId, db: &Database) -> Result<bool, AppError> {
128- pub async fn delete(self, db: &Database) -> Result<Term, AppError> {140+ let mut result = db
129- db.query("UPDATE course SET term = NONE WHERE term = $term")141+ .query("SELECT VALUE id FROM course WHERE term = $term LIMIT 1")
130- .bind(("term", self.id.record()))142+ .bind(("term", id.record()))
131 .await?143 .await?
132 .check()?;144 .check()?;
145+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
146+ }
147+
148+ /// Delete the term. Callers must refuse while [`Term::any_course`] holds —
149+ /// nothing here unlinks or cascades, so a term is only ever dropped once no
150+ /// course points at it.
151+ pub async fn delete(self, db: &Database) -> Result<Term, AppError> {
133 let deleted: Option<Term> = db.delete(self.id.record()).await?;152 let deleted: Option<Term> = db.delete(self.id.record()).await?;
134 deleted.ok_or(AppError::NotFound)153 deleted.ok_or(AppError::NotFound)
135 }154 }
src/lib.rsmodified+3 -3
@@ -44,7 +44,7 @@ use crate::state::AppState;
44 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),44 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
45 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`trash`. `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),45 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`trash`. `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
46 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),46 (name = "events", description = "Events with an audience (school-wide, one role, a course's enrollment, or a registration signup list — the expected-attendee roster; every event stays visible to all) and their attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts"),
47- (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list"),47+ (name = "courses", description = "Courses — kind `course` (regular class), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
48 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),48 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
49 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),49 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
50 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),50 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
@@ -52,10 +52,10 @@ use crate::state::AppState;
52 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),52 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
53 (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),53 (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),
54 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),54 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
55- (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"),55+ (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Read: any authenticated user; edit: manager+"),
56 (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, assigned teachers, manager+); edit follows course management rights"),56 (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, assigned teachers, manager+); edit follows course management rights"),
57 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),57 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),
58- (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),58+ (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) — unlink those courses first. Read: any authenticated user; edit: manager+"),
59 ),59 ),
60 )]60 )]
61 struct ApiDoc;61 struct ApiDoc;
src/web/courses.rsmodified+31 -5
@@ -12,7 +12,7 @@ use crate::database::Database;
12 use crate::domain::answer_image::AnswerImage;12 use crate::domain::answer_image::AnswerImage;
13 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};13 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
14 use crate::domain::course_session::{CourseSession, SessionTopic};14 use crate::domain::course_session::{CourseSession, SessionTopic};
15-use crate::domain::enrollment::Enrollment;15+use crate::domain::enrollment::{ENROLL_LOCK, Enrollment};
16 use crate::domain::exam::{16 use crate::domain::exam::{
17 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,17 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
18 ExamTitle,18 ExamTitle,
@@ -23,6 +23,7 @@ use crate::domain::question_image::QuestionImage;
23 use crate::domain::role::Role;23 use crate::domain::role::Role;
24 use crate::domain::settings::Settings;24 use crate::domain::settings::Settings;
25 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};25 use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
26+use crate::domain::term::TERM_LOCK;
26 use crate::domain::timestamp::Timestamp;27 use crate::domain::timestamp::Timestamp;
27 use crate::domain::user::{User, UserId};28 use crate::domain::user::{User, UserId};
28 use crate::error::{AppError, ErrorResponse, ValidationError};29 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -266,6 +267,13 @@ async fn create_course(
266 Some(ref kind) => CourseKind::try_new(kind)?,267 Some(ref kind) => CourseKind::try_new(kind)?,
267 None => CourseKind::course(),268 None => CourseKind::course(),
268 };269 };
270+ // [`TERM_LOCK`] holds the term lookup and the save together, so the link
271+ // can't be written onto a term a concurrent delete just cleared. Only a
272+ // write that actually links a term needs it.
273+ let _term_guard = match req.term_id {
274+ Some(_) => Some(TERM_LOCK.lock().await),
275+ None => None,
276+ };
269 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;277 let term = resolve_term(req.term_id.as_deref(), &st.db).await?;
270 check_capacity(req.capacity)?;278 check_capacity(req.capacity)?;
271 let course = Course::create(279 let course = Course::create(
@@ -429,6 +437,12 @@ async fn update_course(
429 Some(ref kind) => CourseKind::try_new(kind)?,437 Some(ref kind) => CourseKind::try_new(kind)?,
430 None => course.get_kind().clone(),438 None => course.get_kind().clone(),
431 };439 };
440+ // Same [`TERM_LOCK`] window as create — held over the lookup and the save
441+ // whenever this PATCH links a term (clearing or omitting needs no guard).
442+ let _term_guard = match req.term_id {
443+ Some(Some(_)) => Some(TERM_LOCK.lock().await),
444+ _ => None,
445+ };
432 let term = match req.term_id {446 let term = match req.term_id {
433 // Explicit `null` clears the link; a value must name a real term.447 // Explicit `null` clears the link; a value must name a real term.
434 Some(update) => resolve_term(update.as_deref(), &st.db).await?,448 Some(update) => resolve_term(update.as_deref(), &st.db).await?,
@@ -451,10 +465,12 @@ async fn update_course(
451 }465 }
452 466
453 /// Delete a course. Requires teacher+; only its creator or a manager/admin may467 /// Delete a course. Requires teacher+; only its creator or a manager/admin may
454-/// delete it — an assigned teacher runs the course but does not own it. Cascades the course's exams (with468+/// delete it — an assigned teacher runs the course but does not own it.
455-/// their results, questions, answers, and question images), its homework (with469+/// Refused with a 409 while anyone is still enrolled — empty the roster first,
456-/// submissions, submission files, and grades), its sessions and roll call, its470+/// so a course that carries students is never dropped by accident. Once empty,
457-/// subjects, and all enrollments.471+/// it cascades the course's exams (with their results, questions, answers, and
472+/// question images), its homework (with submissions, submission files, and
473+/// grades), its sessions and roll call, and its subjects.
458 #[utoipa::path(474 #[utoipa::path(
459 delete,475 delete,
460 path = "/{id}",476 path = "/{id}",
@@ -466,6 +482,7 @@ async fn update_course(
466 (status = 401, description = "Not authenticated", body = ErrorResponse),482 (status = 401, description = "Not authenticated", body = ErrorResponse),
467 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),483 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
468 (status = 404, description = "Not found", body = ErrorResponse),484 (status = 404, description = "Not found", body = ErrorResponse),
485+ (status = 409, description = "Students are still enrolled in this course", body = ErrorResponse),
469 ),486 ),
470 )]487 )]
471 async fn delete_course(488 async fn delete_course(
@@ -481,6 +498,15 @@ async fn delete_course(
481 "only the course creator or a manager/admin can delete this course",498 "only the course creator or a manager/admin can delete this course",
482 ));499 ));
483 }500 }
501+ // [`ENROLL_LOCK`] holds the roster check and the delete together, so an
502+ // enroll that just passed its capacity check can't land its row on a
503+ // course that vanished mid-flight.
504+ let _guard = ENROLL_LOCK.lock().await;
505+ if Enrollment::any_for_course(course.get_id(), &st.db).await? {
506+ return Err(AppError::Conflict(
507+ "students are still enrolled in this course — remove them first",
508+ ));
509+ }
484 // Rows go first (the delete cascades them), blobs after — a crash in510 // Rows go first (the delete cascades them), blobs after — a crash in
485 // between strands at worst an unreachable blob.511 // between strands at worst an unreachable blob.
486 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;512 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;
src/web/settings.rsmodified+30 -3
@@ -6,10 +6,12 @@ use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8 use crate::constant::SETTINGS_UPDATE_RETRIES;8 use crate::constant::SETTINGS_UPDATE_RETRIES;
9+use crate::domain::exam_result::ExamResult;
9 use crate::domain::settings::{ExamKindDef, GradeBand, Settings};10 use crate::domain::settings::{ExamKindDef, GradeBand, Settings};
10 use crate::error::{AppError, ErrorResponse};11 use crate::error::{AppError, ErrorResponse};
11 use crate::state::AppState;12 use crate::state::AppState;
12 13
14+use super::exams::EXAM_LOCK;
13 use super::{CurrentUser, RequireManager};15 use super::{CurrentUser, RequireManager};
14 16
15 pub fn routes() -> OpenApiRouter<AppState> {17 pub fn routes() -> OpenApiRouter<AppState> {
@@ -133,8 +135,10 @@ async fn get_settings(
133 /// untouched — a removed exam kind or status lives on in old records; only135 /// untouched — a removed exam kind or status lives on in old records; only
134 /// new writes are held to the new lists. Kind weights, though, apply live:136 /// new writes are held to the new lists. Kind weights, though, apply live:
135 /// mark reports read them at request time, so editing a weight re-weights137 /// mark reports read them at request time, so editing a weight re-weights
136-/// every exam of that kind, and an exam whose kind was removed from the list138+/// every exam of that kind. For that reason a kind whose exams already carry
137-/// counts with weight 1 until the kind returns. `max_file_bytes` likewise139+/// marks cannot be dropped from the list (409) — those marks would silently
140+/// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
141+/// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise
138 /// applies at upload time only — already-stored files keep their size.142 /// applies at upload time only — already-stored files keep their size.
139 #[utoipa::path(143 #[utoipa::path(
140 patch,144 patch,
@@ -147,7 +151,7 @@ async fn get_settings(
147 (status = 400, description = "Invalid lists, bands, or file limit", body = ErrorResponse),151 (status = 400, description = "Invalid lists, bands, or file limit", body = ErrorResponse),
148 (status = 401, description = "Not authenticated", body = ErrorResponse),152 (status = 401, description = "Not authenticated", body = ErrorResponse),
149 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),153 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
150- (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse),154+ (status = 409, description = "A removed exam kind still has graded exams, or concurrent edits kept changing the settings mid-save", body = ErrorResponse),
151 ),155 ),
152 )]156 )]
153 async fn update_settings(157 async fn update_settings(
@@ -159,6 +163,13 @@ async fn update_settings(
159 // otherwise a concurrent PATCH of a *different* field would be silently163 // otherwise a concurrent PATCH of a *different* field would be silently
160 // reverted by whichever whole-row write lands second. A refused save164 // reverted by whichever whole-row write lands second. A refused save
161 // reloads and re-merges, so both edits land.165 // reloads and re-merges, so both edits land.
166+ // Writer lease of [`EXAM_LOCK`] while the kind list is being replaced: the
167+ // no-marks check below and the save are one unit, so a grade (a reader)
168+ // can't land the first mark of a kind that is being dropped mid-flight.
169+ let _guard = match req.exam_kinds {
170+ Some(_) => Some(EXAM_LOCK.write().await),
171+ None => None,
172+ };
162 for _ in 0..SETTINGS_UPDATE_RETRIES {173 for _ in 0..SETTINGS_UPDATE_RETRIES {
163 let current = Settings::load(&st.db).await?;174 let current = Settings::load(&st.db).await?;
164 175
@@ -169,6 +180,22 @@ async fn update_settings(
169 .collect::<Result<Vec<_>, _>>()?,180 .collect::<Result<Vec<_>, _>>()?,
170 None => current.get_exam_kinds().to_vec(),181 None => current.get_exam_kinds().to_vec(),
171 };182 };
183+ // A kind that graded exams still count under cannot leave the list —
184+ // weights are read live, so dropping it would silently re-weight every
185+ // mark of that kind. Re-checked on every retry: the snapshot it is
186+ // diffed against is the one the save is conditioned on.
187+ for gone in current.get_exam_kinds().iter().filter(|kind| {
188+ !exam_kinds
189+ .iter()
190+ .any(|new| new.get_name() == kind.get_name())
191+ }) {
192+ if ExamResult::any_for_kind(gone.get_name(), &st.db).await? {
193+ return Err(AppError::ConflictOwned(format!(
194+ "exams of kind '{}' are already graded — the kind cannot be removed",
195+ gone.get_name()
196+ )));
197+ }
198+ }
172 let attendance_statuses = req199 let attendance_statuses = req
173 .attendance_statuses200 .attendance_statuses
174 .clone()201 .clone()
src/web/terms.rsmodified+15 -4
@@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter;
7 use utoipa_axum::routes;7 use utoipa_axum::routes;
8 8
9 use crate::database::Database;9 use crate::database::Database;
10-use crate::domain::term::{Term, TermId, TermName};10+use crate::domain::term::{TERM_LOCK, Term, TermId, TermName};
11 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
12 use crate::error::{AppError, ErrorResponse, ValidationError};12 use crate::error::{AppError, ErrorResponse, ValidationError};
13 use crate::state::AppState;13 use crate::state::AppState;
@@ -209,8 +209,10 @@ async fn update_term(
209 Ok(Json(TermResponse::new(&updated)))209 Ok(Json(TermResponse::new(&updated)))
210 }210 }
211 211
212-/// Delete a term. Requires manager+. Courses linked to it survive — they just212+/// Delete a term. Requires manager+. Refused with a 409 while any course still
213-/// lose the term link.213+/// links to it — unlink those courses (`PATCH /courses/{id}` with
214+/// `"term_id": null`) or delete them first, so a term is never dropped out from
215+/// under the calendar its courses hang on.
214 #[utoipa::path(216 #[utoipa::path(
215 delete,217 delete,
216 path = "/{id}",218 path = "/{id}",
@@ -218,10 +220,11 @@ async fn update_term(
218 security(("session_cookie" = [])),220 security(("session_cookie" = [])),
219 params(("id" = String, Path, description = "Term id")),221 params(("id" = String, Path, description = "Term id")),
220 responses(222 responses(
221- (status = 204, description = "Deleted (courses unlinked)"),223+ (status = 204, description = "Deleted"),
222 (status = 401, description = "Not authenticated", body = ErrorResponse),224 (status = 401, description = "Not authenticated", body = ErrorResponse),
223 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),225 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
224 (status = 404, description = "Not found", body = ErrorResponse),226 (status = 404, description = "Not found", body = ErrorResponse),
227+ (status = 409, description = "Courses are still linked to this term", body = ErrorResponse),
225 ),228 ),
226 )]229 )]
227 async fn delete_term(230 async fn delete_term(
@@ -232,6 +235,14 @@ async fn delete_term(
232 let term = Term::read(&TermId::from_key(&id), &st.db)235 let term = Term::read(&TermId::from_key(&id), &st.db)
233 .await?236 .await?
234 .ok_or(AppError::NotFound)?;237 .ok_or(AppError::NotFound)?;
238+ // [`TERM_LOCK`] holds the link check and the delete together, so a course
239+ // write that just resolved this term can't land its link on a dead row.
240+ let _guard = TERM_LOCK.lock().await;
241+ if Term::any_course(term.get_id(), &st.db).await? {
242+ return Err(AppError::Conflict(
243+ "courses are still linked to this term — unlink them first",
244+ ));
245+ }
235 term.delete(&st.db).await?;246 term.delete(&st.db).await?;
236 Ok(StatusCode::NO_CONTENT)247 Ok(StatusCode::NO_CONTENT)
237 }248 }
tests/common/mod.rsmodified+15 -0
@@ -357,6 +357,21 @@ pub async fn create_session(app: &Router, cookie: &str, course: &str, starts_at:
357 id_of(&res.body)357 id_of(&res.body)
358 }358 }
359 359
360+/// Drop `user_id` from `course`'s roster as `cookie` (asserts 204). Deleting a
361+/// course is refused while anyone is still enrolled, so cascade tests empty the
362+/// roster first.
363+pub async fn unenroll(app: &Router, cookie: &str, course: &str, user_id: &str) {
364+ let res = send(
365+ app,
366+ "DELETE",
367+ &format!("/courses/{course}/enrollments/{user_id}"),
368+ Some(cookie),
369+ None,
370+ )
371+ .await;
372+ assert_eq!(res.status, StatusCode::NO_CONTENT, "unenroll {user_id}");
373+}
374+
360 /// Enroll `user_id` into `course` as `cookie` (asserts 200).375 /// Enroll `user_id` into `course` as `cookie` (asserts 200).
361 pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) {376 pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) {
362 let res = send(377 let res = send(
tests/integration.rsmodified+173 -22
@@ -7,7 +7,7 @@ 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_homework, create_session,9 app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session,
10- create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role,10+ create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll,
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;
@@ -3127,6 +3127,8 @@ async fn kind_weight_edits_reweight_reports_live() {
3127 enroll(&app, &teacher, &course, &alice_id).await;3127 enroll(&app, &teacher, &course, &alice_id).await;
3128 let quiz = create_exam(&app, &teacher, &course, "q", "quiz").await;3128 let quiz = create_exam(&app, &teacher, &course, "q", "quiz").await;
3129 let oral = create_exam(&app, &teacher, &course, "o", "oral").await;3129 let oral = create_exam(&app, &teacher, &course, "o", "oral").await;
3130+ // Ungraded for now — its kind gets retired below, out from under it.
3131+ let project = create_exam(&app, &teacher, &course, "p", "project").await;
3130 for (exam, mark) in [(&quiz, 40), (&oral, 80)] {3132 for (exam, mark) in [(&quiz, 40), (&oral, 80)] {
3131 let res = send(3133 let res = send(
3132 &app,3134 &app,
@@ -3160,26 +3162,30 @@ async fn kind_weight_edits_reweight_reports_live() {
3160 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;3162 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
3161 assert_eq!(report.body["courses"][0]["average"], 70.0);3163 assert_eq!(report.body["courses"][0]["average"], 70.0);
3162 3164
3163- // Retire the oral kind altogether: its exam keeps counting, weight 1.3165+ // The PATCH above also retired `project` (allowed — no marks of that kind
3166+ // existed yet; a graded kind can't leave at all, see
3167+ // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on and
3168+ // counts with weight 1.
3164 let res = send(3169 let res = send(
3165 &app,3170 &app,
3166- "PATCH",3171+ "POST",
3167- "/settings",3172+ &format!("/exams/{project}/results"),
3168- Some(&manager),3173+ Some(&teacher),
3169- Some(json!({ "exam_kinds": [{"name": "quiz", "weight": 1}] })),3174+ Some(json!({ "mark": 60, "user_id": alice_id })),
3170 )3175 )
3171 .await;3176 .await;
3172 assert_eq!(res.status, StatusCode::OK);3177 assert_eq!(res.status, StatusCode::OK);
3178+ // (40 + 240 + 60) / 5 = 68.
3173 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;3179 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
3174- assert_eq!(report.body["courses"][0]["average"], 60.0);3180+ assert_eq!(report.body["courses"][0]["average"], 68.0);
3175- let oral_entry = report.body["courses"][0]["results"]3181+ let project_entry = report.body["courses"][0]["results"]
3176 .as_array()3182 .as_array()
3177 .unwrap()3183 .unwrap()
3178 .iter()3184 .iter()
3179- .find(|entry| entry["kind"] == "oral")3185+ .find(|entry| entry["kind"] == "project")
3180 .unwrap()3186 .unwrap()
3181 .clone();3187 .clone();
3182- assert_eq!(oral_entry["weight"], 1);3188+ assert_eq!(project_entry["weight"], 1);
3183 }3189 }
3184 3190
3185 #[tokio::test]3191 #[tokio::test]
@@ -3345,6 +3351,7 @@ async fn deleting_course_cascades_enrollments_exams_and_results() {
3345 )3351 )
3346 .await;3352 .await;
3347 3353
3354+ unenroll(&app, &teacher, &course_id, &alice_id).await;
3348 assert_eq!(3355 assert_eq!(
3349 send(3356 send(
3350 &app,3357 &app,
@@ -6561,6 +6568,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() {
6561 )6568 )
6562 .await;6569 .await;
6563 assert_eq!(res.status, StatusCode::CREATED);6570 assert_eq!(res.status, StatusCode::CREATED);
6571+ unenroll(&app, &teacher, &course, &student_id).await;
6564 let res = send(6572 let res = send(
6565 &app,6573 &app,
6566 "DELETE",6574 "DELETE",
@@ -8429,6 +8437,7 @@ async fn questions_and_answers_cascade_with_deletes() {
8429 .await;8437 .await;
8430 assert_eq!(res.status, StatusCode::OK);8438 assert_eq!(res.status, StatusCode::OK);
8431 8439
8440+ unenroll(&app, &teacher, &course, &student_id).await;
8432 let res = send(8441 let res = send(
8433 &app,8442 &app,
8434 "DELETE",8443 "DELETE",
@@ -9235,6 +9244,7 @@ async fn deleting_session_or_course_cascades_roll_call() {
9235 assert_eq!(report.body["sessions"]["total"], 1);9244 assert_eq!(report.body["sessions"]["total"], 1);
9236 9245
9237 // ...and deleting the course removes the rest, sessions included.9246 // ...and deleting the course removes the rest, sessions included.
9247+ unenroll(&app, &owner, &course, &ali_id).await;
9238 let res = send(9248 let res = send(
9239 &app,9249 &app,
9240 "DELETE",9250 "DELETE",
@@ -10286,7 +10296,26 @@ async fn terms_crud_gates_and_links_to_courses() {
10286 .await;10296 .await;
10287 assert_eq!(res.body["term"].as_str(), Some(term.as_str()));10297 assert_eq!(res.body["term"].as_str(), Some(term.as_str()));
10288 10298
10289- // Deleting the term unlinks its courses but never deletes them.10299+ // A term a course still points at cannot be deleted; unlinking the course
10300+ // clears the way, and the course itself survives untouched.
10301+ let res = send(
10302+ &app,
10303+ "DELETE",
10304+ &format!("/terms/{term}"),
10305+ Some(&manager),
10306+ None,
10307+ )
10308+ .await;
10309+ assert_eq!(res.status, StatusCode::CONFLICT);
10310+ let res = send(
10311+ &app,
10312+ "PATCH",
10313+ &format!("/courses/{course}"),
10314+ Some(&teacher),
10315+ Some(json!({ "term_id": null })),
10316+ )
10317+ .await;
10318+ assert_eq!(res.status, StatusCode::OK);
10290 let res = send(10319 let res = send(
10291 &app,10320 &app,
10292 "DELETE",10321 "DELETE",
@@ -10372,7 +10401,7 @@ async fn roll_call_accepts_school_statuses_and_buckets_session_reports() {
10372 }10401 }
10373 10402
10374 #[tokio::test]10403 #[tokio::test]
10375-async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() {10404+async fn terms_list_newest_first_require_auth_and_guard_delete_per_term() {
10376 let (app, db) = app_and_db().await;10405 let (app, db) = app_and_db().await;
10377 let manager = login_as(&app, &db, "bulk.manager", "manager").await;10406 let manager = login_as(&app, &db, "bulk.manager", "manager").await;
10378 let teacher = login_as(&app, &db, "bulk.teacher", "teacher").await;10407 let teacher = login_as(&app, &db, "bulk.teacher", "teacher").await;
@@ -10407,8 +10436,8 @@ async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() {
10407 .collect();10436 .collect();
10408 assert_eq!(names, ["2026 Spring", "2025 Fall"]);10437 assert_eq!(names, ["2026 Spring", "2025 Fall"]);
10409 10438
10410- // Deleting a term unlinks EVERY linked course in one stroke, and leaves10439+ // The delete guard counts EVERY linked course — unlinking one of two is
10411- // courses on other terms alone.10440+ // not enough — and it is per term: a course on another term never blocks.
10412 let mut linked = Vec::new();10441 let mut linked = Vec::new();
10413 for title in ["Algebra", "Geometry"] {10442 for title in ["Algebra", "Geometry"] {
10414 let res = send(10443 let res = send(
@@ -10440,22 +10469,33 @@ async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() {
10440 None,10469 None,
10441 )10470 )
10442 .await;10471 .await;
10443- assert_eq!(res.status, StatusCode::NO_CONTENT);10472+ assert_eq!(res.status, StatusCode::CONFLICT);
10444 10473
10445- for course in &linked {10474+ for (i, course) in linked.iter().enumerate() {
10446 let res = send(10475 let res = send(
10447 &app,10476 &app,
10448- "GET",10477+ "PATCH",
10449 &format!("/courses/{course}"),10478 &format!("/courses/{course}"),
10450 Some(&teacher),10479 Some(&teacher),
10480+ Some(json!({ "term_id": null })),
10481+ )
10482+ .await;
10483+ assert_eq!(res.status, StatusCode::OK);
10484+ // Still blocked until the LAST linked course lets go.
10485+ let res = send(
10486+ &app,
10487+ "DELETE",
10488+ &format!("/terms/{newer}"),
10489+ Some(&manager),
10451 None,10490 None,
10452 )10491 )
10453 .await;10492 .await;
10454- assert_eq!(10493+ let expected = if i + 1 == linked.len() {
10455- res.body["term"],10494+ StatusCode::NO_CONTENT
10456- serde_json::Value::Null,10495+ } else {
10457- "unlinked {course}"10496+ StatusCode::CONFLICT
10458- );10497+ };
10498+ assert_eq!(res.status, expected, "after unlinking {course}");
10459 }10499 }
10460 let res = send(10500 let res = send(
10461 &app,10501 &app,
@@ -14084,6 +14124,8 @@ async fn homework_gc_removes_rows_and_blobs() {
14084 assert_eq!(res.status, StatusCode::OK, "{}", res.body);14124 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
14085 let keys = homework_blob_keys(&db).await;14125 let keys = homework_blob_keys(&db).await;
14086 assert_eq!(keys.len(), 1);14126 assert_eq!(keys.len(), 1);
14127+ unenroll(&app, &w.teacher, &w.course, &w.ali_id).await;
14128+ unenroll(&app, &w.teacher, &w.course, &w.veli_id).await;
14087 let res = send(14129 let res = send(
14088 &app,14130 &app,
14089 "DELETE",14131 "DELETE",
@@ -14275,3 +14317,112 @@ async fn homework_lists_paginate() {
14275 assert_eq!(res.body["offset"], 2);14317 assert_eq!(res.body["offset"], 2);
14276 }14318 }
14277 }14319 }
14320+
14321+/// A course carrying students can't be deleted (409) until the roster is
14322+/// emptied — the cascade would otherwise take the enrollments with it.
14323+#[tokio::test]
14324+async fn course_delete_blocks_while_students_are_enrolled() {
14325+ let (app, db) = app_and_db().await;
14326+ let teacher = login_as(&app, &db, "cdb_t", "teacher").await;
14327+ let student = login(&app, "cdb_s").await;
14328+ let student_id = me_id(&app, &student).await;
14329+ let course = create_course(&app, &teacher, "Chemistry").await;
14330+ enroll(&app, &teacher, &course, &student_id).await;
14331+
14332+ let res = send(
14333+ &app,
14334+ "DELETE",
14335+ &format!("/courses/{course}"),
14336+ Some(&teacher),
14337+ None,
14338+ )
14339+ .await;
14340+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
14341+ let res = send(
14342+ &app,
14343+ "GET",
14344+ &format!("/courses/{course}"),
14345+ Some(&teacher),
14346+ None,
14347+ )
14348+ .await;
14349+ assert_eq!(res.status, StatusCode::OK);
14350+
14351+ // Empty the roster: the delete goes through.
14352+ let res = send(
14353+ &app,
14354+ "DELETE",
14355+ &format!("/courses/{course}/enrollments/{student_id}"),
14356+ Some(&teacher),
14357+ None,
14358+ )
14359+ .await;
14360+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
14361+ let res = send(
14362+ &app,
14363+ "DELETE",
14364+ &format!("/courses/{course}"),
14365+ Some(&teacher),
14366+ None,
14367+ )
14368+ .await;
14369+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
14370+}
14371+
14372+/// An exam kind whose exams already carry marks can't leave the settings list
14373+/// (409) — weights are read live, so those marks would silently re-weight.
14374+/// Ungraded kinds still leave freely.
14375+#[tokio::test]
14376+async fn exam_kind_removal_blocks_while_marks_exist() {
14377+ let (app, db) = app_and_db().await;
14378+ let teacher = login_as(&app, &db, "ekd_t", "teacher").await;
14379+ let manager = login_as(&app, &db, "ekd_m", "manager").await;
14380+ let student = login(&app, "ekd_s").await;
14381+ let student_id = me_id(&app, &student).await;
14382+
14383+ let course = create_course(&app, &teacher, "Biology").await;
14384+ enroll(&app, &teacher, &course, &student_id).await;
14385+ let exam = create_exam(&app, &teacher, &course, "Final", "final").await;
14386+ let res = send(
14387+ &app,
14388+ "POST",
14389+ &format!("/exams/{exam}/results"),
14390+ Some(&teacher),
14391+ Some(json!({ "user_id": student_id, "mark": 70 })),
14392+ )
14393+ .await;
14394+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
14395+
14396+ // Dropping the graded kind is refused; the list is untouched.
14397+ let res = send(
14398+ &app,
14399+ "PATCH",
14400+ "/settings",
14401+ Some(&manager),
14402+ Some(json!({ "exam_kinds": [{ "name": "quiz", "weight": 1 }] })),
14403+ )
14404+ .await;
14405+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
14406+ let res = send(&app, "GET", "/settings", Some(&manager), None).await;
14407+ let kinds: Vec<String> = res.body["exam_kinds"]
14408+ .as_array()
14409+ .unwrap()
14410+ .iter()
14411+ .map(|kind| kind["name"].as_str().unwrap().to_string())
14412+ .collect();
14413+ assert!(kinds.contains(&"final".to_string()), "{}", res.body);
14414+ assert!(kinds.contains(&"quiz".to_string()), "{}", res.body);
14415+
14416+ // Keeping the graded kind, dropping the ungraded ones, is fine.
14417+ let res = send(
14418+ &app,
14419+ "PATCH",
14420+ "/settings",
14421+ Some(&manager),
14422+ Some(json!({ "exam_kinds": [{ "name": "final", "weight": 5 }] })),
14423+ )
14424+ .await;
14425+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
14426+ assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 1);
14427+ assert_eq!(res.body["exam_kinds"][0]["weight"], 5);
14428+}