diff --git a/src/db/cap.rs b/src/db/cap.rs index 8201c26..e13fb3f 100644 --- a/src/db/cap.rs +++ b/src/db/cap.rs @@ -386,7 +386,7 @@ const GONE_MARK: &str = "cap_gone"; /// `UPDATE` that leaves the document unchanged is elided and never enters the /// write set: `SET x = x` sits on no key at all and collides with nothing /// (measured on 3.2.3, and the reason -/// [`crate::domain::class_pump::Axis::pivot_claim`] and +/// [`crate::db::class_pump::Axis::pivot_claim`] and /// [`crate::db::exam_answer::save`] have the same shape). Both /// statements are inside the transaction, so an abort between them cannot leave /// the counter up. diff --git a/src/db/class_blueprint.rs b/src/db/class_blueprint.rs index 8c64671..7926f8f 100644 --- a/src/db/class_blueprint.rs +++ b/src/db/class_blueprint.rs @@ -8,10 +8,10 @@ use surrealdb::types::{RecordId, SurrealValue}; use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD}; use crate::database::{Database, transaction_with_retry}; +use crate::db::class_pump::{Axis, detach}; use crate::db::page::PagedList; use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId}; use crate::domain::class_group::{ClassGrade, ClassGroupId}; -use crate::domain::class_pump::{Axis, detach}; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -41,7 +41,7 @@ pub struct Held { /// and the list keeps an id nothing points at. [`prune`] only fires /// while walking a section, so at a grade carrying none the id is permanent. /// -/// The claim is [`crate::domain::class_pump::Axis::pivot_claim`]'s exactly: +/// The claim is [`crate::db::class_pump::Axis::pivot_claim`]'s exactly: /// the counter is *moved* — bumped, gated, restored to the value this /// transaction found, `NONE` included — because an `UPDATE` leaving the /// document unchanged is elided by 3.2.3 and enters no write set. Moving it @@ -330,13 +330,13 @@ pub async fn drop_links( ) -> Result<(), AppError> { for link in links { detach( + db, "$link WHERE source = $blueprint", Axis::Course, &[ ("link".into(), link.into_value()), ("blueprint".into(), id.record().into_value()), ], - db, ) .await?; } diff --git a/src/db/class_course.rs b/src/db/class_course.rs new file mode 100644 index 0000000..5869e0e --- /dev/null +++ b/src/db/class_course.rs @@ -0,0 +1,77 @@ +//! The `class_course` table: the course-axis attach transaction and the +//! attachment listing. The refusals-to-errors policy and the detach that turns +//! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the +//! transaction itself is the pump's, [`crate::db::class_pump`]. + +use crate::constant::CLASS_COURSE_TABLE; +use crate::database::Database; +use crate::db::class_pump::{Attached, Axis}; +use crate::db::page::PagedList; +use crate::domain::class_blueprint::ClassBlueprintId; +use crate::domain::class_course::{ClassCourse, ClassCourseId}; +use crate::domain::class_group::ClassGroupId; +use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The attach itself, with the refusals left *unmapped*. +/// +/// A hand attach ([`crate::service::class_course::attach`]) turns each of them +/// into the error the route answers with, because one call is one course and a +/// refusal is that call's whole answer. A blueprint pump cannot: it runs +/// one of these per (class, course), and a course that does not fit one +/// section must not abort the other eleven — so it needs to *read* the +/// refusal and carry on ([`crate::domain::class_blueprint`]). +/// +/// `source` is the provenance tag, and it is written by the same statement +/// that writes the link, so no attachment can exist without the answer to +/// "may a blueprint take this back". It is also *claimed* in that +/// transaction ([`Attached::SourceGone`]): a blueprint deleted while this +/// pump ran has already swept by that tag, so a row landing afterwards +/// would carry a name nothing can reach. +pub(crate) async fn attach_sourced( + db: &Database, + class: &ClassGroupId, + course: &CourseId, + attached_by: &UserId, + source: Option<&ClassBlueprintId>, +) -> Result, AppError> { + let link = ClassCourse { + id: ClassCourseId::composite(class, course), + class: class.clone(), + course: course.clone(), + attached_by: attached_by.clone(), + source: source.cloned(), + attached_at: Some(Timestamp::now()), + }; + crate::db::class_pump::attach( + db, + class, + Axis::Course, + (&link.id.record(), &link), + course.record(), + attached_by.record(), + source.map(ClassBlueprintId::record), + ) + .await +} + +/// The courses a class is attached to, newest first — by when they were +/// attached, not by the course's own id, which is what the composite record +/// id sorts on. A row older than the column carries no stamp at all, and +/// NONE sorts last under DESC — the honest place for a row of unknown age. +pub async fn list_for_class( + db: &Database, + class: &ClassGroupId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_COURSE_TABLE} WHERE class = $class"), + "ORDER BY attached_at DESC, id DESC", + ) + .bind("class", class.record()) + .run(limit, offset, db) + .await +} diff --git a/src/db/class_group.rs b/src/db/class_group.rs new file mode 100644 index 0000000..d52b796 --- /dev/null +++ b/src/db/class_group.rs @@ -0,0 +1,728 @@ +//! The `class_group` table: the row, its term reference claimed through +//! [`crate::db::cap`] in the same transaction as the link, and the 0/0 delete +//! guard. The archived-term guard and the route-facing wrappers live in +//! [`crate::service::class_group`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{CLASS_COURSE_COUNT_FIELD, CLASS_MEMBER_COUNT_FIELD, TERM_CLASS_COUNT_FIELD}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::term::{self, TermId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// 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"; + +/// Create the class, claiming a reference on the term it links (if any) in +/// the *same transaction* as the row, exactly as +/// [`crate::db::course::create`] does: the claim is a +/// conditional write on the term row, so it fails when the term is already +/// gone, it makes the term undeletable the instant this link exists, and no +/// crash can leave either half without the other. +pub async fn create( + db: &Database, + creator: &UserId, + name: ClassName, + grade: Option, + term: Option, + teacher: Option, +) -> Result { + let class = ClassGroup { + id: ClassGroupId::generate(), + creator: creator.clone(), + name, + grade, + term, + teacher, + }; + let id = class.id.record(); + let Some(term) = class.term.clone() else { + let created: Option = db.create(id).content(class).await?; + return created.ok_or_else(|| AppError::Internal("failed to create class".into())); + }; + match cap::claim_and_create( + &term.record(), + TERM_CLASS_COUNT_FIELD, + cap::UNLIMITED, + &id, + &class, + db, + ) + .await? + { + cap::Claimed::Made(created) => Ok(created), + // Uncapped, so "full" can only mean the conditional write matched no + // term row at all — the claim doubles as the existence check. + cap::Claimed::Full => Err(term::gone_error()), + // Unreachable: the id is a ULID this call just generated. + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())), + } +} + +pub async fn read(db: &Database, id: &ClassGroupId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every class, newest first — or one grade's, when `grade` narrows it: +/// `Some(Some(label))` is the sections carrying that exact label (no trim, +/// no case folding, matching [`list_for_grade`] and the +/// blueprint keyed by that very string), `Some(None)` the sections carrying +/// no grade at all, `None` the whole list. +/// +/// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the +/// filtered set and a client can page through it. +pub async fn list_all( + db: &Database, + grade: Option>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let list = match grade { + None => PagedList::new("class_group", "ORDER BY id DESC"), + // A gradeless class stores no `grade` key at all (SurrealDB drops a + // key valued NONE), and an absent field reads back as NONE — so the + // one comparison covers both spellings. + Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"), + Some(Some(grade)) => PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC") + .bind("grade", grade.as_str().to_string()), + }; + list.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`, `term` and `teacher` are +/// nullable, so they take the outer/inner `Option>`: `None` = +/// omitted (keep), `Some(None)` = clear. +/// +/// A term move claims the new term and releases the old one inside the very +/// transaction that moves the link, exactly as in +/// [`crate::db::course::update`]: both counters and the link +/// commit together, so no crash can strand a count on a term nothing links. +pub async fn update( + db: &Database, + class: ClassGroup, + name: Option, + grade: Option>, + term: Option>, + teacher: Option>, +) -> Result { + let (claim, release) = term::ref_move(class.term.as_ref(), &term); + let expected = class.term.as_ref().map(TermId::record); + FieldUpdate::new(class.id.record()) + .set("name", name) + .set("grade", grade) + .set("term", term.map(|term| term.map(|term| term.record()))) + // Not refcounted: a homeroom assignment is a label, so it rides the + // plain `set` path and never arms the term CAS. + .set( + "teacher", + teacher.map(|teacher| teacher.map(|teacher| teacher.record())), + ) + .refcount( + TERM_CLASS_COUNT_FIELD, + "term", + expected, + claim, + release, + term::gone_error(), + ) + .run::(db) + .await +} + +/// The classes `ids` names, in no particular order — the join behind +/// "which class section is this student in", where the ids come from +/// `class_member` rows already paged. Ids that name no row are simply +/// absent. +pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(ClassGroupId::record).collect(); + let mut result = db + .query("SELECT * FROM class_group WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Every class section at one grade label, in no particular order — what a +/// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all +/// of them, and a page would silently stock only the first window. +pub async fn list_for_grade( + db: &Database, + grade: &ClassGrade, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM class_group WHERE grade = $grade") + .bind(("grade", grade.as_str().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Strip `user` from every class they were the homeroom teacher of — the +/// sweep for a user demoted below `teacher`, who may no longer hold one. +/// The mirror of [`crate::db::course::unassign_everywhere`]; +/// nothing is counted on this column, so there is no reference to give back. +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { + db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(()) +} + +/// 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(db: &Database, class: ClassGroup) -> 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(), class.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 read(db, &class.id).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + }; + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::term::{Term, TermName}; + + async fn class_on(term: Option, db: &Database) -> ClassGroup { + create( + db, + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + term, + None, + ) + .await + .unwrap() + } + + /// A class with a homeroom teacher, no term. + async fn class_of(teacher: Option, db: &Database) -> ClassGroup { + create( + db, + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + None, + teacher, + ) + .await + .unwrap() + } + + /// The stored `teacher` column, re-read. + async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option { + read(db, class) + .await + .unwrap() + .unwrap() + .get_teacher() + .cloned() + } + + 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::db::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() + } + + /// The stored `class_count` on one term, absent counting as zero. + async fn count_on(term: &TermId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" + )) + .bind(("term", term.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + } + + /// 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() + } + + /// The homeroom teacher survives a create, is set and cleared by a PATCH, + /// and — the part a `.content(self)` save would break — is left alone by a + /// PATCH of another field. A row written before the column exists carries + /// no key at all, which must read back as `None`, not fail the decode. + #[tokio::test] + async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { + let db = crate::database::init_mem().await.unwrap(); + let ada = UserId::from_key("ada"); + let boole = UserId::from_key("boole"); + + let bare = class_of(None, &db).await; + assert_eq!(teacher_of(bare.get_id(), &db).await, None); + let held = class_of(Some(ada.clone()), &db).await; + assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada.clone())); + + // A name-only PATCH must not re-state the teacher out of its snapshot. + let renamed = update( + &db, + held, + Some(ClassName::try_new("9-B").unwrap()), + None, + None, + None, + ) + .await + .unwrap(); + assert_eq!(renamed.get_name().as_str(), "9-B"); + assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada)); + + let moved = update(&db, renamed, None, None, None, Some(Some(boole.clone()))) + .await + .unwrap(); + assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole)); + + let cleared = update(&db, moved, None, None, None, Some(None)) + .await + .unwrap(); + assert_eq!(teacher_of(cleared.get_id(), &db).await, None); + + // …and the mirror: a teacher-only PATCH leaves the name alone. + let again = update( + &db, + cleared, + None, + None, + None, + Some(Some(UserId::from_key("ada"))), + ) + .await + .unwrap(); + assert_eq!(again.get_name().as_str(), "9-B"); + + // A row that predates the column: absent key, not NULL. + db.query("UPDATE $class UNSET teacher") + .bind(("class", bare.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + assert_eq!(teacher_of(bare.get_id(), &db).await, None); + } + + /// The demotion sweep: a user who drops below `teacher` is cleared from + /// *every* class they homeroomed, and nobody else's is touched. + #[tokio::test] + async fn unassign_everywhere_clears_only_that_users_classes() { + let db = crate::database::init_mem().await.unwrap(); + let ada = UserId::from_key("ada"); + let boole = UserId::from_key("boole"); + let first = class_of(Some(ada.clone()), &db).await; + let second = class_of(Some(ada.clone()), &db).await; + let other = class_of(Some(boole.clone()), &db).await; + let none = class_of(None, &db).await; + + unassign_everywhere(&db, &ada).await.unwrap(); + for class in [&first, &second] { + assert_eq!( + teacher_of(class.get_id(), &db).await, + None, + "every class the demoted user homeroomed must be cleared" + ); + } + assert_eq!( + teacher_of(other.get_id(), &db).await, + Some(boole), + "…and nobody else's" + ); + assert_eq!(teacher_of(none.get_id(), &db).await, None); + } + + /// 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" + ); + + update(&db, patched, None, None, Some(None), None) + .await + .unwrap(); + assert!( + !term.clone().delete(&db).await.unwrap(), + "one link is still one link" + ); + + assert!(delete(&db, linked).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!( + !delete(&db, class.clone()).await.unwrap(), + "{field} above zero must refuse the delete" + ); + assert!( + read(&db, class.get_id()).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!(delete(&db, class.clone()).await.unwrap()); + assert_eq!( + stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await, + 0 + ); + let again = delete(&db, class).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second delete is a 404, not a refusal: {again:?}" + ); + } + } + + /// The class half of the invariant on the create path: a refused create + /// leaves neither the row nor a count stranded on a term (which the term's + /// delete guard reads, so a stray one would make it undeletable forever). + #[tokio::test] + async fn a_refused_create_writes_neither_row_nor_count() { + let db = crate::database::init_mem().await.unwrap(); + let term = a_term(&db).await; + let id = term.get_id().clone(); + assert!(term.delete(&db).await.unwrap()); + + let error = create( + &db, + &UserId::from_key("manager"), + ClassName::try_new("9-A").unwrap(), + None, + Some(id), + None, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + assert_eq!( + rows("SELECT VALUE id FROM class_group", &db).await, + 0, + "a refused create may write no row" + ); + assert_eq!( + rows("SELECT VALUE id FROM term", &db).await, + 0, + "…and least of all a count on a term it just brought back" + ); + } + + /// The class mirror of + /// [`crate::db::course`]'s move tests: a term move carries both + /// counters with the link, and a move to a term that is gone rolls the + /// release back with the abort (the transaction releases before it claims, + /// so the old count would be 0 if the abort did not undo it). + #[tokio::test] + async fn a_class_term_move_moves_both_counts_or_neither() { + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let from = a_term(&db).await; + let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let dead_id = dead.get_id().clone(); + assert!(dead.delete(&db).await.unwrap()); + let class = class_on(Some(from.get_id().clone()), &db).await; + + let error = update( + &db, + class.clone(), + Some(ClassName::try_new("9-B").unwrap()), + None, + Some(Some(dead_id)), + None, + ) + .await + .expect_err("a term that is gone must not be linkable"); + assert!(error.to_string().contains("term does not exist")); + let stored = read(&db, class.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); + assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); + assert_eq!( + count_on(from.get_id(), &db).await, + 1, + "the release must roll back with the abort" + ); + + let moved = update( + &db, + class, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + assert_eq!(moved.get_term(), Some(to.get_id())); + assert_eq!( + count_on(from.get_id(), &db).await, + 0, + "the old term is free" + ); + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); + } + + /// The class twin of + /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing` + /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both + /// PATCHes compute their counter move from the row as *they* read it, so a + /// second one running on the pre-move struct would claim a second seat for + /// one link (the mover) or drag the link back and strand the winner's claim + /// (the re-stater, which shifts no counter at all and so is only ever + /// stopped by a guard armed off the *carried column*). Both must be refused + /// with the counts reading as if they never ran. + #[tokio::test] + async fn a_stale_class_term_write_is_refused_and_moves_no_count() { + let db = crate::database::init_mem().await.unwrap(); + let at = crate::domain::timestamp::Timestamp::from_millis; + let from = a_term(&db).await; + let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db) + .await + .unwrap(); + let class = class_on(Some(from.get_id().clone()), &db).await; + let stale = class.clone(); + update( + &db, + class, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .unwrap(); + + // The mover: its snapshot says `from`, so it would release `from` and + // claim `other` on top of the winner's claim on `to`. + let error = update( + &db, + stale.clone(), + None, + None, + Some(Some(other.get_id().clone())), + None, + ) + .await + .expect_err("a mover that read a link it no longer holds must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + // The re-stater: shifts no counter, so only the CAS can stop it. + let error = update( + &db, + stale.clone(), + None, + None, + Some(Some(from.get_id().clone())), + None, + ) + .await + .expect_err("re-stating a link someone else moved must be refused"); + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); + + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); + assert_eq!(count_on(from.get_id(), &db).await, 0, "released once"); + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); + + // A genuine no-op re-state still lands and still moves nothing. + let same = update( + &db, + stored, + None, + None, + Some(Some(to.get_id().clone())), + None, + ) + .await + .expect("re-stating the link the row really holds is not a conflict"); + assert_eq!(same.get_term(), Some(to.get_id())); + assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); + } + + /// [`crate::db::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::{CourseDescription, CourseKind, CourseTitle}; + + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let course = crate::db::course::create( + &db, + &manager, + CourseTitle::try_new("algebra").unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + None, + ) + .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!(crate::db::course::delete(&db, course).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!(delete(&db, class).await.unwrap()); + } +} diff --git a/src/db/class_member.rs b/src/db/class_member.rs new file mode 100644 index 0000000..69ba1db --- /dev/null +++ b/src/db/class_member.rs @@ -0,0 +1,136 @@ +//! The `class_member` table: the roster reads. The membership writes are the +//! pump's, along the member axis ([`crate::db::class_pump`]); the +//! refusals-to-errors policy and the detach live in +//! [`crate::service::class_member`]. + +use crate::constant::CLASS_MEMBER_TABLE; +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::class_group::ClassGroupId; +use crate::domain::class_member::ClassMember; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// The class's roster, newest first — by when the student was added, not by +/// their account id, which is what the composite record id sorts on. +/// A row older than the column carries no stamp at all, and NONE sorts last +/// under DESC — which is the honest place for a row of unknown age. +pub async fn list_for_class( + db: &Database, + class: &ClassGroupId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_MEMBER_TABLE} WHERE class = $class"), + "ORDER BY added_at DESC, id DESC", + ) + .bind("class", class.record()) + .run(limit, offset, db) + .await +} + +/// The classes one student belongs to, newest membership first — the read +/// behind "which class section (şube) am I in". Same ordering story as +/// [`list_for_class`], along the other axis of the same index. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), + "ORDER BY added_at DESC, id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::domain::class_group::ClassName; + use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; + use surrealdb::types::RecordId; + + pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { + crate::db::class_group::create( + db, + &UserId::from_key("manager"), + ClassName::try_new(name).unwrap(), + None, + None, + None, + ) + .await + .unwrap() + .get_id() + .clone() + } + + pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { + crate::db::course::create( + db, + &UserId::from_key("manager"), + CourseTitle::try_new(title).unwrap(), + CourseDescription::try_new("").unwrap(), + CourseKind::course(), + None, + capacity, + ) + .await + .unwrap() + .get_id() + .clone() + } + + /// A counter, re-read out of the store — never off a return value, which + /// the in-memory engine forges wins on (see [`crate::db::cap`]). + pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 { + let mut result = db + .query(format!("SELECT VALUE {field} ?? 0 FROM $of")) + .bind(("of", of)) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap() + } + + /// How many rows `sql` selects ids for. + pub(crate) async fn rows(sql: &str, db: &Database) -> usize { + let mut result = db.query(sql).await.unwrap().check().unwrap(); + result.take::>(0).unwrap().len() + } + + /// Whether `id` names a live row. + pub(crate) async fn exists(id: RecordId, db: &Database) -> bool { + let mut result = db + .query("SELECT VALUE id FROM $id") + .bind(("id", id)) + .await + .unwrap() + .check() + .unwrap(); + !result.take::>(0).unwrap().is_empty() + } + + /// The class that wrote an enrollment, or `None` for a hand-placed row. + pub(crate) async fn source_of( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Option> { + crate::db::enrollment::read_for_user(db, course, user) + .await + .unwrap() + .map(|row| row.get_source().cloned()) + } +} diff --git a/src/domain/class_pump.rs b/src/db/class_pump.rs similarity index 98% rename from src/domain/class_pump.rs rename to src/db/class_pump.rs index 7ca5a32..ac51124 100644 --- a/src/domain/class_pump.rs +++ b/src/db/class_pump.rs @@ -31,7 +31,8 @@ use crate::constant::{ }; use crate::database::{Database, transaction_with_retry}; use crate::db::cap; -use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::db::class_group; +use crate::domain::class_group::ClassGroupId; use crate::error::AppError; /// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK` @@ -386,13 +387,13 @@ impl Axis { /// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and /// passes `None`. pub(crate) async fn attach( + db: &Database, class: &ClassGroupId, axis: Axis, new: (&RecordId, &T), pivot: RecordId, by: RecordId, source: Option, - db: &Database, ) -> Result, AppError> { let (link, row) = new; let count_field = axis.counter(); @@ -527,7 +528,7 @@ pub(crate) async fn attach( .values() .any(|error| error.to_string().contains(CAP_MARK)) { - return Ok(match ClassGroup::read(class, db).await? { + return Ok(match class_group::read(db, class).await? { Some(_) => Attached::ClassFull, None => Attached::Gone, }); @@ -612,10 +613,10 @@ fn named_course(message: &str, mark: &str) -> Option { /// the cascade can answer "already exists" and every lost round is a plain /// re-send. pub(crate) async fn detach( + db: &Database, links: &str, axis: Axis, bindings: &[(String, Value)], - db: &Database, ) -> Result { let count_field = axis.counter(); let scope = axis.scope(); @@ -680,11 +681,11 @@ pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordI mod tests { use super::*; use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE}; + use crate::db::class_member::tests::{a_class, counter, rows}; use crate::domain::class_group::ClassGroupId; - use crate::domain::class_member::ClassMember; - use crate::domain::class_member::tests::{a_class, counter, rows}; use crate::domain::user::UserId; use crate::error::AppError; + use crate::service::{class_course, class_member}; /// The class counter is claimed conditionally, so a class that is not there /// stops the cascade before anything is written — rather than leaving a @@ -695,11 +696,11 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let refused = ClassMember::add( + let refused = class_member::add( + &db, &ghost, &UserId::from_key("student"), &UserId::from_key("manager"), - &db, ) .await; assert!( @@ -725,16 +726,16 @@ mod tests { a_class("club", &db).await, ]; for class in &classes { - ClassMember::add(class, &student, &manager, &db) + class_member::add(&db, class, &student, &manager) .await .unwrap(); } let gone = detach( + &db, &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), Axis::Member, &[("usr".into(), student.record().into_value())], - &db, ) .await .unwrap(); @@ -753,10 +754,10 @@ mod tests { // And a run that unlinks nothing answers zero, which is what turns a // single-pair detach into a 404 instead of a silent success. let again = detach( + &db, &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), Axis::Member, &[("usr".into(), student.record().into_value())], - &db, ) .await .unwrap(); @@ -791,8 +792,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() { - use crate::domain::class_course::ClassCourse; - use crate::domain::class_member::tests::{a_course, source_of}; + use crate::db::class_member::tests::{a_course, source_of}; let (db, _serialized) = crate::database::init_test_server("class_heir_race").await; let manager = UserId::from_key("manager"); @@ -803,10 +803,10 @@ mod tests { let owner = a_class(&format!("9-{round}-owner"), &db).await; let heir = a_class(&format!("9-{round}-heir"), &db).await; for class in [&owner, &heir] { - ClassMember::add(class, &student, &manager, &db) + class_member::add(&db, class, &student, &manager) .await .unwrap(); - ClassCourse::attach(class, &algebra, &manager, &db) + class_course::attach(&db, class, &algebra, &manager) .await .unwrap(); } @@ -828,7 +828,7 @@ mod tests { let detaching = { let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone()); - tokio::spawn(async move { ClassCourse::detach(&owner, &algebra, &db).await }) + tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await }) }; tokio::time::sleep(std::time::Duration::from_millis(500)).await; assert!( @@ -837,8 +837,8 @@ mod tests { ); // The heir lets the row go, twice over, while that sweep is still // choosing it. - ClassMember::remove(&heir, &student, &db).await.unwrap(); - ClassCourse::detach(&heir, &algebra, &db).await.unwrap(); + class_member::remove(&db, &heir, &student).await.unwrap(); + class_course::detach(&db, &heir, &algebra).await.unwrap(); let swept = detaching.await.unwrap(); assert!( !matches!(swept, Err(AppError::Db(_))), diff --git a/src/db/enrollment.rs b/src/db/enrollment.rs index 50acecb..7e122e2 100644 --- a/src/db/enrollment.rs +++ b/src/db/enrollment.rs @@ -43,7 +43,7 @@ const UNFIT_MARK: &str = "enroll_not_student"; /// landed inside this very window — and the re-send then sees that row at /// the `$held` gate and takes the other branch, so the loop converges /// instead of re-asking a settled question. Same shape, same reason, as -/// [`crate::domain::class_pump::attach`]. +/// [`crate::db::class_pump::attach`]. pub async fn enroll( db: &Database, course: &CourseId, diff --git a/src/db/mod.rs b/src/db/mod.rs index fbe8c3f..81e8cf4 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -9,6 +9,10 @@ pub mod cap; pub mod chatbot_message; pub mod chatbot_thread; pub mod class_blueprint; +pub mod class_course; +pub mod class_group; +pub mod class_member; +pub mod class_pump; pub mod course; pub mod course_session; pub mod dietary_profile; diff --git a/src/domain/class_blueprint.rs b/src/domain/class_blueprint.rs index d9b483a..69be878 100644 --- a/src/domain/class_blueprint.rs +++ b/src/domain/class_blueprint.rs @@ -3,8 +3,8 @@ //! //! A school runs many şube at grade "9" and stocks each of them by hand, one //! attach at a time. A blueprint is that list said once. It is a layer *above* -//! [`crate::domain::class_pump`], never a replacement for it: applying a -//! blueprint calls the same [`ClassCourse::attach`] a manager's own call does, +//! [`crate::db::class_pump`], never a replacement for it: applying a +//! blueprint calls the same [`crate::service::class_course::attach`] a manager's own call does, //! so the rows it lands are ordinary `class_course` links and ordinary //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is //! still an individual enrollment nothing here can see. @@ -22,9 +22,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES}; +use crate::db::class_pump::{Attached, Axis}; use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroupId}; -use crate::domain::class_pump::{Attached, Axis}; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -82,7 +82,7 @@ pub struct Skip { /// /// `matched` exists because an empty `skipped` is not success on its own. A /// grade label is free text ([`ClassGrade`]) and -/// [`crate::domain::class_group::ClassGroup::list_for_grade`] +/// [`crate::db::class_group::list_for_grade`] /// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections /// keyed `"9"` — and with nothing to skip it answers exactly like a pump that /// stocked every one of them. The count is the only thing that tells those diff --git a/src/domain/class_course.rs b/src/domain/class_course.rs index a2d747c..3ec2313 100644 --- a/src/domain/class_course.rs +++ b/src/domain/class_course.rs @@ -2,20 +2,20 @@ //! //! The mirror of [`crate::domain::class_member`] along the pump's other axis: //! attaching a course enrolls the class's whole roster into it, detaching it -//! sweeps the rows that attach wrote. +//! sweeps the rows that attach wrote. The attach/detach workflows live in +//! [`crate::service::class_course`]; the row's reads in +//! [`crate::db::class_course`] — this file is the row shape and its +//! composite id. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; -use crate::database::Database; -use crate::db::page::PagedList; +use crate::constant::CLASS_COURSE_TABLE; +use crate::db::class_pump::link_id; use crate::domain::class_blueprint::ClassBlueprintId; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; use crate::domain::course::CourseId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ClassCourseId(RecordId); @@ -41,22 +41,22 @@ impl ClassCourseId { /// One course a class is attached to. `attached_by` is who attached it. #[derive(Debug, Clone, SurrealValue)] pub struct ClassCourse { - id: ClassCourseId, - class: ClassGroupId, - course: CourseId, - attached_by: UserId, + pub(crate) id: ClassCourseId, + pub(crate) class: ClassGroupId, + pub(crate) course: CourseId, + pub(crate) attached_by: UserId, /// The grade blueprint that placed this attachment, absent when a human /// attached the course to this class directly — the mirror of /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a /// row carrying the key is a blueprint's to take back, so a hand-attached /// course survives every blueprint sweep. Rows written before the column /// carry no key at all, which is exactly "hand-attached". - source: Option, + pub(crate) source: Option, /// When it was attached, and the *only* thing "newest first" can mean here: /// the row's id is the (class, course) pair, so ordering by it sorts the /// list by the course's own ULID. Optional because rows written before this /// column carry no stamp — see the migration note. - attached_at: Option, + pub(crate) attached_at: Option, } impl ClassCourse { @@ -80,501 +80,4 @@ impl ClassCourse { pub fn get_source(&self) -> Option<&ClassBlueprintId> { self.source.as_ref() } - - /// Attach `course` to `class` and enroll the class's whole roster into it, - /// in one transaction. - /// - /// Students already in the course keep the rows they have — no seat - /// charged, `source` untouched — and a roster that does not fit refuses the - /// whole attach rather than filling the course to its cap and stopping. - pub async fn attach( - class: &ClassGroupId, - course: &CourseId, - attached_by: &UserId, - db: &Database, - ) -> Result { - let landed = Self::attach_sourced(class, course, attached_by, None, db).await?; - // Read off the refusal, never respelled here: this route and a - // blueprint pump answer one vocabulary. `Made` is the only `None`, and - // it takes the `Ok` arm below. - let code = landed.refusal_code(&Axis::Course).unwrap_or_default(); - match landed { - Attached::Made(saved) => Ok(saved), - Attached::Duplicate => Err(AppError::ConflictCoded { - code, - message: "the course is already on this class".into(), - }), - // The class or the course: either end of the link being gone is a - // 404 on this route, and only a blueprint's skip list needs them - // told apart. - Attached::Gone | Attached::PivotGone => Err(AppError::NotFound), - Attached::ClassFull => Err(AppError::ConflictCoded { - code, - message: format!("this class already holds {MAX_CLASS_COURSES} courses"), - }), - // The other axis: attaching one course enrolls the whole roster, so - // a class over *that* ceiling cannot take a course however few it - // carries. Only a class predating the ceiling can be here. - Attached::ClassOverloaded => Err(AppError::ConflictCoded { - code, - message: format!( - "this class holds more than {MAX_CLASS_MEMBERS} students — \ - remove some before attaching a course" - ), - }), - Attached::Full(full) => Err(AppError::ConflictCoded { - code, - message: format!("{full} cannot hold the whole class"), - }), - // Unreachable on this axis, and kept because the match is - // exhaustive: the pair loop enrolls the roster into `$pivot` and - // nothing else, and the pivot claim already proved *that* course - // alive inside the same transaction. Only a member add walks a - // class's existing course links, so `linked_course_missing` is that - // route's alone — which is why this route's `409` does not publish - // it. Left mapped rather than folded into an `Internal`, so a future - // axis change is a wrong-looking 409, not a 500. - Attached::CourseGone(course) => Err(AppError::ConflictCoded { - code, - message: format!("{course} no longer exists — detach it from this class first"), - }), - // This path passes no source, so the claim that answers this is - // never in the transaction it ran. - Attached::SourceGone => Err(AppError::Internal( - "a hand attach has no blueprint to lose".into(), - )), - } - } - - /// The attach itself, with the refusals left *unmapped*. - /// - /// A hand attach ([`ClassCourse::attach`]) turns each of them into the - /// error the route answers with, because one call is one course and a - /// refusal is that call's whole answer. A blueprint pump cannot: it runs - /// one of these per (class, course), and a course that does not fit one - /// section must not abort the other eleven — so it needs to *read* the - /// refusal and carry on ([`crate::domain::class_blueprint`]). - /// - /// `source` is the provenance tag, and it is written by the same statement - /// that writes the link, so no attachment can exist without the answer to - /// "may a blueprint take this back". It is also *claimed* in that - /// transaction ([`Attached::SourceGone`]): a blueprint deleted while this - /// pump ran has already swept by that tag, so a row landing afterwards - /// would carry a name nothing can reach. - pub(crate) async fn attach_sourced( - class: &ClassGroupId, - course: &CourseId, - attached_by: &UserId, - source: Option<&ClassBlueprintId>, - db: &Database, - ) -> Result, AppError> { - let link = ClassCourse { - id: ClassCourseId::composite(class, course), - class: class.clone(), - course: course.clone(), - attached_by: attached_by.clone(), - source: source.cloned(), - attached_at: Some(Timestamp::now()), - }; - attach( - class, - Axis::Course, - (&link.id.record(), &link), - course.record(), - attached_by.record(), - source.map(ClassBlueprintId::record), - db, - ) - .await - } - - /// Detach `course` from `class` and sweep the enrollments the class pumped - /// into it. A course that was not attached is a [`AppError::NotFound`], - /// raised here rather than left to each caller to re-derive from a boolean. - /// - /// A student another attached class still claims keeps their row, re-tagged - /// to that class (see [`crate::domain::class_pump::detach`]). - pub async fn detach( - class: &ClassGroupId, - course: &CourseId, - db: &Database, - ) -> Result<(), AppError> { - let gone = detach( - "$link", - Axis::Course, - &[( - "link".into(), - ClassCourseId::composite(class, course) - .record() - .into_value(), - )], - db, - ) - .await?; - (gone > 0).then_some(()).ok_or(AppError::NotFound) - } - - /// The courses a class is attached to, newest first — by when they were - /// attached, not by the course's own id, which is what the composite record - /// id sorts on. A row older than the column carries no stamp at all, and - /// NONE sorts last under DESC — the honest place for a row of unknown age. - pub async fn list_for_class( - class: &ClassGroupId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - format!("{CLASS_COURSE_TABLE} WHERE class = $class"), - "ORDER BY attached_at DESC, id DESC", - ) - .bind("class", class.record()) - .run(limit, offset, db) - .await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::class_member::ClassMember; - use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; - - /// Attaching seeds the course from the roster the class already holds. - #[tokio::test] - async fn an_attach_enrolls_the_whole_roster() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - let students = [UserId::from_key("a"), UserId::from_key("b")]; - for student in &students { - ClassMember::add(&class, student, &manager, &db) - .await - .unwrap(); - } - - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - for student in &students { - assert_eq!( - source_of(&algebra, student, &db).await, - Some(Some(class.clone())) - ); - } - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2); - assert_eq!(counter("class_course_count", class.record(), &db).await, 1); - - let again = ClassCourse::attach(&class, &algebra, &manager, &db).await; - assert!( - matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"), - "a second attach is a 409 coded `duplicate`: {again:?}" - ); - } - - /// A course with room for only part of the roster takes none of it: zero - /// enrollments, the counter unmoved, and no attachment row. - #[tokio::test] - async fn a_roster_that_does_not_fit_attaches_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let class = a_class("9-A", &db).await; - let tight = a_course("algebra", Some(2), &db).await; - for student in ["a", "b", "c"] { - ClassMember::add(&class, &UserId::from_key(student), &manager, &db) - .await - .unwrap(); - } - - let refused = ClassCourse::attach(&class, &tight, &manager, &db).await; - assert!( - matches!(refused, Err(AppError::ConflictCoded { code, ref message }) - if code == "course_full" && message.contains(tight.key())), - "the refusal must be coded `course_full` and name the course: {refused:?}" - ); - assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, - 0, - "the two seats that did fit must be given back with the third" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_course", &db).await, - 0, - "…and no attachment row may survive" - ); - assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0); - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); - } - - /// A hand-placed row is skipped on the way in and left standing on the way - /// out — the class never owned it. - #[tokio::test] - async fn a_hand_placed_row_survives_the_detach() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - crate::db::enrollment::enroll(&db, &algebra, &student, &manager) - .await - .unwrap(); - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(None), - "an attach may not adopt a hand-placed row" - ); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 1, - "…nor charge a seat for it" - ); - - ClassCourse::detach(&class, &algebra, &db).await.unwrap(); - assert_eq!(source_of(&algebra, &student, &db).await, Some(None)); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); - let again = ClassCourse::detach(&class, &algebra, &db).await; - assert!( - matches!(again, Err(AppError::NotFound)), - "a second detach is a 404: {again:?}" - ); - } - - /// Detaching with nobody else claiming the rows deletes them and gives the - /// seats back. - #[tokio::test] - async fn a_detach_sweeps_the_rows_it_pumped() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - - ClassCourse::detach(&class, &algebra, &db).await.unwrap(); - assert_eq!(source_of(&algebra, &student, &db).await, None); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); - assert_eq!(counter("class_course_count", class.record(), &db).await, 0); - assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, - 1, - "the two axes are independent: dropping the course may not drop \ - the student out of the class as well" - ); - } - - /// Two classes, one course, one student in both: the second attach skipped - /// the row the first wrote, so the row names only the first class — and - /// detaching *that* class must hand the row to the second rather than - /// unenroll a student the second is still responsible for. Detaching the - /// second then finds nobody left and takes the seat back. - #[tokio::test] - async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let algebra = a_course("algebra", None, &db).await; - let first = a_class("9-A", &db).await; - let second = a_class("club", &db).await; - for class in [&first, &second] { - ClassMember::add(class, &student, &manager, &db) - .await - .unwrap(); - ClassCourse::attach(class, &algebra, &manager, &db) - .await - .unwrap(); - } - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(Some(first.clone())), - "the second attach must skip the row the first wrote" - ); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 1, - "…and pay no second seat for it" - ); - - ClassCourse::detach(&first, &algebra, &db).await.unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(Some(second.clone())), - "the row must be handed to the class that still claims it" - ); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 1, - "a repair is not a release" - ); - - ClassCourse::detach(&second, &algebra, &db).await.unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - None, - "the last claimant leaving takes the row with it" - ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); - } - - /// The same repair along the member axis: removing the student from the - /// class that owns the row hands it to the other class they are in. - #[tokio::test] - async fn a_member_removal_hands_a_shared_row_over_too() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let algebra = a_course("algebra", None, &db).await; - let first = a_class("9-A", &db).await; - let second = a_class("club", &db).await; - for class in [&first, &second] { - ClassCourse::attach(class, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(class, &student, &manager, &db) - .await - .unwrap(); - } - - ClassMember::remove(&first, &student, &db).await.unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(Some(second.clone())), - "the student is still in the second class, so the row stays" - ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); - - ClassMember::remove(&second, &student, &db).await.unwrap(); - assert_eq!(source_of(&algebra, &student, &db).await, None); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); - } - - /// The restore half of the pivot claim: it bumps the course's counter to - /// prove the row is there and must put it back *exactly* as it found it — - /// absent, which the boot backfill keys on (`WHERE enrollment_count = - /// NONE`). An empty roster is the case that has no seat write to hide a - /// leftover bump behind. - #[tokio::test] - async fn the_pivot_claim_gives_the_courses_counter_back_untouched() { - let db = crate::database::init_mem().await.unwrap(); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; - assert_eq!( - rows(absent, &db).await, - 1, - "a fresh course carries no count" - ); - - ClassCourse::attach(&class, &algebra, &UserId::from_key("manager"), &db) - .await - .unwrap(); - assert_eq!( - rows(absent, &db).await, - 1, - "the claim's bump must be restored to absent, not to 0" - ); - } - - /// The `Menu::delete` defect on the class layer: a `class_course` row must - /// not outlive the course it names. The attach's proof that the course is - /// still there is a *write* on the course row - /// ([`crate::domain::class_pump::Axis::pivot_claim`]), landing it on the - /// very key `Course::delete`'s guard writes — but only because that write - /// now *moves* the counter. The `count = count` this shipped with left the - /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write - /// set, collided with nothing, and both callers were told OK while the link - /// stayed pointing at a deleted course. - /// - /// The roster is empty deliberately — that is the only shape where nothing - /// else in the transaction touches the course row, so the claim is the - /// whole guard. One child per round, for the reason the menu twin - /// documents: a second writer makes the delete lose and re-send, and the - /// re-sent sweep clears the evidence. - /// - /// The window is opened by the schema, not by a lucky interleaving: a - /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the - /// instant the row goes, so the `SLEEP` lands between the delete and its - /// `DELETE class_course WHERE course = $course` sweep every time. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both and answers `Ok` to each, so this passes there on broken - /// code. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_class_course_link_never_outlives_the_course() { - let (db, _serialized) = crate::database::init_test_server("class_course_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let manager = UserId::from_key("manager"); - let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); - for round in 0..4 { - let class = a_class(&format!("9-{round}"), &db).await; - let algebra = a_course(&format!("algebra{round}"), None, &db).await; - let course = crate::db::course::read(&db, &algebra) - .await - .unwrap() - .unwrap(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { crate::db::course::delete(&db, course).await }) - }; - // The attach starts inside the held window — the course row is gone - // but uncommitted, which is exactly what a course read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, class, algebra, manager) = - (db.clone(), class.clone(), algebra.clone(), manager.clone()); - tokio::spawn( - async move { ClassCourse::attach(&class, &algebra, &manager, &db).await }, - ) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the attach, or a refusal for the delete, is a correct - // answer — the only defect is stored state. - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced attach must be answered, not 500: {child:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if !exists(algebra.record(), &db).await { - swept += 1; - let link = ClassCourseId::composite(&class, &algebra); - if exists(link.record(), &db).await { - orphans += 1; - } - miscounted += counter("class_course_count", class.record(), &db).await; - } else if matches!(drop_it, Ok(true)) { - panic!("round {round}: the delete reported success but the course is still there"); - } - } - eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); - assert!( - swept > 0, - "no round ever deleted the course, so the window was never reached" - ); - assert_eq!(orphans, 0, "a class_course link outlived its course"); - assert_eq!(miscounted, 0, "a class counts a course that is gone"); - } } diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index a56779c..1f92ed1 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -6,31 +6,23 @@ //! //! 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 +//! ([`crate::constant::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. +//! +//! The queries live in [`crate::db::class_group`]; the archived-term guard and +//! the route-facing wrappers in [`crate::service::class_group`] — this file is +//! the row shape, its newtypes and getters. 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::db::cap; -use crate::db::field_update::FieldUpdate; -use crate::db::page::PagedList; +use crate::constant::{CLASS_GROUP_TABLE, MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN}; use crate::domain::monotonic_id::next_ulid; -use crate::domain::term::{TermId, gone_error, ref_move}; +use crate::domain::term::TermId; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; -use crate::service::term; +use crate::error::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); @@ -93,16 +85,16 @@ impl ClassGrade { /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not /// refcounted, and merely a label pointing at a teacher-or-higher account — the /// web layer holds that bar, and a demotion sweeps the column -/// ([`ClassGroup::unassign_everywhere`]). Rows written before the column exists -/// carry no key at all, which reads back as `None`. +/// ([`crate::db::class_group::unassign_everywhere`]). Rows written before the +/// column exists carry no key at all, which reads back as `None`. #[derive(Debug, Clone, SurrealValue)] pub struct ClassGroup { - id: ClassGroupId, - creator: UserId, - name: ClassName, - grade: Option, - term: Option, - teacher: Option, + pub(crate) id: ClassGroupId, + pub(crate) creator: UserId, + pub(crate) name: ClassName, + pub(crate) grade: Option, + pub(crate) term: Option, + pub(crate) teacher: Option, } impl ClassGroup { @@ -126,16 +118,6 @@ impl ClassGroup { self.term.as_ref() } - /// Refuse the write when this class's term is archived — a pre-flight guard, - /// accepted race (see README concurrency model): a term archived after this - /// read still lets the write through. - pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { - match self.get_term() { - None => Ok(()), - Some(term) => term::require_open(db, term).await, - } - } - /// The homeroom teacher (sınıf öğretmeni), if one is assigned. pub fn get_teacher(&self) -> Option<&UserId> { self.teacher.as_ref() @@ -144,313 +126,11 @@ impl ClassGroup { pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } - - /// Create the class, claiming a reference on the term it links (if any) in - /// the *same transaction* as the row, exactly as - /// [`crate::db::course::create`] does: the claim is a - /// conditional write on the term row, so it fails when the term is already - /// gone, it makes the term undeletable the instant this link exists, and no - /// crash can leave either half without the other. - pub async fn create( - creator: &UserId, - name: ClassName, - grade: Option, - term: Option, - teacher: Option, - db: &Database, - ) -> Result { - let class = ClassGroup { - id: ClassGroupId::generate(), - creator: creator.clone(), - name, - grade, - term, - teacher, - }; - let id = class.id.record(); - let Some(term) = class.term.clone() else { - let created: Option = db.create(id).content(class).await?; - return created.ok_or_else(|| AppError::Internal("failed to create class".into())); - }; - match cap::claim_and_create( - &term.record(), - TERM_CLASS_COUNT_FIELD, - cap::UNLIMITED, - &id, - &class, - db, - ) - .await? - { - cap::Claimed::Made(created) => Ok(created), - // Uncapped, so "full" can only mean the conditional write matched no - // term row at all — the claim doubles as the existence check. - cap::Claimed::Full => Err(gone_error()), - // Unreachable: the id is a ULID this call just generated. - cap::Claimed::Duplicate => 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 — or one grade's, when `grade` narrows it: - /// `Some(Some(label))` is the sections carrying that exact label (no trim, - /// no case folding, matching [`ClassGroup::list_for_grade`] and the - /// blueprint keyed by that very string), `Some(None)` the sections carrying - /// no grade at all, `None` the whole list. - /// - /// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the - /// filtered set and a client can page through it. - pub async fn list_all( - grade: Option>, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let list = match grade { - None => PagedList::new("class_group", "ORDER BY id DESC"), - // A gradeless class stores no `grade` key at all (SurrealDB drops a - // key valued NONE), and an absent field reads back as NONE — so the - // one comparison covers both spellings. - Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"), - Some(Some(grade)) => { - PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC") - .bind("grade", grade.as_str().to_string()) - } - }; - list.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`, `term` and `teacher` are - /// nullable, so they take the outer/inner `Option>`: `None` = - /// omitted (keep), `Some(None)` = clear. - /// - /// A term move claims the new term and releases the old one inside the very - /// transaction that moves the link, exactly as in - /// [`crate::db::course::update`]: both counters and the link - /// commit together, so no crash can strand a count on a term nothing links. - pub async fn update( - self, - name: Option, - grade: Option>, - term: Option>, - teacher: Option>, - db: &Database, - ) -> Result { - let (claim, release) = ref_move(self.term.as_ref(), &term); - let expected = self.term.as_ref().map(TermId::record); - FieldUpdate::new(self.id.record()) - .set("name", name) - .set("grade", grade) - .set("term", term.map(|term| term.map(|term| term.record()))) - // Not refcounted: a homeroom assignment is a label, so it rides the - // plain `set` path and never arms the term CAS. - .set( - "teacher", - teacher.map(|teacher| teacher.map(|teacher| teacher.record())), - ) - .refcount( - TERM_CLASS_COUNT_FIELD, - "term", - expected, - claim, - release, - gone_error(), - ) - .run::(db) - .await - } - - /// The classes `ids` names, in no particular order — the join behind - /// "which class section is this student in", where the ids come from - /// `class_member` rows already paged. Ids that name no row are simply - /// absent. - pub async fn list_by_ids( - ids: &[ClassGroupId], - db: &Database, - ) -> Result, AppError> { - if ids.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = ids.iter().map(ClassGroupId::record).collect(); - let mut result = db - .query("SELECT * FROM class_group WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Every class section at one grade label, in no particular order — what a - /// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all - /// of them, and a page would silently stock only the first window. - pub async fn list_for_grade( - grade: &ClassGrade, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM class_group WHERE grade = $grade") - .bind(("grade", grade.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Strip `user` from every class they were the homeroom teacher of — the - /// sweep for a user demoted below `teacher`, who may no longer hold one. - /// The mirror of [`crate::db::course::unassign_everywhere`]; - /// nothing is counted on this column, so there is no reference to give back. - pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { - db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(()) - } - - /// 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) - } } #[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, - None, - db, - ) - .await - .unwrap() - } - - /// A class with a homeroom teacher, no term. - async fn class_of(teacher: Option, db: &Database) -> ClassGroup { - ClassGroup::create( - &UserId::from_key("manager"), - ClassName::try_new("9-A").unwrap(), - None, - None, - teacher, - db, - ) - .await - .unwrap() - } - - /// The stored `teacher` column, re-read. - async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option { - ClassGroup::read(class, db) - .await - .unwrap() - .unwrap() - .get_teacher() - .cloned() - } - - async fn a_term(db: &Database) -> Term { - let at = crate::domain::timestamp::Timestamp::from_millis; - crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200)) - .await - .unwrap() - } - - /// The stored counter, re-read — never off a return value, which the - /// in-memory engine forges wins on (see [`crate::db::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() - } - - /// The stored `class_count` on one term, absent counting as zero. - async fn count_on(term: &TermId, db: &Database) -> i64 { - let mut result = db - .query(format!( - "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term" - )) - .bind(("term", term.record())) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap_or(0) - } - - /// 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() { @@ -462,391 +142,4 @@ mod tests { assert!(ClassGrade::try_new("anaokulu").is_ok()); assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err()); } - - /// The homeroom teacher survives a create, is set and cleared by a PATCH, - /// and — the part a `.content(self)` save would break — is left alone by a - /// PATCH of another field. A row written before the column exists carries - /// no key at all, which must read back as `None`, not fail the decode. - #[tokio::test] - async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { - let db = crate::database::init_mem().await.unwrap(); - let ada = UserId::from_key("ada"); - let boole = UserId::from_key("boole"); - - let bare = class_of(None, &db).await; - assert_eq!(teacher_of(bare.get_id(), &db).await, None); - let held = class_of(Some(ada.clone()), &db).await; - assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada.clone())); - - // A name-only PATCH must not re-state the teacher out of its snapshot. - let renamed = held - .update( - Some(ClassName::try_new("9-B").unwrap()), - None, - None, - None, - &db, - ) - .await - .unwrap(); - assert_eq!(renamed.get_name().as_str(), "9-B"); - assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada)); - - let moved = renamed - .update(None, None, None, Some(Some(boole.clone())), &db) - .await - .unwrap(); - assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole)); - - let cleared = moved - .update(None, None, None, Some(None), &db) - .await - .unwrap(); - assert_eq!(teacher_of(cleared.get_id(), &db).await, None); - - // …and the mirror: a teacher-only PATCH leaves the name alone. - let again = cleared - .update(None, None, None, Some(Some(UserId::from_key("ada"))), &db) - .await - .unwrap(); - assert_eq!(again.get_name().as_str(), "9-B"); - - // A row that predates the column: absent key, not NULL. - db.query("UPDATE $class UNSET teacher") - .bind(("class", bare.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - assert_eq!(teacher_of(bare.get_id(), &db).await, None); - } - - /// The demotion sweep: a user who drops below `teacher` is cleared from - /// *every* class they homeroomed, and nobody else's is touched. - #[tokio::test] - async fn unassign_everywhere_clears_only_that_users_classes() { - let db = crate::database::init_mem().await.unwrap(); - let ada = UserId::from_key("ada"); - let boole = UserId::from_key("boole"); - let first = class_of(Some(ada.clone()), &db).await; - let second = class_of(Some(ada.clone()), &db).await; - let other = class_of(Some(boole.clone()), &db).await; - let none = class_of(None, &db).await; - - ClassGroup::unassign_everywhere(&ada, &db).await.unwrap(); - for class in [&first, &second] { - assert_eq!( - teacher_of(class.get_id(), &db).await, - None, - "every class the demoted user homeroomed must be cleared" - ); - } - assert_eq!( - teacher_of(other.get_id(), &db).await, - Some(boole), - "…and nobody else's" - ); - assert_eq!(teacher_of(none.get_id(), &db).await, None); - } - - /// 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!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), - "two linked classes must refuse the delete" - ); - - patched - .update(None, None, Some(None), None, &db) - .await - .unwrap(); - assert!( - !crate::db::term::delete(&db, term.clone()).await.unwrap(), - "one link is still one link" - ); - - assert!(linked.delete(&db).await.unwrap()); - assert!( - crate::db::term::delete(&db, term.clone()).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:?}" - ); - } - } - - /// The class half of the invariant on the create path: a refused create - /// leaves neither the row nor a count stranded on a term (which the term's - /// delete guard reads, so a stray one would make it undeletable forever). - #[tokio::test] - async fn a_refused_create_writes_neither_row_nor_count() { - let db = crate::database::init_mem().await.unwrap(); - let term = a_term(&db).await; - let id = term.get_id().clone(); - assert!(crate::db::term::delete(&db, term).await.unwrap()); - - let error = ClassGroup::create( - &UserId::from_key("manager"), - ClassName::try_new("9-A").unwrap(), - None, - Some(id), - None, - &db, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - assert_eq!( - rows("SELECT VALUE id FROM class_group", &db).await, - 0, - "a refused create may write no row" - ); - assert_eq!( - rows("SELECT VALUE id FROM term", &db).await, - 0, - "…and least of all a count on a term it just brought back" - ); - } - - /// The class mirror of - /// [`crate::db::course`]'s move tests: a term move carries both - /// counters with the link, and a move to a term that is gone rolls the - /// release back with the abort (the transaction releases before it claims, - /// so the old count would be 0 if the abort did not undo it). - #[tokio::test] - async fn a_class_term_move_moves_both_counts_or_neither() { - let db = crate::database::init_mem().await.unwrap(); - let at = crate::domain::timestamp::Timestamp::from_millis; - let from = a_term(&db).await; - let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) - .await - .unwrap(); - let dead = - crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); - let dead_id = dead.get_id().clone(); - assert!(crate::db::term::delete(&db, dead).await.unwrap()); - let class = class_on(Some(from.get_id().clone()), &db).await; - - let error = class - .clone() - .update( - Some(ClassName::try_new("9-B").unwrap()), - None, - Some(Some(dead_id)), - None, - &db, - ) - .await - .expect_err("a term that is gone must not be linkable"); - assert!(error.to_string().contains("term does not exist")); - let stored = ClassGroup::read(class.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); - assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); - assert_eq!( - count_on(from.get_id(), &db).await, - 1, - "the release must roll back with the abort" - ); - - let moved = class - .update(None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - assert_eq!(moved.get_term(), Some(to.get_id())); - assert_eq!( - count_on(from.get_id(), &db).await, - 0, - "the old term is free" - ); - assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); - } - - /// The class twin of - /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing` - /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both - /// PATCHes compute their counter move from the row as *they* read it, so a - /// second one running on the pre-move struct would claim a second seat for - /// one link (the mover) or drag the link back and strand the winner's claim - /// (the re-stater, which shifts no counter at all and so is only ever - /// stopped by a guard armed off the *carried column*). Both must be refused - /// with the counts reading as if they never ran. - #[tokio::test] - async fn a_stale_class_term_write_is_refused_and_moves_no_count() { - let db = crate::database::init_mem().await.unwrap(); - let at = crate::domain::timestamp::Timestamp::from_millis; - let from = a_term(&db).await; - let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200)) - .await - .unwrap(); - let other = - crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200)) - .await - .unwrap(); - let class = class_on(Some(from.get_id().clone()), &db).await; - let stale = class.clone(); - class - .update(None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .unwrap(); - - // The mover: its snapshot says `from`, so it would release `from` and - // claim `other` on top of the winner's claim on `to`. - let error = stale - .clone() - .update(None, None, Some(Some(other.get_id().clone())), None, &db) - .await - .expect_err("a mover that read a link it no longer holds must be refused"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - // The re-stater: shifts no counter, so only the CAS can stop it. - let error = stale - .clone() - .update(None, None, Some(Some(from.get_id().clone())), None, &db) - .await - .expect_err("re-stating a link someone else moved must be refused"); - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); - - let stored = ClassGroup::read(stale.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); - assert_eq!(count_on(from.get_id(), &db).await, 0, "released once"); - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); - - // A genuine no-op re-state still lands and still moves nothing. - let same = stored - .update(None, None, Some(Some(to.get_id().clone())), None, &db) - .await - .expect("re-stating the link the row really holds is not a conflict"); - assert_eq!(same.get_term(), Some(to.get_id())); - assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); - } - - /// [`crate::db::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::{CourseDescription, CourseKind, CourseTitle}; - - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let course = crate::db::course::create( - &db, - &manager, - CourseTitle::try_new("algebra").unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - None, - ) - .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!(crate::db::course::delete(&db, course).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/class_member.rs b/src/domain/class_member.rs index 36b19ea..3cee472 100644 --- a/src/domain/class_member.rs +++ b/src/domain/class_member.rs @@ -1,20 +1,19 @@ //! A student's place in a class, and the enrollments that place implies. //! -//! Both writes here are one call into [`crate::domain::class_pump`]: this file -//! only names the axis, the counter and the composite id, because adding a -//! member and attaching a course to the class are the same pump seen from its -//! two ends. +//! Both writes are one call into [`crate::db::class_pump`]: adding a member +//! and attaching a course to the class are the same pump seen from its two +//! ends. The refusals-to-errors policy and the detach live in +//! [`crate::service::class_member`]; the roster reads in +//! [`crate::db::class_member`] — this file is the row shape and its +//! composite id. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; -use crate::database::Database; -use crate::db::page::PagedList; +use crate::constant::CLASS_MEMBER_TABLE; +use crate::db::class_pump::link_id; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ClassMemberId(RecordId); @@ -40,15 +39,15 @@ impl ClassMemberId { /// One student in one class. `added_by` is who put them there. #[derive(Debug, Clone, SurrealValue)] pub struct ClassMember { - id: ClassMemberId, - class: ClassGroupId, - user: UserId, - added_by: UserId, + pub(crate) id: ClassMemberId, + pub(crate) class: ClassGroupId, + pub(crate) user: UserId, + pub(crate) added_by: UserId, /// When they were added, and the *only* thing "newest first" can mean here: /// the row's id is the (class, user) pair, so ordering by it sorts the /// roster by the student's account ULID. Optional because rows written /// before this column carry no stamp — see the migration note. - added_at: Option, + pub(crate) added_at: Option, } impl ClassMember { @@ -67,541 +66,4 @@ impl ClassMember { pub fn get_added_by(&self) -> &UserId { &self.added_by } - - /// Put `user` in `class` and enroll them into every course the class is - /// already attached to, in one transaction. - /// - /// A student already enrolled in one of those courses keeps the row they - /// have — no seat is charged and their `source` is untouched, so a - /// hand-placed enrollment is never adopted by the class — and a course with - /// no free seat refuses the *whole* join rather than half of it. - pub async fn add( - class: &ClassGroupId, - user: &UserId, - added_by: &UserId, - db: &Database, - ) -> Result { - let member = ClassMember { - id: ClassMemberId::composite(class, user), - class: class.clone(), - user: user.clone(), - added_by: added_by.clone(), - added_at: Some(Timestamp::now()), - }; - let landed = attach( - class, - Axis::Member, - (&member.id.record(), &member), - user.record(), - added_by.record(), - None, - db, - ) - .await?; - // Read off the refusal, never respelled here: this route and a - // blueprint pump answer one vocabulary. `Made` is the only `None`, and - // it takes the `Ok` arm below. - let code = landed.refusal_code(&Axis::Member).unwrap_or_default(); - match landed { - Attached::Made(saved) => Ok(saved), - Attached::Duplicate => Err(AppError::ConflictCoded { - code, - message: "the student is already in this class".into(), - }), - Attached::Gone => Err(AppError::NotFound), - // The pivot is the student: they were demoted while this ran, which - // is the refusal the caller's own read makes a moment earlier and - // the only one that can arrive after it. - Attached::PivotGone => Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be added to a class", - })), - Attached::ClassFull => Err(AppError::ConflictCoded { - code, - message: format!("this class already holds {MAX_CLASS_MEMBERS} students"), - }), - // The other axis: adding one student enrolls them into every - // attached course, so a class over *that* ceiling cannot take a - // member however much room its roster has. - Attached::ClassOverloaded => Err(AppError::ConflictCoded { - code, - message: format!( - "this class holds more than {MAX_CLASS_COURSES} courses — \ - detach some before adding a student" - ), - }), - Attached::Full(course) => Err(AppError::ConflictCoded { - code, - message: format!("{course} is full, so the class cannot take this student"), - }), - // Not a capacity problem, and told apart from one on purpose: no - // number anyone can raise unblocks this class, only detaching the - // link the deleted course left behind. - Attached::CourseGone(course) => Err(AppError::ConflictCoded { - code, - message: format!("{course} no longer exists — detach it from this class first"), - }), - // Only an attach run on a blueprint's behalf states that claim, and - // a membership is nobody's but its own. - Attached::SourceGone => Err(AppError::Internal( - "a class membership has no blueprint to lose".into(), - )), - } - } - - /// Take `user` out of `class` and sweep the enrollments the class pumped - /// for them. A student who was not in the class is a - /// [`AppError::NotFound`], raised here rather than left to each caller to - /// re-derive from a boolean. - /// - /// An enrollment another attached class still claims is re-tagged to that - /// class instead of deleted (see [`crate::domain::class_pump::detach`]). - pub async fn remove( - class: &ClassGroupId, - user: &UserId, - db: &Database, - ) -> Result<(), AppError> { - let gone = detach( - "$link", - Axis::Member, - &[( - "link".into(), - ClassMemberId::composite(class, user).record().into_value(), - )], - db, - ) - .await?; - (gone > 0).then_some(()).ok_or(AppError::NotFound) - } - - /// The class's roster, newest first — by when the student was added, not by - /// their account id, which is what the composite record id sorts on. - /// A row older than the column carries no stamp at all, and NONE sorts last - /// under DESC — which is the honest place for a row of unknown age. - pub async fn list_for_class( - class: &ClassGroupId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE class = $class"), - "ORDER BY added_at DESC, id DESC", - ) - .bind("class", class.record()) - .run(limit, offset, db) - .await - } - - /// The classes one student belongs to, newest membership first — the read - /// behind "which class section (şube) am I in". Same ordering story as - /// [`ClassMember::list_for_class`], along the other axis of the same index. - pub async fn list_for_user( - user: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"), - "ORDER BY added_at DESC, id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await - } -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use crate::domain::class_course::ClassCourse; - use crate::domain::class_group::{ClassGroup, ClassName}; - use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; - - pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { - ClassGroup::create( - &UserId::from_key("manager"), - ClassName::try_new(name).unwrap(), - None, - None, - None, - db, - ) - .await - .unwrap() - .get_id() - .clone() - } - - pub(crate) async fn a_course(title: &str, capacity: Option, db: &Database) -> CourseId { - crate::db::course::create( - db, - &UserId::from_key("manager"), - CourseTitle::try_new(title).unwrap(), - CourseDescription::try_new("").unwrap(), - CourseKind::course(), - None, - capacity, - ) - .await - .unwrap() - .get_id() - .clone() - } - - /// A counter, re-read out of the store — never off a return value, which - /// the in-memory engine forges wins on (see [`crate::db::cap`]). - pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 { - let mut result = db - .query(format!("SELECT VALUE {field} ?? 0 FROM $of")) - .bind(("of", of)) - .await - .unwrap() - .check() - .unwrap(); - result - .take::>(0) - .unwrap() - .first() - .copied() - .unwrap() - } - - /// How many rows `sql` selects ids for. - pub(crate) async fn rows(sql: &str, db: &Database) -> usize { - let mut result = db.query(sql).await.unwrap().check().unwrap(); - result.take::>(0).unwrap().len() - } - - /// Whether `id` names a live row. - pub(crate) async fn exists(id: RecordId, db: &Database) -> bool { - let mut result = db - .query("SELECT VALUE id FROM $id") - .bind(("id", id)) - .await - .unwrap() - .check() - .unwrap(); - !result.take::>(0).unwrap().is_empty() - } - - /// The class that wrote an enrollment, or `None` for a hand-placed row. - pub(crate) async fn source_of( - course: &CourseId, - user: &UserId, - db: &Database, - ) -> Option> { - crate::db::enrollment::read_for_user(db, course, user) - .await - .unwrap() - .map(|row| row.get_source().cloned()) - } - - #[tokio::test] - async fn a_member_is_enrolled_into_every_attached_course() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - let physics = a_course("physics", None, &db).await; - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - ClassCourse::attach(&class, &physics, &manager, &db) - .await - .unwrap(); - - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - for course in [&algebra, &physics] { - assert_eq!( - source_of(course, &student, &db).await, - Some(Some(class.clone())), - "every attached course must hold a row tagged with the class" - ); - assert_eq!(counter("enrollment_count", course.record(), &db).await, 1); - } - assert_eq!(counter("class_member_count", class.record(), &db).await, 1); - } - - /// The pumped row must carry the *same* composite id a hand enroll would - /// mint, or the two paths would key one pair two ways and only the unique - /// index (a 500) would notice. - #[tokio::test] - async fn a_pumped_row_uses_the_hand_enrolls_composite_id() { - use crate::domain::enrollment::EnrollmentId; - - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - assert!( - exists(EnrollmentId::composite(&algebra, &student).record(), &db).await, - "the pump must key the pair the way Enrollment::composite does" - ); - } - - /// Re-adding is a 409, and it must cost nothing: no second counter tick and - /// no second sweep of anybody's enrollment. - #[tokio::test] - async fn a_second_add_is_refused_and_writes_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - let again = ClassMember::add(&class, &student, &manager, &db).await; - assert!( - matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"), - "a second add is a 409 coded `duplicate`: {again:?}" - ); - assert_eq!( - counter("class_member_count", class.record(), &db).await, - 1, - "a refused add may not tick the counter" - ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); - } - - /// Adding into a class whose courses have no room refuses the *whole* join: - /// the roomy course must not keep a seat the full one denied. - #[tokio::test] - async fn a_full_course_refuses_the_whole_join() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let roomy = a_course("algebra", None, &db).await; - let full = a_course("physics", Some(0), &db).await; - ClassCourse::attach(&class, &roomy, &manager, &db) - .await - .unwrap(); - ClassCourse::attach(&class, &full, &manager, &db) - .await - .unwrap(); - - // The whole record id, not just the key: a caller reading the 409 must - // not have to guess which table the name came from. - let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key()); - let refused = ClassMember::add(&class, &student, &manager, &db).await; - assert!( - matches!(refused, Err(AppError::ConflictCoded { code, ref message }) - if code == "course_full" && message.contains(&named)), - "the refusal must be coded `course_full` and name the course that had no seat \ - as {named}: {refused:?}" - ); - assert_eq!( - rows("SELECT VALUE id FROM enrollment", &db).await, - 0, - "not one seat may survive the refusal" - ); - assert_eq!( - rows("SELECT VALUE id FROM class_member", &db).await, - 0, - "…nor the membership row itself" - ); - assert_eq!( - counter("enrollment_count", roomy.record(), &db).await, - 0, - "…nor the roomy course's counter" - ); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); - } - - /// A student already enrolled by hand keeps their own row: no seat is - /// charged for them, the row's `source` stays empty, and removing them from - /// the class leaves it standing. - #[tokio::test] - async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - crate::db::enrollment::enroll(&db, &algebra, &student, &manager) - .await - .unwrap(); - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(None), - "the class must not adopt a hand-placed row" - ); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 1, - "the skipped pair may not be charged a second seat" - ); - - ClassMember::remove(&class, &student, &db).await.unwrap(); - assert_eq!( - source_of(&algebra, &student, &db).await, - Some(None), - "the sweep may only take back the rows the class wrote" - ); - assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); - } - - /// Removal with nobody else claiming the row: the enrollment goes and its - /// seat comes back. - #[tokio::test] - async fn removal_deletes_the_rows_the_class_pumped() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - ClassMember::remove(&class, &student, &db).await.unwrap(); - assert_eq!(source_of(&algebra, &student, &db).await, None); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 0, - "the seat must come back with the row that held it" - ); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); - let again = ClassMember::remove(&class, &student, &db).await; - assert!( - matches!(again, Err(AppError::NotFound)), - "a second removal is a 404, not a second sweep: {again:?}" - ); - } - - /// A member who is not in any attached course still removes cleanly, and a - /// course deleted out from under the class leaves nothing to sweep — the - /// membership row and the pumped enrollment are independent facts. - #[tokio::test] - async fn a_sweep_tolerates_rows_a_course_delete_already_took() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - let student = UserId::from_key("student"); - let class = a_class("9-A", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassCourse::attach(&class, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(&class, &student, &manager, &db) - .await - .unwrap(); - - // `Course::delete` refuses while the roster is occupied, so the wipe is - // spelled the way the cascade does it, minus the guard. - db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;") - .bind(("course", algebra.record())) - .await - .unwrap() - .check() - .unwrap(); - - ClassMember::remove(&class, &student, &db) - .await - .expect("the membership must still be removable with its enrollment gone"); - assert_eq!(counter("class_member_count", class.record(), &db).await, 0); - } - - /// The role-change sweep, which is one transaction with the role write - /// itself: the memberships go with their counters, the enrollment rows go - /// with their seats, and each seat comes back exactly once — the double - /// decrement the old two-call split existed to avoid. - #[tokio::test] - async fn the_role_sweep_takes_memberships_and_enrollments_together() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("manager"); - // A real row, because the sweep now rides on the role write. - let hash = crate::domain::user::Password::try_new("secret1") - .unwrap() - .hash_async() - .await - .unwrap(); - let account = crate::db::user::create( - &db, - crate::domain::user::Username::try_new("ogrenci").unwrap(), - hash, - ) - .await - .unwrap(); - let student = account.get_id().clone(); - let first = a_class("9-A", &db).await; - let second = a_class("club", &db).await; - let algebra = a_course("algebra", None, &db).await; - ClassCourse::attach(&first, &algebra, &manager, &db) - .await - .unwrap(); - ClassMember::add(&first, &student, &manager, &db) - .await - .unwrap(); - ClassMember::add(&second, &student, &manager, &db) - .await - .unwrap(); - - crate::service::user::set_role( - &db, - account.get_id(), - crate::domain::role::Role::Teacher, - ) - .await - .unwrap(); - assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); - for class in [&first, &second] { - assert_eq!( - counter("class_member_count", class.record(), &db).await, - 0, - "every class must get its member count back" - ); - } - assert_eq!( - source_of(&algebra, &student, &db).await, - None, - "the enrollment goes in the same transaction as the membership" - ); - assert_eq!( - counter("enrollment_count", algebra.record(), &db).await, - 0, - "…and its seat comes back once, not twice" - ); - // Which is the point of folding them: the class the student was in is - // free of them entirely — no membership, no count, and no enrollment - // row left tagged with a class that is about to be deletable. - assert!( - crate::domain::class_group::ClassGroup::read(&second, &db) - .await - .unwrap() - .unwrap() - .delete(&db) - .await - .unwrap(), - "a class holding neither members nor courses must delete" - ); - } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 856592f..c4f78a2 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -18,7 +18,6 @@ pub mod class_blueprint; pub mod class_course; pub mod class_group; pub mod class_member; -pub mod class_pump; pub mod course; pub mod course_note; pub mod course_note_file; diff --git a/src/service/class_blueprint.rs b/src/service/class_blueprint.rs index 2cc9aa0..99809c4 100644 --- a/src/service/class_blueprint.rs +++ b/src/service/class_blueprint.rs @@ -23,7 +23,7 @@ //! a `class_course` row this blueprint wrote carries `source`, a row a human //! attached carries no such key at all, and dropping a course from the //! blueprint sweeps only the former. The sweep is the pump's own -//! [`crate::domain::class_pump::detach`], so a class losing a course still +//! [`crate::db::class_pump::detach`], so a class losing a course still //! repairs before it deletes — and it runs one transaction per pair too, for //! the same reason the pump does. @@ -33,12 +33,13 @@ use surrealdb::types::RecordId; use crate::database::Database; use crate::db::class_blueprint; +use crate::db::class_course; +use crate::db::class_group; +use crate::db::class_pump::Attached; use crate::domain::class_blueprint::{ ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason, }; -use crate::domain::class_course::ClassCourse; use crate::domain::class_group::{ClassGrade, ClassGroup}; -use crate::domain::class_pump::Attached; use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::AppError; @@ -47,7 +48,7 @@ use crate::error::AppError; /// /// [`delete`] removes the row and then sweeps by the provenance /// tag, and every guarded attach reads that same row *inside* its own -/// transaction ([`crate::domain::class_pump::attach`]'s `source` claim). Those +/// transaction ([`crate::db::class_pump::attach`]'s `source` claim). Those /// two are a cross-record read-then-write racing a write to the record read, /// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can /// see the blueprint alive, have the delete commit and sweep past it, and only @@ -290,7 +291,8 @@ async fn apply_courses( } let landed = { let _lease = BLUEPRINT_LOCK.read().await; - ClassCourse::attach_sourced(class.get_id(), course, by, Some(&blueprint.id), db).await? + class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id)) + .await? }; if matches!(landed, Attached::PivotGone) { class_blueprint::prune(db, &blueprint.id, course).await?; @@ -346,7 +348,7 @@ pub async fn pump( skipped: Vec::new(), }; let mut dead = Vec::new(); - for class in ClassGroup::list_for_grade(&blueprint.grade, db).await? { + for class in class_group::list_for_grade(db, &blueprint.grade).await? { pumped.matched += 1; if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? { break; @@ -378,14 +380,14 @@ pub async fn pump( /// pump's own window ([`class_blueprint::prune`]) is about to clear, can /// still show it. /// -/// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set +/// Unpaged, like the [`crate::db::class_group::list_for_grade`] it is built on: the set /// is the şube one school runs at one grade, and the caller is asking about /// all of them. pub async fn status( db: &Database, blueprint: &ClassBlueprint, ) -> Result, AppError> { - let sections = ClassGroup::list_for_grade(&blueprint.grade, db).await?; + let sections = class_group::list_for_grade(db, &blueprint.grade).await?; if sections.is_empty() { return Ok(Vec::new()); } @@ -417,20 +419,20 @@ pub async fn status( mod tests { use super::*; use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES}; + use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows}; use crate::domain::class_course::ClassCourseId; - use crate::domain::class_group::ClassName; - use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows}; + use crate::domain::class_group::{ClassGroup, ClassName}; /// A section that a pump's own grade loop can actually find — [`a_class`] /// carries no grade at all, so `list_for_grade` reaches none of them. async fn a_section(name: &str, db: &Database) -> ClassGroup { - ClassGroup::create( + class_group::create( + db, &UserId::from_key("manager"), ClassName::try_new(name).unwrap(), Some(ClassBlueprint::grade_key("9").unwrap()), None, None, - db, ) .await .unwrap() @@ -463,7 +465,7 @@ mod tests { // matches nothing. let db = crate::database::init_mem().await.unwrap(); let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); @@ -496,7 +498,7 @@ mod tests { // matches nothing and the read that follows finds no row. let db = crate::database::init_mem().await.unwrap(); let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); @@ -527,7 +529,7 @@ mod tests { // but the row is there — and that is the one a manager can act on. let db = crate::database::init_mem().await.unwrap(); let course = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); @@ -563,7 +565,7 @@ mod tests { let manager = UserId::from_key("manager"); let algebra = a_course("algebra", None, &db).await; let physics = a_course("physics", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); @@ -616,7 +618,7 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let manager = UserId::from_key("manager"); let algebra = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); @@ -685,7 +687,7 @@ mod tests { ]; let blueprint = a_blueprint(courses, &db).await; for name in ["9-A", "9-B"] { - let class = ClassGroup::read(&a_class(name, &db).await, &db) + let class = class_group::read(&db, &a_class(name, &db).await) .await .unwrap() .unwrap(); @@ -743,7 +745,7 @@ mod tests { let db = crate::database::init_mem().await.unwrap(); let manager = UserId::from_key("manager"); let algebra = a_course("algebra", None, &db).await; - let class = ClassGroup::read(&a_class("9-A", &db).await, &db) + let class = class_group::read(&db, &a_class("9-A", &db).await) .await .unwrap() .unwrap(); diff --git a/src/service/class_course.rs b/src/service/class_course.rs new file mode 100644 index 0000000..de102f9 --- /dev/null +++ b/src/service/class_course.rs @@ -0,0 +1,452 @@ +//! Class-course workflows: the attach that maps the pump's refusals to this +//! route's answers, and the detach that turns a zero-row sweep into a 404. +//! The transactions live in [`crate::db::class_pump`] and +//! [`crate::db::class_course`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; +use crate::database::Database; +use crate::db::class_course; +use crate::db::class_pump::{self, Axis}; +use crate::domain::class_course::ClassCourse; +use crate::domain::class_group::ClassGroupId; +use crate::domain::course::CourseId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Attach `course` to `class` and enroll the class's whole roster into it, +/// in one transaction. +/// +/// Students already in the course keep the rows they have — no seat +/// charged, `source` untouched — and a roster that does not fit refuses the +/// whole attach rather than filling the course to its cap and stopping. +pub async fn attach( + db: &Database, + class: &ClassGroupId, + course: &CourseId, + attached_by: &UserId, +) -> Result { + let landed = class_course::attach_sourced(db, class, course, attached_by, None).await?; + // Read off the refusal, never respelled here: this route and a + // blueprint pump answer one vocabulary. `Made` is the only `None`, and + // it takes the `Ok` arm below. + let code = landed.refusal_code(&Axis::Course).unwrap_or_default(); + match landed { + class_pump::Attached::Made(saved) => Ok(saved), + class_pump::Attached::Duplicate => Err(AppError::ConflictCoded { + code, + message: "the course is already on this class".into(), + }), + // The class or the course: either end of the link being gone is a + // 404 on this route, and only a blueprint's skip list needs them + // told apart. + class_pump::Attached::Gone | class_pump::Attached::PivotGone => Err(AppError::NotFound), + class_pump::Attached::ClassFull => Err(AppError::ConflictCoded { + code, + message: format!("this class already holds {MAX_CLASS_COURSES} courses"), + }), + // The other axis: attaching one course enrolls the whole roster, so + // a class over *that* ceiling cannot take a course however few it + // carries. Only a class predating the ceiling can be here. + class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded { + code, + message: format!( + "this class holds more than {MAX_CLASS_MEMBERS} students — \ + remove some before attaching a course" + ), + }), + class_pump::Attached::Full(full) => Err(AppError::ConflictCoded { + code, + message: format!("{full} cannot hold the whole class"), + }), + // Unreachable on this axis, and kept because the match is + // exhaustive: the pair loop enrolls the roster into `$pivot` and + // nothing else, and the pivot claim already proved *that* course + // alive inside the same transaction. Only a member add walks a + // class's existing course links, so `linked_course_missing` is that + // route's alone — which is why this route's `409` does not publish + // it. Left mapped rather than folded into an `Internal`, so a future + // axis change is a wrong-looking 409, not a 500. + class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded { + code, + message: format!("{course} no longer exists — detach it from this class first"), + }), + // This path passes no source, so the claim that answers this is + // never in the transaction it ran. + class_pump::Attached::SourceGone => Err(AppError::Internal( + "a hand attach has no blueprint to lose".into(), + )), + } +} + +/// Detach `course` from `class` and sweep the enrollments the class pumped +/// into it. A course that was not attached is a [`AppError::NotFound`], +/// raised here rather than left to each caller to re-derive from a boolean. +/// +/// A student another attached class still claims keeps their row, re-tagged +/// to that class (see [`crate::db::class_pump::detach`]). +pub async fn detach( + db: &Database, + class: &ClassGroupId, + course: &CourseId, +) -> Result<(), AppError> { + let gone = class_pump::detach( + db, + "$link", + Axis::Course, + &[( + "link".into(), + crate::domain::class_course::ClassCourseId::composite(class, course) + .record() + .into_value(), + )], + ) + .await?; + (gone > 0).then_some(()).ok_or(AppError::NotFound) +} + +/// The courses a class is attached to, newest first, paged — the read behind +/// `GET /classes/{id}/courses`. +pub async fn list_for_class( + db: &Database, + class: &ClassGroupId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + class_course::list_for_class(db, class, limit, offset).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; + use crate::domain::class_course::ClassCourseId; + use crate::service::class_member; + + /// Attaching seeds the course from the roster the class already holds. + #[tokio::test] + async fn an_attach_enrolls_the_whole_roster() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + let students = [UserId::from_key("a"), UserId::from_key("b")]; + for student in &students { + class_member::add(&db, &class, student, &manager) + .await + .unwrap(); + } + + attach(&db, &class, &algebra, &manager).await.unwrap(); + for student in &students { + assert_eq!( + source_of(&algebra, student, &db).await, + Some(Some(class.clone())) + ); + } + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2); + assert_eq!(counter("class_course_count", class.record(), &db).await, 1); + + let again = attach(&db, &class, &algebra, &manager).await; + assert!( + matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"), + "a second attach is a 409 coded `duplicate`: {again:?}" + ); + } + + /// A course with room for only part of the roster takes none of it: zero + /// enrollments, the counter unmoved, and no attachment row. + #[tokio::test] + async fn a_roster_that_does_not_fit_attaches_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let class = a_class("9-A", &db).await; + let tight = a_course("algebra", Some(2), &db).await; + for student in ["a", "b", "c"] { + class_member::add(&db, &class, &UserId::from_key(student), &manager) + .await + .unwrap(); + } + + let refused = attach(&db, &class, &tight, &manager).await; + assert!( + matches!(refused, Err(AppError::ConflictCoded { code, ref message }) + if code == "course_full" && message.contains(tight.key())), + "the refusal must be coded `course_full` and name the course: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 0, + "the two seats that did fit must be given back with the third" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_course", &db).await, + 0, + "…and no attachment row may survive" + ); + assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0); + assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + } + + /// A hand-placed row is skipped on the way in and left standing on the way + /// out — the class never owned it. + #[tokio::test] + async fn a_hand_placed_row_survives_the_detach() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + crate::db::enrollment::enroll(&db, &algebra, &student, &manager) + .await + .unwrap(); + class_member::add(&db, &class, &student, &manager) + .await + .unwrap(); + + attach(&db, &class, &algebra, &manager).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "an attach may not adopt a hand-placed row" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "…nor charge a seat for it" + ); + + detach(&db, &class, &algebra).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, Some(None)); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + let again = detach(&db, &class, &algebra).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second detach is a 404: {again:?}" + ); + } + + /// Detaching with nobody else claiming the rows deletes them and gives the + /// seats back. + #[tokio::test] + async fn a_detach_sweeps_the_rows_it_pumped() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_member::add(&db, &class, &student, &manager) + .await + .unwrap(); + attach(&db, &class, &algebra, &manager).await.unwrap(); + + detach(&db, &class, &algebra).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + assert_eq!(counter("class_course_count", class.record(), &db).await, 0); + assert_eq!( + rows("SELECT VALUE id FROM class_member", &db).await, + 1, + "the two axes are independent: dropping the course may not drop \ + the student out of the class as well" + ); + } + + /// Two classes, one course, one student in both: the second attach skipped + /// the row the first wrote, so the row names only the first class — and + /// detaching *that* class must hand the row to the second rather than + /// unenroll a student the second is still responsible for. Detaching the + /// second then finds nobody left and takes the seat back. + #[tokio::test] + async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let algebra = a_course("algebra", None, &db).await; + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + for class in [&first, &second] { + class_member::add(&db, class, &student, &manager) + .await + .unwrap(); + attach(&db, class, &algebra, &manager).await.unwrap(); + } + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(first.clone())), + "the second attach must skip the row the first wrote" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "…and pay no second seat for it" + ); + + detach(&db, &first, &algebra).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(second.clone())), + "the row must be handed to the class that still claims it" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "a repair is not a release" + ); + + detach(&db, &second, &algebra).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + None, + "the last claimant leaving takes the row with it" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + } + + /// The same repair along the member axis: removing the student from the + /// class that owns the row hands it to the other class they are in. + #[tokio::test] + async fn a_member_removal_hands_a_shared_row_over_too() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let algebra = a_course("algebra", None, &db).await; + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + for class in [&first, &second] { + attach(&db, class, &algebra, &manager).await.unwrap(); + class_member::add(&db, class, &student, &manager) + .await + .unwrap(); + } + + class_member::remove(&db, &first, &student).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(Some(second.clone())), + "the student is still in the second class, so the row stays" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + + class_member::remove(&db, &second, &student).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0); + } + + /// The restore half of the pivot claim: it bumps the course's counter to + /// prove the row is there and must put it back *exactly* as it found it — + /// absent, which the boot backfill keys on (`WHERE enrollment_count = + /// NONE`). An empty roster is the case that has no seat write to hide a + /// leftover bump behind. + #[tokio::test] + async fn the_pivot_claim_gives_the_courses_counter_back_untouched() { + let db = crate::database::init_mem().await.unwrap(); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE"; + assert_eq!( + rows(absent, &db).await, + 1, + "a fresh course carries no count" + ); + + attach(&db, &class, &algebra, &UserId::from_key("manager")) + .await + .unwrap(); + assert_eq!( + rows(absent, &db).await, + 1, + "the claim's bump must be restored to absent, not to 0" + ); + } + + /// The `Menu::delete` defect on the class layer: a `class_course` row must + /// not outlive the course it names. The attach's proof that the course is + /// still there is a *write* on the course row + /// ([`crate::db::class_pump::Axis::pivot_claim`]), landing it on the + /// very key `Course::delete`'s guard writes — but only because that write + /// now *moves* the counter. The `count = count` this shipped with left the + /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write + /// set, collided with nothing, and both callers were told OK while the link + /// stayed pointing at a deleted course. + /// + /// The roster is empty deliberately — that is the only shape where nothing + /// else in the transaction touches the course row, so the claim is the + /// whole guard. One child per round, for the reason the menu twin + /// documents: a second writer makes the delete lose and re-send, and the + /// re-sent sweep clears the evidence. + /// + /// The window is opened by the schema, not by a lucky interleaving: a + /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the + /// instant the row goes, so the `SLEEP` lands between the delete and its + /// `DELETE class_course WHERE course = $course` sweep every time. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both and answers `Ok` to each, so this passes there on broken + /// code. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_class_course_link_never_outlives_the_course() { + let (db, _serialized) = crate::database::init_test_server("class_course_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let manager = UserId::from_key("manager"); + let (mut orphans, mut swept, mut miscounted) = (0, 0, 0); + for round in 0..4 { + let class = a_class(&format!("9-{round}"), &db).await; + let algebra = a_course(&format!("algebra{round}"), None, &db).await; + let course = crate::db::course::read(&db, &algebra) + .await + .unwrap() + .unwrap(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { crate::db::course::delete(&db, course).await }) + }; + // The attach starts inside the held window — the course row is gone + // but uncommitted, which is exactly what a course read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, class, algebra, manager) = + (db.clone(), class.clone(), algebra.clone(), manager.clone()); + tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the attach, or a refusal for the delete, is a correct + // answer — the only defect is stored state. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced attach must be answered, not 500: {child:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if !exists(algebra.record(), &db).await { + swept += 1; + let link = ClassCourseId::composite(&class, &algebra); + if exists(link.record(), &db).await { + orphans += 1; + } + miscounted += counter("class_course_count", class.record(), &db).await; + } else if matches!(drop_it, Ok(true)) { + panic!("round {round}: the delete reported success but the course is still there"); + } + } + eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course"); + assert!( + swept > 0, + "no round ever deleted the course, so the window was never reached" + ); + assert_eq!(orphans, 0, "a class_course link outlived its course"); + assert_eq!(miscounted, 0, "a class counts a course that is gone"); + } +} diff --git a/src/service/class_group.rs b/src/service/class_group.rs new file mode 100644 index 0000000..eecfcf2 --- /dev/null +++ b/src/service/class_group.rs @@ -0,0 +1,81 @@ +//! Class workflows: the archived-term guard every class write re-checks, and +//! the thin route-facing wrappers the handlers call. The queries live in +//! [`crate::db::class_group`]. + +use crate::database::Database; +use crate::db::class_group; +use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; +use crate::domain::term::{self, TermId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Refuse the write when this class's term is archived — a pre-flight guard, +/// accepted race (see README concurrency model): a term archived after this +/// read still lets the write through. +pub async fn require_open(db: &Database, class: &ClassGroup) -> Result<(), AppError> { + match class.get_term() { + None => Ok(()), + Some(term) => term::Term::require_open(term, db).await, + } +} + +/// Create a class, claiming the term reference in the same transaction — +/// see [`class_group::create`]. +pub async fn create( + db: &Database, + creator: &UserId, + name: ClassName, + grade: Option, + term: Option, + teacher: Option, +) -> Result { + class_group::create(db, creator, name, grade, term, teacher).await +} + +/// The row, for callers that only inspect it — the web layer's +/// `class_or_404` reads through here. +pub async fn read(db: &Database, id: &ClassGroupId) -> Result, AppError> { + class_group::read(db, id).await +} + +/// Every class, newest first — or one grade's, when `grade` narrows it: the +/// read behind the class index. +pub async fn list_all( + db: &Database, + grade: Option>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + class_group::list_all(db, grade, limit, offset).await +} + +/// The classes `ids` names, in no particular order — the join behind the two +/// membership reads. +pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result, AppError> { + class_group::list_by_ids(db, ids).await +} + +/// Write only the fields the PATCH carried; a term move claims the new term +/// and releases the old one inside the very transaction that moves the link. +pub async fn update( + db: &Database, + class: ClassGroup, + name: Option, + grade: Option>, + term: Option>, + teacher: Option>, +) -> Result { + class_group::update(db, class, name, grade, term, teacher).await +} + +/// Delete the class and give its term reference back; `false` = refused, +/// nothing was written (the class still holds students or courses). +pub async fn delete(db: &Database, class: ClassGroup) -> Result { + class_group::delete(db, class).await +} + +/// Strip `user` from every class they were the homeroom teacher of — the +/// sweep for a user demoted below `teacher`. +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { + class_group::unassign_everywhere(db, user).await +} diff --git a/src/service/class_member.rs b/src/service/class_member.rs new file mode 100644 index 0000000..3ea4166 --- /dev/null +++ b/src/service/class_member.rs @@ -0,0 +1,439 @@ +//! Class-membership workflows: the member-axis add and remove — the pump's +//! refusals mapped to this route's answers, and a zero-row sweep turned into +//! a 404 — plus the roster reads the web layer pages through. The transaction +//! itself lives in [`crate::db::class_pump`]; the table reads in +//! [`crate::db::class_member`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; +use crate::database::Database; +use crate::db::class_member; +use crate::db::class_pump::{self, Axis}; +use crate::domain::class_group::ClassGroupId; +use crate::domain::class_member::{ClassMember, ClassMemberId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// Put `user` in `class` and enroll them into every course the class is +/// already attached to, in one transaction. +/// +/// A student already enrolled in one of those courses keeps the row they +/// have — no seat is charged and their `source` is untouched, so a +/// hand-placed enrollment is never adopted by the class — and a course with +/// no free seat refuses the *whole* join rather than half of it. +pub async fn add( + db: &Database, + class: &ClassGroupId, + user: &UserId, + added_by: &UserId, +) -> Result { + let member = ClassMember { + id: ClassMemberId::composite(class, user), + class: class.clone(), + user: user.clone(), + added_by: added_by.clone(), + added_at: Some(Timestamp::now()), + }; + let landed = class_pump::attach( + db, + class, + Axis::Member, + (&member.id.record(), &member), + user.record(), + added_by.record(), + None, + ) + .await?; + // Read off the refusal, never respelled here: this route and a + // blueprint pump answer one vocabulary. `Made` is the only `None`, and + // it takes the `Ok` arm below. + let code = landed.refusal_code(&Axis::Member).unwrap_or_default(); + match landed { + class_pump::Attached::Made(saved) => Ok(saved), + class_pump::Attached::Duplicate => Err(AppError::ConflictCoded { + code, + message: "the student is already in this class".into(), + }), + class_pump::Attached::Gone => Err(AppError::NotFound), + // The pivot is the student: they were demoted while this ran, which + // is the refusal the caller's own read makes a moment earlier and + // the only one that can arrive after it. + class_pump::Attached::PivotGone => Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be added to a class", + })), + class_pump::Attached::ClassFull => Err(AppError::ConflictCoded { + code, + message: format!("this class already holds {MAX_CLASS_MEMBERS} students"), + }), + // The other axis: adding one student enrolls them into every + // attached course, so a class over *that* ceiling cannot take a + // member however much room its roster has. + class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded { + code, + message: format!( + "this class holds more than {MAX_CLASS_COURSES} courses — \ + detach some before adding a student" + ), + }), + class_pump::Attached::Full(course) => Err(AppError::ConflictCoded { + code, + message: format!("{course} is full, so the class cannot take this student"), + }), + // Not a capacity problem, and told apart from one on purpose: no + // number anyone can raise unblocks this class, only detaching the + // link the deleted course left behind. + class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded { + code, + message: format!("{course} no longer exists — detach it from this class first"), + }), + // Only an attach run on a blueprint's behalf states that claim, and + // a membership is nobody's but its own. + class_pump::Attached::SourceGone => Err(AppError::Internal( + "a class membership has no blueprint to lose".into(), + )), + } +} + +/// Take `user` out of `class` and sweep the enrollments the class pumped +/// for them. A student who was not in the class is a +/// [`AppError::NotFound`], raised here rather than left to each caller to +/// re-derive from a boolean. +/// +/// An enrollment another attached class still claims is re-tagged to that +/// class instead of deleted (see [`crate::db::class_pump::detach`]). +pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> { + let gone = class_pump::detach( + db, + "$link", + Axis::Member, + &[( + "link".into(), + ClassMemberId::composite(class, user).record().into_value(), + )], + ) + .await?; + (gone > 0).then_some(()).ok_or(AppError::NotFound) +} + +/// The class's roster, newest first, paged — the read behind +/// `GET /classes/{id}/members`. +pub async fn list_for_class( + db: &Database, + class: &ClassGroupId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + class_member::list_for_class(db, class, limit, offset).await +} + +/// The classes one student belongs to, newest membership first, paged — the +/// read behind `GET /classes/me` and `GET /classes/user/{user}`. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + class_member::list_for_user(db, user, limit, offset).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; + use crate::domain::enrollment::EnrollmentId; + use crate::service::class_course; + + /// Adding a member enrolls them into every course the class already + /// carries, each row tagged with the class, and the class's own member + /// counter ticks once. + #[tokio::test] + async fn a_member_is_enrolled_into_every_attached_course() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + let physics = a_course("physics", None, &db).await; + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + class_course::attach(&db, &class, &physics, &manager) + .await + .unwrap(); + + add(&db, &class, &student, &manager).await.unwrap(); + + for course in [&algebra, &physics] { + assert_eq!( + source_of(course, &student, &db).await, + Some(Some(class.clone())), + "every attached course must hold a row tagged with the class" + ); + assert_eq!(counter("enrollment_count", course.record(), &db).await, 1); + } + assert_eq!(counter("class_member_count", class.record(), &db).await, 1); + } + + /// The pumped row must carry the *same* composite id a hand enroll would + /// mint, or the two paths would key one pair two ways and only the unique + /// index (a 500) would notice. + #[tokio::test] + async fn a_pumped_row_uses_the_hand_enrolls_composite_id() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + add(&db, &class, &student, &manager).await.unwrap(); + + assert!( + exists(EnrollmentId::composite(&algebra, &student).record(), &db).await, + "the pump must key the pair the way Enrollment::composite does" + ); + } + + /// Re-adding is a 409, and it must cost nothing: no second counter tick and + /// no second sweep of anybody's enrollment. + #[tokio::test] + async fn a_second_add_is_refused_and_writes_nothing() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + add(&db, &class, &student, &manager).await.unwrap(); + + let again = add(&db, &class, &student, &manager).await; + assert!( + matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"), + "a second add is a 409 coded `duplicate`: {again:?}" + ); + assert_eq!( + counter("class_member_count", class.record(), &db).await, + 1, + "a refused add may not tick the counter" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + } + + /// Adding into a class whose courses have no room refuses the *whole* join: + /// the roomy course must not keep a seat the full one denied. + #[tokio::test] + async fn a_full_course_refuses_the_whole_join() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let roomy = a_course("algebra", None, &db).await; + let full = a_course("physics", Some(0), &db).await; + class_course::attach(&db, &class, &roomy, &manager) + .await + .unwrap(); + class_course::attach(&db, &class, &full, &manager) + .await + .unwrap(); + + // The whole record id, not just the key: a caller reading the 409 must + // not have to guess which table the name came from. + let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key()); + let refused = add(&db, &class, &student, &manager).await; + assert!( + matches!(refused, Err(AppError::ConflictCoded { code, ref message }) + if code == "course_full" && message.contains(&named)), + "the refusal must be coded `course_full` and name the course that had no seat \ + as {named}: {refused:?}" + ); + assert_eq!( + rows("SELECT VALUE id FROM enrollment", &db).await, + 0, + "not one seat may survive the refusal" + ); + assert_eq!( + rows("SELECT VALUE id FROM class_member", &db).await, + 0, + "…nor the membership row itself" + ); + assert_eq!( + counter("enrollment_count", roomy.record(), &db).await, + 0, + "…nor the roomy course's counter" + ); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + } + + /// A student already enrolled by hand keeps their own row: no seat is + /// charged for them, the row's `source` stays empty, and removing them from + /// the class leaves it standing. + #[tokio::test] + async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + crate::db::enrollment::enroll(&db, &algebra, &student, &manager) + .await + .unwrap(); + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + + add(&db, &class, &student, &manager).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "the class must not adopt a hand-placed row" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 1, + "the skipped pair may not be charged a second seat" + ); + + remove(&db, &class, &student).await.unwrap(); + assert_eq!( + source_of(&algebra, &student, &db).await, + Some(None), + "the sweep may only take back the rows the class wrote" + ); + assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1); + } + + /// Removal with nobody else claiming the row: the enrollment goes and its + /// seat comes back. + #[tokio::test] + async fn removal_deletes_the_rows_the_class_pumped() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + add(&db, &class, &student, &manager).await.unwrap(); + + remove(&db, &class, &student).await.unwrap(); + assert_eq!(source_of(&algebra, &student, &db).await, None); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 0, + "the seat must come back with the row that held it" + ); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + let again = remove(&db, &class, &student).await; + assert!( + matches!(again, Err(AppError::NotFound)), + "a second removal is a 404, not a second sweep: {again:?}" + ); + } + + /// A member who is not in any attached course still removes cleanly, and a + /// course deleted out from under the class leaves nothing to sweep — the + /// membership row and the pumped enrollment are independent facts. + #[tokio::test] + async fn a_sweep_tolerates_rows_a_course_delete_already_took() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + let student = UserId::from_key("student"); + let class = a_class("9-A", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_course::attach(&db, &class, &algebra, &manager) + .await + .unwrap(); + add(&db, &class, &student, &manager).await.unwrap(); + + // `Course::delete` refuses while the roster is occupied, so the wipe is + // spelled the way the cascade does it, minus the guard. + db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;") + .bind(("course", algebra.record())) + .await + .unwrap() + .check() + .unwrap(); + + remove(&db, &class, &student) + .await + .expect("the membership must still be removable with its enrollment gone"); + assert_eq!(counter("class_member_count", class.record(), &db).await, 0); + } + + /// The role-change sweep, which is one transaction with the role write + /// itself: the memberships go with their counters, the enrollment rows go + /// with their seats, and each seat comes back exactly once — the double + /// decrement the old two-call split existed to avoid. + #[tokio::test] + async fn the_role_sweep_takes_memberships_and_enrollments_together() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("manager"); + // A real row, because the sweep now rides on the role write. + let hash = crate::domain::user::Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(); + let account = crate::db::user::create( + &db, + crate::domain::user::Username::try_new("ogrenci").unwrap(), + hash, + ) + .await + .unwrap(); + let student = account.get_id().clone(); + let first = a_class("9-A", &db).await; + let second = a_class("club", &db).await; + let algebra = a_course("algebra", None, &db).await; + class_course::attach(&db, &first, &algebra, &manager) + .await + .unwrap(); + add(&db, &first, &student, &manager).await.unwrap(); + add(&db, &second, &student, &manager).await.unwrap(); + + crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher) + .await + .unwrap(); + assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0); + for class in [&first, &second] { + assert_eq!( + counter("class_member_count", class.record(), &db).await, + 0, + "every class must get its member count back" + ); + } + assert_eq!( + source_of(&algebra, &student, &db).await, + None, + "the enrollment goes in the same transaction as the membership" + ); + assert_eq!( + counter("enrollment_count", algebra.record(), &db).await, + 0, + "…and its seat comes back once, not twice" + ); + // Which is the point of folding them: the class the student was in is + // free of them entirely — no membership, no count, and no enrollment + // row left tagged with a class that is about to be deletable. + assert!( + crate::db::class_group::delete( + &db, + crate::db::class_group::read(&db, &second) + .await + .unwrap() + .unwrap(), + ) + .await + .unwrap(), + "a class holding neither members nor courses must delete" + ); + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index ee50ae2..8a1f9f6 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -9,6 +9,9 @@ pub mod builder; pub mod chatbot_message; pub mod chatbot_thread; pub mod class_blueprint; +pub mod class_course; +pub mod class_group; +pub mod class_member; pub mod course; pub mod course_session; pub mod dietary_profile; diff --git a/src/web/boards.rs b/src/web/boards.rs index 4544096..c2f0233 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -32,8 +32,7 @@ use crate::constant::MAX_BOARD_PARTICIPANTS; use crate::database::Database; use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; use crate::domain::board_stroke::BoardStroke; -use crate::domain::class_group::{ClassGroup, ClassGroupId}; -use crate::domain::class_member::ClassMember; +use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::event::EventId; use crate::domain::role::Role; @@ -727,18 +726,23 @@ impl InviteSource { )); } let class = ClassGroupId::from_key(&class); - if ClassGroup::read(&class, db).await?.is_none() { + if crate::service::class_group::read(db, &class) + .await? + .is_none() + { return Err(AppError::Validation(ValidationError::Invalid { field: "class", reason: "no such class section", })); } - Ok(ClassMember::list_for_class(&class, None, 0, db) - .await? - .0 - .iter() - .map(|member| member.get_user().clone()) - .collect()) + Ok( + crate::service::class_member::list_for_class(db, &class, None, 0) + .await? + .0 + .iter() + .map(|member| member.get_user().clone()) + .collect(), + ) } InviteSource::Course { course } => { let course = crate::service::course::read(db, &CourseId::from_key(&course)) diff --git a/src/web/classes.rs b/src/web/classes.rs index 5109c87..586643a 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -25,9 +25,9 @@ use crate::domain::course::CourseId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; -use crate::service::class_blueprint; use crate::service::parent_link::ensure_can_observe; use crate::service::term; +use crate::service::{class_blueprint, class_course, class_group, class_member}; use crate::state::AppState; use super::courses::can_manage_course; @@ -238,7 +238,7 @@ impl ClassCourseResponse { /// The class a path id names, or a 404 — every route under `/classes/{id}` /// gates on it, so a missing class never reads as an empty roster. async fn class_or_404(id: &str, db: &Database) -> Result { - ClassGroup::read(&ClassGroupId::from_key(id), db) + class_group::read(db, &ClassGroupId::from_key(id)) .await? .ok_or(AppError::NotFound) } @@ -300,7 +300,7 @@ async fn classes_page( with_creator: bool, db: &Database, ) -> Result, AppError> { - let classes = ClassGroup::list_by_ids(ids, db).await?; + let classes = class_group::list_by_ids(db, ids).await?; let by_id: std::collections::HashMap<&str, &ClassGroup> = classes .iter() .map(|class| (class.get_id().key(), class)) @@ -357,13 +357,13 @@ async fn create_class( // with this very error — so an unknown id reads the same whichever side wins. let term = term::resolve(&st.db, req.term_id.as_deref()).await?; let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?; - let class = ClassGroup::create( + let class = class_group::create( + &st.db, user.get_id(), name, grade, term, teacher.as_ref().map(|t| t.get_id().clone()), - &st.db, ) .await?; // The row is written; a demotion that raced this request's role check swept @@ -380,7 +380,7 @@ async fn create_class( // and both of its counters are still absent — so a refusal is a broken // invariant, not a client error, and it must not be reported as the // `409` whose text promises nothing was created. - if !class.clone().delete(&st.db).await? { + if !class_group::delete(&st.db, class.clone()).await? { return Err(AppError::Internal(format!( "class {} took a member or a course between its create and the \ rollback of a demoted homeroom teacher; it is still there, \ @@ -489,7 +489,7 @@ async fn list_classes( .as_deref() .map(|grade| grade_or_none(Some(grade))) .transpose()?; - let (classes, total) = ClassGroup::list_all(grade, limit, offset, &st.db).await?; + let (classes, total) = class_group::list_all(&st.db, grade, limit, offset).await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( classes.iter().flat_map(|class| class_people(class, true)), @@ -555,7 +555,7 @@ async fn update_class( let class = class_or_404(&id, &st.db).await?; // The class's *current* term, so a move off an archived year is refused // too; `term::resolve` below holds the other end (the term moved onto). - class.require_open(&st.db).await?; + class_group::require_open(&st.db, &class).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -579,15 +579,15 @@ async fn update_class( let assigned = teacher .as_ref() .and_then(|teacher| teacher.as_ref().map(|teacher| teacher.get_id().clone())); - let updated = class - .update( - name, - grade, - term, - teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())), - &st.db, - ) - .await?; + let updated = class_group::update( + &st.db, + class, + name, + grade, + term, + teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())), + ) + .await?; // Only when this request named a teacher: a PATCH that left the column // alone raced nobody's demotion (see [`undo_if_demoted`]). The undo clears // the column, which is the whole of what this request wrote to it. @@ -678,7 +678,7 @@ async fn classes_of( with_creator: bool, db: &Database, ) -> Result, AppError> { - let (rows, total) = ClassMember::list_for_user(user, limit, offset, db).await?; + let (rows, total) = class_member::list_for_user(db, user, limit, offset).await?; let ids: Vec = rows.iter().map(|row| row.get_class().clone()).collect(); classes_page(&ids, total, limit, offset, with_creator, db).await } @@ -706,8 +706,8 @@ async fn delete_class( Path(id): Path, ) -> Result { let class = class_or_404(&id, &st.db).await?; - class.require_open(&st.db).await?; - if !class.delete(&st.db).await? { + class_group::require_open(&st.db, &class).await?; + if !class_group::delete(&st.db, class).await? { return Err(AppError::Conflict( "this class still holds students or courses — remove its members and detach its courses first", )); @@ -746,7 +746,7 @@ async fn add_member( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let class = class_or_404(&id, &st.db).await?; - class.require_open(&st.db).await?; + class_group::require_open(&st.db, &class).await?; let target = UserId::from_key(&req.user_id); let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { @@ -764,7 +764,7 @@ async fn add_member( })); } - let member = ClassMember::add(class.get_id(), &target, user.get_id(), &st.db).await?; + let member = class_member::add(&st.db, class.get_id(), &target, user.get_id()).await?; let people = PersonRef::map_of(&[&target_user, &user]); Ok(( StatusCode::CREATED, @@ -797,7 +797,7 @@ async fn list_members( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let class = class_or_404(&id, &st.db).await?; - let (rows, total) = ClassMember::list_for_class(class.get_id(), limit, offset, &st.db).await?; + let (rows, total) = class_member::list_for_class(&st.db, class.get_id(), limit, offset).await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( rows.iter() @@ -839,8 +839,8 @@ async fn remove_member( Path((id, target)): Path<(String, String)>, ) -> Result { let class = class_or_404(&id, &st.db).await?; - class.require_open(&st.db).await?; - ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?; + class_group::require_open(&st.db, &class).await?; + class_member::remove(&st.db, class.get_id(), &UserId::from_key(&target)).await?; Ok(StatusCode::NO_CONTENT) } @@ -890,10 +890,10 @@ async fn attach_course( )); } // Both ends: neither a class nor a course on a past year takes a new link. - class.require_open(&st.db).await?; + class_group::require_open(&st.db, &class).await?; crate::service::course::require_open(&st.db, &course).await?; - let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; + let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?; let people = PersonRef::map_of(&[&user]); Ok(( StatusCode::CREATED, @@ -926,7 +926,7 @@ async fn list_class_courses( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let class = class_or_404(&id, &st.db).await?; - let (rows, total) = ClassCourse::list_for_class(class.get_id(), limit, offset, &st.db).await?; + let (rows, total) = class_course::list_for_class(&st.db, class.get_id(), limit, offset).await?; let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?; let items = rows .iter() @@ -982,11 +982,11 @@ async fn detach_course( } // Both ends, and only what is still there: a link whose course row is gone // has no term to read, and sweeping it is the whole point of the route. - class.require_open(&st.db).await?; + class_group::require_open(&st.db, &class).await?; if let Some(row) = row.as_ref() { crate::service::course::require_open(&st.db, row).await?; } - ClassCourse::detach(class.get_id(), &course, &st.db).await?; + class_course::detach(&st.db, class.get_id(), &course).await?; Ok(StatusCode::NO_CONTENT) } @@ -1455,7 +1455,7 @@ async fn apply_blueprint( // The pump writes both ends, so both are guarded — the class, and every // course the template would attach. A course the template names that is // already gone is the pump's own `skipped` business, not a term refusal. - class.require_open(&st.db).await?; + class_group::require_open(&st.db, &class).await?; for id in blueprint.get_courses() { if let Some(course) = crate::service::course::read(&st.db, id).await? { crate::service::course::require_open(&st.db, &course).await?; diff --git a/src/web/events.rs b/src/web/events.rs index 230473b..72feaf3 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -11,7 +11,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::{Attendance, AttendanceStatus}; -use crate::domain::class_group::{ClassGroup, ClassGroupId}; +use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; use crate::domain::role::Role; @@ -100,7 +100,10 @@ impl AudienceDto { } AudienceDto::Class { class } => { let class = ClassGroupId::from_key(&class); - if ClassGroup::read(&class, db).await?.is_none() { + if crate::service::class_group::read(db, &class) + .await? + .is_none() + { return Err(AppError::Validation(ValidationError::Invalid { field: "audience", reason: "class does not exist", diff --git a/src/web/mod.rs b/src/web/mod.rs index ab98370..33d0833 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -105,7 +105,7 @@ pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<() { return Ok(()); } - crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?; + crate::service::class_group::unassign_everywhere(db, target).await?; crate::service::course::unassign_everywhere(db, target).await?; Err(AppError::Conflict( "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry", @@ -376,7 +376,7 @@ mod tests { /// forges those (see [`crate::db::cap`]). #[tokio::test] async fn undo_if_demoted_repairs_both_assignments_or_neither() { - use crate::domain::class_group::{ClassGroup, ClassName}; + use crate::domain::class_group::ClassName; use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; use crate::domain::user::{Password, Username}; @@ -398,13 +398,13 @@ mod tests { .unwrap() .0; let assigned = async |db: &Database| { - let class = ClassGroup::create( + let class = crate::service::class_group::create( + db, &office, ClassName::try_new("9-A").unwrap(), None, None, Some(teacher.get_id().clone()), - db, ) .await .unwrap(); @@ -434,7 +434,7 @@ mod tests { db: &Database, ) -> (Option, Vec) { ( - ClassGroup::read(class, db) + crate::service::class_group::read(db, class) .await .unwrap() .unwrap() diff --git a/src/web/users.rs b/src/web/users.rs index b11b43a..a260921 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -14,8 +14,7 @@ use crate::constant::{ }; use crate::database::Database; use crate::domain::badge::{self, BadgeAward}; -use crate::domain::class_group::{ClassGroup, ClassGroupId}; -use crate::domain::class_member::ClassMember; +use crate::domain::class_group::ClassGroupId; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; @@ -927,8 +926,13 @@ async fn profile_of( courses.retain(|course| readable.contains(course.get_id())); } courses.truncate(MAX_PROFILE_COURSES); - let (mut members, class_total) = - ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?; + let (mut members, class_total) = crate::service::class_member::list_for_user( + &st.db, + id, + Some(MAX_PROFILE_CLASSES as i64), + 0, + ) + .await?; // The window is safe to take from the database here: the class gate is // all-or-nothing, so it drops the whole page or none of it — never a row // out of the middle of one. @@ -936,7 +940,7 @@ async fn profile_of( members.clear(); } let class_ids: Vec = members.iter().map(|row| row.get_class().clone()).collect(); - let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; + let classes = crate::service::class_group::list_by_ids(&st.db, &class_ids).await?; // Both totals are the full counts, not the windowed ones — the blocks are a // preview, the stats are the truth. let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?; diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index 5e29c32..174dcd3 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -9,12 +9,11 @@ use axum::http::StatusCode; use common::{Res, app_and_db, create_course, login_as, me_id, send, total}; use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS}; use hezarfen_backend::database::Database; -use hezarfen_backend::domain::class_course::ClassCourse; -use hezarfen_backend::domain::class_group::{ClassGroup, ClassName}; -use hezarfen_backend::domain::class_member::ClassMember; +use hezarfen_backend::domain::class_group::ClassName; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; +use hezarfen_backend::service::{class_course, class_group, class_member}; use serde_json::json; /// One counter, re-read out of the store — never off a response body. @@ -59,13 +58,13 @@ async fn wipe_course_row(course: &str, db: &Database) { async fn an_attach_onto_a_deleted_course_writes_no_link() { let (_app, db) = app_and_db().await; let manager = UserId::from_key("manager"); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-A").unwrap(), None, None, None, - &db, ) .await .unwrap(); @@ -73,7 +72,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() { // leaves behind. let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T"); - let refused = ClassCourse::attach(class.get_id(), &ghost, &manager, &db).await; + let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await; assert!( refused.is_err(), "attaching a course that is gone must be refused: {refused:?}" @@ -506,13 +505,13 @@ async fn the_roster_cap_is_claimed_off_the_live_capacity_column() { async fn a_roster_is_ordered_by_when_a_student_was_added() { let (_app, db) = app_and_db().await; let manager = UserId::from_key("manager"); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-A").unwrap(), None, None, None, - &db, ) .await .unwrap() @@ -525,13 +524,13 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { // which is the very order under test. let added = ["a", "c", "b"]; for key in added { - ClassMember::add(&class, &UserId::from_key(key), &manager, &db) + class_member::add(&db, &class, &UserId::from_key(key), &manager) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(2)).await; } - let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db) + let (roster, _) = class_member::list_for_class(&db, &class, None, 0) .await .unwrap(); let order: Vec<&str> = roster @@ -554,7 +553,7 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() { .unwrap() .check() .unwrap(); - let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db) + let (roster, _) = class_member::list_for_class(&db, &class, None, 0) .await .unwrap(); assert_eq!( @@ -574,13 +573,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { let (app, db) = app_and_db().await; let manager_cookie = login_as(&app, &db, "manager", "manager").await; let manager = UserId::from_key(&me_id(&app, &manager_cookie).await); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-A").unwrap(), None, None, None, - &db, ) .await .unwrap() @@ -596,13 +595,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { )); } for course in courses.iter().rev() { - ClassCourse::attach(&class, course, &manager, &db) + class_course::attach(&db, &class, course, &manager) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(2)).await; } - let (attached, _) = ClassCourse::list_for_class(&class, None, 0, &db) + let (attached, _) = class_course::list_for_class(&db, &class, None, 0) .await .unwrap(); let order: Vec<&str> = attached @@ -628,13 +627,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() { async fn a_class_refuses_the_member_past_its_ceiling() { let (_app, db) = app_and_db().await; let manager = UserId::from_key("manager"); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-A").unwrap(), None, None, None, - &db, ) .await .unwrap() @@ -648,10 +647,10 @@ async fn a_class_refuses_the_member_past_its_ceiling() { .check() .unwrap(); - ClassMember::add(&class, &UserId::from_key("last"), &manager, &db) + class_member::add(&db, &class, &UserId::from_key("last"), &manager) .await .expect("the place under the ceiling is still free"); - let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await; + let refused = class_member::add(&db, &class, &UserId::from_key("over"), &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) if code == "class_at_roster_ceiling" @@ -675,7 +674,7 @@ async fn a_class_refuses_the_member_past_its_ceiling() { .unwrap() .check() .unwrap(); - let gone = ClassMember::add(&class, &UserId::from_key("ghost"), &manager, &db).await; + let gone = class_member::add(&db, &class, &UserId::from_key("ghost"), &manager).await; assert!( matches!(gone, Err(AppError::NotFound)), "a class that is gone is a 404: {gone:?}" @@ -697,13 +696,13 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { let (app, db) = app_and_db().await; let cookie = login_as(&app, &db, "manager", "manager").await; let manager = UserId::from_key(&me_id(&app, &cookie).await); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-A").unwrap(), None, None, None, - &db, ) .await .unwrap() @@ -718,7 +717,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { .check() .unwrap(); - let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await; + let refused = class_course::attach(&db, &class, &algebra, &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) if code == "class_roster_too_large" @@ -745,7 +744,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { .unwrap() .check() .unwrap(); - ClassCourse::attach(&class, &algebra, &manager, &db) + class_course::attach(&db, &class, &algebra, &manager) .await .expect("a class exactly at the ceiling is still a bounded transaction"); } @@ -756,13 +755,13 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() { async fn a_class_over_the_course_ceiling_takes_no_member() { let (_app, db) = app_and_db().await; let manager = UserId::from_key("manager"); - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new("9-B").unwrap(), None, None, None, - &db, ) .await .unwrap() @@ -776,7 +775,7 @@ async fn a_class_over_the_course_ceiling_takes_no_member() { .check() .unwrap(); - let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await; + let refused = class_member::add(&db, &class, &UserId::from_key("ali"), &manager).await; assert!( matches!(refused, Err(AppError::ConflictCoded { code, ref message }) if code == "class_course_list_too_large" @@ -1764,21 +1763,21 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() { let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await); let mut made = Vec::new(); for name in ["9-B", "9-A"] { - let class = ClassGroup::create( + let class = class_group::create( + &db, &manager, ClassName::try_new(name).unwrap(), None, None, None, - &db, ) .await .unwrap(); let class = class.get_id().clone(); - ClassMember::add(&class, &student, &manager, &db) + class_member::add(&db, &class, &student, &manager) .await .unwrap(); - ClassCourse::attach(&class, &algebra, &manager, &db) + class_course::attach(&db, &class, &algebra, &manager) .await .unwrap(); made.push(class); @@ -1806,7 +1805,7 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() { .check() .unwrap(); - ClassCourse::detach(&owner, &algebra, &db).await.unwrap(); + class_course::detach(&db, &owner, &algebra).await.unwrap(); assert_eq!( rows("SELECT VALUE id FROM enrollment", &db).await, 0, diff --git a/tests/regress_role_sweep.rs b/tests/regress_role_sweep.rs index c71649e..9e46861 100644 --- a/tests/regress_role_sweep.rs +++ b/tests/regress_role_sweep.rs @@ -22,14 +22,14 @@ use axum::http::StatusCode; use common::{app_and_db, login_as, me_id, send}; use hezarfen_backend::database::Database; use hezarfen_backend::db::enrollment; -use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; -use hezarfen_backend::domain::class_member::ClassMember; +use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName}; use hezarfen_backend::domain::course::CourseId; use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::role::Role; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::service::registration; +use hezarfen_backend::service::{class_group, class_member}; use serde_json::json; /// How many rows `sql` selects ids for. @@ -321,13 +321,13 @@ async fn a_class(db: &Database) -> ClassGroupId { } async fn a_class_named(name: &str, db: &Database) -> ClassGroupId { - ClassGroup::create( + class_group::create( + db, &UserId::from_key("manager"), ClassName::try_new(name).unwrap(), None, None, None, - db, ) .await .unwrap() @@ -342,7 +342,7 @@ async fn a_membership_is_refused_once_the_student_is_demoted() { let class = a_class(&db).await; demote(&student, Role::Parent, &db).await; - let refused = ClassMember::add(&class, &student, &UserId::from_key("manager"), &db).await; + let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; assert!( refused.is_err(), "only students belong to a class: {refused:?}" @@ -363,13 +363,13 @@ async fn a_membership_never_survives_the_demotion_it_raced() { let class = a_class(&db).await; // The bait: a membership the sweep will delete, which holds it open. let earlier = a_class_named("9-B", &db).await; - ClassMember::add(&earlier, &student, &UserId::from_key("manager"), &db) + class_member::add(&db, &earlier, &student, &UserId::from_key("manager")) .await .unwrap(); hold_the_sweep("class_member", &db).await; let demoting = demote_in_the_window(&student, Role::Parent, &db).await; - let joined = ClassMember::add(&class, &student, &UserId::from_key("manager"), &db).await; + let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await; still_running(&demoting); demoting.await.unwrap();