From 4715b083462d9b41237efb8a598ab722330e9bb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 1 Aug 2026 21:29:49 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8F=AB=20add=20class=20groups=20a?= =?UTF-8?q?nd=20enrollment=20provenance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +- src/domain/class_group.rs | 493 ++++++++++++++++++++++++++++++++++++++ src/domain/course.rs | 13 +- src/domain/enrollment.rs | 85 +++++++ src/domain/mod.rs | 1 + src/domain/term.rs | 15 +- 6 files changed, 604 insertions(+), 8 deletions(-) create mode 100644 src/domain/class_group.rs diff --git a/README.md b/README.md index 688a028..91d76a8 100644 --- a/README.md +++ b/README.md @@ -2764,7 +2764,10 @@ src/ course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson) session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user) work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction) - enrollment.rs EnrollmentId · Enrollment (one row per course+user) + enrollment.rs EnrollmentId · Enrollment (one row per course+user; `source` + names the class that pumped it, absent when hand-placed) + class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube; + deletable only with no members and no attached courses) exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight · ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course) exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts) diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs new file mode 100644 index 0000000..0277c69 --- /dev/null +++ b/src/domain/class_group.rs @@ -0,0 +1,493 @@ +//! A class (şube): a named set of students the school manages as one, so a +//! course attach enrolls the whole set at once. The membership and the +//! attachments live in their own tables (`class_member`, `class_course`) and are +//! counted on this row — a class may only be deleted at zero on both, the same +//! stored guard shape courses and terms use. +//! +//! A class links a term exactly like a course does, and claims a reference on it +//! before the link is written. The reference is its *own* column +//! ([`TERM_CLASS_COUNT_FIELD`]) rather than the courses' `course_count`, because +//! boot seeds that one from the course rows alone and would wipe a class's share +//! of it on the next migration. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::{ + CLASS_COURSE_COUNT_FIELD, CLASS_GROUP_TABLE, CLASS_MEMBER_COUNT_FIELD, MAX_CLASS_GRADE_LEN, + MAX_CLASS_NAME_LEN, TERM_CLASS_COUNT_FIELD, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::cap; +use crate::domain::field_update::FieldUpdate; +use crate::domain::monotonic_id::next_ulid; +use crate::domain::page::PagedList; +use crate::domain::term::TermId; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +/// The `THROW` marker the delete guard aborts with — a class that still holds +/// students or courses, or a class row that is no longer there. +const LINKS_MARK: &str = "class_links"; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ClassGroupId(RecordId); + +impl ClassGroupId { + pub fn generate() -> Self { + Self(RecordId::new(CLASS_GROUP_TABLE, next_ulid().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(CLASS_GROUP_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ClassName(String); + +impl ClassName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_CLASS_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The school's own label for the year a class sits in ("9", "10-A", +/// "anaokulu"). Free text on purpose — no school's grade ladder is the next +/// one's — and optional: a club-shaped class has no grade at all. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ClassGrade(String); + +impl ClassGrade { + pub fn try_new(value: &str) -> Result { + validate_optional("grade", value, MAX_CLASS_GRADE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One class. `creator` is who made it; the two refcounts behind the delete +/// guard are database-side columns only, so no whole-row save can clobber one +/// (see [`crate::domain::cap`]). +#[derive(Debug, Clone, SurrealValue)] +pub struct ClassGroup { + id: ClassGroupId, + creator: UserId, + name: ClassName, + grade: Option, + term: Option, +} + +impl ClassGroup { + pub fn get_id(&self) -> &ClassGroupId { + &self.id + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_name(&self) -> &ClassName { + &self.name + } + + pub fn get_grade(&self) -> Option<&ClassGrade> { + self.grade.as_ref() + } + + pub fn get_term(&self) -> Option<&TermId> { + self.term.as_ref() + } + + pub fn is_creator(&self, user: &UserId) -> bool { + &self.creator == user + } + + /// Create the class, claiming a reference on the term it links (if any) + /// *before* the row is written: the claim is a conditional write on the term + /// row, so it fails when the term is already gone and it makes the term + /// undeletable the instant this link exists. + pub async fn create( + creator: &UserId, + name: ClassName, + grade: Option, + term: Option, + db: &Database, + ) -> Result { + if let Some(term) = &term { + claim_term(term, db).await?; + } + let claimed = term.clone(); + let class = ClassGroup { + id: ClassGroupId::generate(), + creator: creator.clone(), + name, + grade, + term, + }; + let created: Result, _> = + db.create(class.id.record()).content(class).await; + match created { + Ok(Some(created)) => Ok(created), + other => { + // The link never landed, so the reference has to go back. + if let Some(term) = &claimed { + cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?; + } + match other { + Err(err) => Err(err.into()), + _ => Err(AppError::Internal("failed to create class".into())), + } + } + } + } + + pub async fn read(id: &ClassGroupId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every class, newest first. + pub async fn list_all( + limit: Option, + offset: i64, + db: &Database, + ) -> Result<(Vec, i64), AppError> { + PagedList::new("class_group", "ORDER BY id DESC") + .run(limit, offset, db) + .await + } + + /// Write only the fields the PATCH carried — `None` means the request + /// omitted it, so the column is left alone rather than re-stated from the + /// snapshot this struct was read into. `grade` and `term` are nullable, so + /// they take the outer/inner `Option>`: `None` = omitted (keep), + /// `Some(None)` = clear. + /// + /// A term move is claim-then-write-then-release, in that order, exactly as + /// in [`crate::domain::course::Course::update`]: the new term is made + /// undeletable before the link points at it, and the old one is only let go + /// once the link has actually moved off it. + pub async fn update( + self, + name: Option, + grade: Option>, + term: Option>, + db: &Database, + ) -> Result { + let claimed = match &term { + Some(Some(new)) if Some(new) != self.term.as_ref() => { + claim_term(new, db).await?; + Some(new.clone()) + } + _ => None, + }; + let updated = FieldUpdate::new(self.id.record()) + .set("name", name) + .set("grade", grade) + .set("term", term.map(|term| term.map(|term| term.record()))) + .run::(db) + .await; + match updated { + Ok(updated) => { + // The stored row is the authority on where the link ended up — + // a PATCH that carried no `term_id` leaves it untouched. + if let Some(old) = &self.term + && updated.term.as_ref() != Some(old) + { + cap::release(&old.record(), TERM_CLASS_COUNT_FIELD, db).await?; + } + Ok(updated) + } + Err(err) => { + if let Some(new) = &claimed { + cap::release(&new.record(), TERM_CLASS_COUNT_FIELD, db).await?; + } + Err(err) + } + } + } + + /// Delete the class and give its term reference back. Nothing cascades: a + /// class that still holds students or courses is refused outright, because + /// dropping it silently would leave the enrollments it pumped behind with + /// nothing left to sweep them. + /// + /// `false` = refused, nothing was written. Both counts are read off the + /// class's own row, so the check and the delete are one conditional write on + /// one record — a member or attach racing this either claims first (and the + /// delete is refused) or finds the row gone (and is refused itself). + /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get. + pub async fn delete(self, db: &Database) -> Result { + // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`, + // which is truthy for every row and would delete a class still in use. + let sql = format!( + "BEGIN TRANSACTION; + LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \ + AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); + IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }}; + FOR $row IN $gone {{ + IF $row.term != NONE {{ + UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \ + math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]); + }}; + }}; + COMMIT TRANSACTION;" + ); + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the marker, and a lost + // round is re-sent rather than reported (see [`transaction_with_retry`]). + let (_, mut errors) = transaction_with_retry( + db, + &sql, + &[("class".into(), self.id.record().into_value())], + &[LINKS_MARK], + ) + .await?; + if errors + .values() + .any(|error| error.to_string().contains(LINKS_MARK)) + { + // Still linked or already gone: the guard cannot tell those apart, + // and only the refusal path pays for the extra read that can. + return match Self::read(&self.id, db).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + }; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(true) + } +} + +/// Take a reference on `term` for a class about to link it. The conditional +/// write doubles as the existence check — the class half of +/// [`crate::domain::course`]'s `claim_term`, against the class column. +async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> { + if cap::claim(&term.record(), TERM_CLASS_COUNT_FIELD, cap::UNLIMITED, db).await? { + return Ok(()); + } + Err(AppError::Validation(ValidationError::Invalid { + field: "term_id", + reason: "term does not exist", + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::term::{Term, TermName}; + + async fn class_on(term: Option, db: &Database) -> ClassGroup { + ClassGroup::create( + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + term, + db, + ) + .await + .unwrap() + } + + async fn a_term(db: &Database) -> Term { + let at = crate::domain::timestamp::Timestamp::from_millis; + Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db) + .await + .unwrap() + } + + /// The stored counter, re-read — never off a return value, which the + /// in-memory engine forges wins on (see [`crate::domain::cap`]). + async fn stored_count(sql: &str, db: &Database) -> i64 { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap() + } + + /// How many rows `sql` selects ids for. + async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + #[test] + fn name_is_required_and_grade_is_optional() { + assert!(ClassName::try_new("9-A").is_ok()); + assert!(ClassName::try_new("").is_err()); + assert!(ClassName::try_new(" ").is_err()); + assert!(ClassName::try_new(&"x".repeat(MAX_CLASS_NAME_LEN + 1)).is_err()); + assert!(ClassGrade::try_new("").is_ok()); + assert!(ClassGrade::try_new("anaokulu").is_ok()); + assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); + } + + /// The bite test for the class half of the term delete guard: a term is + /// undeletable while a *class* links it, on its own column, and every way + /// that link can end gives the reference back. Claiming into `course_count` + /// instead would pass the first assert and fail the roundtrip through boot. + #[tokio::test] + async fn a_term_is_deletable_only_once_no_class_links_it() { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term(&db).await; + + let linked = class_on(Some(term.get_id().clone()), &db).await; + let patched = class_on(Some(term.get_id().clone()), &db).await; + assert_eq!( + stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + 2, + "classes must count on class_count, not course_count" + ); + assert_eq!( + stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await, + 0, + "the courses' counter is seeded from course rows and must stay untouched" + ); + assert!( + !term.clone().delete(&db).await.unwrap(), + "two linked classes must refuse the delete" + ); + + patched.update(None, None, Some(None), &db).await.unwrap(); + assert!( + !term.clone().delete(&db).await.unwrap(), + "one link is still one link" + ); + + assert!(linked.delete(&db).await.unwrap()); + assert!( + term.clone().delete(&db).await.unwrap(), + "the last link gone, the term may go" + ); + } + + /// The bite test for the class delete guard, both arms: either count above + /// zero refuses, having written nothing — the term reference least of all, + /// which a refusal that released it would strand. + #[tokio::test] + async fn a_class_with_members_or_courses_refuses_to_delete() { + for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term(&db).await; + let class = class_on(Some(term.get_id().clone()), &db).await; + db.query(format!("UPDATE $class SET {field} = 1")) + .bind(("class", class.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + + assert!( + !class.clone().delete(&db).await.unwrap(), + "{field} above zero must refuse the delete" + ); + assert!( + ClassGroup::read(class.get_id(), &db) + .await + .unwrap() + .is_some(), + "a refused delete may write nothing" + ); + assert_eq!( + stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + 1, + "…the term reference least of all" + ); + + // Back to zero, and the same class deletes and releases the term. + db.query(format!("UPDATE $class SET {field} = 0")) + .bind(("class", class.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + assert!(class.clone().delete(&db).await.unwrap()); + assert_eq!( + stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + 0 + ); + let again = class.delete(&db).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second delete is a 404, not a refusal: {again:?}" + ); + } + } + + /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course + /// takes its `class_course` attachments with it and gives each class its + /// count back, or the classes would be undeletable forever over rows that + /// point at nothing. + #[tokio::test] + async fn deleting_a_course_sweeps_its_class_attachments() { + use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let course = Course::create( + &manager, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + &db, + ) + .await + .unwrap(); + let class = class_on(None, &db).await; + db.query(format!( + "CREATE class_course SET class = $class, course = $course, attached_by = $usr; + UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;" + )) + .bind(("class", class.get_id().record())) + .bind(("course", course.get_id().record())) + .bind(("usr", manager.record())) + .await + .unwrap() + .check() + .unwrap(); + + assert!(course.delete(&db).await.unwrap()); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "the attachment rows must go with the course" + ); + assert_eq!( + stored_count( + &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"), + &db + ) + .await, + 0, + "…and each class must get its count back" + ); + // Which is the whole point: the class is deletable again. + assert!(class.delete(&db).await.unwrap()); + } +} diff --git a/src/domain/course.rs b/src/domain/course.rs index ea80912..12c1e88 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::{ - COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN, - MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, + CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, + MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; @@ -386,7 +386,9 @@ impl Course { /// Delete the course and cascade-remove everything inside it: results, /// attempts, answers, and question/answer images of its exams, its /// homework with their submissions, submission files, and grades, its - /// enrollments, its sessions with their roll call, its subjects, and the + /// enrollments, the class attachments that pumped some of them (each class + /// gets its count back, or it would be undeletable over rows pointing at + /// nothing), its sessions with their roll call, its subjects, and the /// exams themselves. The children go in one transaction so a crash can't /// leave an exam pointing at a deleted course. The image and /// homework-file *blobs* are the web layer's to remove — it collects @@ -429,6 +431,11 @@ impl Course { DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); + LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); + FOR $row IN ($detached ?? []) {{ + UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ + math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); + }}; DELETE session_attendance WHERE course = $course; DELETE course_session WHERE course = $course; DELETE enrollment WHERE course = $course; diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs index 9b5338b..2cc54ab 100644 --- a/src/domain/enrollment.rs +++ b/src/domain/enrollment.rs @@ -3,6 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; use crate::database::Database; use crate::domain::cap; +use crate::domain::class_group::ClassGroupId; use crate::domain::course::{Course, CourseId}; use crate::domain::page::PagedList; use crate::domain::user::UserId; @@ -37,12 +38,19 @@ impl EnrollmentId { /// A user's membership in a course. Grading requires it; removing it hides the /// user's marks from the report but never deletes result rows. +/// +/// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that +/// pumped this row, and is absent when a human placed the student directly — +/// every row written before classes existed, and every row placed by hand since. +/// Absence *is* the meaning, so nothing backfills it: a class sweep may only take +/// back the rows it wrote. #[derive(Debug, Clone, SurrealValue)] pub struct Enrollment { id: EnrollmentId, course: CourseId, user: UserId, enrolled_by: UserId, + source: Option, } impl Enrollment { @@ -62,6 +70,11 @@ impl Enrollment { &self.enrolled_by } + /// The class that pumped this row, or `None` for a hand-placed one. + pub fn get_source(&self) -> Option<&ClassGroupId> { + self.source.as_ref() + } + /// Enroll (idempotently) `user` into `course`. One row per (course, user), /// keyed by a deterministic composite id, so concurrent enrolls of the same /// pair converge on one row instead of racing the unique index into a 500: @@ -92,6 +105,9 @@ impl Enrollment { course: course.clone(), user: user.clone(), enrolled_by: enrolled_by.clone(), + // Hand-placed: no source key at all is written, which is what makes + // a class sweep unable to take this row back. + source: None, }; // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has // to be *seen*, or the pair's second writer would keep the seat it @@ -189,3 +205,72 @@ impl Enrollment { Ok(result.take::>(3)?.into_iter().next()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The database strips `NONE`-valued optional columns, and every enrollment + /// row written before classes existed has no `source` key at all — both must + /// decode as a hand-placed row, never as a decode error that 500s a roster. + #[tokio::test] + async fn enrollment_decodes_without_source_key() { + use surrealdb::types::Value; + + let class = crate::domain::class_group::ClassGroupId::from_key("9a"); + let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); + let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U"); + let enrollment = Enrollment { + id: EnrollmentId::composite(&course, &student), + course, + user: student, + enrolled_by: UserId::from_key("mgr"), + source: Some(class.clone()), + }; + assert_eq!(enrollment.get_source(), Some(&class)); + + let Value::Object(mut object) = enrollment.into_value() else { + panic!("an enrollment must encode as an object"); + }; + object.remove("source"); + let decoded = Enrollment::from_value(Value::Object(object)).unwrap(); + assert_eq!(decoded.get_source(), None); + } + + /// And the other half of "absence is the meaning": a hand-placed enrollment + /// must store *no* source key, or a class sweep would take back a row it + /// never wrote. Asserted on the stored row, not the returned one. + #[tokio::test] + async fn a_hand_placed_enrollment_stores_no_source_key() { + use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; + + let db = crate::database::init_mem().await.unwrap(); + let teacher = UserId::from_key("teacher"); + let course = Course::create( + &teacher, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + &db, + ) + .await + .unwrap(); + Enrollment::enroll(course.get_id(), &UserId::from_key("student"), &teacher, &db) + .await + .unwrap(); + + let mut result = db + .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment") + .await + .unwrap() + .check() + .unwrap(); + assert_eq!( + result.take::>(0).unwrap(), + vec![false], + "a hand-placed row may carry no source key" + ); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index d351f7d..cad8891 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -13,6 +13,7 @@ pub mod board_stroke; pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; +pub mod class_group; pub mod course; pub mod course_session; pub mod dietary_profile; diff --git a/src/domain/term.rs b/src/domain/term.rs index 5308ff5..87ebed3 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -9,7 +9,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE}; +use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_CLASS_COUNT_FIELD, TERM_TABLE}; use crate::database::{Database, write_with_retry}; use crate::domain::field_update::FieldUpdate; use crate::domain::page::PagedList; @@ -133,8 +133,8 @@ impl Term { .await } - /// Delete the term, but only while no course links it — nothing here - /// unlinks or cascades. `false` = refused, nothing was written. + /// Delete the term, but only while no course *and no class* links it — + /// nothing here unlinks or cascades. `false` = refused, nothing was written. /// /// The roster of linking courses is the term's own `course_count` /// refcount, claimed by [`crate::domain::course::Course::create`] and @@ -143,8 +143,15 @@ impl Term { /// claims first (and the delete is refused) or finds the row gone (and is /// refused itself, with the same 400 the lookup gives). `Err(NotFound)` /// keeps the answer a concurrent *delete* used to get. + /// + /// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same + /// way and count on `class_count` — a column of their own, because + /// `course_count` is seeded at boot from the course rows alone. pub async fn delete(self, db: &Database) -> Result { - let sql = format!("DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"); + let sql = format!( + "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \ + AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE" + ); // Through the retry, because the guard reads the very column a course // create claims: a lost round writes nothing, and re-sending it is what // keeps the answer the 404 or 409 it owes instead of a 500.