diff --git a/README.md b/README.md index d6660e8..b83d17f 100644 --- a/README.md +++ b/README.md @@ -435,7 +435,7 @@ 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, assigned teacher, or manager+) | | PATCH | `/courses/{id}` | teacher | Edit course incl. `kind` and `capacity` (`null` lifts the cap) (course manager) | -| 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) | +| 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) | | POST | `/courses/{id}/teachers` | manager | `{user_id}` — assign a **teacher+** to run the course (idempotent; returns the course) | | DELETE | `/courses/{id}/teachers/{user}` | manager | Unassign a teacher (`404` if they weren't assigned) | | 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 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher* | A user's attendance report, narrowed to the caller's courses (manager+: full); *or a `parent` linked to `{user}` — full | | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` | -| PATCH | `/settings` | manager | Replace any subset of the fields (lists wholesale); concurrent edits merge, never silently revert each other (see "Per-school policy") | +| 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") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first · paged | | GET | `/terms/{id}` | student | Get one term | | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) | -| DELETE | `/terms/{id}` | manager | Delete a term — linked courses are unlinked, never deleted | +| DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it | `status` must be one of the school's attendance statuses (`GET /settings`); 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* 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, all enrollments, and its subjects. +report until re-enrollment, but stay visible on the exam itself. A course +with anyone still on its roster refuses deletion (`409`) — empty the roster +first; once empty, deleting it cascades its exams, their results, its +sessions and roll call, 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 @@ -702,8 +704,10 @@ editable `settings` singleton (`GET /settings` for any signed-in user, final, project, oral`, all weighing `1` (a plain average); replace the list with whatever the school grades and weighs (`{"name": "final", "weight": 3}`, …). Reports resolve weights live: editing a weight - re-weights every exam of that kind at once, and an exam keeping a - since-removed kind counts with weight `1`. + re-weights every exam of that kind at once. For the same reason a kind + whose exams already carry marks cannot be removed from the list (`409`): + those marks would silently re-weight. An unmarked kind leaves freely, and + an exam keeping a since-removed kind counts with weight `1`. - **`attendance_statuses`** — what attendance marking accepts. The core four (`present`, `absent`, `late`, `excused`) are mandatory because the attendance rate is defined over them (`(present+late) / @@ -731,7 +735,9 @@ retired status — only **new writes** are held to the current lists. Academic structure is data too. **Terms** (`/terms`) model whatever calendar the school runs — semester, trimester, quarter systems are just rows with a name and a date range. Courses may link to one via `term_id` (nullable), and -deleting a term only unlinks its courses. Term dates may lie in the past, +deleting a term is refused with a `409` while any course still links to it — +unlink those courses (`PATCH /courses/{id}` with `"term_id": null`) or delete +them first, so the calendar never disappears under them. Term dates may lie in the past, deliberately: a school adopting the app mid-year backfills its calendar — unlike exam/lesson/event times, which reject backdating. diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index e749534..e6dee35 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -9,7 +9,9 @@ use crate::error::AppError; /// Serializes enrolls so the capacity check (count, then write) can't /// over-admit under concurrency — the database's optimistic transactions /// don't serialize cross-record counts against concurrent inserts. -static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); +/// It also serializes the roster check of a course delete against a concurrent +/// enroll, so a student can't join a course that is already on its way out. +pub(crate) static ENROLL_LOCK: Mutex<()> = Mutex::const_new(()); #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct EnrollmentId(RecordId); @@ -121,6 +123,16 @@ impl Enrollment { Ok(result.take::>(0)?.into_iter().next()) } + /// True iff anyone is still on the course's roster — the delete guard. + pub async fn any_for_course(course: &CourseId, db: &Database) -> Result { + let mut result = db + .query("SELECT VALUE id FROM enrollment WHERE course = $course LIMIT 1") + .bind(("course", course.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + pub async fn list_for_course( course: &CourseId, db: &Database, diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index f47b4a3..fb81bc7 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -145,6 +145,22 @@ impl ExamResult { Ok(result.take::>(0)?) } + /// True iff any exam of `kind` has produced a mark — the settings guard + /// against removing an exam kind that grades already depend on (weights are + /// read live from settings, so dropping the kind would silently re-weight + /// those marks). + pub async fn any_for_kind(kind: &str, db: &Database) -> Result { + let mut result = db + .query( + "SELECT VALUE id FROM exam_result + WHERE exam IN (SELECT VALUE id FROM exam WHERE kind = $kind) LIMIT 1", + ) + .bind(("kind", kind.to_string())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { let mut result = db .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") diff --git a/src/domain/term.rs b/src/domain/term.rs index ce4ccb8..102035d 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -7,6 +7,7 @@ //! rule that guards exams/lessons/events deliberately does not apply here. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; use ulid::Ulid; use crate::constant::MAX_TERM_NAME_LEN; @@ -15,6 +16,17 @@ use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ValidationError}; use crate::validate::validate_required; +/// Serializes the term delete guard (does any course still link it?) against +/// the course writes that assign a term, so a course can't land on a term that +/// is already on its way out. Course writes take it only when they actually +/// link a term. +/// +/// Lock order: no path ever holds this and `ENROLL_LOCK` at the same time — the +/// course writes that take this one touch no roster, and the course delete that +/// takes `ENROLL_LOCK` touches no term — so the two cannot deadlock. Should a +/// future path need both, take `ENROLL_LOCK` first. +pub(crate) static TERM_LOCK: Mutex<()> = Mutex::const_new(()); + #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct TermId(RecordId); @@ -123,13 +135,20 @@ impl Term { updated.ok_or(AppError::NotFound) } - /// Delete the term. Courses keep existing — they just lose the link, so - /// deleting a term can never take a course (or its marks) with it. - pub async fn delete(self, db: &Database) -> Result { - db.query("UPDATE course SET term = NONE WHERE term = $term") - .bind(("term", self.id.record())) + /// True iff any course still links to this term — the delete guard. + pub async fn any_course(id: &TermId, db: &Database) -> Result { + let mut result = db + .query("SELECT VALUE id FROM course WHERE term = $term LIMIT 1") + .bind(("term", id.record())) .await? .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + + /// Delete the term. Callers must refuse while [`Term::any_course`] holds — + /// nothing here unlinks or cascades, so a term is only ever dropped once no + /// course points at it. + pub async fn delete(self, db: &Database) -> Result { let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/lib.rs b/src/lib.rs index c47a881..3432a45 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,7 +44,7 @@ use crate::state::AppState; (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`)"), (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"), (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"), - (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"), + (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"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), @@ -52,10 +52,10 @@ use crate::state::AppState; (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (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+"), + (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+"), (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"), (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"), - (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), + (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+"), ), )] struct ApiDoc; diff --git a/src/web/courses.rs b/src/web/courses.rs index 88a6195..e06d29c 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -12,7 +12,7 @@ use crate::database::Database; use crate::domain::answer_image::AnswerImage; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; use crate::domain::course_session::{CourseSession, SessionTopic}; -use crate::domain::enrollment::Enrollment; +use crate::domain::enrollment::{ENROLL_LOCK, Enrollment}; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, @@ -23,6 +23,7 @@ use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; +use crate::domain::term::TERM_LOCK; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -266,6 +267,13 @@ async fn create_course( Some(ref kind) => CourseKind::try_new(kind)?, None => CourseKind::course(), }; + // [`TERM_LOCK`] holds the term lookup and the save together, so the link + // can't be written onto a term a concurrent delete just cleared. Only a + // write that actually links a term needs it. + let _term_guard = match req.term_id { + Some(_) => Some(TERM_LOCK.lock().await), + None => None, + }; let term = resolve_term(req.term_id.as_deref(), &st.db).await?; check_capacity(req.capacity)?; let course = Course::create( @@ -429,6 +437,12 @@ async fn update_course( Some(ref kind) => CourseKind::try_new(kind)?, None => course.get_kind().clone(), }; + // Same [`TERM_LOCK`] window as create — held over the lookup and the save + // whenever this PATCH links a term (clearing or omitting needs no guard). + let _term_guard = match req.term_id { + Some(Some(_)) => Some(TERM_LOCK.lock().await), + _ => None, + }; let term = match req.term_id { // Explicit `null` clears the link; a value must name a real term. Some(update) => resolve_term(update.as_deref(), &st.db).await?, @@ -451,10 +465,12 @@ async fn update_course( } /// Delete a course. Requires teacher+; only its creator or a manager/admin may -/// delete it — an assigned teacher runs the course but does not own it. Cascades the course's exams (with -/// their results, questions, answers, and question images), its homework (with -/// submissions, submission files, and grades), its sessions and roll call, its -/// subjects, and all enrollments. +/// delete it — an assigned teacher runs the course but does not own it. +/// Refused with a 409 while anyone is still enrolled — empty the roster first, +/// so a course that carries students is never dropped by accident. Once empty, +/// it cascades the course's exams (with their results, questions, answers, and +/// question images), its homework (with submissions, submission files, and +/// grades), its sessions and roll call, and its subjects. #[utoipa::path( delete, path = "/{id}", @@ -466,6 +482,7 @@ async fn update_course( (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 = "Students are still enrolled in this course", body = ErrorResponse), ), )] async fn delete_course( @@ -481,6 +498,15 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } + // [`ENROLL_LOCK`] holds the roster check and the delete together, so an + // enroll that just passed its capacity check can't land its row on a + // course that vanished mid-flight. + let _guard = ENROLL_LOCK.lock().await; + if Enrollment::any_for_course(course.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "students are still enrolled in this course — remove them first", + )); + } // Rows go first (the delete cascades them), blobs after — a crash in // between strands at worst an unreachable blob. let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?; diff --git a/src/web/settings.rs b/src/web/settings.rs index b79a05d..e27f2b9 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -6,10 +6,12 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::SETTINGS_UPDATE_RETRIES; +use crate::domain::exam_result::ExamResult; use crate::domain::settings::{ExamKindDef, GradeBand, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; +use super::exams::EXAM_LOCK; use super::{CurrentUser, RequireManager}; pub fn routes() -> OpenApiRouter { @@ -133,8 +135,10 @@ async fn get_settings( /// untouched — a removed exam kind or status lives on in old records; only /// new writes are held to the new lists. Kind weights, though, apply live: /// mark reports read them at request time, so editing a weight re-weights -/// every exam of that kind, and an exam whose kind was removed from the list -/// counts with weight 1 until the kind returns. `max_file_bytes` likewise +/// every exam of that kind. For that reason a kind whose exams already carry +/// marks cannot be dropped from the list (409) — those marks would silently +/// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is +/// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise /// applies at upload time only — already-stored files keep their size. #[utoipa::path( patch, @@ -147,7 +151,7 @@ async fn get_settings( (status = 400, description = "Invalid lists, bands, or file limit", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), - (status = 409, description = "Concurrent edits kept changing the settings mid-save", body = ErrorResponse), + (status = 409, description = "A removed exam kind still has graded exams, or concurrent edits kept changing the settings mid-save", body = ErrorResponse), ), )] async fn update_settings( @@ -159,6 +163,13 @@ async fn update_settings( // otherwise a concurrent PATCH of a *different* field would be silently // reverted by whichever whole-row write lands second. A refused save // reloads and re-merges, so both edits land. + // Writer lease of [`EXAM_LOCK`] while the kind list is being replaced: the + // no-marks check below and the save are one unit, so a grade (a reader) + // can't land the first mark of a kind that is being dropped mid-flight. + let _guard = match req.exam_kinds { + Some(_) => Some(EXAM_LOCK.write().await), + None => None, + }; for _ in 0..SETTINGS_UPDATE_RETRIES { let current = Settings::load(&st.db).await?; @@ -169,6 +180,22 @@ async fn update_settings( .collect::, _>>()?, None => current.get_exam_kinds().to_vec(), }; + // A kind that graded exams still count under cannot leave the list — + // weights are read live, so dropping it would silently re-weight every + // mark of that kind. Re-checked on every retry: the snapshot it is + // diffed against is the one the save is conditioned on. + for gone in current.get_exam_kinds().iter().filter(|kind| { + !exam_kinds + .iter() + .any(|new| new.get_name() == kind.get_name()) + }) { + if ExamResult::any_for_kind(gone.get_name(), &st.db).await? { + return Err(AppError::ConflictOwned(format!( + "exams of kind '{}' are already graded — the kind cannot be removed", + gone.get_name() + ))); + } + } let attendance_statuses = req .attendance_statuses .clone() diff --git a/src/web/terms.rs b/src/web/terms.rs index 238e2af..aa9e931 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::term::{Term, TermId, TermName}; +use crate::domain::term::{TERM_LOCK, Term, TermId, TermName}; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; @@ -209,8 +209,10 @@ async fn update_term( Ok(Json(TermResponse::new(&updated))) } -/// Delete a term. Requires manager+. Courses linked to it survive — they just -/// lose the term link. +/// Delete a term. Requires manager+. Refused with a 409 while any course still +/// links to it — unlink those courses (`PATCH /courses/{id}` with +/// `"term_id": null`) or delete them first, so a term is never dropped out from +/// under the calendar its courses hang on. #[utoipa::path( delete, path = "/{id}", @@ -218,10 +220,11 @@ async fn update_term( security(("session_cookie" = [])), params(("id" = String, Path, description = "Term id")), responses( - (status = 204, description = "Deleted (courses unlinked)"), + (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "Courses are still linked to this term", body = ErrorResponse), ), )] async fn delete_term( @@ -232,6 +235,14 @@ async fn delete_term( let term = Term::read(&TermId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + // [`TERM_LOCK`] holds the link check and the delete together, so a course + // write that just resolved this term can't land its link on a dead row. + let _guard = TERM_LOCK.lock().await; + if Term::any_course(term.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "courses are still linked to this term — unlink them first", + )); + } term.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 4d13208..6637471 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -357,6 +357,21 @@ pub async fn create_session(app: &Router, cookie: &str, course: &str, starts_at: id_of(&res.body) } +/// Drop `user_id` from `course`'s roster as `cookie` (asserts 204). Deleting a +/// course is refused while anyone is still enrolled, so cascade tests empty the +/// roster first. +pub async fn unenroll(app: &Router, cookie: &str, course: &str, user_id: &str) { + let res = send( + app, + "DELETE", + &format!("/courses/{course}/enrollments/{user_id}"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "unenroll {user_id}"); +} + /// Enroll `user_id` into `course` as `cookie` (asserts 200). pub async fn enroll(app: &Router, cookie: &str, course: &str, user_id: &str) { let res = send( diff --git a/tests/integration.rs b/tests/integration.rs index 61fd381..81fdc64 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -7,7 +7,7 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use common::{ app_and_db, create_course, create_exam, create_exam_with, create_homework, create_session, - create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, + create_subject, enroll, id_of, login, login_as, me_id, mem_app, send, set_role, unenroll, }; use hezarfen_backend::domain::exam::ExamId; use hezarfen_backend::domain::exam_attempt::ExamAttempt; @@ -3127,6 +3127,8 @@ async fn kind_weight_edits_reweight_reports_live() { enroll(&app, &teacher, &course, &alice_id).await; let quiz = create_exam(&app, &teacher, &course, "q", "quiz").await; let oral = create_exam(&app, &teacher, &course, "o", "oral").await; + // Ungraded for now — its kind gets retired below, out from under it. + let project = create_exam(&app, &teacher, &course, "p", "project").await; for (exam, mark) in [(&quiz, 40), (&oral, 80)] { let res = send( &app, @@ -3160,26 +3162,30 @@ async fn kind_weight_edits_reweight_reports_live() { let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; assert_eq!(report.body["courses"][0]["average"], 70.0); - // Retire the oral kind altogether: its exam keeps counting, weight 1. + // The PATCH above also retired `project` (allowed — no marks of that kind + // existed yet; a graded kind can't leave at all, see + // `exam_kind_removal_blocks_while_marks_exist`). Its exam lives on and + // counts with weight 1. let res = send( &app, - "PATCH", - "/settings", - Some(&manager), - Some(json!({ "exam_kinds": [{"name": "quiz", "weight": 1}] })), + "POST", + &format!("/exams/{project}/results"), + Some(&teacher), + Some(json!({ "mark": 60, "user_id": alice_id })), ) .await; assert_eq!(res.status, StatusCode::OK); + // (40 + 240 + 60) / 5 = 68. let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; - assert_eq!(report.body["courses"][0]["average"], 60.0); - let oral_entry = report.body["courses"][0]["results"] + assert_eq!(report.body["courses"][0]["average"], 68.0); + let project_entry = report.body["courses"][0]["results"] .as_array() .unwrap() .iter() - .find(|entry| entry["kind"] == "oral") + .find(|entry| entry["kind"] == "project") .unwrap() .clone(); - assert_eq!(oral_entry["weight"], 1); + assert_eq!(project_entry["weight"], 1); } #[tokio::test] @@ -3345,6 +3351,7 @@ async fn deleting_course_cascades_enrollments_exams_and_results() { ) .await; + unenroll(&app, &teacher, &course_id, &alice_id).await; assert_eq!( send( &app, @@ -6561,6 +6568,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() { ) .await; assert_eq!(res.status, StatusCode::CREATED); + unenroll(&app, &teacher, &course, &student_id).await; let res = send( &app, "DELETE", @@ -8429,6 +8437,7 @@ async fn questions_and_answers_cascade_with_deletes() { .await; assert_eq!(res.status, StatusCode::OK); + unenroll(&app, &teacher, &course, &student_id).await; let res = send( &app, "DELETE", @@ -9235,6 +9244,7 @@ async fn deleting_session_or_course_cascades_roll_call() { assert_eq!(report.body["sessions"]["total"], 1); // ...and deleting the course removes the rest, sessions included. + unenroll(&app, &owner, &course, &ali_id).await; let res = send( &app, "DELETE", @@ -10286,7 +10296,26 @@ async fn terms_crud_gates_and_links_to_courses() { .await; assert_eq!(res.body["term"].as_str(), Some(term.as_str())); - // Deleting the term unlinks its courses but never deletes them. + // A term a course still points at cannot be deleted; unlinking the course + // clears the way, and the course itself survives untouched. + let res = send( + &app, + "DELETE", + &format!("/terms/{term}"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + let res = send( + &app, + "PATCH", + &format!("/courses/{course}"), + Some(&teacher), + Some(json!({ "term_id": null })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); let res = send( &app, "DELETE", @@ -10372,7 +10401,7 @@ async fn roll_call_accepts_school_statuses_and_buckets_session_reports() { } #[tokio::test] -async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() { +async fn terms_list_newest_first_require_auth_and_guard_delete_per_term() { let (app, db) = app_and_db().await; let manager = login_as(&app, &db, "bulk.manager", "manager").await; 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() { .collect(); assert_eq!(names, ["2026 Spring", "2025 Fall"]); - // Deleting a term unlinks EVERY linked course in one stroke, and leaves - // courses on other terms alone. + // The delete guard counts EVERY linked course — unlinking one of two is + // not enough — and it is per term: a course on another term never blocks. let mut linked = Vec::new(); for title in ["Algebra", "Geometry"] { let res = send( @@ -10440,22 +10469,33 @@ async fn terms_list_newest_first_require_auth_and_unlink_in_bulk() { None, ) .await; - assert_eq!(res.status, StatusCode::NO_CONTENT); + assert_eq!(res.status, StatusCode::CONFLICT); - for course in &linked { + for (i, course) in linked.iter().enumerate() { let res = send( &app, - "GET", + "PATCH", &format!("/courses/{course}"), Some(&teacher), + Some(json!({ "term_id": null })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + // Still blocked until the LAST linked course lets go. + let res = send( + &app, + "DELETE", + &format!("/terms/{newer}"), + Some(&manager), None, ) .await; - assert_eq!( - res.body["term"], - serde_json::Value::Null, - "unlinked {course}" - ); + let expected = if i + 1 == linked.len() { + StatusCode::NO_CONTENT + } else { + StatusCode::CONFLICT + }; + assert_eq!(res.status, expected, "after unlinking {course}"); } let res = send( &app, @@ -14084,6 +14124,8 @@ async fn homework_gc_removes_rows_and_blobs() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); let keys = homework_blob_keys(&db).await; assert_eq!(keys.len(), 1); + unenroll(&app, &w.teacher, &w.course, &w.ali_id).await; + unenroll(&app, &w.teacher, &w.course, &w.veli_id).await; let res = send( &app, "DELETE", @@ -14275,3 +14317,112 @@ async fn homework_lists_paginate() { assert_eq!(res.body["offset"], 2); } } + +/// A course carrying students can't be deleted (409) until the roster is +/// emptied — the cascade would otherwise take the enrollments with it. +#[tokio::test] +async fn course_delete_blocks_while_students_are_enrolled() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "cdb_t", "teacher").await; + let student = login(&app, "cdb_s").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Chemistry").await; + enroll(&app, &teacher, &course, &student_id).await; + + let res = send( + &app, + "DELETE", + &format!("/courses/{course}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/courses/{course}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + + // Empty the roster: the delete goes through. + let res = send( + &app, + "DELETE", + &format!("/courses/{course}/enrollments/{student_id}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/courses/{course}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +} + +/// An exam kind whose exams already carry marks can't leave the settings list +/// (409) — weights are read live, so those marks would silently re-weight. +/// Ungraded kinds still leave freely. +#[tokio::test] +async fn exam_kind_removal_blocks_while_marks_exist() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "ekd_t", "teacher").await; + let manager = login_as(&app, &db, "ekd_m", "manager").await; + let student = login(&app, "ekd_s").await; + let student_id = me_id(&app, &student).await; + + let course = create_course(&app, &teacher, "Biology").await; + enroll(&app, &teacher, &course, &student_id).await; + let exam = create_exam(&app, &teacher, &course, "Final", "final").await; + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "user_id": student_id, "mark": 70 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Dropping the graded kind is refused; the list is untouched. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [{ "name": "quiz", "weight": 1 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let res = send(&app, "GET", "/settings", Some(&manager), None).await; + let kinds: Vec = res.body["exam_kinds"] + .as_array() + .unwrap() + .iter() + .map(|kind| kind["name"].as_str().unwrap().to_string()) + .collect(); + assert!(kinds.contains(&"final".to_string()), "{}", res.body); + assert!(kinds.contains(&"quiz".to_string()), "{}", res.body); + + // Keeping the graded kind, dropping the ungraded ones, is fine. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [{ "name": "final", "weight": 5 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 1); + assert_eq!(res.body["exam_kinds"][0]["weight"], 5); +}