forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/class'

Browse files at this commit

dc8a63522af11a255e540b08026b8b8f88fa52a3Ahmet Kaan GümüşParent: 3d88507b1261c7
# Conflicts:
#	src/db/cap.rs
#	src/domain/class_group.rs
#	src/domain/event.rs
#	src/web/classes.rs
#	src/web/users.rs
#	tests/regress_role_sweep.rs

25 changed files +2110 -1921

src/db/cap.rsmodified+1 -1
@@ -386,7 +386,7 @@ const GONE_MARK: &str = "cap_gone";
386 /// `UPDATE` that leaves the document unchanged is elided and never enters the386 /// `UPDATE` that leaves the document unchanged is elided and never enters the
387 /// write set: `SET x = x` sits on no key at all and collides with nothing387 /// write set: `SET x = x` sits on no key at all and collides with nothing
388 /// (measured on 3.2.3, and the reason388 /// (measured on 3.2.3, and the reason
389-/// [`crate::domain::class_pump::Axis::pivot_claim`] and389+/// [`crate::db::class_pump::Axis::pivot_claim`] and
390 /// [`crate::db::exam_answer::save`] have the same shape). Both390 /// [`crate::db::exam_answer::save`] have the same shape). Both
391 /// statements are inside the transaction, so an abort between them cannot leave391 /// statements are inside the transaction, so an abort between them cannot leave
392 /// the counter up.392 /// the counter up.
src/db/class_blueprint.rsmodified+3 -3
@@ -8,10 +8,10 @@ use surrealdb::types::{RecordId, SurrealValue};
8 8
9 use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD};9 use crate::constant::{CLASS_BLUEPRINT_TABLE, CLASS_COURSE_TABLE, ENROLLMENT_COUNT_FIELD};
10 use crate::database::{Database, transaction_with_retry};10 use crate::database::{Database, transaction_with_retry};
11+use crate::db::class_pump::{Axis, detach};
11 use crate::db::page::PagedList;12 use crate::db::page::PagedList;
12 use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId};13 use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId};
13 use crate::domain::class_group::{ClassGrade, ClassGroupId};14 use crate::domain::class_group::{ClassGrade, ClassGroupId};
14-use crate::domain::class_pump::{Axis, detach};
15 use crate::domain::course::CourseId;15 use crate::domain::course::CourseId;
16 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
17 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
@@ -41,7 +41,7 @@ pub struct Held {
41 /// and the list keeps an id nothing points at. [`prune`] only fires41 /// and the list keeps an id nothing points at. [`prune`] only fires
42 /// while walking a section, so at a grade carrying none the id is permanent.42 /// while walking a section, so at a grade carrying none the id is permanent.
43 ///43 ///
44-/// The claim is [`crate::domain::class_pump::Axis::pivot_claim`]'s exactly:44+/// The claim is [`crate::db::class_pump::Axis::pivot_claim`]'s exactly:
45 /// the counter is *moved* — bumped, gated, restored to the value this45 /// the counter is *moved* — bumped, gated, restored to the value this
46 /// transaction found, `NONE` included — because an `UPDATE` leaving the46 /// transaction found, `NONE` included — because an `UPDATE` leaving the
47 /// document unchanged is elided by 3.2.3 and enters no write set. Moving it47 /// document unchanged is elided by 3.2.3 and enters no write set. Moving it
@@ -330,13 +330,13 @@ pub async fn drop_links(
330 ) -> Result<(), AppError> {330 ) -> Result<(), AppError> {
331 for link in links {331 for link in links {
332 detach(332 detach(
333+ db,
333 "$link WHERE source = $blueprint",334 "$link WHERE source = $blueprint",
334 Axis::Course,335 Axis::Course,
335 &[336 &[
336 ("link".into(), link.into_value()),337 ("link".into(), link.into_value()),
337 ("blueprint".into(), id.record().into_value()),338 ("blueprint".into(), id.record().into_value()),
338 ],339 ],
339- db,
340 )340 )
341 .await?;341 .await?;
342 }342 }
src/db/class_course.rsadded+77 -0
@@ -0,0 +1,77 @@
1+//! The `class_course` table: the course-axis attach transaction and the
2+//! attachment listing. The refusals-to-errors policy and the detach that turns
3+//! a zero-row sweep into a 404 live in [`crate::service::class_course`]; the
4+//! transaction itself is the pump's, [`crate::db::class_pump`].
5+
6+use crate::constant::CLASS_COURSE_TABLE;
7+use crate::database::Database;
8+use crate::db::class_pump::{Attached, Axis};
9+use crate::db::page::PagedList;
10+use crate::domain::class_blueprint::ClassBlueprintId;
11+use crate::domain::class_course::{ClassCourse, ClassCourseId};
12+use crate::domain::class_group::ClassGroupId;
13+use crate::domain::course::CourseId;
14+use crate::domain::timestamp::Timestamp;
15+use crate::domain::user::UserId;
16+use crate::error::AppError;
17+
18+/// The attach itself, with the refusals left *unmapped*.
19+///
20+/// A hand attach ([`crate::service::class_course::attach`]) turns each of them
21+/// into the error the route answers with, because one call is one course and a
22+/// refusal is that call's whole answer. A blueprint pump cannot: it runs
23+/// one of these per (class, course), and a course that does not fit one
24+/// section must not abort the other eleven — so it needs to *read* the
25+/// refusal and carry on ([`crate::domain::class_blueprint`]).
26+///
27+/// `source` is the provenance tag, and it is written by the same statement
28+/// that writes the link, so no attachment can exist without the answer to
29+/// "may a blueprint take this back". It is also *claimed* in that
30+/// transaction ([`Attached::SourceGone`]): a blueprint deleted while this
31+/// pump ran has already swept by that tag, so a row landing afterwards
32+/// would carry a name nothing can reach.
33+pub(crate) async fn attach_sourced(
34+ db: &Database,
35+ class: &ClassGroupId,
36+ course: &CourseId,
37+ attached_by: &UserId,
38+ source: Option<&ClassBlueprintId>,
39+) -> Result<Attached<ClassCourse>, AppError> {
40+ let link = ClassCourse {
41+ id: ClassCourseId::composite(class, course),
42+ class: class.clone(),
43+ course: course.clone(),
44+ attached_by: attached_by.clone(),
45+ source: source.cloned(),
46+ attached_at: Some(Timestamp::now()),
47+ };
48+ crate::db::class_pump::attach(
49+ db,
50+ class,
51+ Axis::Course,
52+ (&link.id.record(), &link),
53+ course.record(),
54+ attached_by.record(),
55+ source.map(ClassBlueprintId::record),
56+ )
57+ .await
58+}
59+
60+/// The courses a class is attached to, newest first — by when they were
61+/// attached, not by the course's own id, which is what the composite record
62+/// id sorts on. A row older than the column carries no stamp at all, and
63+/// NONE sorts last under DESC — the honest place for a row of unknown age.
64+pub async fn list_for_class(
65+ db: &Database,
66+ class: &ClassGroupId,
67+ limit: Option<i64>,
68+ offset: i64,
69+) -> Result<(Vec<ClassCourse>, i64), AppError> {
70+ PagedList::new(
71+ format!("{CLASS_COURSE_TABLE} WHERE class = $class"),
72+ "ORDER BY attached_at DESC, id DESC",
73+ )
74+ .bind("class", class.record())
75+ .run(limit, offset, db)
76+ .await
77+}
src/db/class_group.rsadded+728 -0
@@ -0,0 +1,728 @@
1+//! The `class_group` table: the row, its term reference claimed through
2+//! [`crate::db::cap`] in the same transaction as the link, and the 0/0 delete
3+//! guard. The archived-term guard and the route-facing wrappers live in
4+//! [`crate::service::class_group`].
5+
6+use surrealdb::types::{RecordId, SurrealValue};
7+
8+use crate::constant::{CLASS_COURSE_COUNT_FIELD, CLASS_MEMBER_COUNT_FIELD, TERM_CLASS_COUNT_FIELD};
9+use crate::database::{Database, transaction_with_retry};
10+use crate::db::cap;
11+use crate::db::field_update::FieldUpdate;
12+use crate::db::page::PagedList;
13+use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
14+use crate::domain::term::{self, TermId};
15+use crate::domain::user::UserId;
16+use crate::error::AppError;
17+
18+/// The `THROW` marker the delete guard aborts with — a class that still holds
19+/// students or courses, or a class row that is no longer there.
20+const LINKS_MARK: &str = "class_links";
21+
22+/// Create the class, claiming a reference on the term it links (if any) in
23+/// the *same transaction* as the row, exactly as
24+/// [`crate::db::course::create`] does: the claim is a
25+/// conditional write on the term row, so it fails when the term is already
26+/// gone, it makes the term undeletable the instant this link exists, and no
27+/// crash can leave either half without the other.
28+pub async fn create(
29+ db: &Database,
30+ creator: &UserId,
31+ name: ClassName,
32+ grade: Option<ClassGrade>,
33+ term: Option<TermId>,
34+ teacher: Option<UserId>,
35+) -> Result<ClassGroup, AppError> {
36+ let class = ClassGroup {
37+ id: ClassGroupId::generate(),
38+ creator: creator.clone(),
39+ name,
40+ grade,
41+ term,
42+ teacher,
43+ };
44+ let id = class.id.record();
45+ let Some(term) = class.term.clone() else {
46+ let created: Option<ClassGroup> = db.create(id).content(class).await?;
47+ return created.ok_or_else(|| AppError::Internal("failed to create class".into()));
48+ };
49+ match cap::claim_and_create(
50+ &term.record(),
51+ TERM_CLASS_COUNT_FIELD,
52+ cap::UNLIMITED,
53+ &id,
54+ &class,
55+ db,
56+ )
57+ .await?
58+ {
59+ cap::Claimed::Made(created) => Ok(created),
60+ // Uncapped, so "full" can only mean the conditional write matched no
61+ // term row at all — the claim doubles as the existence check.
62+ cap::Claimed::Full => Err(term::gone_error()),
63+ // Unreachable: the id is a ULID this call just generated.
64+ cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())),
65+ }
66+}
67+
68+pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> {
69+ Ok(db.select(id.record()).await?)
70+}
71+
72+/// Every class, newest first — or one grade's, when `grade` narrows it:
73+/// `Some(Some(label))` is the sections carrying that exact label (no trim,
74+/// no case folding, matching [`list_for_grade`] and the
75+/// blueprint keyed by that very string), `Some(None)` the sections carrying
76+/// no grade at all, `None` the whole list.
77+///
78+/// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the
79+/// filtered set and a client can page through it.
80+pub async fn list_all(
81+ db: &Database,
82+ grade: Option<Option<ClassGrade>>,
83+ limit: Option<i64>,
84+ offset: i64,
85+) -> Result<(Vec<ClassGroup>, i64), AppError> {
86+ let list = match grade {
87+ None => PagedList::new("class_group", "ORDER BY id DESC"),
88+ // A gradeless class stores no `grade` key at all (SurrealDB drops a
89+ // key valued NONE), and an absent field reads back as NONE — so the
90+ // one comparison covers both spellings.
91+ Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"),
92+ Some(Some(grade)) => PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC")
93+ .bind("grade", grade.as_str().to_string()),
94+ };
95+ list.run(limit, offset, db).await
96+}
97+
98+/// Write only the fields the PATCH carried — `None` means the request
99+/// omitted it, so the column is left alone rather than re-stated from the
100+/// snapshot this struct was read into. `grade`, `term` and `teacher` are
101+/// nullable, so they take the outer/inner `Option<Option<_>>`: `None` =
102+/// omitted (keep), `Some(None)` = clear.
103+///
104+/// A term move claims the new term and releases the old one inside the very
105+/// transaction that moves the link, exactly as in
106+/// [`crate::db::course::update`]: both counters and the link
107+/// commit together, so no crash can strand a count on a term nothing links.
108+pub async fn update(
109+ db: &Database,
110+ class: ClassGroup,
111+ name: Option<ClassName>,
112+ grade: Option<Option<ClassGrade>>,
113+ term: Option<Option<TermId>>,
114+ teacher: Option<Option<UserId>>,
115+) -> Result<ClassGroup, AppError> {
116+ let (claim, release) = term::ref_move(class.term.as_ref(), &term);
117+ let expected = class.term.as_ref().map(TermId::record);
118+ FieldUpdate::new(class.id.record())
119+ .set("name", name)
120+ .set("grade", grade)
121+ .set("term", term.map(|term| term.map(|term| term.record())))
122+ // Not refcounted: a homeroom assignment is a label, so it rides the
123+ // plain `set` path and never arms the term CAS.
124+ .set(
125+ "teacher",
126+ teacher.map(|teacher| teacher.map(|teacher| teacher.record())),
127+ )
128+ .refcount(
129+ TERM_CLASS_COUNT_FIELD,
130+ "term",
131+ expected,
132+ claim,
133+ release,
134+ term::gone_error(),
135+ )
136+ .run::<ClassGroup>(db)
137+ .await
138+}
139+
140+/// The classes `ids` names, in no particular order — the join behind
141+/// "which class section is this student in", where the ids come from
142+/// `class_member` rows already paged. Ids that name no row are simply
143+/// absent.
144+pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<ClassGroup>, AppError> {
145+ if ids.is_empty() {
146+ return Ok(Vec::new());
147+ }
148+ let records: Vec<RecordId> = ids.iter().map(ClassGroupId::record).collect();
149+ let mut result = db
150+ .query("SELECT * FROM class_group WHERE id IN $ids")
151+ .bind(("ids", records))
152+ .await?
153+ .check()?;
154+ Ok(result.take::<Vec<ClassGroup>>(0)?)
155+}
156+
157+/// Every class section at one grade label, in no particular order — what a
158+/// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all
159+/// of them, and a page would silently stock only the first window.
160+pub async fn list_for_grade(
161+ db: &Database,
162+ grade: &ClassGrade,
163+) -> Result<Vec<ClassGroup>, AppError> {
164+ let mut result = db
165+ .query("SELECT * FROM class_group WHERE grade = $grade")
166+ .bind(("grade", grade.as_str().to_string()))
167+ .await?
168+ .check()?;
169+ Ok(result.take::<Vec<ClassGroup>>(0)?)
170+}
171+
172+/// Strip `user` from every class they were the homeroom teacher of — the
173+/// sweep for a user demoted below `teacher`, who may no longer hold one.
174+/// The mirror of [`crate::db::course::unassign_everywhere`];
175+/// nothing is counted on this column, so there is no reference to give back.
176+pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
177+ db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr")
178+ .bind(("usr", user.record()))
179+ .await?
180+ .check()?;
181+ Ok(())
182+}
183+
184+/// Delete the class and give its term reference back. Nothing cascades: a
185+/// class that still holds students or courses is refused outright, because
186+/// dropping it silently would leave the enrollments it pumped behind with
187+/// nothing left to sweep them.
188+///
189+/// `false` = refused, nothing was written. Both counts are read off the
190+/// class's own row, so the check and the delete are one conditional write on
191+/// one record — a member or attach racing this either claims first (and the
192+/// delete is refused) or finds the row gone (and is refused itself).
193+/// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
194+pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
195+ // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`,
196+ // which is truthy for every row and would delete a class still in use.
197+ let sql = format!(
198+ "BEGIN TRANSACTION;
199+ LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \
200+ AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
201+ IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }};
202+ FOR $row IN $gone {{
203+ IF $row.term != NONE {{
204+ UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \
205+ math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]);
206+ }};
207+ }};
208+ COMMIT TRANSACTION;"
209+ );
210+ // An aborted transaction errors *every* slot, most with a generic "not
211+ // executed" — only the THROW's own slot names the marker, and a lost
212+ // round is re-sent rather than reported (see [`transaction_with_retry`]).
213+ let (_, mut errors) = transaction_with_retry(
214+ db,
215+ &sql,
216+ &[("class".into(), class.id.record().into_value())],
217+ &[LINKS_MARK],
218+ )
219+ .await?;
220+ if errors
221+ .values()
222+ .any(|error| error.to_string().contains(LINKS_MARK))
223+ {
224+ // Still linked or already gone: the guard cannot tell those apart,
225+ // and only the refusal path pays for the extra read that can.
226+ return match read(db, &class.id).await? {
227+ Some(_) => Ok(false),
228+ None => Err(AppError::NotFound),
229+ };
230+ }
231+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
232+ return Err(error.into());
233+ }
234+ Ok(true)
235+}
236+
237+#[cfg(test)]
238+mod tests {
239+ use super::*;
240+ use crate::domain::term::{Term, TermName};
241+
242+ async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
243+ create(
244+ db,
245+ &UserId::from_key("manager"),
246+ ClassName::try_new("9-A").unwrap(),
247+ None,
248+ term,
249+ None,
250+ )
251+ .await
252+ .unwrap()
253+ }
254+
255+ /// A class with a homeroom teacher, no term.
256+ async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
257+ create(
258+ db,
259+ &UserId::from_key("manager"),
260+ ClassName::try_new("9-A").unwrap(),
261+ None,
262+ None,
263+ teacher,
264+ )
265+ .await
266+ .unwrap()
267+ }
268+
269+ /// The stored `teacher` column, re-read.
270+ async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option<UserId> {
271+ read(db, class)
272+ .await
273+ .unwrap()
274+ .unwrap()
275+ .get_teacher()
276+ .cloned()
277+ }
278+
279+ async fn a_term(db: &Database) -> Term {
280+ let at = crate::domain::timestamp::Timestamp::from_millis;
281+ Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db)
282+ .await
283+ .unwrap()
284+ }
285+
286+ /// The stored counter, re-read — never off a return value, which the
287+ /// in-memory engine forges wins on (see [`crate::db::cap`]).
288+ async fn stored_count(sql: &str, db: &Database) -> i64 {
289+ let mut result = db.query(sql).await.unwrap().check().unwrap();
290+ result
291+ .take::<Vec<i64>>(0)
292+ .unwrap()
293+ .first()
294+ .copied()
295+ .unwrap()
296+ }
297+
298+ /// The stored `class_count` on one term, absent counting as zero.
299+ async fn count_on(term: &TermId, db: &Database) -> i64 {
300+ let mut result = db
301+ .query(format!(
302+ "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term"
303+ ))
304+ .bind(("term", term.record()))
305+ .await
306+ .unwrap()
307+ .check()
308+ .unwrap();
309+ result
310+ .take::<Vec<i64>>(0)
311+ .unwrap()
312+ .first()
313+ .copied()
314+ .unwrap_or(0)
315+ }
316+
317+ /// How many rows `sql` selects ids for.
318+ async fn rows(sql: &str, db: &Database) -> usize {
319+ let mut result = db.query(sql).await.unwrap().check().unwrap();
320+ result.take::<Vec<RecordId>>(0).unwrap().len()
321+ }
322+
323+ /// The homeroom teacher survives a create, is set and cleared by a PATCH,
324+ /// and — the part a `.content(self)` save would break — is left alone by a
325+ /// PATCH of another field. A row written before the column exists carries
326+ /// no key at all, which must read back as `None`, not fail the decode.
327+ #[tokio::test]
328+ async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {
329+ let db = crate::database::init_mem().await.unwrap();
330+ let ada = UserId::from_key("ada");
331+ let boole = UserId::from_key("boole");
332+
333+ let bare = class_of(None, &db).await;
334+ assert_eq!(teacher_of(bare.get_id(), &db).await, None);
335+ let held = class_of(Some(ada.clone()), &db).await;
336+ assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada.clone()));
337+
338+ // A name-only PATCH must not re-state the teacher out of its snapshot.
339+ let renamed = update(
340+ &db,
341+ held,
342+ Some(ClassName::try_new("9-B").unwrap()),
343+ None,
344+ None,
345+ None,
346+ )
347+ .await
348+ .unwrap();
349+ assert_eq!(renamed.get_name().as_str(), "9-B");
350+ assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada));
351+
352+ let moved = update(&db, renamed, None, None, None, Some(Some(boole.clone())))
353+ .await
354+ .unwrap();
355+ assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole));
356+
357+ let cleared = update(&db, moved, None, None, None, Some(None))
358+ .await
359+ .unwrap();
360+ assert_eq!(teacher_of(cleared.get_id(), &db).await, None);
361+
362+ // …and the mirror: a teacher-only PATCH leaves the name alone.
363+ let again = update(
364+ &db,
365+ cleared,
366+ None,
367+ None,
368+ None,
369+ Some(Some(UserId::from_key("ada"))),
370+ )
371+ .await
372+ .unwrap();
373+ assert_eq!(again.get_name().as_str(), "9-B");
374+
375+ // A row that predates the column: absent key, not NULL.
376+ db.query("UPDATE $class UNSET teacher")
377+ .bind(("class", bare.get_id().record()))
378+ .await
379+ .unwrap()
380+ .check()
381+ .unwrap();
382+ assert_eq!(teacher_of(bare.get_id(), &db).await, None);
383+ }
384+
385+ /// The demotion sweep: a user who drops below `teacher` is cleared from
386+ /// *every* class they homeroomed, and nobody else's is touched.
387+ #[tokio::test]
388+ async fn unassign_everywhere_clears_only_that_users_classes() {
389+ let db = crate::database::init_mem().await.unwrap();
390+ let ada = UserId::from_key("ada");
391+ let boole = UserId::from_key("boole");
392+ let first = class_of(Some(ada.clone()), &db).await;
393+ let second = class_of(Some(ada.clone()), &db).await;
394+ let other = class_of(Some(boole.clone()), &db).await;
395+ let none = class_of(None, &db).await;
396+
397+ unassign_everywhere(&db, &ada).await.unwrap();
398+ for class in [&first, &second] {
399+ assert_eq!(
400+ teacher_of(class.get_id(), &db).await,
401+ None,
402+ "every class the demoted user homeroomed must be cleared"
403+ );
404+ }
405+ assert_eq!(
406+ teacher_of(other.get_id(), &db).await,
407+ Some(boole),
408+ "…and nobody else's"
409+ );
410+ assert_eq!(teacher_of(none.get_id(), &db).await, None);
411+ }
412+
413+ /// The bite test for the class half of the term delete guard: a term is
414+ /// undeletable while a *class* links it, on its own column, and every way
415+ /// that link can end gives the reference back. Claiming into `course_count`
416+ /// instead would pass the first assert and fail the roundtrip through boot.
417+ #[tokio::test]
418+ async fn a_term_is_deletable_only_once_no_class_links_it() {
419+ let db = crate::database::init_mem().await.unwrap();
420+ let term = a_term(&db).await;
421+
422+ let linked = class_on(Some(term.get_id().clone()), &db).await;
423+ let patched = class_on(Some(term.get_id().clone()), &db).await;
424+ assert_eq!(
425+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
426+ 2,
427+ "classes must count on class_count, not course_count"
428+ );
429+ assert_eq!(
430+ stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await,
431+ 0,
432+ "the courses' counter is seeded from course rows and must stay untouched"
433+ );
434+ assert!(
435+ !term.clone().delete(&db).await.unwrap(),
436+ "two linked classes must refuse the delete"
437+ );
438+
439+ update(&db, patched, None, None, Some(None), None)
440+ .await
441+ .unwrap();
442+ assert!(
443+ !term.clone().delete(&db).await.unwrap(),
444+ "one link is still one link"
445+ );
446+
447+ assert!(delete(&db, linked).await.unwrap());
448+ assert!(
449+ term.clone().delete(&db).await.unwrap(),
450+ "the last link gone, the term may go"
451+ );
452+ }
453+
454+ /// The bite test for the class delete guard, both arms: either count above
455+ /// zero refuses, having written nothing — the term reference least of all,
456+ /// which a refusal that released it would strand.
457+ #[tokio::test]
458+ async fn a_class_with_members_or_courses_refuses_to_delete() {
459+ for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] {
460+ let db = crate::database::init_mem().await.unwrap();
461+ let term = a_term(&db).await;
462+ let class = class_on(Some(term.get_id().clone()), &db).await;
463+ db.query(format!("UPDATE $class SET {field} = 1"))
464+ .bind(("class", class.get_id().record()))
465+ .await
466+ .unwrap()
467+ .check()
468+ .unwrap();
469+
470+ assert!(
471+ !delete(&db, class.clone()).await.unwrap(),
472+ "{field} above zero must refuse the delete"
473+ );
474+ assert!(
475+ read(&db, class.get_id()).await.unwrap().is_some(),
476+ "a refused delete may write nothing"
477+ );
478+ assert_eq!(
479+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
480+ 1,
481+ "…the term reference least of all"
482+ );
483+
484+ // Back to zero, and the same class deletes and releases the term.
485+ db.query(format!("UPDATE $class SET {field} = 0"))
486+ .bind(("class", class.get_id().record()))
487+ .await
488+ .unwrap()
489+ .check()
490+ .unwrap();
491+ assert!(delete(&db, class.clone()).await.unwrap());
492+ assert_eq!(
493+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
494+ 0
495+ );
496+ let again = delete(&db, class).await;
497+ assert!(
498+ matches!(again, Err(AppError::NotFound)),
499+ "a second delete is a 404, not a refusal: {again:?}"
500+ );
501+ }
502+ }
503+
504+ /// The class half of the invariant on the create path: a refused create
505+ /// leaves neither the row nor a count stranded on a term (which the term's
506+ /// delete guard reads, so a stray one would make it undeletable forever).
507+ #[tokio::test]
508+ async fn a_refused_create_writes_neither_row_nor_count() {
509+ let db = crate::database::init_mem().await.unwrap();
510+ let term = a_term(&db).await;
511+ let id = term.get_id().clone();
512+ assert!(term.delete(&db).await.unwrap());
513+
514+ let error = create(
515+ &db,
516+ &UserId::from_key("manager"),
517+ ClassName::try_new("9-A").unwrap(),
518+ None,
519+ Some(id),
520+ None,
521+ )
522+ .await
523+ .expect_err("a term that is gone must not be linkable");
524+ assert!(error.to_string().contains("term does not exist"));
525+ assert_eq!(
526+ rows("SELECT VALUE id FROM class_group", &db).await,
527+ 0,
528+ "a refused create may write no row"
529+ );
530+ assert_eq!(
531+ rows("SELECT VALUE id FROM term", &db).await,
532+ 0,
533+ "…and least of all a count on a term it just brought back"
534+ );
535+ }
536+
537+ /// The class mirror of
538+ /// [`crate::db::course`]'s move tests: a term move carries both
539+ /// counters with the link, and a move to a term that is gone rolls the
540+ /// release back with the abort (the transaction releases before it claims,
541+ /// so the old count would be 0 if the abort did not undo it).
542+ #[tokio::test]
543+ async fn a_class_term_move_moves_both_counts_or_neither() {
544+ let db = crate::database::init_mem().await.unwrap();
545+ let at = crate::domain::timestamp::Timestamp::from_millis;
546+ let from = a_term(&db).await;
547+ let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db)
548+ .await
549+ .unwrap();
550+ let dead = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db)
551+ .await
552+ .unwrap();
553+ let dead_id = dead.get_id().clone();
554+ assert!(dead.delete(&db).await.unwrap());
555+ let class = class_on(Some(from.get_id().clone()), &db).await;
556+
557+ let error = update(
558+ &db,
559+ class.clone(),
560+ Some(ClassName::try_new("9-B").unwrap()),
561+ None,
562+ Some(Some(dead_id)),
563+ None,
564+ )
565+ .await
566+ .expect_err("a term that is gone must not be linkable");
567+ assert!(error.to_string().contains("term does not exist"));
568+ let stored = read(&db, class.get_id()).await.unwrap().unwrap();
569+ assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
570+ assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row");
571+ assert_eq!(
572+ count_on(from.get_id(), &db).await,
573+ 1,
574+ "the release must roll back with the abort"
575+ );
576+
577+ let moved = update(
578+ &db,
579+ class,
580+ None,
581+ None,
582+ Some(Some(to.get_id().clone())),
583+ None,
584+ )
585+ .await
586+ .unwrap();
587+ assert_eq!(moved.get_term(), Some(to.get_id()));
588+ assert_eq!(
589+ count_on(from.get_id(), &db).await,
590+ 0,
591+ "the old term is free"
592+ );
593+ assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
594+ }
595+
596+ /// The class twin of
597+ /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing`
598+ /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
599+ /// PATCHes compute their counter move from the row as *they* read it, so a
600+ /// second one running on the pre-move struct would claim a second seat for
601+ /// one link (the mover) or drag the link back and strand the winner's claim
602+ /// (the re-stater, which shifts no counter at all and so is only ever
603+ /// stopped by a guard armed off the *carried column*). Both must be refused
604+ /// with the counts reading as if they never ran.
605+ #[tokio::test]
606+ async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
607+ let db = crate::database::init_mem().await.unwrap();
608+ let at = crate::domain::timestamp::Timestamp::from_millis;
609+ let from = a_term(&db).await;
610+ let to = Term::create(TermName::try_new("2027").unwrap(), at(100), at(200), &db)
611+ .await
612+ .unwrap();
613+ let other = Term::create(TermName::try_new("2028").unwrap(), at(100), at(200), &db)
614+ .await
615+ .unwrap();
616+ let class = class_on(Some(from.get_id().clone()), &db).await;
617+ let stale = class.clone();
618+ update(
619+ &db,
620+ class,
621+ None,
622+ None,
623+ Some(Some(to.get_id().clone())),
624+ None,
625+ )
626+ .await
627+ .unwrap();
628+
629+ // The mover: its snapshot says `from`, so it would release `from` and
630+ // claim `other` on top of the winner's claim on `to`.
631+ let error = update(
632+ &db,
633+ stale.clone(),
634+ None,
635+ None,
636+ Some(Some(other.get_id().clone())),
637+ None,
638+ )
639+ .await
640+ .expect_err("a mover that read a link it no longer holds must be refused");
641+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
642+ // The re-stater: shifts no counter, so only the CAS can stop it.
643+ let error = update(
644+ &db,
645+ stale.clone(),
646+ None,
647+ None,
648+ Some(Some(from.get_id().clone())),
649+ None,
650+ )
651+ .await
652+ .expect_err("re-stating a link someone else moved must be refused");
653+ assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
654+
655+ let stored = read(&db, stale.get_id()).await.unwrap().unwrap();
656+ assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
657+ assert_eq!(count_on(from.get_id(), &db).await, 0, "released once");
658+ assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
659+ assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
660+
661+ // A genuine no-op re-state still lands and still moves nothing.
662+ let same = update(
663+ &db,
664+ stored,
665+ None,
666+ None,
667+ Some(Some(to.get_id().clone())),
668+ None,
669+ )
670+ .await
671+ .expect("re-stating the link the row really holds is not a conflict");
672+ assert_eq!(same.get_term(), Some(to.get_id()));
673+ assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat");
674+ }
675+
676+ /// [`crate::db::course::delete`]'s class sweep: deleting a course
677+ /// takes its `class_course` attachments with it and gives each class its
678+ /// count back, or the classes would be undeletable forever over rows that
679+ /// point at nothing.
680+ #[tokio::test]
681+ async fn deleting_a_course_sweeps_its_class_attachments() {
682+ use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
683+
684+ let db = crate::database::init_mem().await.unwrap();
685+ let manager = UserId::from_key("manager");
686+ let course = crate::db::course::create(
687+ &db,
688+ &manager,
689+ CourseTitle::try_new("algebra").unwrap(),
690+ CourseDescription::try_new("").unwrap(),
691+ CourseKind::course(),
692+ None,
693+ None,
694+ )
695+ .await
696+ .unwrap();
697+ let class = class_on(None, &db).await;
698+ db.query(format!(
699+ "CREATE class_course SET class = $class, course = $course, attached_by = $usr;
700+ UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;"
701+ ))
702+ .bind(("class", class.get_id().record()))
703+ .bind(("course", course.get_id().record()))
704+ .bind(("usr", manager.record()))
705+ .await
706+ .unwrap()
707+ .check()
708+ .unwrap();
709+
710+ assert!(crate::db::course::delete(&db, course).await.unwrap());
711+ assert_eq!(
712+ rows("SELECT VALUE id FROM class_course", &db).await,
713+ 0,
714+ "the attachment rows must go with the course"
715+ );
716+ assert_eq!(
717+ stored_count(
718+ &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"),
719+ &db
720+ )
721+ .await,
722+ 0,
723+ "…and each class must get its count back"
724+ );
725+ // Which is the whole point: the class is deletable again.
726+ assert!(delete(&db, class).await.unwrap());
727+ }
728+}
src/db/class_member.rsadded+136 -0
@@ -0,0 +1,136 @@
1+//! The `class_member` table: the roster reads. The membership writes are the
2+//! pump's, along the member axis ([`crate::db::class_pump`]); the
3+//! refusals-to-errors policy and the detach live in
4+//! [`crate::service::class_member`].
5+
6+use crate::constant::CLASS_MEMBER_TABLE;
7+use crate::database::Database;
8+use crate::db::page::PagedList;
9+use crate::domain::class_group::ClassGroupId;
10+use crate::domain::class_member::ClassMember;
11+use crate::domain::user::UserId;
12+use crate::error::AppError;
13+
14+/// The class's roster, newest first — by when the student was added, not by
15+/// their account id, which is what the composite record id sorts on.
16+/// A row older than the column carries no stamp at all, and NONE sorts last
17+/// under DESC — which is the honest place for a row of unknown age.
18+pub async fn list_for_class(
19+ db: &Database,
20+ class: &ClassGroupId,
21+ limit: Option<i64>,
22+ offset: i64,
23+) -> Result<(Vec<ClassMember>, i64), AppError> {
24+ PagedList::new(
25+ format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),
26+ "ORDER BY added_at DESC, id DESC",
27+ )
28+ .bind("class", class.record())
29+ .run(limit, offset, db)
30+ .await
31+}
32+
33+/// The classes one student belongs to, newest membership first — the read
34+/// behind "which class section (şube) am I in". Same ordering story as
35+/// [`list_for_class`], along the other axis of the same index.
36+pub async fn list_for_user(
37+ db: &Database,
38+ user: &UserId,
39+ limit: Option<i64>,
40+ offset: i64,
41+) -> Result<(Vec<ClassMember>, i64), AppError> {
42+ PagedList::new(
43+ format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
44+ "ORDER BY added_at DESC, id DESC",
45+ )
46+ .bind("usr", user.record())
47+ .run(limit, offset, db)
48+ .await
49+}
50+
51+#[cfg(test)]
52+pub(crate) mod tests {
53+ use super::*;
54+ use crate::domain::class_group::ClassName;
55+ use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
56+ use surrealdb::types::RecordId;
57+
58+ pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
59+ crate::db::class_group::create(
60+ db,
61+ &UserId::from_key("manager"),
62+ ClassName::try_new(name).unwrap(),
63+ None,
64+ None,
65+ None,
66+ )
67+ .await
68+ .unwrap()
69+ .get_id()
70+ .clone()
71+ }
72+
73+ pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
74+ crate::db::course::create(
75+ db,
76+ &UserId::from_key("manager"),
77+ CourseTitle::try_new(title).unwrap(),
78+ CourseDescription::try_new("").unwrap(),
79+ CourseKind::course(),
80+ None,
81+ capacity,
82+ )
83+ .await
84+ .unwrap()
85+ .get_id()
86+ .clone()
87+ }
88+
89+ /// A counter, re-read out of the store — never off a return value, which
90+ /// the in-memory engine forges wins on (see [`crate::db::cap`]).
91+ pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 {
92+ let mut result = db
93+ .query(format!("SELECT VALUE {field} ?? 0 FROM $of"))
94+ .bind(("of", of))
95+ .await
96+ .unwrap()
97+ .check()
98+ .unwrap();
99+ result
100+ .take::<Vec<i64>>(0)
101+ .unwrap()
102+ .first()
103+ .copied()
104+ .unwrap()
105+ }
106+
107+ /// How many rows `sql` selects ids for.
108+ pub(crate) async fn rows(sql: &str, db: &Database) -> usize {
109+ let mut result = db.query(sql).await.unwrap().check().unwrap();
110+ result.take::<Vec<RecordId>>(0).unwrap().len()
111+ }
112+
113+ /// Whether `id` names a live row.
114+ pub(crate) async fn exists(id: RecordId, db: &Database) -> bool {
115+ let mut result = db
116+ .query("SELECT VALUE id FROM $id")
117+ .bind(("id", id))
118+ .await
119+ .unwrap()
120+ .check()
121+ .unwrap();
122+ !result.take::<Vec<RecordId>>(0).unwrap().is_empty()
123+ }
124+
125+ /// The class that wrote an enrollment, or `None` for a hand-placed row.
126+ pub(crate) async fn source_of(
127+ course: &CourseId,
128+ user: &UserId,
129+ db: &Database,
130+ ) -> Option<Option<ClassGroupId>> {
131+ crate::db::enrollment::read_for_user(db, course, user)
132+ .await
133+ .unwrap()
134+ .map(|row| row.get_source().cloned())
135+ }
136+}
src/domain/class_pump.rs → src/db/class_pump.rsrenamed+18 -18
@@ -31,7 +31,8 @@ use crate::constant::{
31 };31 };
32 use crate::database::{Database, transaction_with_retry};32 use crate::database::{Database, transaction_with_retry};
33 use crate::db::cap;33 use crate::db::cap;
34-use crate::domain::class_group::{ClassGroup, ClassGroupId};34+use crate::db::class_group;
35+use crate::domain::class_group::ClassGroupId;
35 use crate::error::AppError;36 use crate::error::AppError;
36 37
37 /// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK`38 /// The `THROW` markers [`attach`] aborts with. `FULL_MARK` and `MISSING_MARK`
@@ -386,13 +387,13 @@ impl Axis {
386 /// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and387 /// transaction runs ([`Attached::SourceGone`]). A hand attach owns itself and
387 /// passes `None`.388 /// passes `None`.
388 pub(crate) async fn attach<T: SurrealValue + Clone>(389 pub(crate) async fn attach<T: SurrealValue + Clone>(
390+ db: &Database,
389 class: &ClassGroupId,391 class: &ClassGroupId,
390 axis: Axis,392 axis: Axis,
391 new: (&RecordId, &T),393 new: (&RecordId, &T),
392 pivot: RecordId,394 pivot: RecordId,
393 by: RecordId,395 by: RecordId,
394 source: Option<RecordId>,396 source: Option<RecordId>,
395- db: &Database,
396 ) -> Result<Attached<T>, AppError> {397 ) -> Result<Attached<T>, AppError> {
397 let (link, row) = new;398 let (link, row) = new;
398 let count_field = axis.counter();399 let count_field = axis.counter();
@@ -527,7 +528,7 @@ pub(crate) async fn attach<T: SurrealValue + Clone>(
527 .values()528 .values()
528 .any(|error| error.to_string().contains(CAP_MARK))529 .any(|error| error.to_string().contains(CAP_MARK))
529 {530 {
530- return Ok(match ClassGroup::read(class, db).await? {531+ return Ok(match class_group::read(db, class).await? {
531 Some(_) => Attached::ClassFull,532 Some(_) => Attached::ClassFull,
532 None => Attached::Gone,533 None => Attached::Gone,
533 });534 });
@@ -612,10 +613,10 @@ fn named_course(message: &str, mark: &str) -> Option<String> {
612 /// the cascade can answer "already exists" and every lost round is a plain613 /// the cascade can answer "already exists" and every lost round is a plain
613 /// re-send.614 /// re-send.
614 pub(crate) async fn detach(615 pub(crate) async fn detach(
616+ db: &Database,
615 links: &str,617 links: &str,
616 axis: Axis,618 axis: Axis,
617 bindings: &[(String, Value)],619 bindings: &[(String, Value)],
618- db: &Database,
619 ) -> Result<i64, AppError> {620 ) -> Result<i64, AppError> {
620 let count_field = axis.counter();621 let count_field = axis.counter();
621 let scope = axis.scope();622 let scope = axis.scope();
@@ -680,11 +681,11 @@ pub(crate) fn link_id(table: &str, class: &ClassGroupId, other: &str) -> RecordI
680 mod tests {681 mod tests {
681 use super::*;682 use super::*;
682 use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};683 use crate::constant::{CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE};
684+ use crate::db::class_member::tests::{a_class, counter, rows};
683 use crate::domain::class_group::ClassGroupId;685 use crate::domain::class_group::ClassGroupId;
684- use crate::domain::class_member::ClassMember;
685- use crate::domain::class_member::tests::{a_class, counter, rows};
686 use crate::domain::user::UserId;686 use crate::domain::user::UserId;
687 use crate::error::AppError;687 use crate::error::AppError;
688+ use crate::service::{class_course, class_member};
688 689
689 /// The class counter is claimed conditionally, so a class that is not there690 /// The class counter is claimed conditionally, so a class that is not there
690 /// stops the cascade before anything is written — rather than leaving a691 /// stops the cascade before anything is written — rather than leaving a
@@ -695,11 +696,11 @@ mod tests {
695 let db = crate::database::init_mem().await.unwrap();696 let db = crate::database::init_mem().await.unwrap();
696 let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");697 let ghost = ClassGroupId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
697 698
698- let refused = ClassMember::add(699+ let refused = class_member::add(
700+ &db,
699 &ghost,701 &ghost,
700 &UserId::from_key("student"),702 &UserId::from_key("student"),
701 &UserId::from_key("manager"),703 &UserId::from_key("manager"),
702- &db,
703 )704 )
704 .await;705 .await;
705 assert!(706 assert!(
@@ -725,16 +726,16 @@ mod tests {
725 a_class("club", &db).await,726 a_class("club", &db).await,
726 ];727 ];
727 for class in &classes {728 for class in &classes {
728- ClassMember::add(class, &student, &manager, &db)729+ class_member::add(&db, class, &student, &manager)
729 .await730 .await
730 .unwrap();731 .unwrap();
731 }732 }
732 733
733 let gone = detach(734 let gone = detach(
735+ &db,
734 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),736 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
735 Axis::Member,737 Axis::Member,
736 &[("usr".into(), student.record().into_value())],738 &[("usr".into(), student.record().into_value())],
737- &db,
738 )739 )
739 .await740 .await
740 .unwrap();741 .unwrap();
@@ -753,10 +754,10 @@ mod tests {
753 // And a run that unlinks nothing answers zero, which is what turns a754 // And a run that unlinks nothing answers zero, which is what turns a
754 // single-pair detach into a 404 instead of a silent success.755 // single-pair detach into a 404 instead of a silent success.
755 let again = detach(756 let again = detach(
757+ &db,
756 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),758 &format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
757 Axis::Member,759 Axis::Member,
758 &[("usr".into(), student.record().into_value())],760 &[("usr".into(), student.record().into_value())],
759- &db,
760 )761 )
761 .await762 .await
762 .unwrap();763 .unwrap();
@@ -791,8 +792,7 @@ mod tests {
791 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]792 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
792 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]793 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
793 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {794 async fn a_detached_row_is_never_handed_to_a_class_that_let_it_go() {
794- use crate::domain::class_course::ClassCourse;795+ use crate::db::class_member::tests::{a_course, source_of};
795- use crate::domain::class_member::tests::{a_course, source_of};
796 796
797 let (db, _serialized) = crate::database::init_test_server("class_heir_race").await;797 let (db, _serialized) = crate::database::init_test_server("class_heir_race").await;
798 let manager = UserId::from_key("manager");798 let manager = UserId::from_key("manager");
@@ -803,10 +803,10 @@ mod tests {
803 let owner = a_class(&format!("9-{round}-owner"), &db).await;803 let owner = a_class(&format!("9-{round}-owner"), &db).await;
804 let heir = a_class(&format!("9-{round}-heir"), &db).await;804 let heir = a_class(&format!("9-{round}-heir"), &db).await;
805 for class in [&owner, &heir] {805 for class in [&owner, &heir] {
806- ClassMember::add(class, &student, &manager, &db)806+ class_member::add(&db, class, &student, &manager)
807 .await807 .await
808 .unwrap();808 .unwrap();
809- ClassCourse::attach(class, &algebra, &manager, &db)809+ class_course::attach(&db, class, &algebra, &manager)
810 .await810 .await
811 .unwrap();811 .unwrap();
812 }812 }
@@ -828,7 +828,7 @@ mod tests {
828 828
829 let detaching = {829 let detaching = {
830 let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone());830 let (db, owner, algebra) = (db.clone(), owner.clone(), algebra.clone());
831- tokio::spawn(async move { ClassCourse::detach(&owner, &algebra, &db).await })831+ tokio::spawn(async move { class_course::detach(&db, &owner, &algebra).await })
832 };832 };
833 tokio::time::sleep(std::time::Duration::from_millis(500)).await;833 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
834 assert!(834 assert!(
@@ -837,8 +837,8 @@ mod tests {
837 );837 );
838 // The heir lets the row go, twice over, while that sweep is still838 // The heir lets the row go, twice over, while that sweep is still
839 // choosing it.839 // choosing it.
840- ClassMember::remove(&heir, &student, &db).await.unwrap();840+ class_member::remove(&db, &heir, &student).await.unwrap();
841- ClassCourse::detach(&heir, &algebra, &db).await.unwrap();841+ class_course::detach(&db, &heir, &algebra).await.unwrap();
842 let swept = detaching.await.unwrap();842 let swept = detaching.await.unwrap();
843 assert!(843 assert!(
844 !matches!(swept, Err(AppError::Db(_))),844 !matches!(swept, Err(AppError::Db(_))),
src/db/enrollment.rsmodified+1 -1
@@ -43,7 +43,7 @@ const UNFIT_MARK: &str = "enroll_not_student";
43 /// landed inside this very window — and the re-send then sees that row at43 /// landed inside this very window — and the re-send then sees that row at
44 /// the `$held` gate and takes the other branch, so the loop converges44 /// the `$held` gate and takes the other branch, so the loop converges
45 /// instead of re-asking a settled question. Same shape, same reason, as45 /// instead of re-asking a settled question. Same shape, same reason, as
46-/// [`crate::domain::class_pump::attach`].46+/// [`crate::db::class_pump::attach`].
47 pub async fn enroll(47 pub async fn enroll(
48 db: &Database,48 db: &Database,
49 course: &CourseId,49 course: &CourseId,
src/db/mod.rsmodified+4 -0
@@ -9,6 +9,10 @@ pub mod cap;
9 pub mod chatbot_message;9 pub mod chatbot_message;
10 pub mod chatbot_thread;10 pub mod chatbot_thread;
11 pub mod class_blueprint;11 pub mod class_blueprint;
12+pub mod class_course;
13+pub mod class_group;
14+pub mod class_member;
15+pub mod class_pump;
12 pub mod course;16 pub mod course;
13 pub mod course_session;17 pub mod course_session;
14 pub mod dietary_profile;18 pub mod dietary_profile;
src/domain/class_blueprint.rsmodified+4 -4
@@ -3,8 +3,8 @@
3 //!3 //!
4 //! A school runs many şube at grade "9" and stocks each of them by hand, one4 //! A school runs many şube at grade "9" and stocks each of them by hand, one
5 //! attach at a time. A blueprint is that list said once. It is a layer *above*5 //! attach at a time. A blueprint is that list said once. It is a layer *above*
6-//! [`crate::domain::class_pump`], never a replacement for it: applying a6+//! [`crate::db::class_pump`], never a replacement for it: applying a
7-//! blueprint calls the same [`ClassCourse::attach`] a manager's own call does,7+//! blueprint calls the same [`crate::service::class_course::attach`] a manager's own call does,
8 //! so the rows it lands are ordinary `class_course` links and ordinary8 //! so the rows it lands are ordinary `class_course` links and ordinary
9 //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is9 //! `enrollment` rows, and an elective (seçmeli) placed by hand next to them is
10 //! still an individual enrollment nothing here can see.10 //! still an individual enrollment nothing here can see.
@@ -22,9 +22,9 @@
22 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};22 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
23 23
24 use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES};24 use crate::constant::{CLASS_BLUEPRINT_TABLE, MAX_CLASS_COURSES};
25+use crate::db::class_pump::{Attached, Axis};
25 use crate::domain::class_course::ClassCourse;26 use crate::domain::class_course::ClassCourse;
26 use crate::domain::class_group::{ClassGrade, ClassGroupId};27 use crate::domain::class_group::{ClassGrade, ClassGroupId};
27-use crate::domain::class_pump::{Attached, Axis};
28 use crate::domain::course::CourseId;28 use crate::domain::course::CourseId;
29 use crate::domain::user::UserId;29 use crate::domain::user::UserId;
30 use crate::error::{AppError, ValidationError};30 use crate::error::{AppError, ValidationError};
@@ -82,7 +82,7 @@ pub struct Skip {
82 ///82 ///
83 /// `matched` exists because an empty `skipped` is not success on its own. A83 /// `matched` exists because an empty `skipped` is not success on its own. A
84 /// grade label is free text ([`ClassGrade`]) and84 /// grade label is free text ([`ClassGrade`]) and
85-/// [`crate::domain::class_group::ClassGroup::list_for_grade`]85+/// [`crate::db::class_group::list_for_grade`]
86 /// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections86 /// matches it exactly, so a blueprint keyed `"9 "` reaches none of the sections
87 /// keyed `"9"` — and with nothing to skip it answers exactly like a pump that87 /// keyed `"9"` — and with nothing to skip it answers exactly like a pump that
88 /// stocked every one of them. The count is the only thing that tells those88 /// stocked every one of them. The count is the only thing that tells those
src/domain/class_course.rsmodified+12 -509
@@ -2,20 +2,20 @@
2 //!2 //!
3 //! The mirror of [`crate::domain::class_member`] along the pump's other axis:3 //! The mirror of [`crate::domain::class_member`] along the pump's other axis:
4 //! attaching a course enrolls the class's whole roster into it, detaching it4 //! attaching a course enrolls the class's whole roster into it, detaching it
5-//! sweeps the rows that attach wrote.5+//! sweeps the rows that attach wrote. The attach/detach workflows live in
6+//! [`crate::service::class_course`]; the row's reads in
7+//! [`crate::db::class_course`] — this file is the row shape and its
8+//! composite id.
6 9
7 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};10 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
8 11
9-use crate::constant::{CLASS_COURSE_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};12+use crate::constant::CLASS_COURSE_TABLE;
10-use crate::database::Database;13+use crate::db::class_pump::link_id;
11-use crate::db::page::PagedList;
12 use crate::domain::class_blueprint::ClassBlueprintId;14 use crate::domain::class_blueprint::ClassBlueprintId;
13 use crate::domain::class_group::ClassGroupId;15 use crate::domain::class_group::ClassGroupId;
14-use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
15 use crate::domain::course::CourseId;16 use crate::domain::course::CourseId;
16 use crate::domain::timestamp::Timestamp;17 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;18 use crate::domain::user::UserId;
18-use crate::error::AppError;
19 19
20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]20 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
21 pub struct ClassCourseId(RecordId);21 pub struct ClassCourseId(RecordId);
@@ -41,22 +41,22 @@ impl ClassCourseId {
41 /// One course a class is attached to. `attached_by` is who attached it.41 /// One course a class is attached to. `attached_by` is who attached it.
42 #[derive(Debug, Clone, SurrealValue)]42 #[derive(Debug, Clone, SurrealValue)]
43 pub struct ClassCourse {43 pub struct ClassCourse {
44- id: ClassCourseId,44+ pub(crate) id: ClassCourseId,
45- class: ClassGroupId,45+ pub(crate) class: ClassGroupId,
46- course: CourseId,46+ pub(crate) course: CourseId,
47- attached_by: UserId,47+ pub(crate) attached_by: UserId,
48 /// The grade blueprint that placed this attachment, absent when a human48 /// The grade blueprint that placed this attachment, absent when a human
49 /// attached the course to this class directly — the mirror of49 /// attached the course to this class directly — the mirror of
50 /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a50 /// [`crate::domain::enrollment`]'s `source`, and read the same way: only a
51 /// row carrying the key is a blueprint's to take back, so a hand-attached51 /// row carrying the key is a blueprint's to take back, so a hand-attached
52 /// course survives every blueprint sweep. Rows written before the column52 /// course survives every blueprint sweep. Rows written before the column
53 /// carry no key at all, which is exactly "hand-attached".53 /// carry no key at all, which is exactly "hand-attached".
54- source: Option<ClassBlueprintId>,54+ pub(crate) source: Option<ClassBlueprintId>,
55 /// When it was attached, and the *only* thing "newest first" can mean here:55 /// When it was attached, and the *only* thing "newest first" can mean here:
56 /// the row's id is the (class, course) pair, so ordering by it sorts the56 /// the row's id is the (class, course) pair, so ordering by it sorts the
57 /// list by the course's own ULID. Optional because rows written before this57 /// list by the course's own ULID. Optional because rows written before this
58 /// column carry no stamp — see the migration note.58 /// column carry no stamp — see the migration note.
59- attached_at: Option<Timestamp>,59+ pub(crate) attached_at: Option<Timestamp>,
60 }60 }
61 61
62 impl ClassCourse {62 impl ClassCourse {
@@ -80,501 +80,4 @@ impl ClassCourse {
80 pub fn get_source(&self) -> Option<&ClassBlueprintId> {80 pub fn get_source(&self) -> Option<&ClassBlueprintId> {
81 self.source.as_ref()81 self.source.as_ref()
82 }82 }
83-
84- /// Attach `course` to `class` and enroll the class's whole roster into it,
85- /// in one transaction.
86- ///
87- /// Students already in the course keep the rows they have — no seat
88- /// charged, `source` untouched — and a roster that does not fit refuses the
89- /// whole attach rather than filling the course to its cap and stopping.
90- pub async fn attach(
91- class: &ClassGroupId,
92- course: &CourseId,
93- attached_by: &UserId,
94- db: &Database,
95- ) -> Result<ClassCourse, AppError> {
96- let landed = Self::attach_sourced(class, course, attached_by, None, db).await?;
97- // Read off the refusal, never respelled here: this route and a
98- // blueprint pump answer one vocabulary. `Made` is the only `None`, and
99- // it takes the `Ok` arm below.
100- let code = landed.refusal_code(&Axis::Course).unwrap_or_default();
101- match landed {
102- Attached::Made(saved) => Ok(saved),
103- Attached::Duplicate => Err(AppError::ConflictCoded {
104- code,
105- message: "the course is already on this class".into(),
106- }),
107- // The class or the course: either end of the link being gone is a
108- // 404 on this route, and only a blueprint's skip list needs them
109- // told apart.
110- Attached::Gone | Attached::PivotGone => Err(AppError::NotFound),
111- Attached::ClassFull => Err(AppError::ConflictCoded {
112- code,
113- message: format!("this class already holds {MAX_CLASS_COURSES} courses"),
114- }),
115- // The other axis: attaching one course enrolls the whole roster, so
116- // a class over *that* ceiling cannot take a course however few it
117- // carries. Only a class predating the ceiling can be here.
118- Attached::ClassOverloaded => Err(AppError::ConflictCoded {
119- code,
120- message: format!(
121- "this class holds more than {MAX_CLASS_MEMBERS} students — \
122- remove some before attaching a course"
123- ),
124- }),
125- Attached::Full(full) => Err(AppError::ConflictCoded {
126- code,
127- message: format!("{full} cannot hold the whole class"),
128- }),
129- // Unreachable on this axis, and kept because the match is
130- // exhaustive: the pair loop enrolls the roster into `$pivot` and
131- // nothing else, and the pivot claim already proved *that* course
132- // alive inside the same transaction. Only a member add walks a
133- // class's existing course links, so `linked_course_missing` is that
134- // route's alone — which is why this route's `409` does not publish
135- // it. Left mapped rather than folded into an `Internal`, so a future
136- // axis change is a wrong-looking 409, not a 500.
137- Attached::CourseGone(course) => Err(AppError::ConflictCoded {
138- code,
139- message: format!("{course} no longer exists — detach it from this class first"),
140- }),
141- // This path passes no source, so the claim that answers this is
142- // never in the transaction it ran.
143- Attached::SourceGone => Err(AppError::Internal(
144- "a hand attach has no blueprint to lose".into(),
145- )),
146- }
147- }
148-
149- /// The attach itself, with the refusals left *unmapped*.
150- ///
151- /// A hand attach ([`ClassCourse::attach`]) turns each of them into the
152- /// error the route answers with, because one call is one course and a
153- /// refusal is that call's whole answer. A blueprint pump cannot: it runs
154- /// one of these per (class, course), and a course that does not fit one
155- /// section must not abort the other eleven — so it needs to *read* the
156- /// refusal and carry on ([`crate::domain::class_blueprint`]).
157- ///
158- /// `source` is the provenance tag, and it is written by the same statement
159- /// that writes the link, so no attachment can exist without the answer to
160- /// "may a blueprint take this back". It is also *claimed* in that
161- /// transaction ([`Attached::SourceGone`]): a blueprint deleted while this
162- /// pump ran has already swept by that tag, so a row landing afterwards
163- /// would carry a name nothing can reach.
164- pub(crate) async fn attach_sourced(
165- class: &ClassGroupId,
166- course: &CourseId,
167- attached_by: &UserId,
168- source: Option<&ClassBlueprintId>,
169- db: &Database,
170- ) -> Result<Attached<ClassCourse>, AppError> {
171- let link = ClassCourse {
172- id: ClassCourseId::composite(class, course),
173- class: class.clone(),
174- course: course.clone(),
175- attached_by: attached_by.clone(),
176- source: source.cloned(),
177- attached_at: Some(Timestamp::now()),
178- };
179- attach(
180- class,
181- Axis::Course,
182- (&link.id.record(), &link),
183- course.record(),
184- attached_by.record(),
185- source.map(ClassBlueprintId::record),
186- db,
187- )
188- .await
189- }
190-
191- /// Detach `course` from `class` and sweep the enrollments the class pumped
192- /// into it. A course that was not attached is a [`AppError::NotFound`],
193- /// raised here rather than left to each caller to re-derive from a boolean.
194- ///
195- /// A student another attached class still claims keeps their row, re-tagged
196- /// to that class (see [`crate::domain::class_pump::detach`]).
197- pub async fn detach(
198- class: &ClassGroupId,
199- course: &CourseId,
200- db: &Database,
201- ) -> Result<(), AppError> {
202- let gone = detach(
203- "$link",
204- Axis::Course,
205- &[(
206- "link".into(),
207- ClassCourseId::composite(class, course)
208- .record()
209- .into_value(),
210- )],
211- db,
212- )
213- .await?;
214- (gone > 0).then_some(()).ok_or(AppError::NotFound)
215- }
216-
217- /// The courses a class is attached to, newest first — by when they were
218- /// attached, not by the course's own id, which is what the composite record
219- /// id sorts on. A row older than the column carries no stamp at all, and
220- /// NONE sorts last under DESC — the honest place for a row of unknown age.
221- pub async fn list_for_class(
222- class: &ClassGroupId,
223- limit: Option<i64>,
224- offset: i64,
225- db: &Database,
226- ) -> Result<(Vec<ClassCourse>, i64), AppError> {
227- PagedList::new(
228- format!("{CLASS_COURSE_TABLE} WHERE class = $class"),
229- "ORDER BY attached_at DESC, id DESC",
230- )
231- .bind("class", class.record())
232- .run(limit, offset, db)
233- .await
234- }
235-}
236-
237-#[cfg(test)]
238-mod tests {
239- use super::*;
240- use crate::domain::class_member::ClassMember;
241- use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
242-
243- /// Attaching seeds the course from the roster the class already holds.
244- #[tokio::test]
245- async fn an_attach_enrolls_the_whole_roster() {
246- let db = crate::database::init_mem().await.unwrap();
247- let manager = UserId::from_key("manager");
248- let class = a_class("9-A", &db).await;
249- let algebra = a_course("algebra", None, &db).await;
250- let students = [UserId::from_key("a"), UserId::from_key("b")];
251- for student in &students {
252- ClassMember::add(&class, student, &manager, &db)
253- .await
254- .unwrap();
255- }
256-
257- ClassCourse::attach(&class, &algebra, &manager, &db)
258- .await
259- .unwrap();
260- for student in &students {
261- assert_eq!(
262- source_of(&algebra, student, &db).await,
263- Some(Some(class.clone()))
264- );
265- }
266- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2);
267- assert_eq!(counter("class_course_count", class.record(), &db).await, 1);
268-
269- let again = ClassCourse::attach(&class, &algebra, &manager, &db).await;
270- assert!(
271- matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
272- "a second attach is a 409 coded `duplicate`: {again:?}"
273- );
274- }
275-
276- /// A course with room for only part of the roster takes none of it: zero
277- /// enrollments, the counter unmoved, and no attachment row.
278- #[tokio::test]
279- async fn a_roster_that_does_not_fit_attaches_nothing() {
280- let db = crate::database::init_mem().await.unwrap();
281- let manager = UserId::from_key("manager");
282- let class = a_class("9-A", &db).await;
283- let tight = a_course("algebra", Some(2), &db).await;
284- for student in ["a", "b", "c"] {
285- ClassMember::add(&class, &UserId::from_key(student), &manager, &db)
286- .await
287- .unwrap();
288- }
289-
290- let refused = ClassCourse::attach(&class, &tight, &manager, &db).await;
291- assert!(
292- matches!(refused, Err(AppError::ConflictCoded { code, ref message })
293- if code == "course_full" && message.contains(tight.key())),
294- "the refusal must be coded `course_full` and name the course: {refused:?}"
295- );
296- assert_eq!(
297- rows("SELECT VALUE id FROM enrollment", &db).await,
298- 0,
299- "the two seats that did fit must be given back with the third"
300- );
301- assert_eq!(
302- rows("SELECT VALUE id FROM class_course", &db).await,
303- 0,
304- "…and no attachment row may survive"
305- );
306- assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0);
307- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
308- }
309-
310- /// A hand-placed row is skipped on the way in and left standing on the way
311- /// out — the class never owned it.
312- #[tokio::test]
313- async fn a_hand_placed_row_survives_the_detach() {
314- let db = crate::database::init_mem().await.unwrap();
315- let manager = UserId::from_key("manager");
316- let student = UserId::from_key("student");
317- let class = a_class("9-A", &db).await;
318- let algebra = a_course("algebra", None, &db).await;
319- crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
320- .await
321- .unwrap();
322- ClassMember::add(&class, &student, &manager, &db)
323- .await
324- .unwrap();
325-
326- ClassCourse::attach(&class, &algebra, &manager, &db)
327- .await
328- .unwrap();
329- assert_eq!(
330- source_of(&algebra, &student, &db).await,
331- Some(None),
332- "an attach may not adopt a hand-placed row"
333- );
334- assert_eq!(
335- counter("enrollment_count", algebra.record(), &db).await,
336- 1,
337- "…nor charge a seat for it"
338- );
339-
340- ClassCourse::detach(&class, &algebra, &db).await.unwrap();
341- assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
342- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
343- let again = ClassCourse::detach(&class, &algebra, &db).await;
344- assert!(
345- matches!(again, Err(AppError::NotFound)),
346- "a second detach is a 404: {again:?}"
347- );
348- }
349-
350- /// Detaching with nobody else claiming the rows deletes them and gives the
351- /// seats back.
352- #[tokio::test]
353- async fn a_detach_sweeps_the_rows_it_pumped() {
354- let db = crate::database::init_mem().await.unwrap();
355- let manager = UserId::from_key("manager");
356- let student = UserId::from_key("student");
357- let class = a_class("9-A", &db).await;
358- let algebra = a_course("algebra", None, &db).await;
359- ClassMember::add(&class, &student, &manager, &db)
360- .await
361- .unwrap();
362- ClassCourse::attach(&class, &algebra, &manager, &db)
363- .await
364- .unwrap();
365-
366- ClassCourse::detach(&class, &algebra, &db).await.unwrap();
367- assert_eq!(source_of(&algebra, &student, &db).await, None);
368- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
369- assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
370- assert_eq!(
371- rows("SELECT VALUE id FROM class_member", &db).await,
372- 1,
373- "the two axes are independent: dropping the course may not drop \
374- the student out of the class as well"
375- );
376- }
377-
378- /// Two classes, one course, one student in both: the second attach skipped
379- /// the row the first wrote, so the row names only the first class — and
380- /// detaching *that* class must hand the row to the second rather than
381- /// unenroll a student the second is still responsible for. Detaching the
382- /// second then finds nobody left and takes the seat back.
383- #[tokio::test]
384- async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
385- let db = crate::database::init_mem().await.unwrap();
386- let manager = UserId::from_key("manager");
387- let student = UserId::from_key("student");
388- let algebra = a_course("algebra", None, &db).await;
389- let first = a_class("9-A", &db).await;
390- let second = a_class("club", &db).await;
391- for class in [&first, &second] {
392- ClassMember::add(class, &student, &manager, &db)
393- .await
394- .unwrap();
395- ClassCourse::attach(class, &algebra, &manager, &db)
396- .await
397- .unwrap();
398- }
399- assert_eq!(
400- source_of(&algebra, &student, &db).await,
401- Some(Some(first.clone())),
402- "the second attach must skip the row the first wrote"
403- );
404- assert_eq!(
405- counter("enrollment_count", algebra.record(), &db).await,
406- 1,
407- "…and pay no second seat for it"
408- );
409-
410- ClassCourse::detach(&first, &algebra, &db).await.unwrap();
411- assert_eq!(
412- source_of(&algebra, &student, &db).await,
413- Some(Some(second.clone())),
414- "the row must be handed to the class that still claims it"
415- );
416- assert_eq!(
417- counter("enrollment_count", algebra.record(), &db).await,
418- 1,
419- "a repair is not a release"
420- );
421-
422- ClassCourse::detach(&second, &algebra, &db).await.unwrap();
423- assert_eq!(
424- source_of(&algebra, &student, &db).await,
425- None,
426- "the last claimant leaving takes the row with it"
427- );
428- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
429- }
430-
431- /// The same repair along the member axis: removing the student from the
432- /// class that owns the row hands it to the other class they are in.
433- #[tokio::test]
434- async fn a_member_removal_hands_a_shared_row_over_too() {
435- let db = crate::database::init_mem().await.unwrap();
436- let manager = UserId::from_key("manager");
437- let student = UserId::from_key("student");
438- let algebra = a_course("algebra", None, &db).await;
439- let first = a_class("9-A", &db).await;
440- let second = a_class("club", &db).await;
441- for class in [&first, &second] {
442- ClassCourse::attach(class, &algebra, &manager, &db)
443- .await
444- .unwrap();
445- ClassMember::add(class, &student, &manager, &db)
446- .await
447- .unwrap();
448- }
449-
450- ClassMember::remove(&first, &student, &db).await.unwrap();
451- assert_eq!(
452- source_of(&algebra, &student, &db).await,
453- Some(Some(second.clone())),
454- "the student is still in the second class, so the row stays"
455- );
456- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
457-
458- ClassMember::remove(&second, &student, &db).await.unwrap();
459- assert_eq!(source_of(&algebra, &student, &db).await, None);
460- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
461- }
462-
463- /// The restore half of the pivot claim: it bumps the course's counter to
464- /// prove the row is there and must put it back *exactly* as it found it —
465- /// absent, which the boot backfill keys on (`WHERE enrollment_count =
466- /// NONE`). An empty roster is the case that has no seat write to hide a
467- /// leftover bump behind.
468- #[tokio::test]
469- async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
470- let db = crate::database::init_mem().await.unwrap();
471- let class = a_class("9-A", &db).await;
472- let algebra = a_course("algebra", None, &db).await;
473- let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
474- assert_eq!(
475- rows(absent, &db).await,
476- 1,
477- "a fresh course carries no count"
478- );
479-
480- ClassCourse::attach(&class, &algebra, &UserId::from_key("manager"), &db)
481- .await
482- .unwrap();
483- assert_eq!(
484- rows(absent, &db).await,
485- 1,
486- "the claim's bump must be restored to absent, not to 0"
487- );
488- }
489-
490- /// The `Menu::delete` defect on the class layer: a `class_course` row must
491- /// not outlive the course it names. The attach's proof that the course is
492- /// still there is a *write* on the course row
493- /// ([`crate::domain::class_pump::Axis::pivot_claim`]), landing it on the
494- /// very key `Course::delete`'s guard writes — but only because that write
495- /// now *moves* the counter. The `count = count` this shipped with left the
496- /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write
497- /// set, collided with nothing, and both callers were told OK while the link
498- /// stayed pointing at a deleted course.
499- ///
500- /// The roster is empty deliberately — that is the only shape where nothing
501- /// else in the transaction touches the course row, so the claim is the
502- /// whole guard. One child per round, for the reason the menu twin
503- /// documents: a second writer makes the delete lose and re-send, and the
504- /// re-sent sweep clears the evidence.
505- ///
506- /// The window is opened by the schema, not by a lucky interleaving: a
507- /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the
508- /// instant the row goes, so the `SLEEP` lands between the delete and its
509- /// `DELETE class_course WHERE course = $course` sweep every time.
510- ///
511- /// Real server, and `#[ignore]`d for it: the subject *is* the store's
512- /// conflict detection, which `init_mem`'s embedded engine does not have —
513- /// it commits both and answers `Ok` to each, so this passes there on broken
514- /// code.
515- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
516- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
517- async fn a_class_course_link_never_outlives_the_course() {
518- let (db, _serialized) = crate::database::init_test_server("class_course_race").await;
519- db.query(
520- "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
521- THEN { SLEEP 1s; };",
522- )
523- .await
524- .unwrap()
525- .check()
526- .unwrap();
527-
528- let manager = UserId::from_key("manager");
529- let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
530- for round in 0..4 {
531- let class = a_class(&format!("9-{round}"), &db).await;
532- let algebra = a_course(&format!("algebra{round}"), None, &db).await;
533- let course = crate::db::course::read(&db, &algebra)
534- .await
535- .unwrap()
536- .unwrap();
537-
538- let drop_it = {
539- let db = db.clone();
540- tokio::spawn(async move { crate::db::course::delete(&db, course).await })
541- };
542- // The attach starts inside the held window — the course row is gone
543- // but uncommitted, which is exactly what a course read believes.
544- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
545- let child = {
546- let (db, class, algebra, manager) =
547- (db.clone(), class.clone(), algebra.clone(), manager.clone());
548- tokio::spawn(
549- async move { ClassCourse::attach(&class, &algebra, &manager, &db).await },
550- )
551- };
552- let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
553- // A 404 for the attach, or a refusal for the delete, is a correct
554- // answer — the only defect is stored state.
555- assert!(
556- !matches!(child, Err(AppError::Db(_))),
557- "round {round}: a raced attach must be answered, not 500: {child:?}"
558- );
559-
560- // Stored state is the whole verdict; a return value is not evidence.
561- if !exists(algebra.record(), &db).await {
562- swept += 1;
563- let link = ClassCourseId::composite(&class, &algebra);
564- if exists(link.record(), &db).await {
565- orphans += 1;
566- }
567- miscounted += counter("class_course_count", class.record(), &db).await;
568- } else if matches!(drop_it, Ok(true)) {
569- panic!("round {round}: the delete reported success but the course is still there");
570- }
571- }
572- eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");
573- assert!(
574- swept > 0,
575- "no round ever deleted the course, so the window was never reached"
576- );
577- assert_eq!(orphans, 0, "a class_course link outlived its course");
578- assert_eq!(miscounted, 0, "a class counts a course that is gone");
579- }
580 }83 }
src/domain/class_group.rsmodified+16 -723
@@ -6,31 +6,23 @@
6 //!6 //!
7 //! A class links a term exactly like a course does, and claims a reference on it7 //! A class links a term exactly like a course does, and claims a reference on it
8 //! before the link is written. The reference is its *own* column8 //! before the link is written. The reference is its *own* column
9-//! ([`TERM_CLASS_COUNT_FIELD`]) rather than the courses' `course_count`, because9+//! ([`crate::constant::TERM_CLASS_COUNT_FIELD`]) rather than the courses' `course_count`, because
10 //! boot seeds that one from the course rows alone and would wipe a class's share10 //! boot seeds that one from the course rows alone and would wipe a class's share
11 //! of it on the next migration.11 //! of it on the next migration.
12+//!
13+//! The queries live in [`crate::db::class_group`]; the archived-term guard and
14+//! the route-facing wrappers in [`crate::service::class_group`] — this file is
15+//! the row shape, its newtypes and getters.
12 16
13 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};17 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14 18
15-use crate::constant::{19+use crate::constant::{CLASS_GROUP_TABLE, MAX_CLASS_GRADE_LEN, MAX_CLASS_NAME_LEN};
16- CLASS_COURSE_COUNT_FIELD, CLASS_GROUP_TABLE, CLASS_MEMBER_COUNT_FIELD, MAX_CLASS_GRADE_LEN,
17- MAX_CLASS_NAME_LEN, TERM_CLASS_COUNT_FIELD,
18-};
19-use crate::database::{Database, transaction_with_retry};
20-use crate::db::cap;
21-use crate::db::field_update::FieldUpdate;
22-use crate::db::page::PagedList;
23 use crate::domain::monotonic_id::next_ulid;20 use crate::domain::monotonic_id::next_ulid;
24-use crate::domain::term::{TermId, gone_error, ref_move};21+use crate::domain::term::TermId;
25 use crate::domain::user::UserId;22 use crate::domain::user::UserId;
26-use crate::error::{AppError, ValidationError};23+use crate::error::ValidationError;
27-use crate::service::term;
28 use crate::validate::{validate_optional, validate_required};24 use crate::validate::{validate_optional, validate_required};
29 25
30-/// The `THROW` marker the delete guard aborts with — a class that still holds
31-/// students or courses, or a class row that is no longer there.
32-const LINKS_MARK: &str = "class_links";
33-
34 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]26 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
35 pub struct ClassGroupId(RecordId);27 pub struct ClassGroupId(RecordId);
36 28
@@ -93,16 +85,16 @@ impl ClassGrade {
93 /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not85 /// `teacher` is the section's homeroom teacher (sınıf öğretmeni): optional, not
94 /// refcounted, and merely a label pointing at a teacher-or-higher account — the86 /// refcounted, and merely a label pointing at a teacher-or-higher account — the
95 /// web layer holds that bar, and a demotion sweeps the column87 /// web layer holds that bar, and a demotion sweeps the column
96-/// ([`ClassGroup::unassign_everywhere`]). Rows written before the column exists88+/// ([`crate::db::class_group::unassign_everywhere`]). Rows written before the
97-/// carry no key at all, which reads back as `None`.89+/// column exists carry no key at all, which reads back as `None`.
98 #[derive(Debug, Clone, SurrealValue)]90 #[derive(Debug, Clone, SurrealValue)]
99 pub struct ClassGroup {91 pub struct ClassGroup {
100- id: ClassGroupId,92+ pub(crate) id: ClassGroupId,
101- creator: UserId,93+ pub(crate) creator: UserId,
102- name: ClassName,94+ pub(crate) name: ClassName,
103- grade: Option<ClassGrade>,95+ pub(crate) grade: Option<ClassGrade>,
104- term: Option<TermId>,96+ pub(crate) term: Option<TermId>,
105- teacher: Option<UserId>,97+ pub(crate) teacher: Option<UserId>,
106 }98 }
107 99
108 impl ClassGroup {100 impl ClassGroup {
@@ -126,16 +118,6 @@ impl ClassGroup {
126 self.term.as_ref()118 self.term.as_ref()
127 }119 }
128 120
129- /// Refuse the write when this class's term is archived — a pre-flight guard,
130- /// accepted race (see README concurrency model): a term archived after this
131- /// read still lets the write through.
132- pub async fn require_open(&self, db: &Database) -> Result<(), AppError> {
133- match self.get_term() {
134- None => Ok(()),
135- Some(term) => term::require_open(db, term).await,
136- }
137- }
138-
139 /// The homeroom teacher (sınıf öğretmeni), if one is assigned.121 /// The homeroom teacher (sınıf öğretmeni), if one is assigned.
140 pub fn get_teacher(&self) -> Option<&UserId> {122 pub fn get_teacher(&self) -> Option<&UserId> {
141 self.teacher.as_ref()123 self.teacher.as_ref()
@@ -144,313 +126,11 @@ impl ClassGroup {
144 pub fn is_creator(&self, user: &UserId) -> bool {126 pub fn is_creator(&self, user: &UserId) -> bool {
145 &self.creator == user127 &self.creator == user
146 }128 }
147-
148- /// Create the class, claiming a reference on the term it links (if any) in
149- /// the *same transaction* as the row, exactly as
150- /// [`crate::db::course::create`] does: the claim is a
151- /// conditional write on the term row, so it fails when the term is already
152- /// gone, it makes the term undeletable the instant this link exists, and no
153- /// crash can leave either half without the other.
154- pub async fn create(
155- creator: &UserId,
156- name: ClassName,
157- grade: Option<ClassGrade>,
158- term: Option<TermId>,
159- teacher: Option<UserId>,
160- db: &Database,
161- ) -> Result<ClassGroup, AppError> {
162- let class = ClassGroup {
163- id: ClassGroupId::generate(),
164- creator: creator.clone(),
165- name,
166- grade,
167- term,
168- teacher,
169- };
170- let id = class.id.record();
171- let Some(term) = class.term.clone() else {
172- let created: Option<ClassGroup> = db.create(id).content(class).await?;
173- return created.ok_or_else(|| AppError::Internal("failed to create class".into()));
174- };
175- match cap::claim_and_create(
176- &term.record(),
177- TERM_CLASS_COUNT_FIELD,
178- cap::UNLIMITED,
179- &id,
180- &class,
181- db,
182- )
183- .await?
184- {
185- cap::Claimed::Made(created) => Ok(created),
186- // Uncapped, so "full" can only mean the conditional write matched no
187- // term row at all — the claim doubles as the existence check.
188- cap::Claimed::Full => Err(gone_error()),
189- // Unreachable: the id is a ULID this call just generated.
190- cap::Claimed::Duplicate => Err(AppError::Internal("failed to create class".into())),
191- }
192- }
193-
194- pub async fn read(id: &ClassGroupId, db: &Database) -> Result<Option<ClassGroup>, AppError> {
195- Ok(db.select(id.record()).await?)
196- }
197-
198- /// Every class, newest first — or one grade's, when `grade` narrows it:
199- /// `Some(Some(label))` is the sections carrying that exact label (no trim,
200- /// no case folding, matching [`ClassGroup::list_for_grade`] and the
201- /// blueprint keyed by that very string), `Some(None)` the sections carrying
202- /// no grade at all, `None` the whole list.
203- ///
204- /// The narrowing is the `WHERE`, so the `total` [`PagedList`] counts is the
205- /// filtered set and a client can page through it.
206- pub async fn list_all(
207- grade: Option<Option<ClassGrade>>,
208- limit: Option<i64>,
209- offset: i64,
210- db: &Database,
211- ) -> Result<(Vec<ClassGroup>, i64), AppError> {
212- let list = match grade {
213- None => PagedList::new("class_group", "ORDER BY id DESC"),
214- // A gradeless class stores no `grade` key at all (SurrealDB drops a
215- // key valued NONE), and an absent field reads back as NONE — so the
216- // one comparison covers both spellings.
217- Some(None) => PagedList::new("class_group WHERE grade IS NONE", "ORDER BY id DESC"),
218- Some(Some(grade)) => {
219- PagedList::new("class_group WHERE grade = $grade", "ORDER BY id DESC")
220- .bind("grade", grade.as_str().to_string())
221- }
222- };
223- list.run(limit, offset, db).await
224- }
225-
226- /// Write only the fields the PATCH carried — `None` means the request
227- /// omitted it, so the column is left alone rather than re-stated from the
228- /// snapshot this struct was read into. `grade`, `term` and `teacher` are
229- /// nullable, so they take the outer/inner `Option<Option<_>>`: `None` =
230- /// omitted (keep), `Some(None)` = clear.
231- ///
232- /// A term move claims the new term and releases the old one inside the very
233- /// transaction that moves the link, exactly as in
234- /// [`crate::db::course::update`]: both counters and the link
235- /// commit together, so no crash can strand a count on a term nothing links.
236- pub async fn update(
237- self,
238- name: Option<ClassName>,
239- grade: Option<Option<ClassGrade>>,
240- term: Option<Option<TermId>>,
241- teacher: Option<Option<UserId>>,
242- db: &Database,
243- ) -> Result<ClassGroup, AppError> {
244- let (claim, release) = ref_move(self.term.as_ref(), &term);
245- let expected = self.term.as_ref().map(TermId::record);
246- FieldUpdate::new(self.id.record())
247- .set("name", name)
248- .set("grade", grade)
249- .set("term", term.map(|term| term.map(|term| term.record())))
250- // Not refcounted: a homeroom assignment is a label, so it rides the
251- // plain `set` path and never arms the term CAS.
252- .set(
253- "teacher",
254- teacher.map(|teacher| teacher.map(|teacher| teacher.record())),
255- )
256- .refcount(
257- TERM_CLASS_COUNT_FIELD,
258- "term",
259- expected,
260- claim,
261- release,
262- gone_error(),
263- )
264- .run::<ClassGroup>(db)
265- .await
266- }
267-
268- /// The classes `ids` names, in no particular order — the join behind
269- /// "which class section is this student in", where the ids come from
270- /// `class_member` rows already paged. Ids that name no row are simply
271- /// absent.
272- pub async fn list_by_ids(
273- ids: &[ClassGroupId],
274- db: &Database,
275- ) -> Result<Vec<ClassGroup>, AppError> {
276- if ids.is_empty() {
277- return Ok(Vec::new());
278- }
279- let records: Vec<RecordId> = ids.iter().map(ClassGroupId::record).collect();
280- let mut result = db
281- .query("SELECT * FROM class_group WHERE id IN $ids")
282- .bind(("ids", records))
283- .await?
284- .check()?;
285- Ok(result.take::<Vec<ClassGroup>>(0)?)
286- }
287-
288- /// Every class section at one grade label, in no particular order — what a
289- /// grade blueprint pumps. Unpaged on purpose: the caller is reconciling all
290- /// of them, and a page would silently stock only the first window.
291- pub async fn list_for_grade(
292- grade: &ClassGrade,
293- db: &Database,
294- ) -> Result<Vec<ClassGroup>, AppError> {
295- let mut result = db
296- .query("SELECT * FROM class_group WHERE grade = $grade")
297- .bind(("grade", grade.as_str().to_string()))
298- .await?
299- .check()?;
300- Ok(result.take::<Vec<ClassGroup>>(0)?)
301- }
302-
303- /// Strip `user` from every class they were the homeroom teacher of — the
304- /// sweep for a user demoted below `teacher`, who may no longer hold one.
305- /// The mirror of [`crate::db::course::unassign_everywhere`];
306- /// nothing is counted on this column, so there is no reference to give back.
307- pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> {
308- db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr")
309- .bind(("usr", user.record()))
310- .await?
311- .check()?;
312- Ok(())
313- }
314-
315- /// Delete the class and give its term reference back. Nothing cascades: a
316- /// class that still holds students or courses is refused outright, because
317- /// dropping it silently would leave the enrollments it pumped behind with
318- /// nothing left to sweep them.
319- ///
320- /// `false` = refused, nothing was written. Both counts are read off the
321- /// class's own row, so the check and the delete are one conditional write on
322- /// one record — a member or attach racing this either claims first (and the
323- /// delete is refused) or finds the row gone (and is refused itself).
324- /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
325- pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
326- // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`,
327- // which is truthy for every row and would delete a class still in use.
328- let sql = format!(
329- "BEGIN TRANSACTION;
330- LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \
331- AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
332- IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }};
333- FOR $row IN $gone {{
334- IF $row.term != NONE {{
335- UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \
336- math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]);
337- }};
338- }};
339- COMMIT TRANSACTION;"
340- );
341- // An aborted transaction errors *every* slot, most with a generic "not
342- // executed" — only the THROW's own slot names the marker, and a lost
343- // round is re-sent rather than reported (see [`transaction_with_retry`]).
344- let (_, mut errors) = transaction_with_retry(
345- db,
346- &sql,
347- &[("class".into(), self.id.record().into_value())],
348- &[LINKS_MARK],
349- )
350- .await?;
351- if errors
352- .values()
353- .any(|error| error.to_string().contains(LINKS_MARK))
354- {
355- // Still linked or already gone: the guard cannot tell those apart,
356- // and only the refusal path pays for the extra read that can.
357- return match Self::read(&self.id, db).await? {
358- Some(_) => Ok(false),
359- None => Err(AppError::NotFound),
360- };
361- }
362- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
363- return Err(error.into());
364- }
365- Ok(true)
366- }
367 }129 }
368 130
369 #[cfg(test)]131 #[cfg(test)]
370 mod tests {132 mod tests {
371 use super::*;133 use super::*;
372- use crate::domain::term::{Term, TermName};
373-
374- async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
375- ClassGroup::create(
376- &UserId::from_key("manager"),
377- ClassName::try_new("9-A").unwrap(),
378- None,
379- term,
380- None,
381- db,
382- )
383- .await
384- .unwrap()
385- }
386-
387- /// A class with a homeroom teacher, no term.
388- async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup {
389- ClassGroup::create(
390- &UserId::from_key("manager"),
391- ClassName::try_new("9-A").unwrap(),
392- None,
393- None,
394- teacher,
395- db,
396- )
397- .await
398- .unwrap()
399- }
400-
401- /// The stored `teacher` column, re-read.
402- async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option<UserId> {
403- ClassGroup::read(class, db)
404- .await
405- .unwrap()
406- .unwrap()
407- .get_teacher()
408- .cloned()
409- }
410-
411- async fn a_term(db: &Database) -> Term {
412- let at = crate::domain::timestamp::Timestamp::from_millis;
413- crate::db::term::create(db, TermName::try_new("2026").unwrap(), at(100), at(200))
414- .await
415- .unwrap()
416- }
417-
418- /// The stored counter, re-read — never off a return value, which the
419- /// in-memory engine forges wins on (see [`crate::db::cap`]).
420- async fn stored_count(sql: &str, db: &Database) -> i64 {
421- let mut result = db.query(sql).await.unwrap().check().unwrap();
422- result
423- .take::<Vec<i64>>(0)
424- .unwrap()
425- .first()
426- .copied()
427- .unwrap()
428- }
429-
430- /// The stored `class_count` on one term, absent counting as zero.
431- async fn count_on(term: &TermId, db: &Database) -> i64 {
432- let mut result = db
433- .query(format!(
434- "SELECT VALUE ({TERM_CLASS_COUNT_FIELD} ?? 0) FROM $term"
435- ))
436- .bind(("term", term.record()))
437- .await
438- .unwrap()
439- .check()
440- .unwrap();
441- result
442- .take::<Vec<i64>>(0)
443- .unwrap()
444- .first()
445- .copied()
446- .unwrap_or(0)
447- }
448-
449- /// How many rows `sql` selects ids for.
450- async fn rows(sql: &str, db: &Database) -> usize {
451- let mut result = db.query(sql).await.unwrap().check().unwrap();
452- result.take::<Vec<RecordId>>(0).unwrap().len()
453- }
454 134
455 #[test]135 #[test]
456 fn name_is_required_and_grade_is_optional() {136 fn name_is_required_and_grade_is_optional() {
@@ -462,391 +142,4 @@ mod tests {
462 assert!(ClassGrade::try_new("anaokulu").is_ok());142 assert!(ClassGrade::try_new("anaokulu").is_ok());
463 assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err());143 assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err());
464 }144 }
465-
466- /// The homeroom teacher survives a create, is set and cleared by a PATCH,
467- /// and — the part a `.content(self)` save would break — is left alone by a
468- /// PATCH of another field. A row written before the column exists carries
469- /// no key at all, which must read back as `None`, not fail the decode.
470- #[tokio::test]
471- async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() {
472- let db = crate::database::init_mem().await.unwrap();
473- let ada = UserId::from_key("ada");
474- let boole = UserId::from_key("boole");
475-
476- let bare = class_of(None, &db).await;
477- assert_eq!(teacher_of(bare.get_id(), &db).await, None);
478- let held = class_of(Some(ada.clone()), &db).await;
479- assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada.clone()));
480-
481- // A name-only PATCH must not re-state the teacher out of its snapshot.
482- let renamed = held
483- .update(
484- Some(ClassName::try_new("9-B").unwrap()),
485- None,
486- None,
487- None,
488- &db,
489- )
490- .await
491- .unwrap();
492- assert_eq!(renamed.get_name().as_str(), "9-B");
493- assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada));
494-
495- let moved = renamed
496- .update(None, None, None, Some(Some(boole.clone())), &db)
497- .await
498- .unwrap();
499- assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole));
500-
501- let cleared = moved
502- .update(None, None, None, Some(None), &db)
503- .await
504- .unwrap();
505- assert_eq!(teacher_of(cleared.get_id(), &db).await, None);
506-
507- // …and the mirror: a teacher-only PATCH leaves the name alone.
508- let again = cleared
509- .update(None, None, None, Some(Some(UserId::from_key("ada"))), &db)
510- .await
511- .unwrap();
512- assert_eq!(again.get_name().as_str(), "9-B");
513-
514- // A row that predates the column: absent key, not NULL.
515- db.query("UPDATE $class UNSET teacher")
516- .bind(("class", bare.get_id().record()))
517- .await
518- .unwrap()
519- .check()
520- .unwrap();
521- assert_eq!(teacher_of(bare.get_id(), &db).await, None);
522- }
523-
524- /// The demotion sweep: a user who drops below `teacher` is cleared from
525- /// *every* class they homeroomed, and nobody else's is touched.
526- #[tokio::test]
527- async fn unassign_everywhere_clears_only_that_users_classes() {
528- let db = crate::database::init_mem().await.unwrap();
529- let ada = UserId::from_key("ada");
530- let boole = UserId::from_key("boole");
531- let first = class_of(Some(ada.clone()), &db).await;
532- let second = class_of(Some(ada.clone()), &db).await;
533- let other = class_of(Some(boole.clone()), &db).await;
534- let none = class_of(None, &db).await;
535-
536- ClassGroup::unassign_everywhere(&ada, &db).await.unwrap();
537- for class in [&first, &second] {
538- assert_eq!(
539- teacher_of(class.get_id(), &db).await,
540- None,
541- "every class the demoted user homeroomed must be cleared"
542- );
543- }
544- assert_eq!(
545- teacher_of(other.get_id(), &db).await,
546- Some(boole),
547- "…and nobody else's"
548- );
549- assert_eq!(teacher_of(none.get_id(), &db).await, None);
550- }
551-
552- /// The bite test for the class half of the term delete guard: a term is
553- /// undeletable while a *class* links it, on its own column, and every way
554- /// that link can end gives the reference back. Claiming into `course_count`
555- /// instead would pass the first assert and fail the roundtrip through boot.
556- #[tokio::test]
557- async fn a_term_is_deletable_only_once_no_class_links_it() {
558- let db = crate::database::init_mem().await.unwrap();
559- let term = a_term(&db).await;
560-
561- let linked = class_on(Some(term.get_id().clone()), &db).await;
562- let patched = class_on(Some(term.get_id().clone()), &db).await;
563- assert_eq!(
564- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
565- 2,
566- "classes must count on class_count, not course_count"
567- );
568- assert_eq!(
569- stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await,
570- 0,
571- "the courses' counter is seeded from course rows and must stay untouched"
572- );
573- assert!(
574- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
575- "two linked classes must refuse the delete"
576- );
577-
578- patched
579- .update(None, None, Some(None), None, &db)
580- .await
581- .unwrap();
582- assert!(
583- !crate::db::term::delete(&db, term.clone()).await.unwrap(),
584- "one link is still one link"
585- );
586-
587- assert!(linked.delete(&db).await.unwrap());
588- assert!(
589- crate::db::term::delete(&db, term.clone()).await.unwrap(),
590- "the last link gone, the term may go"
591- );
592- }
593-
594- /// The bite test for the class delete guard, both arms: either count above
595- /// zero refuses, having written nothing — the term reference least of all,
596- /// which a refusal that released it would strand.
597- #[tokio::test]
598- async fn a_class_with_members_or_courses_refuses_to_delete() {
599- for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] {
600- let db = crate::database::init_mem().await.unwrap();
601- let term = a_term(&db).await;
602- let class = class_on(Some(term.get_id().clone()), &db).await;
603- db.query(format!("UPDATE $class SET {field} = 1"))
604- .bind(("class", class.get_id().record()))
605- .await
606- .unwrap()
607- .check()
608- .unwrap();
609-
610- assert!(
611- !class.clone().delete(&db).await.unwrap(),
612- "{field} above zero must refuse the delete"
613- );
614- assert!(
615- ClassGroup::read(class.get_id(), &db)
616- .await
617- .unwrap()
618- .is_some(),
619- "a refused delete may write nothing"
620- );
621- assert_eq!(
622- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
623- 1,
624- "…the term reference least of all"
625- );
626-
627- // Back to zero, and the same class deletes and releases the term.
628- db.query(format!("UPDATE $class SET {field} = 0"))
629- .bind(("class", class.get_id().record()))
630- .await
631- .unwrap()
632- .check()
633- .unwrap();
634- assert!(class.clone().delete(&db).await.unwrap());
635- assert_eq!(
636- stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
637- 0
638- );
639- let again = class.delete(&db).await;
640- assert!(
641- matches!(again, Err(AppError::NotFound)),
642- "a second delete is a 404, not a refusal: {again:?}"
643- );
644- }
645- }
646-
647- /// The class half of the invariant on the create path: a refused create
648- /// leaves neither the row nor a count stranded on a term (which the term's
649- /// delete guard reads, so a stray one would make it undeletable forever).
650- #[tokio::test]
651- async fn a_refused_create_writes_neither_row_nor_count() {
652- let db = crate::database::init_mem().await.unwrap();
653- let term = a_term(&db).await;
654- let id = term.get_id().clone();
655- assert!(crate::db::term::delete(&db, term).await.unwrap());
656-
657- let error = ClassGroup::create(
658- &UserId::from_key("manager"),
659- ClassName::try_new("9-A").unwrap(),
660- None,
661- Some(id),
662- None,
663- &db,
664- )
665- .await
666- .expect_err("a term that is gone must not be linkable");
667- assert!(error.to_string().contains("term does not exist"));
668- assert_eq!(
669- rows("SELECT VALUE id FROM class_group", &db).await,
670- 0,
671- "a refused create may write no row"
672- );
673- assert_eq!(
674- rows("SELECT VALUE id FROM term", &db).await,
675- 0,
676- "…and least of all a count on a term it just brought back"
677- );
678- }
679-
680- /// The class mirror of
681- /// [`crate::db::course`]'s move tests: a term move carries both
682- /// counters with the link, and a move to a term that is gone rolls the
683- /// release back with the abort (the transaction releases before it claims,
684- /// so the old count would be 0 if the abort did not undo it).
685- #[tokio::test]
686- async fn a_class_term_move_moves_both_counts_or_neither() {
687- let db = crate::database::init_mem().await.unwrap();
688- let at = crate::domain::timestamp::Timestamp::from_millis;
689- let from = a_term(&db).await;
690- let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
691- .await
692- .unwrap();
693- let dead =
694- crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
695- .await
696- .unwrap();
697- let dead_id = dead.get_id().clone();
698- assert!(crate::db::term::delete(&db, dead).await.unwrap());
699- let class = class_on(Some(from.get_id().clone()), &db).await;
700-
701- let error = class
702- .clone()
703- .update(
704- Some(ClassName::try_new("9-B").unwrap()),
705- None,
706- Some(Some(dead_id)),
707- None,
708- &db,
709- )
710- .await
711- .expect_err("a term that is gone must not be linkable");
712- assert!(error.to_string().contains("term does not exist"));
713- let stored = ClassGroup::read(class.get_id(), &db)
714- .await
715- .unwrap()
716- .unwrap();
717- assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put");
718- assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row");
719- assert_eq!(
720- count_on(from.get_id(), &db).await,
721- 1,
722- "the release must roll back with the abort"
723- );
724-
725- let moved = class
726- .update(None, None, Some(Some(to.get_id().clone())), None, &db)
727- .await
728- .unwrap();
729- assert_eq!(moved.get_term(), Some(to.get_id()));
730- assert_eq!(
731- count_on(from.get_id(), &db).await,
732- 0,
733- "the old term is free"
734- );
735- assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not");
736- }
737-
738- /// The class twin of
739- /// [`crate::domain::course`]'s `a_stale_mover_is_refused_and_claims_nothing`
740- /// and `a_stale_re_stater_is_refused_and_reverts_nothing`, in one: both
741- /// PATCHes compute their counter move from the row as *they* read it, so a
742- /// second one running on the pre-move struct would claim a second seat for
743- /// one link (the mover) or drag the link back and strand the winner's claim
744- /// (the re-stater, which shifts no counter at all and so is only ever
745- /// stopped by a guard armed off the *carried column*). Both must be refused
746- /// with the counts reading as if they never ran.
747- #[tokio::test]
748- async fn a_stale_class_term_write_is_refused_and_moves_no_count() {
749- let db = crate::database::init_mem().await.unwrap();
750- let at = crate::domain::timestamp::Timestamp::from_millis;
751- let from = a_term(&db).await;
752- let to = crate::db::term::create(&db, TermName::try_new("2027").unwrap(), at(100), at(200))
753- .await
754- .unwrap();
755- let other =
756- crate::db::term::create(&db, TermName::try_new("2028").unwrap(), at(100), at(200))
757- .await
758- .unwrap();
759- let class = class_on(Some(from.get_id().clone()), &db).await;
760- let stale = class.clone();
761- class
762- .update(None, None, Some(Some(to.get_id().clone())), None, &db)
763- .await
764- .unwrap();
765-
766- // The mover: its snapshot says `from`, so it would release `from` and
767- // claim `other` on top of the winner's claim on `to`.
768- let error = stale
769- .clone()
770- .update(None, None, Some(Some(other.get_id().clone())), None, &db)
771- .await
772- .expect_err("a mover that read a link it no longer holds must be refused");
773- assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
774- // The re-stater: shifts no counter, so only the CAS can stop it.
775- let error = stale
776- .clone()
777- .update(None, None, Some(Some(from.get_id().clone())), None, &db)
778- .await
779- .expect_err("re-stating a link someone else moved must be refused");
780- assert!(matches!(error, AppError::Conflict(_)), "{error:?}");
781-
782- let stored = ClassGroup::read(stale.get_id(), &db)
783- .await
784- .unwrap()
785- .unwrap();
786- assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link");
787- assert_eq!(count_on(from.get_id(), &db).await, 0, "released once");
788- assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once");
789- assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed");
790-
791- // A genuine no-op re-state still lands and still moves nothing.
792- let same = stored
793- .update(None, None, Some(Some(to.get_id().clone())), None, &db)
794- .await
795- .expect("re-stating the link the row really holds is not a conflict");
796- assert_eq!(same.get_term(), Some(to.get_id()));
797- assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat");
798- }
799-
800- /// [`crate::db::course::delete`]'s class sweep: deleting a course
801- /// takes its `class_course` attachments with it and gives each class its
802- /// count back, or the classes would be undeletable forever over rows that
803- /// point at nothing.
804- #[tokio::test]
805- async fn deleting_a_course_sweeps_its_class_attachments() {
806- use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
807-
808- let db = crate::database::init_mem().await.unwrap();
809- let manager = UserId::from_key("manager");
810- let course = crate::db::course::create(
811- &db,
812- &manager,
813- CourseTitle::try_new("algebra").unwrap(),
814- CourseDescription::try_new("").unwrap(),
815- CourseKind::course(),
816- None,
817- None,
818- )
819- .await
820- .unwrap();
821- let class = class_on(None, &db).await;
822- db.query(format!(
823- "CREATE class_course SET class = $class, course = $course, attached_by = $usr;
824- UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;"
825- ))
826- .bind(("class", class.get_id().record()))
827- .bind(("course", course.get_id().record()))
828- .bind(("usr", manager.record()))
829- .await
830- .unwrap()
831- .check()
832- .unwrap();
833-
834- assert!(crate::db::course::delete(&db, course).await.unwrap());
835- assert_eq!(
836- rows("SELECT VALUE id FROM class_course", &db).await,
837- 0,
838- "the attachment rows must go with the course"
839- );
840- assert_eq!(
841- stored_count(
842- &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"),
843- &db
844- )
845- .await,
846- 0,
847- "…and each class must get its count back"
848- );
849- // Which is the whole point: the class is deletable again.
850- assert!(class.delete(&db).await.unwrap());
851- }
852 }145 }
src/domain/class_member.rsmodified+13 -551
@@ -1,20 +1,19 @@
1 //! A student's place in a class, and the enrollments that place implies.1 //! A student's place in a class, and the enrollments that place implies.
2 //!2 //!
3-//! Both writes here are one call into [`crate::domain::class_pump`]: this file3+//! Both writes are one call into [`crate::db::class_pump`]: adding a member
4-//! only names the axis, the counter and the composite id, because adding a4+//! and attaching a course to the class are the same pump seen from its two
5-//! member and attaching a course to the class are the same pump seen from its5+//! ends. The refusals-to-errors policy and the detach live in
6-//! two ends.6+//! [`crate::service::class_member`]; the roster reads in
7+//! [`crate::db::class_member`] — this file is the row shape and its
8+//! composite id.
7 9
8 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};10 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
9 11
10-use crate::constant::{CLASS_MEMBER_TABLE, MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};12+use crate::constant::CLASS_MEMBER_TABLE;
11-use crate::database::Database;13+use crate::db::class_pump::link_id;
12-use crate::db::page::PagedList;
13 use crate::domain::class_group::ClassGroupId;14 use crate::domain::class_group::ClassGroupId;
14-use crate::domain::class_pump::{Attached, Axis, attach, detach, link_id};
15 use crate::domain::timestamp::Timestamp;15 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;16 use crate::domain::user::UserId;
17-use crate::error::{AppError, ValidationError};
18 17
19 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]18 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
20 pub struct ClassMemberId(RecordId);19 pub struct ClassMemberId(RecordId);
@@ -40,15 +39,15 @@ impl ClassMemberId {
40 /// One student in one class. `added_by` is who put them there.39 /// One student in one class. `added_by` is who put them there.
41 #[derive(Debug, Clone, SurrealValue)]40 #[derive(Debug, Clone, SurrealValue)]
42 pub struct ClassMember {41 pub struct ClassMember {
43- id: ClassMemberId,42+ pub(crate) id: ClassMemberId,
44- class: ClassGroupId,43+ pub(crate) class: ClassGroupId,
45- user: UserId,44+ pub(crate) user: UserId,
46- added_by: UserId,45+ pub(crate) added_by: UserId,
47 /// When they were added, and the *only* thing "newest first" can mean here:46 /// When they were added, and the *only* thing "newest first" can mean here:
48 /// the row's id is the (class, user) pair, so ordering by it sorts the47 /// the row's id is the (class, user) pair, so ordering by it sorts the
49 /// roster by the student's account ULID. Optional because rows written48 /// roster by the student's account ULID. Optional because rows written
50 /// before this column carry no stamp — see the migration note.49 /// before this column carry no stamp — see the migration note.
51- added_at: Option<Timestamp>,50+ pub(crate) added_at: Option<Timestamp>,
52 }51 }
53 52
54 impl ClassMember {53 impl ClassMember {
@@ -67,541 +66,4 @@ impl ClassMember {
67 pub fn get_added_by(&self) -> &UserId {66 pub fn get_added_by(&self) -> &UserId {
68 &self.added_by67 &self.added_by
69 }68 }
70-
71- /// Put `user` in `class` and enroll them into every course the class is
72- /// already attached to, in one transaction.
73- ///
74- /// A student already enrolled in one of those courses keeps the row they
75- /// have — no seat is charged and their `source` is untouched, so a
76- /// hand-placed enrollment is never adopted by the class — and a course with
77- /// no free seat refuses the *whole* join rather than half of it.
78- pub async fn add(
79- class: &ClassGroupId,
80- user: &UserId,
81- added_by: &UserId,
82- db: &Database,
83- ) -> Result<ClassMember, AppError> {
84- let member = ClassMember {
85- id: ClassMemberId::composite(class, user),
86- class: class.clone(),
87- user: user.clone(),
88- added_by: added_by.clone(),
89- added_at: Some(Timestamp::now()),
90- };
91- let landed = attach(
92- class,
93- Axis::Member,
94- (&member.id.record(), &member),
95- user.record(),
96- added_by.record(),
97- None,
98- db,
99- )
100- .await?;
101- // Read off the refusal, never respelled here: this route and a
102- // blueprint pump answer one vocabulary. `Made` is the only `None`, and
103- // it takes the `Ok` arm below.
104- let code = landed.refusal_code(&Axis::Member).unwrap_or_default();
105- match landed {
106- Attached::Made(saved) => Ok(saved),
107- Attached::Duplicate => Err(AppError::ConflictCoded {
108- code,
109- message: "the student is already in this class".into(),
110- }),
111- Attached::Gone => Err(AppError::NotFound),
112- // The pivot is the student: they were demoted while this ran, which
113- // is the refusal the caller's own read makes a moment earlier and
114- // the only one that can arrive after it.
115- Attached::PivotGone => Err(AppError::Validation(ValidationError::Invalid {
116- field: "user_id",
117- reason: "only students can be added to a class",
118- })),
119- Attached::ClassFull => Err(AppError::ConflictCoded {
120- code,
121- message: format!("this class already holds {MAX_CLASS_MEMBERS} students"),
122- }),
123- // The other axis: adding one student enrolls them into every
124- // attached course, so a class over *that* ceiling cannot take a
125- // member however much room its roster has.
126- Attached::ClassOverloaded => Err(AppError::ConflictCoded {
127- code,
128- message: format!(
129- "this class holds more than {MAX_CLASS_COURSES} courses — \
130- detach some before adding a student"
131- ),
132- }),
133- Attached::Full(course) => Err(AppError::ConflictCoded {
134- code,
135- message: format!("{course} is full, so the class cannot take this student"),
136- }),
137- // Not a capacity problem, and told apart from one on purpose: no
138- // number anyone can raise unblocks this class, only detaching the
139- // link the deleted course left behind.
140- Attached::CourseGone(course) => Err(AppError::ConflictCoded {
141- code,
142- message: format!("{course} no longer exists — detach it from this class first"),
143- }),
144- // Only an attach run on a blueprint's behalf states that claim, and
145- // a membership is nobody's but its own.
146- Attached::SourceGone => Err(AppError::Internal(
147- "a class membership has no blueprint to lose".into(),
148- )),
149- }
150- }
151-
152- /// Take `user` out of `class` and sweep the enrollments the class pumped
153- /// for them. A student who was not in the class is a
154- /// [`AppError::NotFound`], raised here rather than left to each caller to
155- /// re-derive from a boolean.
156- ///
157- /// An enrollment another attached class still claims is re-tagged to that
158- /// class instead of deleted (see [`crate::domain::class_pump::detach`]).
159- pub async fn remove(
160- class: &ClassGroupId,
161- user: &UserId,
162- db: &Database,
163- ) -> Result<(), AppError> {
164- let gone = detach(
165- "$link",
166- Axis::Member,
167- &[(
168- "link".into(),
169- ClassMemberId::composite(class, user).record().into_value(),
170- )],
171- db,
172- )
173- .await?;
174- (gone > 0).then_some(()).ok_or(AppError::NotFound)
175- }
176-
177- /// The class's roster, newest first — by when the student was added, not by
178- /// their account id, which is what the composite record id sorts on.
179- /// A row older than the column carries no stamp at all, and NONE sorts last
180- /// under DESC — which is the honest place for a row of unknown age.
181- pub async fn list_for_class(
182- class: &ClassGroupId,
183- limit: Option<i64>,
184- offset: i64,
185- db: &Database,
186- ) -> Result<(Vec<ClassMember>, i64), AppError> {
187- PagedList::new(
188- format!("{CLASS_MEMBER_TABLE} WHERE class = $class"),
189- "ORDER BY added_at DESC, id DESC",
190- )
191- .bind("class", class.record())
192- .run(limit, offset, db)
193- .await
194- }
195-
196- /// The classes one student belongs to, newest membership first — the read
197- /// behind "which class section (şube) am I in". Same ordering story as
198- /// [`ClassMember::list_for_class`], along the other axis of the same index.
199- pub async fn list_for_user(
200- user: &UserId,
201- limit: Option<i64>,
202- offset: i64,
203- db: &Database,
204- ) -> Result<(Vec<ClassMember>, i64), AppError> {
205- PagedList::new(
206- format!("{CLASS_MEMBER_TABLE} WHERE user = $usr"),
207- "ORDER BY added_at DESC, id DESC",
208- )
209- .bind("usr", user.record())
210- .run(limit, offset, db)
211- .await
212- }
213-}
214-
215-#[cfg(test)]
216-pub(crate) mod tests {
217- use super::*;
218- use crate::domain::class_course::ClassCourse;
219- use crate::domain::class_group::{ClassGroup, ClassName};
220- use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
221-
222- pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId {
223- ClassGroup::create(
224- &UserId::from_key("manager"),
225- ClassName::try_new(name).unwrap(),
226- None,
227- None,
228- None,
229- db,
230- )
231- .await
232- .unwrap()
233- .get_id()
234- .clone()
235- }
236-
237- pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId {
238- crate::db::course::create(
239- db,
240- &UserId::from_key("manager"),
241- CourseTitle::try_new(title).unwrap(),
242- CourseDescription::try_new("").unwrap(),
243- CourseKind::course(),
244- None,
245- capacity,
246- )
247- .await
248- .unwrap()
249- .get_id()
250- .clone()
251- }
252-
253- /// A counter, re-read out of the store — never off a return value, which
254- /// the in-memory engine forges wins on (see [`crate::db::cap`]).
255- pub(crate) async fn counter(field: &str, of: RecordId, db: &Database) -> i64 {
256- let mut result = db
257- .query(format!("SELECT VALUE {field} ?? 0 FROM $of"))
258- .bind(("of", of))
259- .await
260- .unwrap()
261- .check()
262- .unwrap();
263- result
264- .take::<Vec<i64>>(0)
265- .unwrap()
266- .first()
267- .copied()
268- .unwrap()
269- }
270-
271- /// How many rows `sql` selects ids for.
272- pub(crate) async fn rows(sql: &str, db: &Database) -> usize {
273- let mut result = db.query(sql).await.unwrap().check().unwrap();
274- result.take::<Vec<RecordId>>(0).unwrap().len()
275- }
276-
277- /// Whether `id` names a live row.
278- pub(crate) async fn exists(id: RecordId, db: &Database) -> bool {
279- let mut result = db
280- .query("SELECT VALUE id FROM $id")
281- .bind(("id", id))
282- .await
283- .unwrap()
284- .check()
285- .unwrap();
286- !result.take::<Vec<RecordId>>(0).unwrap().is_empty()
287- }
288-
289- /// The class that wrote an enrollment, or `None` for a hand-placed row.
290- pub(crate) async fn source_of(
291- course: &CourseId,
292- user: &UserId,
293- db: &Database,
294- ) -> Option<Option<ClassGroupId>> {
295- crate::db::enrollment::read_for_user(db, course, user)
296- .await
297- .unwrap()
298- .map(|row| row.get_source().cloned())
299- }
300-
301- #[tokio::test]
302- async fn a_member_is_enrolled_into_every_attached_course() {
303- let db = crate::database::init_mem().await.unwrap();
304- let manager = UserId::from_key("manager");
305- let student = UserId::from_key("student");
306- let class = a_class("9-A", &db).await;
307- let algebra = a_course("algebra", None, &db).await;
308- let physics = a_course("physics", None, &db).await;
309- ClassCourse::attach(&class, &algebra, &manager, &db)
310- .await
311- .unwrap();
312- ClassCourse::attach(&class, &physics, &manager, &db)
313- .await
314- .unwrap();
315-
316- ClassMember::add(&class, &student, &manager, &db)
317- .await
318- .unwrap();
319-
320- for course in [&algebra, &physics] {
321- assert_eq!(
322- source_of(course, &student, &db).await,
323- Some(Some(class.clone())),
324- "every attached course must hold a row tagged with the class"
325- );
326- assert_eq!(counter("enrollment_count", course.record(), &db).await, 1);
327- }
328- assert_eq!(counter("class_member_count", class.record(), &db).await, 1);
329- }
330-
331- /// The pumped row must carry the *same* composite id a hand enroll would
332- /// mint, or the two paths would key one pair two ways and only the unique
333- /// index (a 500) would notice.
334- #[tokio::test]
335- async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
336- use crate::domain::enrollment::EnrollmentId;
337-
338- let db = crate::database::init_mem().await.unwrap();
339- let manager = UserId::from_key("manager");
340- let student = UserId::from_key("student");
341- let class = a_class("9-A", &db).await;
342- let algebra = a_course("algebra", None, &db).await;
343- ClassCourse::attach(&class, &algebra, &manager, &db)
344- .await
345- .unwrap();
346- ClassMember::add(&class, &student, &manager, &db)
347- .await
348- .unwrap();
349-
350- assert!(
351- exists(EnrollmentId::composite(&algebra, &student).record(), &db).await,
352- "the pump must key the pair the way Enrollment::composite does"
353- );
354- }
355-
356- /// Re-adding is a 409, and it must cost nothing: no second counter tick and
357- /// no second sweep of anybody's enrollment.
358- #[tokio::test]
359- async fn a_second_add_is_refused_and_writes_nothing() {
360- let db = crate::database::init_mem().await.unwrap();
361- let manager = UserId::from_key("manager");
362- let student = UserId::from_key("student");
363- let class = a_class("9-A", &db).await;
364- let algebra = a_course("algebra", None, &db).await;
365- ClassCourse::attach(&class, &algebra, &manager, &db)
366- .await
367- .unwrap();
368- ClassMember::add(&class, &student, &manager, &db)
369- .await
370- .unwrap();
371-
372- let again = ClassMember::add(&class, &student, &manager, &db).await;
373- assert!(
374- matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
375- "a second add is a 409 coded `duplicate`: {again:?}"
376- );
377- assert_eq!(
378- counter("class_member_count", class.record(), &db).await,
379- 1,
380- "a refused add may not tick the counter"
381- );
382- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
383- }
384-
385- /// Adding into a class whose courses have no room refuses the *whole* join:
386- /// the roomy course must not keep a seat the full one denied.
387- #[tokio::test]
388- async fn a_full_course_refuses_the_whole_join() {
389- let db = crate::database::init_mem().await.unwrap();
390- let manager = UserId::from_key("manager");
391- let student = UserId::from_key("student");
392- let class = a_class("9-A", &db).await;
393- let roomy = a_course("algebra", None, &db).await;
394- let full = a_course("physics", Some(0), &db).await;
395- ClassCourse::attach(&class, &roomy, &manager, &db)
396- .await
397- .unwrap();
398- ClassCourse::attach(&class, &full, &manager, &db)
399- .await
400- .unwrap();
401-
402- // The whole record id, not just the key: a caller reading the 409 must
403- // not have to guess which table the name came from.
404- let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key());
405- let refused = ClassMember::add(&class, &student, &manager, &db).await;
406- assert!(
407- matches!(refused, Err(AppError::ConflictCoded { code, ref message })
408- if code == "course_full" && message.contains(&named)),
409- "the refusal must be coded `course_full` and name the course that had no seat \
410- as {named}: {refused:?}"
411- );
412- assert_eq!(
413- rows("SELECT VALUE id FROM enrollment", &db).await,
414- 0,
415- "not one seat may survive the refusal"
416- );
417- assert_eq!(
418- rows("SELECT VALUE id FROM class_member", &db).await,
419- 0,
420- "…nor the membership row itself"
421- );
422- assert_eq!(
423- counter("enrollment_count", roomy.record(), &db).await,
424- 0,
425- "…nor the roomy course's counter"
426- );
427- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
428- }
429-
430- /// A student already enrolled by hand keeps their own row: no seat is
431- /// charged for them, the row's `source` stays empty, and removing them from
432- /// the class leaves it standing.
433- #[tokio::test]
434- async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
435- let db = crate::database::init_mem().await.unwrap();
436- let manager = UserId::from_key("manager");
437- let student = UserId::from_key("student");
438- let class = a_class("9-A", &db).await;
439- let algebra = a_course("algebra", None, &db).await;
440- crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
441- .await
442- .unwrap();
443- ClassCourse::attach(&class, &algebra, &manager, &db)
444- .await
445- .unwrap();
446-
447- ClassMember::add(&class, &student, &manager, &db)
448- .await
449- .unwrap();
450- assert_eq!(
451- source_of(&algebra, &student, &db).await,
452- Some(None),
453- "the class must not adopt a hand-placed row"
454- );
455- assert_eq!(
456- counter("enrollment_count", algebra.record(), &db).await,
457- 1,
458- "the skipped pair may not be charged a second seat"
459- );
460-
461- ClassMember::remove(&class, &student, &db).await.unwrap();
462- assert_eq!(
463- source_of(&algebra, &student, &db).await,
464- Some(None),
465- "the sweep may only take back the rows the class wrote"
466- );
467- assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
468- }
469-
470- /// Removal with nobody else claiming the row: the enrollment goes and its
471- /// seat comes back.
472- #[tokio::test]
473- async fn removal_deletes_the_rows_the_class_pumped() {
474- let db = crate::database::init_mem().await.unwrap();
475- let manager = UserId::from_key("manager");
476- let student = UserId::from_key("student");
477- let class = a_class("9-A", &db).await;
478- let algebra = a_course("algebra", None, &db).await;
479- ClassCourse::attach(&class, &algebra, &manager, &db)
480- .await
481- .unwrap();
482- ClassMember::add(&class, &student, &manager, &db)
483- .await
484- .unwrap();
485-
486- ClassMember::remove(&class, &student, &db).await.unwrap();
487- assert_eq!(source_of(&algebra, &student, &db).await, None);
488- assert_eq!(
489- counter("enrollment_count", algebra.record(), &db).await,
490- 0,
491- "the seat must come back with the row that held it"
492- );
493- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
494- let again = ClassMember::remove(&class, &student, &db).await;
495- assert!(
496- matches!(again, Err(AppError::NotFound)),
497- "a second removal is a 404, not a second sweep: {again:?}"
498- );
499- }
500-
501- /// A member who is not in any attached course still removes cleanly, and a
502- /// course deleted out from under the class leaves nothing to sweep — the
503- /// membership row and the pumped enrollment are independent facts.
504- #[tokio::test]
505- async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
506- let db = crate::database::init_mem().await.unwrap();
507- let manager = UserId::from_key("manager");
508- let student = UserId::from_key("student");
509- let class = a_class("9-A", &db).await;
510- let algebra = a_course("algebra", None, &db).await;
511- ClassCourse::attach(&class, &algebra, &manager, &db)
512- .await
513- .unwrap();
514- ClassMember::add(&class, &student, &manager, &db)
515- .await
516- .unwrap();
517-
518- // `Course::delete` refuses while the roster is occupied, so the wipe is
519- // spelled the way the cascade does it, minus the guard.
520- db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;")
521- .bind(("course", algebra.record()))
522- .await
523- .unwrap()
524- .check()
525- .unwrap();
526-
527- ClassMember::remove(&class, &student, &db)
528- .await
529- .expect("the membership must still be removable with its enrollment gone");
530- assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
531- }
532-
533- /// The role-change sweep, which is one transaction with the role write
534- /// itself: the memberships go with their counters, the enrollment rows go
535- /// with their seats, and each seat comes back exactly once — the double
536- /// decrement the old two-call split existed to avoid.
537- #[tokio::test]
538- async fn the_role_sweep_takes_memberships_and_enrollments_together() {
539- let db = crate::database::init_mem().await.unwrap();
540- let manager = UserId::from_key("manager");
541- // A real row, because the sweep now rides on the role write.
542- let hash = crate::domain::user::Password::try_new("secret1")
543- .unwrap()
544- .hash_async()
545- .await
546- .unwrap();
547- let account = crate::db::user::create(
548- &db,
549- crate::domain::user::Username::try_new("ogrenci").unwrap(),
550- hash,
551- )
552- .await
553- .unwrap();
554- let student = account.get_id().clone();
555- let first = a_class("9-A", &db).await;
556- let second = a_class("club", &db).await;
557- let algebra = a_course("algebra", None, &db).await;
558- ClassCourse::attach(&first, &algebra, &manager, &db)
559- .await
560- .unwrap();
561- ClassMember::add(&first, &student, &manager, &db)
562- .await
563- .unwrap();
564- ClassMember::add(&second, &student, &manager, &db)
565- .await
566- .unwrap();
567-
568- crate::service::user::set_role(
569- &db,
570- account.get_id(),
571- crate::domain::role::Role::Teacher,
572- )
573- .await
574- .unwrap();
575- assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
576- for class in [&first, &second] {
577- assert_eq!(
578- counter("class_member_count", class.record(), &db).await,
579- 0,
580- "every class must get its member count back"
581- );
582- }
583- assert_eq!(
584- source_of(&algebra, &student, &db).await,
585- None,
586- "the enrollment goes in the same transaction as the membership"
587- );
588- assert_eq!(
589- counter("enrollment_count", algebra.record(), &db).await,
590- 0,
591- "…and its seat comes back once, not twice"
592- );
593- // Which is the point of folding them: the class the student was in is
594- // free of them entirely — no membership, no count, and no enrollment
595- // row left tagged with a class that is about to be deletable.
596- assert!(
597- crate::domain::class_group::ClassGroup::read(&second, &db)
598- .await
599- .unwrap()
600- .unwrap()
601- .delete(&db)
602- .await
603- .unwrap(),
604- "a class holding neither members nor courses must delete"
605- );
606- }
607 }69 }
src/domain/mod.rsmodified+0 -1
@@ -18,7 +18,6 @@ pub mod class_blueprint;
18 pub mod class_course;18 pub mod class_course;
19 pub mod class_group;19 pub mod class_group;
20 pub mod class_member;20 pub mod class_member;
21-pub mod class_pump;
22 pub mod course;21 pub mod course;
23 pub mod course_note;22 pub mod course_note;
24 pub mod course_note_file;23 pub mod course_note_file;
src/service/class_blueprint.rsmodified+21 -19
@@ -23,7 +23,7 @@
23 //! a `class_course` row this blueprint wrote carries `source`, a row a human23 //! a `class_course` row this blueprint wrote carries `source`, a row a human
24 //! attached carries no such key at all, and dropping a course from the24 //! attached carries no such key at all, and dropping a course from the
25 //! blueprint sweeps only the former. The sweep is the pump's own25 //! blueprint sweeps only the former. The sweep is the pump's own
26-//! [`crate::domain::class_pump::detach`], so a class losing a course still26+//! [`crate::db::class_pump::detach`], so a class losing a course still
27 //! repairs before it deletes — and it runs one transaction per pair too, for27 //! repairs before it deletes — and it runs one transaction per pair too, for
28 //! the same reason the pump does.28 //! the same reason the pump does.
29 29
@@ -33,12 +33,13 @@ use surrealdb::types::RecordId;
33 33
34 use crate::database::Database;34 use crate::database::Database;
35 use crate::db::class_blueprint;35 use crate::db::class_blueprint;
36+use crate::db::class_course;
37+use crate::db::class_group;
38+use crate::db::class_pump::Attached;
36 use crate::domain::class_blueprint::{39 use crate::domain::class_blueprint::{
37 ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason,40 ClassBlueprint, ClassBlueprintId, Pumped, SectionStatus, Skip, skip_reason,
38 };41 };
39-use crate::domain::class_course::ClassCourse;
40 use crate::domain::class_group::{ClassGrade, ClassGroup};42 use crate::domain::class_group::{ClassGrade, ClassGroup};
41-use crate::domain::class_pump::Attached;
42 use crate::domain::course::CourseId;43 use crate::domain::course::CourseId;
43 use crate::domain::user::UserId;44 use crate::domain::user::UserId;
44 use crate::error::AppError;45 use crate::error::AppError;
@@ -47,7 +48,7 @@ use crate::error::AppError;
47 ///48 ///
48 /// [`delete`] removes the row and then sweeps by the provenance49 /// [`delete`] removes the row and then sweeps by the provenance
49 /// tag, and every guarded attach reads that same row *inside* its own50 /// tag, and every guarded attach reads that same row *inside* its own
50-/// transaction ([`crate::domain::class_pump::attach`]'s `source` claim). Those51+/// transaction ([`crate::db::class_pump::attach`]'s `source` claim). Those
51 /// two are a cross-record read-then-write racing a write to the record read,52 /// two are a cross-record read-then-write racing a write to the record read,
52 /// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can53 /// which `BEGIN`/`COMMIT` does not serialize (SurrealDB write skew): a pump can
53 /// see the blueprint alive, have the delete commit and sweep past it, and only54 /// see the blueprint alive, have the delete commit and sweep past it, and only
@@ -290,7 +291,8 @@ async fn apply_courses(
290 }291 }
291 let landed = {292 let landed = {
292 let _lease = BLUEPRINT_LOCK.read().await;293 let _lease = BLUEPRINT_LOCK.read().await;
293- ClassCourse::attach_sourced(class.get_id(), course, by, Some(&blueprint.id), db).await?294+ class_course::attach_sourced(db, class.get_id(), course, by, Some(&blueprint.id))
295+ .await?
294 };296 };
295 if matches!(landed, Attached::PivotGone) {297 if matches!(landed, Attached::PivotGone) {
296 class_blueprint::prune(db, &blueprint.id, course).await?;298 class_blueprint::prune(db, &blueprint.id, course).await?;
@@ -346,7 +348,7 @@ pub async fn pump(
346 skipped: Vec::new(),348 skipped: Vec::new(),
347 };349 };
348 let mut dead = Vec::new();350 let mut dead = Vec::new();
349- for class in ClassGroup::list_for_grade(&blueprint.grade, db).await? {351+ for class in class_group::list_for_grade(db, &blueprint.grade).await? {
350 pumped.matched += 1;352 pumped.matched += 1;
351 if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? {353 if !apply_courses(db, blueprint, &class, by, &mut dead, &mut pumped.skipped).await? {
352 break;354 break;
@@ -378,14 +380,14 @@ pub async fn pump(
378 /// pump's own window ([`class_blueprint::prune`]) is about to clear, can380 /// pump's own window ([`class_blueprint::prune`]) is about to clear, can
379 /// still show it.381 /// still show it.
380 ///382 ///
381-/// Unpaged, like the [`ClassGroup::list_for_grade`] it is built on: the set383+/// Unpaged, like the [`crate::db::class_group::list_for_grade`] it is built on: the set
382 /// is the şube one school runs at one grade, and the caller is asking about384 /// is the şube one school runs at one grade, and the caller is asking about
383 /// all of them.385 /// all of them.
384 pub async fn status(386 pub async fn status(
385 db: &Database,387 db: &Database,
386 blueprint: &ClassBlueprint,388 blueprint: &ClassBlueprint,
387 ) -> Result<Vec<SectionStatus>, AppError> {389 ) -> Result<Vec<SectionStatus>, AppError> {
388- let sections = ClassGroup::list_for_grade(&blueprint.grade, db).await?;390+ let sections = class_group::list_for_grade(db, &blueprint.grade).await?;
389 if sections.is_empty() {391 if sections.is_empty() {
390 return Ok(Vec::new());392 return Ok(Vec::new());
391 }393 }
@@ -417,20 +419,20 @@ pub async fn status(
417 mod tests {419 mod tests {
418 use super::*;420 use super::*;
419 use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES};421 use crate::constant::{CLASS_COURSE_COUNT_FIELD, MAX_CLASS_COURSES};
422+ use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows};
420 use crate::domain::class_course::ClassCourseId;423 use crate::domain::class_course::ClassCourseId;
421- use crate::domain::class_group::ClassName;424+ use crate::domain::class_group::{ClassGroup, ClassName};
422- use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows};
423 425
424 /// A section that a pump's own grade loop can actually find — [`a_class`]426 /// A section that a pump's own grade loop can actually find — [`a_class`]
425 /// carries no grade at all, so `list_for_grade` reaches none of them.427 /// carries no grade at all, so `list_for_grade` reaches none of them.
426 async fn a_section(name: &str, db: &Database) -> ClassGroup {428 async fn a_section(name: &str, db: &Database) -> ClassGroup {
427- ClassGroup::create(429+ class_group::create(
430+ db,
428 &UserId::from_key("manager"),431 &UserId::from_key("manager"),
429 ClassName::try_new(name).unwrap(),432 ClassName::try_new(name).unwrap(),
430 Some(ClassBlueprint::grade_key("9").unwrap()),433 Some(ClassBlueprint::grade_key("9").unwrap()),
431 None,434 None,
432 None,435 None,
433- db,
434 )436 )
435 .await437 .await
436 .unwrap()438 .unwrap()
@@ -463,7 +465,7 @@ mod tests {
463 // matches nothing.465 // matches nothing.
464 let db = crate::database::init_mem().await.unwrap();466 let db = crate::database::init_mem().await.unwrap();
465 let course = a_course("algebra", None, &db).await;467 let course = a_course("algebra", None, &db).await;
466- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)468+ let class = class_group::read(&db, &a_class("9-A", &db).await)
467 .await469 .await
468 .unwrap()470 .unwrap()
469 .unwrap();471 .unwrap();
@@ -496,7 +498,7 @@ mod tests {
496 // matches nothing and the read that follows finds no row.498 // matches nothing and the read that follows finds no row.
497 let db = crate::database::init_mem().await.unwrap();499 let db = crate::database::init_mem().await.unwrap();
498 let course = a_course("algebra", None, &db).await;500 let course = a_course("algebra", None, &db).await;
499- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)501+ let class = class_group::read(&db, &a_class("9-A", &db).await)
500 .await502 .await
501 .unwrap()503 .unwrap()
502 .unwrap();504 .unwrap();
@@ -527,7 +529,7 @@ mod tests {
527 // but the row is there — and that is the one a manager can act on.529 // but the row is there — and that is the one a manager can act on.
528 let db = crate::database::init_mem().await.unwrap();530 let db = crate::database::init_mem().await.unwrap();
529 let course = a_course("algebra", None, &db).await;531 let course = a_course("algebra", None, &db).await;
530- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)532+ let class = class_group::read(&db, &a_class("9-A", &db).await)
531 .await533 .await
532 .unwrap()534 .unwrap()
533 .unwrap();535 .unwrap();
@@ -563,7 +565,7 @@ mod tests {
563 let manager = UserId::from_key("manager");565 let manager = UserId::from_key("manager");
564 let algebra = a_course("algebra", None, &db).await;566 let algebra = a_course("algebra", None, &db).await;
565 let physics = a_course("physics", None, &db).await;567 let physics = a_course("physics", None, &db).await;
566- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)568+ let class = class_group::read(&db, &a_class("9-A", &db).await)
567 .await569 .await
568 .unwrap()570 .unwrap()
569 .unwrap();571 .unwrap();
@@ -616,7 +618,7 @@ mod tests {
616 let db = crate::database::init_mem().await.unwrap();618 let db = crate::database::init_mem().await.unwrap();
617 let manager = UserId::from_key("manager");619 let manager = UserId::from_key("manager");
618 let algebra = a_course("algebra", None, &db).await;620 let algebra = a_course("algebra", None, &db).await;
619- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)621+ let class = class_group::read(&db, &a_class("9-A", &db).await)
620 .await622 .await
621 .unwrap()623 .unwrap()
622 .unwrap();624 .unwrap();
@@ -685,7 +687,7 @@ mod tests {
685 ];687 ];
686 let blueprint = a_blueprint(courses, &db).await;688 let blueprint = a_blueprint(courses, &db).await;
687 for name in ["9-A", "9-B"] {689 for name in ["9-A", "9-B"] {
688- let class = ClassGroup::read(&a_class(name, &db).await, &db)690+ let class = class_group::read(&db, &a_class(name, &db).await)
689 .await691 .await
690 .unwrap()692 .unwrap()
691 .unwrap();693 .unwrap();
@@ -743,7 +745,7 @@ mod tests {
743 let db = crate::database::init_mem().await.unwrap();745 let db = crate::database::init_mem().await.unwrap();
744 let manager = UserId::from_key("manager");746 let manager = UserId::from_key("manager");
745 let algebra = a_course("algebra", None, &db).await;747 let algebra = a_course("algebra", None, &db).await;
746- let class = ClassGroup::read(&a_class("9-A", &db).await, &db)748+ let class = class_group::read(&db, &a_class("9-A", &db).await)
747 .await749 .await
748 .unwrap()750 .unwrap()
749 .unwrap();751 .unwrap();
src/service/class_course.rsadded+452 -0
@@ -0,0 +1,452 @@
1+//! Class-course workflows: the attach that maps the pump's refusals to this
2+//! route's answers, and the detach that turns a zero-row sweep into a 404.
3+//! The transactions live in [`crate::db::class_pump`] and
4+//! [`crate::db::class_course`].
5+
6+use surrealdb::types::SurrealValue;
7+
8+use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
9+use crate::database::Database;
10+use crate::db::class_course;
11+use crate::db::class_pump::{self, Axis};
12+use crate::domain::class_course::ClassCourse;
13+use crate::domain::class_group::ClassGroupId;
14+use crate::domain::course::CourseId;
15+use crate::domain::user::UserId;
16+use crate::error::AppError;
17+
18+/// Attach `course` to `class` and enroll the class's whole roster into it,
19+/// in one transaction.
20+///
21+/// Students already in the course keep the rows they have — no seat
22+/// charged, `source` untouched — and a roster that does not fit refuses the
23+/// whole attach rather than filling the course to its cap and stopping.
24+pub async fn attach(
25+ db: &Database,
26+ class: &ClassGroupId,
27+ course: &CourseId,
28+ attached_by: &UserId,
29+) -> Result<ClassCourse, AppError> {
30+ let landed = class_course::attach_sourced(db, class, course, attached_by, None).await?;
31+ // Read off the refusal, never respelled here: this route and a
32+ // blueprint pump answer one vocabulary. `Made` is the only `None`, and
33+ // it takes the `Ok` arm below.
34+ let code = landed.refusal_code(&Axis::Course).unwrap_or_default();
35+ match landed {
36+ class_pump::Attached::Made(saved) => Ok(saved),
37+ class_pump::Attached::Duplicate => Err(AppError::ConflictCoded {
38+ code,
39+ message: "the course is already on this class".into(),
40+ }),
41+ // The class or the course: either end of the link being gone is a
42+ // 404 on this route, and only a blueprint's skip list needs them
43+ // told apart.
44+ class_pump::Attached::Gone | class_pump::Attached::PivotGone => Err(AppError::NotFound),
45+ class_pump::Attached::ClassFull => Err(AppError::ConflictCoded {
46+ code,
47+ message: format!("this class already holds {MAX_CLASS_COURSES} courses"),
48+ }),
49+ // The other axis: attaching one course enrolls the whole roster, so
50+ // a class over *that* ceiling cannot take a course however few it
51+ // carries. Only a class predating the ceiling can be here.
52+ class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded {
53+ code,
54+ message: format!(
55+ "this class holds more than {MAX_CLASS_MEMBERS} students — \
56+ remove some before attaching a course"
57+ ),
58+ }),
59+ class_pump::Attached::Full(full) => Err(AppError::ConflictCoded {
60+ code,
61+ message: format!("{full} cannot hold the whole class"),
62+ }),
63+ // Unreachable on this axis, and kept because the match is
64+ // exhaustive: the pair loop enrolls the roster into `$pivot` and
65+ // nothing else, and the pivot claim already proved *that* course
66+ // alive inside the same transaction. Only a member add walks a
67+ // class's existing course links, so `linked_course_missing` is that
68+ // route's alone — which is why this route's `409` does not publish
69+ // it. Left mapped rather than folded into an `Internal`, so a future
70+ // axis change is a wrong-looking 409, not a 500.
71+ class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded {
72+ code,
73+ message: format!("{course} no longer exists — detach it from this class first"),
74+ }),
75+ // This path passes no source, so the claim that answers this is
76+ // never in the transaction it ran.
77+ class_pump::Attached::SourceGone => Err(AppError::Internal(
78+ "a hand attach has no blueprint to lose".into(),
79+ )),
80+ }
81+}
82+
83+/// Detach `course` from `class` and sweep the enrollments the class pumped
84+/// into it. A course that was not attached is a [`AppError::NotFound`],
85+/// raised here rather than left to each caller to re-derive from a boolean.
86+///
87+/// A student another attached class still claims keeps their row, re-tagged
88+/// to that class (see [`crate::db::class_pump::detach`]).
89+pub async fn detach(
90+ db: &Database,
91+ class: &ClassGroupId,
92+ course: &CourseId,
93+) -> Result<(), AppError> {
94+ let gone = class_pump::detach(
95+ db,
96+ "$link",
97+ Axis::Course,
98+ &[(
99+ "link".into(),
100+ crate::domain::class_course::ClassCourseId::composite(class, course)
101+ .record()
102+ .into_value(),
103+ )],
104+ )
105+ .await?;
106+ (gone > 0).then_some(()).ok_or(AppError::NotFound)
107+}
108+
109+/// The courses a class is attached to, newest first, paged — the read behind
110+/// `GET /classes/{id}/courses`.
111+pub async fn list_for_class(
112+ db: &Database,
113+ class: &ClassGroupId,
114+ limit: Option<i64>,
115+ offset: i64,
116+) -> Result<(Vec<ClassCourse>, i64), AppError> {
117+ class_course::list_for_class(db, class, limit, offset).await
118+}
119+
120+#[cfg(test)]
121+mod tests {
122+ use super::*;
123+ use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
124+ use crate::domain::class_course::ClassCourseId;
125+ use crate::service::class_member;
126+
127+ /// Attaching seeds the course from the roster the class already holds.
128+ #[tokio::test]
129+ async fn an_attach_enrolls_the_whole_roster() {
130+ let db = crate::database::init_mem().await.unwrap();
131+ let manager = UserId::from_key("manager");
132+ let class = a_class("9-A", &db).await;
133+ let algebra = a_course("algebra", None, &db).await;
134+ let students = [UserId::from_key("a"), UserId::from_key("b")];
135+ for student in &students {
136+ class_member::add(&db, &class, student, &manager)
137+ .await
138+ .unwrap();
139+ }
140+
141+ attach(&db, &class, &algebra, &manager).await.unwrap();
142+ for student in &students {
143+ assert_eq!(
144+ source_of(&algebra, student, &db).await,
145+ Some(Some(class.clone()))
146+ );
147+ }
148+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 2);
149+ assert_eq!(counter("class_course_count", class.record(), &db).await, 1);
150+
151+ let again = attach(&db, &class, &algebra, &manager).await;
152+ assert!(
153+ matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
154+ "a second attach is a 409 coded `duplicate`: {again:?}"
155+ );
156+ }
157+
158+ /// A course with room for only part of the roster takes none of it: zero
159+ /// enrollments, the counter unmoved, and no attachment row.
160+ #[tokio::test]
161+ async fn a_roster_that_does_not_fit_attaches_nothing() {
162+ let db = crate::database::init_mem().await.unwrap();
163+ let manager = UserId::from_key("manager");
164+ let class = a_class("9-A", &db).await;
165+ let tight = a_course("algebra", Some(2), &db).await;
166+ for student in ["a", "b", "c"] {
167+ class_member::add(&db, &class, &UserId::from_key(student), &manager)
168+ .await
169+ .unwrap();
170+ }
171+
172+ let refused = attach(&db, &class, &tight, &manager).await;
173+ assert!(
174+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
175+ if code == "course_full" && message.contains(tight.key())),
176+ "the refusal must be coded `course_full` and name the course: {refused:?}"
177+ );
178+ assert_eq!(
179+ rows("SELECT VALUE id FROM enrollment", &db).await,
180+ 0,
181+ "the two seats that did fit must be given back with the third"
182+ );
183+ assert_eq!(
184+ rows("SELECT VALUE id FROM class_course", &db).await,
185+ 0,
186+ "…and no attachment row may survive"
187+ );
188+ assert_eq!(counter("enrollment_count", tight.record(), &db).await, 0);
189+ assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
190+ }
191+
192+ /// A hand-placed row is skipped on the way in and left standing on the way
193+ /// out — the class never owned it.
194+ #[tokio::test]
195+ async fn a_hand_placed_row_survives_the_detach() {
196+ let db = crate::database::init_mem().await.unwrap();
197+ let manager = UserId::from_key("manager");
198+ let student = UserId::from_key("student");
199+ let class = a_class("9-A", &db).await;
200+ let algebra = a_course("algebra", None, &db).await;
201+ crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
202+ .await
203+ .unwrap();
204+ class_member::add(&db, &class, &student, &manager)
205+ .await
206+ .unwrap();
207+
208+ attach(&db, &class, &algebra, &manager).await.unwrap();
209+ assert_eq!(
210+ source_of(&algebra, &student, &db).await,
211+ Some(None),
212+ "an attach may not adopt a hand-placed row"
213+ );
214+ assert_eq!(
215+ counter("enrollment_count", algebra.record(), &db).await,
216+ 1,
217+ "…nor charge a seat for it"
218+ );
219+
220+ detach(&db, &class, &algebra).await.unwrap();
221+ assert_eq!(source_of(&algebra, &student, &db).await, Some(None));
222+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
223+ let again = detach(&db, &class, &algebra).await;
224+ assert!(
225+ matches!(again, Err(AppError::NotFound)),
226+ "a second detach is a 404: {again:?}"
227+ );
228+ }
229+
230+ /// Detaching with nobody else claiming the rows deletes them and gives the
231+ /// seats back.
232+ #[tokio::test]
233+ async fn a_detach_sweeps_the_rows_it_pumped() {
234+ let db = crate::database::init_mem().await.unwrap();
235+ let manager = UserId::from_key("manager");
236+ let student = UserId::from_key("student");
237+ let class = a_class("9-A", &db).await;
238+ let algebra = a_course("algebra", None, &db).await;
239+ class_member::add(&db, &class, &student, &manager)
240+ .await
241+ .unwrap();
242+ attach(&db, &class, &algebra, &manager).await.unwrap();
243+
244+ detach(&db, &class, &algebra).await.unwrap();
245+ assert_eq!(source_of(&algebra, &student, &db).await, None);
246+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
247+ assert_eq!(counter("class_course_count", class.record(), &db).await, 0);
248+ assert_eq!(
249+ rows("SELECT VALUE id FROM class_member", &db).await,
250+ 1,
251+ "the two axes are independent: dropping the course may not drop \
252+ the student out of the class as well"
253+ );
254+ }
255+
256+ /// Two classes, one course, one student in both: the second attach skipped
257+ /// the row the first wrote, so the row names only the first class — and
258+ /// detaching *that* class must hand the row to the second rather than
259+ /// unenroll a student the second is still responsible for. Detaching the
260+ /// second then finds nobody left and takes the seat back.
261+ #[tokio::test]
262+ async fn a_detach_hands_a_shared_row_to_the_class_that_still_claims_it() {
263+ let db = crate::database::init_mem().await.unwrap();
264+ let manager = UserId::from_key("manager");
265+ let student = UserId::from_key("student");
266+ let algebra = a_course("algebra", None, &db).await;
267+ let first = a_class("9-A", &db).await;
268+ let second = a_class("club", &db).await;
269+ for class in [&first, &second] {
270+ class_member::add(&db, class, &student, &manager)
271+ .await
272+ .unwrap();
273+ attach(&db, class, &algebra, &manager).await.unwrap();
274+ }
275+ assert_eq!(
276+ source_of(&algebra, &student, &db).await,
277+ Some(Some(first.clone())),
278+ "the second attach must skip the row the first wrote"
279+ );
280+ assert_eq!(
281+ counter("enrollment_count", algebra.record(), &db).await,
282+ 1,
283+ "…and pay no second seat for it"
284+ );
285+
286+ detach(&db, &first, &algebra).await.unwrap();
287+ assert_eq!(
288+ source_of(&algebra, &student, &db).await,
289+ Some(Some(second.clone())),
290+ "the row must be handed to the class that still claims it"
291+ );
292+ assert_eq!(
293+ counter("enrollment_count", algebra.record(), &db).await,
294+ 1,
295+ "a repair is not a release"
296+ );
297+
298+ detach(&db, &second, &algebra).await.unwrap();
299+ assert_eq!(
300+ source_of(&algebra, &student, &db).await,
301+ None,
302+ "the last claimant leaving takes the row with it"
303+ );
304+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
305+ }
306+
307+ /// The same repair along the member axis: removing the student from the
308+ /// class that owns the row hands it to the other class they are in.
309+ #[tokio::test]
310+ async fn a_member_removal_hands_a_shared_row_over_too() {
311+ let db = crate::database::init_mem().await.unwrap();
312+ let manager = UserId::from_key("manager");
313+ let student = UserId::from_key("student");
314+ let algebra = a_course("algebra", None, &db).await;
315+ let first = a_class("9-A", &db).await;
316+ let second = a_class("club", &db).await;
317+ for class in [&first, &second] {
318+ attach(&db, class, &algebra, &manager).await.unwrap();
319+ class_member::add(&db, class, &student, &manager)
320+ .await
321+ .unwrap();
322+ }
323+
324+ class_member::remove(&db, &first, &student).await.unwrap();
325+ assert_eq!(
326+ source_of(&algebra, &student, &db).await,
327+ Some(Some(second.clone())),
328+ "the student is still in the second class, so the row stays"
329+ );
330+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
331+
332+ class_member::remove(&db, &second, &student).await.unwrap();
333+ assert_eq!(source_of(&algebra, &student, &db).await, None);
334+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
335+ }
336+
337+ /// The restore half of the pivot claim: it bumps the course's counter to
338+ /// prove the row is there and must put it back *exactly* as it found it —
339+ /// absent, which the boot backfill keys on (`WHERE enrollment_count =
340+ /// NONE`). An empty roster is the case that has no seat write to hide a
341+ /// leftover bump behind.
342+ #[tokio::test]
343+ async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
344+ let db = crate::database::init_mem().await.unwrap();
345+ let class = a_class("9-A", &db).await;
346+ let algebra = a_course("algebra", None, &db).await;
347+ let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
348+ assert_eq!(
349+ rows(absent, &db).await,
350+ 1,
351+ "a fresh course carries no count"
352+ );
353+
354+ attach(&db, &class, &algebra, &UserId::from_key("manager"))
355+ .await
356+ .unwrap();
357+ assert_eq!(
358+ rows(absent, &db).await,
359+ 1,
360+ "the claim's bump must be restored to absent, not to 0"
361+ );
362+ }
363+
364+ /// The `Menu::delete` defect on the class layer: a `class_course` row must
365+ /// not outlive the course it names. The attach's proof that the course is
366+ /// still there is a *write* on the course row
367+ /// ([`crate::db::class_pump::Axis::pivot_claim`]), landing it on the
368+ /// very key `Course::delete`'s guard writes — but only because that write
369+ /// now *moves* the counter. The `count = count` this shipped with left the
370+ /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write
371+ /// set, collided with nothing, and both callers were told OK while the link
372+ /// stayed pointing at a deleted course.
373+ ///
374+ /// The roster is empty deliberately — that is the only shape where nothing
375+ /// else in the transaction touches the course row, so the claim is the
376+ /// whole guard. One child per round, for the reason the menu twin
377+ /// documents: a second writer makes the delete lose and re-send, and the
378+ /// re-sent sweep clears the evidence.
379+ ///
380+ /// The window is opened by the schema, not by a lucky interleaving: a
381+ /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the
382+ /// instant the row goes, so the `SLEEP` lands between the delete and its
383+ /// `DELETE class_course WHERE course = $course` sweep every time.
384+ ///
385+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
386+ /// conflict detection, which `init_mem`'s embedded engine does not have —
387+ /// it commits both and answers `Ok` to each, so this passes there on broken
388+ /// code.
389+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
390+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
391+ async fn a_class_course_link_never_outlives_the_course() {
392+ let (db, _serialized) = crate::database::init_test_server("class_course_race").await;
393+ db.query(
394+ "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
395+ THEN { SLEEP 1s; };",
396+ )
397+ .await
398+ .unwrap()
399+ .check()
400+ .unwrap();
401+
402+ let manager = UserId::from_key("manager");
403+ let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
404+ for round in 0..4 {
405+ let class = a_class(&format!("9-{round}"), &db).await;
406+ let algebra = a_course(&format!("algebra{round}"), None, &db).await;
407+ let course = crate::db::course::read(&db, &algebra)
408+ .await
409+ .unwrap()
410+ .unwrap();
411+
412+ let drop_it = {
413+ let db = db.clone();
414+ tokio::spawn(async move { crate::db::course::delete(&db, course).await })
415+ };
416+ // The attach starts inside the held window — the course row is gone
417+ // but uncommitted, which is exactly what a course read believes.
418+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
419+ let child = {
420+ let (db, class, algebra, manager) =
421+ (db.clone(), class.clone(), algebra.clone(), manager.clone());
422+ tokio::spawn(async move { attach(&db, &class, &algebra, &manager).await })
423+ };
424+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
425+ // A 404 for the attach, or a refusal for the delete, is a correct
426+ // answer — the only defect is stored state.
427+ assert!(
428+ !matches!(child, Err(AppError::Db(_))),
429+ "round {round}: a raced attach must be answered, not 500: {child:?}"
430+ );
431+
432+ // Stored state is the whole verdict; a return value is not evidence.
433+ if !exists(algebra.record(), &db).await {
434+ swept += 1;
435+ let link = ClassCourseId::composite(&class, &algebra);
436+ if exists(link.record(), &db).await {
437+ orphans += 1;
438+ }
439+ miscounted += counter("class_course_count", class.record(), &db).await;
440+ } else if matches!(drop_it, Ok(true)) {
441+ panic!("round {round}: the delete reported success but the course is still there");
442+ }
443+ }
444+ eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");
445+ assert!(
446+ swept > 0,
447+ "no round ever deleted the course, so the window was never reached"
448+ );
449+ assert_eq!(orphans, 0, "a class_course link outlived its course");
450+ assert_eq!(miscounted, 0, "a class counts a course that is gone");
451+ }
452+}
src/service/class_group.rsadded+81 -0
@@ -0,0 +1,81 @@
1+//! Class workflows: the archived-term guard every class write re-checks, and
2+//! the thin route-facing wrappers the handlers call. The queries live in
3+//! [`crate::db::class_group`].
4+
5+use crate::database::Database;
6+use crate::db::class_group;
7+use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName};
8+use crate::domain::term::{self, TermId};
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+/// Refuse the write when this class's term is archived — a pre-flight guard,
13+/// accepted race (see README concurrency model): a term archived after this
14+/// read still lets the write through.
15+pub async fn require_open(db: &Database, class: &ClassGroup) -> Result<(), AppError> {
16+ match class.get_term() {
17+ None => Ok(()),
18+ Some(term) => term::Term::require_open(term, db).await,
19+ }
20+}
21+
22+/// Create a class, claiming the term reference in the same transaction —
23+/// see [`class_group::create`].
24+pub async fn create(
25+ db: &Database,
26+ creator: &UserId,
27+ name: ClassName,
28+ grade: Option<ClassGrade>,
29+ term: Option<TermId>,
30+ teacher: Option<UserId>,
31+) -> Result<ClassGroup, AppError> {
32+ class_group::create(db, creator, name, grade, term, teacher).await
33+}
34+
35+/// The row, for callers that only inspect it — the web layer's
36+/// `class_or_404` reads through here.
37+pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> {
38+ class_group::read(db, id).await
39+}
40+
41+/// Every class, newest first — or one grade's, when `grade` narrows it: the
42+/// read behind the class index.
43+pub async fn list_all(
44+ db: &Database,
45+ grade: Option<Option<ClassGrade>>,
46+ limit: Option<i64>,
47+ offset: i64,
48+) -> Result<(Vec<ClassGroup>, i64), AppError> {
49+ class_group::list_all(db, grade, limit, offset).await
50+}
51+
52+/// The classes `ids` names, in no particular order — the join behind the two
53+/// membership reads.
54+pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<ClassGroup>, AppError> {
55+ class_group::list_by_ids(db, ids).await
56+}
57+
58+/// Write only the fields the PATCH carried; a term move claims the new term
59+/// and releases the old one inside the very transaction that moves the link.
60+pub async fn update(
61+ db: &Database,
62+ class: ClassGroup,
63+ name: Option<ClassName>,
64+ grade: Option<Option<ClassGrade>>,
65+ term: Option<Option<TermId>>,
66+ teacher: Option<Option<UserId>>,
67+) -> Result<ClassGroup, AppError> {
68+ class_group::update(db, class, name, grade, term, teacher).await
69+}
70+
71+/// Delete the class and give its term reference back; `false` = refused,
72+/// nothing was written (the class still holds students or courses).
73+pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> {
74+ class_group::delete(db, class).await
75+}
76+
77+/// Strip `user` from every class they were the homeroom teacher of — the
78+/// sweep for a user demoted below `teacher`.
79+pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
80+ class_group::unassign_everywhere(db, user).await
81+}
src/service/class_member.rsadded+439 -0
@@ -0,0 +1,439 @@
1+//! Class-membership workflows: the member-axis add and remove — the pump's
2+//! refusals mapped to this route's answers, and a zero-row sweep turned into
3+//! a 404 — plus the roster reads the web layer pages through. The transaction
4+//! itself lives in [`crate::db::class_pump`]; the table reads in
5+//! [`crate::db::class_member`].
6+
7+use surrealdb::types::SurrealValue;
8+
9+use crate::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
10+use crate::database::Database;
11+use crate::db::class_member;
12+use crate::db::class_pump::{self, Axis};
13+use crate::domain::class_group::ClassGroupId;
14+use crate::domain::class_member::{ClassMember, ClassMemberId};
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::UserId;
17+use crate::error::{AppError, ValidationError};
18+
19+/// Put `user` in `class` and enroll them into every course the class is
20+/// already attached to, in one transaction.
21+///
22+/// A student already enrolled in one of those courses keeps the row they
23+/// have — no seat is charged and their `source` is untouched, so a
24+/// hand-placed enrollment is never adopted by the class — and a course with
25+/// no free seat refuses the *whole* join rather than half of it.
26+pub async fn add(
27+ db: &Database,
28+ class: &ClassGroupId,
29+ user: &UserId,
30+ added_by: &UserId,
31+) -> Result<ClassMember, AppError> {
32+ let member = ClassMember {
33+ id: ClassMemberId::composite(class, user),
34+ class: class.clone(),
35+ user: user.clone(),
36+ added_by: added_by.clone(),
37+ added_at: Some(Timestamp::now()),
38+ };
39+ let landed = class_pump::attach(
40+ db,
41+ class,
42+ Axis::Member,
43+ (&member.id.record(), &member),
44+ user.record(),
45+ added_by.record(),
46+ None,
47+ )
48+ .await?;
49+ // Read off the refusal, never respelled here: this route and a
50+ // blueprint pump answer one vocabulary. `Made` is the only `None`, and
51+ // it takes the `Ok` arm below.
52+ let code = landed.refusal_code(&Axis::Member).unwrap_or_default();
53+ match landed {
54+ class_pump::Attached::Made(saved) => Ok(saved),
55+ class_pump::Attached::Duplicate => Err(AppError::ConflictCoded {
56+ code,
57+ message: "the student is already in this class".into(),
58+ }),
59+ class_pump::Attached::Gone => Err(AppError::NotFound),
60+ // The pivot is the student: they were demoted while this ran, which
61+ // is the refusal the caller's own read makes a moment earlier and
62+ // the only one that can arrive after it.
63+ class_pump::Attached::PivotGone => Err(AppError::Validation(ValidationError::Invalid {
64+ field: "user_id",
65+ reason: "only students can be added to a class",
66+ })),
67+ class_pump::Attached::ClassFull => Err(AppError::ConflictCoded {
68+ code,
69+ message: format!("this class already holds {MAX_CLASS_MEMBERS} students"),
70+ }),
71+ // The other axis: adding one student enrolls them into every
72+ // attached course, so a class over *that* ceiling cannot take a
73+ // member however much room its roster has.
74+ class_pump::Attached::ClassOverloaded => Err(AppError::ConflictCoded {
75+ code,
76+ message: format!(
77+ "this class holds more than {MAX_CLASS_COURSES} courses — \
78+ detach some before adding a student"
79+ ),
80+ }),
81+ class_pump::Attached::Full(course) => Err(AppError::ConflictCoded {
82+ code,
83+ message: format!("{course} is full, so the class cannot take this student"),
84+ }),
85+ // Not a capacity problem, and told apart from one on purpose: no
86+ // number anyone can raise unblocks this class, only detaching the
87+ // link the deleted course left behind.
88+ class_pump::Attached::CourseGone(course) => Err(AppError::ConflictCoded {
89+ code,
90+ message: format!("{course} no longer exists — detach it from this class first"),
91+ }),
92+ // Only an attach run on a blueprint's behalf states that claim, and
93+ // a membership is nobody's but its own.
94+ class_pump::Attached::SourceGone => Err(AppError::Internal(
95+ "a class membership has no blueprint to lose".into(),
96+ )),
97+ }
98+}
99+
100+/// Take `user` out of `class` and sweep the enrollments the class pumped
101+/// for them. A student who was not in the class is a
102+/// [`AppError::NotFound`], raised here rather than left to each caller to
103+/// re-derive from a boolean.
104+///
105+/// An enrollment another attached class still claims is re-tagged to that
106+/// class instead of deleted (see [`crate::db::class_pump::detach`]).
107+pub async fn remove(db: &Database, class: &ClassGroupId, user: &UserId) -> Result<(), AppError> {
108+ let gone = class_pump::detach(
109+ db,
110+ "$link",
111+ Axis::Member,
112+ &[(
113+ "link".into(),
114+ ClassMemberId::composite(class, user).record().into_value(),
115+ )],
116+ )
117+ .await?;
118+ (gone > 0).then_some(()).ok_or(AppError::NotFound)
119+}
120+
121+/// The class's roster, newest first, paged — the read behind
122+/// `GET /classes/{id}/members`.
123+pub async fn list_for_class(
124+ db: &Database,
125+ class: &ClassGroupId,
126+ limit: Option<i64>,
127+ offset: i64,
128+) -> Result<(Vec<ClassMember>, i64), AppError> {
129+ class_member::list_for_class(db, class, limit, offset).await
130+}
131+
132+/// The classes one student belongs to, newest membership first, paged — the
133+/// read behind `GET /classes/me` and `GET /classes/user/{user}`.
134+pub async fn list_for_user(
135+ db: &Database,
136+ user: &UserId,
137+ limit: Option<i64>,
138+ offset: i64,
139+) -> Result<(Vec<ClassMember>, i64), AppError> {
140+ class_member::list_for_user(db, user, limit, offset).await
141+}
142+
143+#[cfg(test)]
144+mod tests {
145+ use super::*;
146+ use crate::db::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
147+ use crate::domain::enrollment::EnrollmentId;
148+ use crate::service::class_course;
149+
150+ /// Adding a member enrolls them into every course the class already
151+ /// carries, each row tagged with the class, and the class's own member
152+ /// counter ticks once.
153+ #[tokio::test]
154+ async fn a_member_is_enrolled_into_every_attached_course() {
155+ let db = crate::database::init_mem().await.unwrap();
156+ let manager = UserId::from_key("manager");
157+ let student = UserId::from_key("student");
158+ let class = a_class("9-A", &db).await;
159+ let algebra = a_course("algebra", None, &db).await;
160+ let physics = a_course("physics", None, &db).await;
161+ class_course::attach(&db, &class, &algebra, &manager)
162+ .await
163+ .unwrap();
164+ class_course::attach(&db, &class, &physics, &manager)
165+ .await
166+ .unwrap();
167+
168+ add(&db, &class, &student, &manager).await.unwrap();
169+
170+ for course in [&algebra, &physics] {
171+ assert_eq!(
172+ source_of(course, &student, &db).await,
173+ Some(Some(class.clone())),
174+ "every attached course must hold a row tagged with the class"
175+ );
176+ assert_eq!(counter("enrollment_count", course.record(), &db).await, 1);
177+ }
178+ assert_eq!(counter("class_member_count", class.record(), &db).await, 1);
179+ }
180+
181+ /// The pumped row must carry the *same* composite id a hand enroll would
182+ /// mint, or the two paths would key one pair two ways and only the unique
183+ /// index (a 500) would notice.
184+ #[tokio::test]
185+ async fn a_pumped_row_uses_the_hand_enrolls_composite_id() {
186+ let db = crate::database::init_mem().await.unwrap();
187+ let manager = UserId::from_key("manager");
188+ let student = UserId::from_key("student");
189+ let class = a_class("9-A", &db).await;
190+ let algebra = a_course("algebra", None, &db).await;
191+ class_course::attach(&db, &class, &algebra, &manager)
192+ .await
193+ .unwrap();
194+ add(&db, &class, &student, &manager).await.unwrap();
195+
196+ assert!(
197+ exists(EnrollmentId::composite(&algebra, &student).record(), &db).await,
198+ "the pump must key the pair the way Enrollment::composite does"
199+ );
200+ }
201+
202+ /// Re-adding is a 409, and it must cost nothing: no second counter tick and
203+ /// no second sweep of anybody's enrollment.
204+ #[tokio::test]
205+ async fn a_second_add_is_refused_and_writes_nothing() {
206+ let db = crate::database::init_mem().await.unwrap();
207+ let manager = UserId::from_key("manager");
208+ let student = UserId::from_key("student");
209+ let class = a_class("9-A", &db).await;
210+ let algebra = a_course("algebra", None, &db).await;
211+ class_course::attach(&db, &class, &algebra, &manager)
212+ .await
213+ .unwrap();
214+ add(&db, &class, &student, &manager).await.unwrap();
215+
216+ let again = add(&db, &class, &student, &manager).await;
217+ assert!(
218+ matches!(again, Err(AppError::ConflictCoded { code, .. }) if code == "duplicate"),
219+ "a second add is a 409 coded `duplicate`: {again:?}"
220+ );
221+ assert_eq!(
222+ counter("class_member_count", class.record(), &db).await,
223+ 1,
224+ "a refused add may not tick the counter"
225+ );
226+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
227+ }
228+
229+ /// Adding into a class whose courses have no room refuses the *whole* join:
230+ /// the roomy course must not keep a seat the full one denied.
231+ #[tokio::test]
232+ async fn a_full_course_refuses_the_whole_join() {
233+ let db = crate::database::init_mem().await.unwrap();
234+ let manager = UserId::from_key("manager");
235+ let student = UserId::from_key("student");
236+ let class = a_class("9-A", &db).await;
237+ let roomy = a_course("algebra", None, &db).await;
238+ let full = a_course("physics", Some(0), &db).await;
239+ class_course::attach(&db, &class, &roomy, &manager)
240+ .await
241+ .unwrap();
242+ class_course::attach(&db, &class, &full, &manager)
243+ .await
244+ .unwrap();
245+
246+ // The whole record id, not just the key: a caller reading the 409 must
247+ // not have to guess which table the name came from.
248+ let named = format!("{}:{}", crate::constant::COURSE_TABLE, full.key());
249+ let refused = add(&db, &class, &student, &manager).await;
250+ assert!(
251+ matches!(refused, Err(AppError::ConflictCoded { code, ref message })
252+ if code == "course_full" && message.contains(&named)),
253+ "the refusal must be coded `course_full` and name the course that had no seat \
254+ as {named}: {refused:?}"
255+ );
256+ assert_eq!(
257+ rows("SELECT VALUE id FROM enrollment", &db).await,
258+ 0,
259+ "not one seat may survive the refusal"
260+ );
261+ assert_eq!(
262+ rows("SELECT VALUE id FROM class_member", &db).await,
263+ 0,
264+ "…nor the membership row itself"
265+ );
266+ assert_eq!(
267+ counter("enrollment_count", roomy.record(), &db).await,
268+ 0,
269+ "…nor the roomy course's counter"
270+ );
271+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
272+ }
273+
274+ /// A student already enrolled by hand keeps their own row: no seat is
275+ /// charged for them, the row's `source` stays empty, and removing them from
276+ /// the class leaves it standing.
277+ #[tokio::test]
278+ async fn a_hand_placed_enrollment_is_skipped_and_survives_removal() {
279+ let db = crate::database::init_mem().await.unwrap();
280+ let manager = UserId::from_key("manager");
281+ let student = UserId::from_key("student");
282+ let class = a_class("9-A", &db).await;
283+ let algebra = a_course("algebra", None, &db).await;
284+ crate::db::enrollment::enroll(&db, &algebra, &student, &manager)
285+ .await
286+ .unwrap();
287+ class_course::attach(&db, &class, &algebra, &manager)
288+ .await
289+ .unwrap();
290+
291+ add(&db, &class, &student, &manager).await.unwrap();
292+ assert_eq!(
293+ source_of(&algebra, &student, &db).await,
294+ Some(None),
295+ "the class must not adopt a hand-placed row"
296+ );
297+ assert_eq!(
298+ counter("enrollment_count", algebra.record(), &db).await,
299+ 1,
300+ "the skipped pair may not be charged a second seat"
301+ );
302+
303+ remove(&db, &class, &student).await.unwrap();
304+ assert_eq!(
305+ source_of(&algebra, &student, &db).await,
306+ Some(None),
307+ "the sweep may only take back the rows the class wrote"
308+ );
309+ assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 1);
310+ }
311+
312+ /// Removal with nobody else claiming the row: the enrollment goes and its
313+ /// seat comes back.
314+ #[tokio::test]
315+ async fn removal_deletes_the_rows_the_class_pumped() {
316+ let db = crate::database::init_mem().await.unwrap();
317+ let manager = UserId::from_key("manager");
318+ let student = UserId::from_key("student");
319+ let class = a_class("9-A", &db).await;
320+ let algebra = a_course("algebra", None, &db).await;
321+ class_course::attach(&db, &class, &algebra, &manager)
322+ .await
323+ .unwrap();
324+ add(&db, &class, &student, &manager).await.unwrap();
325+
326+ remove(&db, &class, &student).await.unwrap();
327+ assert_eq!(source_of(&algebra, &student, &db).await, None);
328+ assert_eq!(
329+ counter("enrollment_count", algebra.record(), &db).await,
330+ 0,
331+ "the seat must come back with the row that held it"
332+ );
333+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
334+ let again = remove(&db, &class, &student).await;
335+ assert!(
336+ matches!(again, Err(AppError::NotFound)),
337+ "a second removal is a 404, not a second sweep: {again:?}"
338+ );
339+ }
340+
341+ /// A member who is not in any attached course still removes cleanly, and a
342+ /// course deleted out from under the class leaves nothing to sweep — the
343+ /// membership row and the pumped enrollment are independent facts.
344+ #[tokio::test]
345+ async fn a_sweep_tolerates_rows_a_course_delete_already_took() {
346+ let db = crate::database::init_mem().await.unwrap();
347+ let manager = UserId::from_key("manager");
348+ let student = UserId::from_key("student");
349+ let class = a_class("9-A", &db).await;
350+ let algebra = a_course("algebra", None, &db).await;
351+ class_course::attach(&db, &class, &algebra, &manager)
352+ .await
353+ .unwrap();
354+ add(&db, &class, &student, &manager).await.unwrap();
355+
356+ // `Course::delete` refuses while the roster is occupied, so the wipe is
357+ // spelled the way the cascade does it, minus the guard.
358+ db.query("DELETE enrollment WHERE course = $course; DELETE class_course WHERE course = $course; DELETE $course;")
359+ .bind(("course", algebra.record()))
360+ .await
361+ .unwrap()
362+ .check()
363+ .unwrap();
364+
365+ remove(&db, &class, &student)
366+ .await
367+ .expect("the membership must still be removable with its enrollment gone");
368+ assert_eq!(counter("class_member_count", class.record(), &db).await, 0);
369+ }
370+
371+ /// The role-change sweep, which is one transaction with the role write
372+ /// itself: the memberships go with their counters, the enrollment rows go
373+ /// with their seats, and each seat comes back exactly once — the double
374+ /// decrement the old two-call split existed to avoid.
375+ #[tokio::test]
376+ async fn the_role_sweep_takes_memberships_and_enrollments_together() {
377+ let db = crate::database::init_mem().await.unwrap();
378+ let manager = UserId::from_key("manager");
379+ // A real row, because the sweep now rides on the role write.
380+ let hash = crate::domain::user::Password::try_new("secret1")
381+ .unwrap()
382+ .hash_async()
383+ .await
384+ .unwrap();
385+ let account = crate::db::user::create(
386+ &db,
387+ crate::domain::user::Username::try_new("ogrenci").unwrap(),
388+ hash,
389+ )
390+ .await
391+ .unwrap();
392+ let student = account.get_id().clone();
393+ let first = a_class("9-A", &db).await;
394+ let second = a_class("club", &db).await;
395+ let algebra = a_course("algebra", None, &db).await;
396+ class_course::attach(&db, &first, &algebra, &manager)
397+ .await
398+ .unwrap();
399+ add(&db, &first, &student, &manager).await.unwrap();
400+ add(&db, &second, &student, &manager).await.unwrap();
401+
402+ crate::service::user::set_role(&db, account.get_id(), crate::domain::role::Role::Teacher)
403+ .await
404+ .unwrap();
405+ assert_eq!(rows("SELECT VALUE id FROM class_member", &db).await, 0);
406+ for class in [&first, &second] {
407+ assert_eq!(
408+ counter("class_member_count", class.record(), &db).await,
409+ 0,
410+ "every class must get its member count back"
411+ );
412+ }
413+ assert_eq!(
414+ source_of(&algebra, &student, &db).await,
415+ None,
416+ "the enrollment goes in the same transaction as the membership"
417+ );
418+ assert_eq!(
419+ counter("enrollment_count", algebra.record(), &db).await,
420+ 0,
421+ "…and its seat comes back once, not twice"
422+ );
423+ // Which is the point of folding them: the class the student was in is
424+ // free of them entirely — no membership, no count, and no enrollment
425+ // row left tagged with a class that is about to be deletable.
426+ assert!(
427+ crate::db::class_group::delete(
428+ &db,
429+ crate::db::class_group::read(&db, &second)
430+ .await
431+ .unwrap()
432+ .unwrap(),
433+ )
434+ .await
435+ .unwrap(),
436+ "a class holding neither members nor courses must delete"
437+ );
438+ }
439+}
src/service/mod.rsmodified+3 -0
@@ -9,6 +9,9 @@ pub mod builder;
9 pub mod chatbot_message;9 pub mod chatbot_message;
10 pub mod chatbot_thread;10 pub mod chatbot_thread;
11 pub mod class_blueprint;11 pub mod class_blueprint;
12+pub mod class_course;
13+pub mod class_group;
14+pub mod class_member;
12 pub mod course;15 pub mod course;
13 pub mod course_session;16 pub mod course_session;
14 pub mod dietary_profile;17 pub mod dietary_profile;
src/web/boards.rsmodified+13 -9
@@ -32,8 +32,7 @@ use crate::constant::MAX_BOARD_PARTICIPANTS;
32 use crate::database::Database;32 use crate::database::Database;
33 use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle};33 use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle};
34 use crate::domain::board_stroke::BoardStroke;34 use crate::domain::board_stroke::BoardStroke;
35-use crate::domain::class_group::{ClassGroup, ClassGroupId};35+use crate::domain::class_group::ClassGroupId;
36-use crate::domain::class_member::ClassMember;
37 use crate::domain::course::CourseId;36 use crate::domain::course::CourseId;
38 use crate::domain::event::EventId;37 use crate::domain::event::EventId;
39 use crate::domain::role::Role;38 use crate::domain::role::Role;
@@ -727,18 +726,23 @@ impl InviteSource {
727 ));726 ));
728 }727 }
729 let class = ClassGroupId::from_key(&class);728 let class = ClassGroupId::from_key(&class);
730- if ClassGroup::read(&class, db).await?.is_none() {729+ if crate::service::class_group::read(db, &class)
730+ .await?
731+ .is_none()
732+ {
731 return Err(AppError::Validation(ValidationError::Invalid {733 return Err(AppError::Validation(ValidationError::Invalid {
732 field: "class",734 field: "class",
733 reason: "no such class section",735 reason: "no such class section",
734 }));736 }));
735 }737 }
736- Ok(ClassMember::list_for_class(&class, None, 0, db)738+ Ok(
737- .await?739+ crate::service::class_member::list_for_class(db, &class, None, 0)
738- .0740+ .await?
739- .iter()741+ .0
740- .map(|member| member.get_user().clone())742+ .iter()
741- .collect())743+ .map(|member| member.get_user().clone())
744+ .collect(),
745+ )
742 }746 }
743 InviteSource::Course { course } => {747 InviteSource::Course { course } => {
744 let course = crate::service::course::read(db, &CourseId::from_key(&course))748 let course = crate::service::course::read(db, &CourseId::from_key(&course))
src/web/classes.rsmodified+31 -31
@@ -25,9 +25,9 @@ use crate::domain::course::CourseId;
25 use crate::domain::role::Role;25 use crate::domain::role::Role;
26 use crate::domain::user::{User, UserId};26 use crate::domain::user::{User, UserId};
27 use crate::error::{AppError, ErrorResponse, ValidationError};27 use crate::error::{AppError, ErrorResponse, ValidationError};
28-use crate::service::class_blueprint;
29 use crate::service::parent_link::ensure_can_observe;28 use crate::service::parent_link::ensure_can_observe;
30 use crate::service::term;29 use crate::service::term;
30+use crate::service::{class_blueprint, class_course, class_group, class_member};
31 use crate::state::AppState;31 use crate::state::AppState;
32 32
33 use super::courses::can_manage_course;33 use super::courses::can_manage_course;
@@ -238,7 +238,7 @@ impl ClassCourseResponse {
238 /// The class a path id names, or a 404 — every route under `/classes/{id}`238 /// The class a path id names, or a 404 — every route under `/classes/{id}`
239 /// gates on it, so a missing class never reads as an empty roster.239 /// gates on it, so a missing class never reads as an empty roster.
240 async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> {240 async fn class_or_404(id: &str, db: &Database) -> Result<ClassGroup, AppError> {
241- ClassGroup::read(&ClassGroupId::from_key(id), db)241+ class_group::read(db, &ClassGroupId::from_key(id))
242 .await?242 .await?
243 .ok_or(AppError::NotFound)243 .ok_or(AppError::NotFound)
244 }244 }
@@ -300,7 +300,7 @@ async fn classes_page(
300 with_creator: bool,300 with_creator: bool,
301 db: &Database,301 db: &Database,
302 ) -> Result<Page<ClassResponse>, AppError> {302 ) -> Result<Page<ClassResponse>, AppError> {
303- let classes = ClassGroup::list_by_ids(ids, db).await?;303+ let classes = class_group::list_by_ids(db, ids).await?;
304 let by_id: std::collections::HashMap<&str, &ClassGroup> = classes304 let by_id: std::collections::HashMap<&str, &ClassGroup> = classes
305 .iter()305 .iter()
306 .map(|class| (class.get_id().key(), class))306 .map(|class| (class.get_id().key(), class))
@@ -357,13 +357,13 @@ async fn create_class(
357 // with this very error — so an unknown id reads the same whichever side wins.357 // with this very error — so an unknown id reads the same whichever side wins.
358 let term = term::resolve(&st.db, req.term_id.as_deref()).await?;358 let term = term::resolve(&st.db, req.term_id.as_deref()).await?;
359 let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?;359 let teacher = teacher_or_none(req.teacher_id.as_deref(), &st.db).await?;
360- let class = ClassGroup::create(360+ let class = class_group::create(
361+ &st.db,
361 user.get_id(),362 user.get_id(),
362 name,363 name,
363 grade,364 grade,
364 term,365 term,
365 teacher.as_ref().map(|t| t.get_id().clone()),366 teacher.as_ref().map(|t| t.get_id().clone()),
366- &st.db,
367 )367 )
368 .await?;368 .await?;
369 // The row is written; a demotion that raced this request's role check swept369 // The row is written; a demotion that raced this request's role check swept
@@ -380,7 +380,7 @@ async fn create_class(
380 // and both of its counters are still absent — so a refusal is a broken380 // and both of its counters are still absent — so a refusal is a broken
381 // invariant, not a client error, and it must not be reported as the381 // invariant, not a client error, and it must not be reported as the
382 // `409` whose text promises nothing was created.382 // `409` whose text promises nothing was created.
383- if !class.clone().delete(&st.db).await? {383+ if !class_group::delete(&st.db, class.clone()).await? {
384 return Err(AppError::Internal(format!(384 return Err(AppError::Internal(format!(
385 "class {} took a member or a course between its create and the \385 "class {} took a member or a course between its create and the \
386 rollback of a demoted homeroom teacher; it is still there, \386 rollback of a demoted homeroom teacher; it is still there, \
@@ -489,7 +489,7 @@ async fn list_classes(
489 .as_deref()489 .as_deref()
490 .map(|grade| grade_or_none(Some(grade)))490 .map(|grade| grade_or_none(Some(grade)))
491 .transpose()?;491 .transpose()?;
492- let (classes, total) = ClassGroup::list_all(grade, limit, offset, &st.db).await?;492+ let (classes, total) = class_group::list_all(&st.db, grade, limit, offset).await?;
493 // Join people onto the page alone — the lookup shrinks with the window.493 // Join people onto the page alone — the lookup shrinks with the window.
494 let people = person_map(494 let people = person_map(
495 classes.iter().flat_map(|class| class_people(class, true)),495 classes.iter().flat_map(|class| class_people(class, true)),
@@ -555,7 +555,7 @@ async fn update_class(
555 let class = class_or_404(&id, &st.db).await?;555 let class = class_or_404(&id, &st.db).await?;
556 // The class's *current* term, so a move off an archived year is refused556 // The class's *current* term, so a move off an archived year is refused
557 // too; `term::resolve` below holds the other end (the term moved onto).557 // too; `term::resolve` below holds the other end (the term moved onto).
558- class.require_open(&st.db).await?;558+ class_group::require_open(&st.db, &class).await?;
559 559
560 // Only what the request actually carried is validated and written — an560 // Only what the request actually carried is validated and written — an
561 // omitted field stays `None` so the save never re-sends this snapshot's561 // omitted field stays `None` so the save never re-sends this snapshot's
@@ -579,15 +579,15 @@ async fn update_class(
579 let assigned = teacher579 let assigned = teacher
580 .as_ref()580 .as_ref()
581 .and_then(|teacher| teacher.as_ref().map(|teacher| teacher.get_id().clone()));581 .and_then(|teacher| teacher.as_ref().map(|teacher| teacher.get_id().clone()));
582- let updated = class582+ let updated = class_group::update(
583- .update(583+ &st.db,
584- name,584+ class,
585- grade,585+ name,
586- term,586+ grade,
587- teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())),587+ term,
588- &st.db,588+ teacher.map(|teacher| teacher.map(|teacher| teacher.get_id().clone())),
589- )589+ )
590- .await?;590+ .await?;
591 // Only when this request named a teacher: a PATCH that left the column591 // Only when this request named a teacher: a PATCH that left the column
592 // alone raced nobody's demotion (see [`undo_if_demoted`]). The undo clears592 // alone raced nobody's demotion (see [`undo_if_demoted`]). The undo clears
593 // the column, which is the whole of what this request wrote to it.593 // the column, which is the whole of what this request wrote to it.
@@ -678,7 +678,7 @@ async fn classes_of(
678 with_creator: bool,678 with_creator: bool,
679 db: &Database,679 db: &Database,
680 ) -> Result<Page<ClassResponse>, AppError> {680 ) -> Result<Page<ClassResponse>, AppError> {
681- let (rows, total) = ClassMember::list_for_user(user, limit, offset, db).await?;681+ let (rows, total) = class_member::list_for_user(db, user, limit, offset).await?;
682 let ids: Vec<ClassGroupId> = rows.iter().map(|row| row.get_class().clone()).collect();682 let ids: Vec<ClassGroupId> = rows.iter().map(|row| row.get_class().clone()).collect();
683 classes_page(&ids, total, limit, offset, with_creator, db).await683 classes_page(&ids, total, limit, offset, with_creator, db).await
684 }684 }
@@ -706,8 +706,8 @@ async fn delete_class(
706 Path(id): Path<String>,706 Path(id): Path<String>,
707 ) -> Result<StatusCode, AppError> {707 ) -> Result<StatusCode, AppError> {
708 let class = class_or_404(&id, &st.db).await?;708 let class = class_or_404(&id, &st.db).await?;
709- class.require_open(&st.db).await?;709+ class_group::require_open(&st.db, &class).await?;
710- if !class.delete(&st.db).await? {710+ if !class_group::delete(&st.db, class).await? {
711 return Err(AppError::Conflict(711 return Err(AppError::Conflict(
712 "this class still holds students or courses — remove its members and detach its courses first",712 "this class still holds students or courses — remove its members and detach its courses first",
713 ));713 ));
@@ -746,7 +746,7 @@ async fn add_member(
746 Json(req): Json<AddMember>,746 Json(req): Json<AddMember>,
747 ) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> {747 ) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> {
748 let class = class_or_404(&id, &st.db).await?;748 let class = class_or_404(&id, &st.db).await?;
749- class.require_open(&st.db).await?;749+ class_group::require_open(&st.db, &class).await?;
750 750
751 let target = UserId::from_key(&req.user_id);751 let target = UserId::from_key(&req.user_id);
752 let Some(target_user) = crate::service::user::read(&st.db, &target).await? else {752 let Some(target_user) = crate::service::user::read(&st.db, &target).await? else {
@@ -764,7 +764,7 @@ async fn add_member(
764 }));764 }));
765 }765 }
766 766
767- let member = ClassMember::add(class.get_id(), &target, user.get_id(), &st.db).await?;767+ let member = class_member::add(&st.db, class.get_id(), &target, user.get_id()).await?;
768 let people = PersonRef::map_of(&[&target_user, &user]);768 let people = PersonRef::map_of(&[&target_user, &user]);
769 Ok((769 Ok((
770 StatusCode::CREATED,770 StatusCode::CREATED,
@@ -797,7 +797,7 @@ async fn list_members(
797 ) -> Result<Json<Page<ClassMemberResponse>>, AppError> {797 ) -> Result<Json<Page<ClassMemberResponse>>, AppError> {
798 let (limit, offset) = page.resolve()?;798 let (limit, offset) = page.resolve()?;
799 let class = class_or_404(&id, &st.db).await?;799 let class = class_or_404(&id, &st.db).await?;
800- let (rows, total) = ClassMember::list_for_class(class.get_id(), limit, offset, &st.db).await?;800+ let (rows, total) = class_member::list_for_class(&st.db, class.get_id(), limit, offset).await?;
801 // Join people onto the page alone — the lookup shrinks with the window.801 // Join people onto the page alone — the lookup shrinks with the window.
802 let people = person_map(802 let people = person_map(
803 rows.iter()803 rows.iter()
@@ -839,8 +839,8 @@ async fn remove_member(
839 Path((id, target)): Path<(String, String)>,839 Path((id, target)): Path<(String, String)>,
840 ) -> Result<StatusCode, AppError> {840 ) -> Result<StatusCode, AppError> {
841 let class = class_or_404(&id, &st.db).await?;841 let class = class_or_404(&id, &st.db).await?;
842- class.require_open(&st.db).await?;842+ class_group::require_open(&st.db, &class).await?;
843- ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?;843+ class_member::remove(&st.db, class.get_id(), &UserId::from_key(&target)).await?;
844 Ok(StatusCode::NO_CONTENT)844 Ok(StatusCode::NO_CONTENT)
845 }845 }
846 846
@@ -890,10 +890,10 @@ async fn attach_course(
890 ));890 ));
891 }891 }
892 // Both ends: neither a class nor a course on a past year takes a new link.892 // Both ends: neither a class nor a course on a past year takes a new link.
893- class.require_open(&st.db).await?;893+ class_group::require_open(&st.db, &class).await?;
894 crate::service::course::require_open(&st.db, &course).await?;894 crate::service::course::require_open(&st.db, &course).await?;
895 895
896- let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?;896+ let link = class_course::attach(&st.db, class.get_id(), course.get_id(), user.get_id()).await?;
897 let people = PersonRef::map_of(&[&user]);897 let people = PersonRef::map_of(&[&user]);
898 Ok((898 Ok((
899 StatusCode::CREATED,899 StatusCode::CREATED,
@@ -926,7 +926,7 @@ async fn list_class_courses(
926 ) -> Result<Json<Page<ClassCourseResponse>>, AppError> {926 ) -> Result<Json<Page<ClassCourseResponse>>, AppError> {
927 let (limit, offset) = page.resolve()?;927 let (limit, offset) = page.resolve()?;
928 let class = class_or_404(&id, &st.db).await?;928 let class = class_or_404(&id, &st.db).await?;
929- let (rows, total) = ClassCourse::list_for_class(class.get_id(), limit, offset, &st.db).await?;929+ let (rows, total) = class_course::list_for_class(&st.db, class.get_id(), limit, offset).await?;
930 let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?;930 let people = person_map(rows.iter().map(|row| row.get_attached_by().clone()), &st.db).await?;
931 let items = rows931 let items = rows
932 .iter()932 .iter()
@@ -982,11 +982,11 @@ async fn detach_course(
982 }982 }
983 // Both ends, and only what is still there: a link whose course row is gone983 // Both ends, and only what is still there: a link whose course row is gone
984 // has no term to read, and sweeping it is the whole point of the route.984 // has no term to read, and sweeping it is the whole point of the route.
985- class.require_open(&st.db).await?;985+ class_group::require_open(&st.db, &class).await?;
986 if let Some(row) = row.as_ref() {986 if let Some(row) = row.as_ref() {
987 crate::service::course::require_open(&st.db, row).await?;987 crate::service::course::require_open(&st.db, row).await?;
988 }988 }
989- ClassCourse::detach(class.get_id(), &course, &st.db).await?;989+ class_course::detach(&st.db, class.get_id(), &course).await?;
990 Ok(StatusCode::NO_CONTENT)990 Ok(StatusCode::NO_CONTENT)
991 }991 }
992 992
@@ -1455,7 +1455,7 @@ async fn apply_blueprint(
1455 // The pump writes both ends, so both are guarded — the class, and every1455 // The pump writes both ends, so both are guarded — the class, and every
1456 // course the template would attach. A course the template names that is1456 // course the template would attach. A course the template names that is
1457 // already gone is the pump's own `skipped` business, not a term refusal.1457 // already gone is the pump's own `skipped` business, not a term refusal.
1458- class.require_open(&st.db).await?;1458+ class_group::require_open(&st.db, &class).await?;
1459 for id in blueprint.get_courses() {1459 for id in blueprint.get_courses() {
1460 if let Some(course) = crate::service::course::read(&st.db, id).await? {1460 if let Some(course) = crate::service::course::read(&st.db, id).await? {
1461 crate::service::course::require_open(&st.db, &course).await?;1461 crate::service::course::require_open(&st.db, &course).await?;
src/web/events.rsmodified+5 -2
@@ -11,7 +11,7 @@ use utoipa_axum::routes;
11 11
12 use crate::database::Database;12 use crate::database::Database;
13 use crate::domain::attendance::{Attendance, AttendanceStatus};13 use crate::domain::attendance::{Attendance, AttendanceStatus};
14-use crate::domain::class_group::{ClassGroup, ClassGroupId};14+use crate::domain::class_group::ClassGroupId;
15 use crate::domain::course::CourseId;15 use crate::domain::course::CourseId;
16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};16 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
17 use crate::domain::role::Role;17 use crate::domain::role::Role;
@@ -100,7 +100,10 @@ impl AudienceDto {
100 }100 }
101 AudienceDto::Class { class } => {101 AudienceDto::Class { class } => {
102 let class = ClassGroupId::from_key(&class);102 let class = ClassGroupId::from_key(&class);
103- if ClassGroup::read(&class, db).await?.is_none() {103+ if crate::service::class_group::read(db, &class)
104+ .await?
105+ .is_none()
106+ {
104 return Err(AppError::Validation(ValidationError::Invalid {107 return Err(AppError::Validation(ValidationError::Invalid {
105 field: "audience",108 field: "audience",
106 reason: "class does not exist",109 reason: "class does not exist",
src/web/mod.rsmodified+5 -5
@@ -105,7 +105,7 @@ pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<()
105 {105 {
106 return Ok(());106 return Ok(());
107 }107 }
108- crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?;108+ crate::service::class_group::unassign_everywhere(db, target).await?;
109 crate::service::course::unassign_everywhere(db, target).await?;109 crate::service::course::unassign_everywhere(db, target).await?;
110 Err(AppError::Conflict(110 Err(AppError::Conflict(
111 "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry",111 "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 {
376 /// forges those (see [`crate::db::cap`]).376 /// forges those (see [`crate::db::cap`]).
377 #[tokio::test]377 #[tokio::test]
378 async fn undo_if_demoted_repairs_both_assignments_or_neither() {378 async fn undo_if_demoted_repairs_both_assignments_or_neither() {
379- use crate::domain::class_group::{ClassGroup, ClassName};379+ use crate::domain::class_group::ClassName;
380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};380 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
381 use crate::domain::user::{Password, Username};381 use crate::domain::user::{Password, Username};
382 382
@@ -398,13 +398,13 @@ mod tests {
398 .unwrap()398 .unwrap()
399 .0;399 .0;
400 let assigned = async |db: &Database| {400 let assigned = async |db: &Database| {
401- let class = ClassGroup::create(401+ let class = crate::service::class_group::create(
402+ db,
402 &office,403 &office,
403 ClassName::try_new("9-A").unwrap(),404 ClassName::try_new("9-A").unwrap(),
404 None,405 None,
405 None,406 None,
406 Some(teacher.get_id().clone()),407 Some(teacher.get_id().clone()),
407- db,
408 )408 )
409 .await409 .await
410 .unwrap();410 .unwrap();
@@ -434,7 +434,7 @@ mod tests {
434 db: &Database,434 db: &Database,
435 ) -> (Option<UserId>, Vec<UserId>) {435 ) -> (Option<UserId>, Vec<UserId>) {
436 (436 (
437- ClassGroup::read(class, db)437+ crate::service::class_group::read(db, class)
438 .await438 .await
439 .unwrap()439 .unwrap()
440 .unwrap()440 .unwrap()
src/web/users.rsmodified+9 -5
@@ -14,8 +14,7 @@ use crate::constant::{
14 };14 };
15 use crate::database::Database;15 use crate::database::Database;
16 use crate::domain::badge::{self, BadgeAward};16 use crate::domain::badge::{self, BadgeAward};
17-use crate::domain::class_group::{ClassGroup, ClassGroupId};17+use crate::domain::class_group::ClassGroupId;
18-use crate::domain::class_member::ClassMember;
19 18
20 use crate::domain::preferences::{Language, PaletteColor, Theme};19 use crate::domain::preferences::{Language, PaletteColor, Theme};
21 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};20 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
@@ -927,8 +926,13 @@ async fn profile_of(
927 courses.retain(|course| readable.contains(course.get_id()));926 courses.retain(|course| readable.contains(course.get_id()));
928 }927 }
929 courses.truncate(MAX_PROFILE_COURSES);928 courses.truncate(MAX_PROFILE_COURSES);
930- let (mut members, class_total) =929+ let (mut members, class_total) = crate::service::class_member::list_for_user(
931- ClassMember::list_for_user(id, Some(MAX_PROFILE_CLASSES as i64), 0, &st.db).await?;930+ &st.db,
931+ id,
932+ Some(MAX_PROFILE_CLASSES as i64),
933+ 0,
934+ )
935+ .await?;
932 // The window is safe to take from the database here: the class gate is936 // The window is safe to take from the database here: the class gate is
933 // all-or-nothing, so it drops the whole page or none of it — never a row937 // all-or-nothing, so it drops the whole page or none of it — never a row
934 // out of the middle of one.938 // out of the middle of one.
@@ -936,7 +940,7 @@ async fn profile_of(
936 members.clear();940 members.clear();
937 }941 }
938 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();942 let class_ids: Vec<ClassGroupId> = members.iter().map(|row| row.get_class().clone()).collect();
939- let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?;943+ let classes = crate::service::class_group::list_by_ids(&st.db, &class_ids).await?;
940 // Both totals are the full counts, not the windowed ones — the blocks are a944 // Both totals are the full counts, not the windowed ones — the blocks are a
941 // preview, the stats are the truth.945 // preview, the stats are the truth.
942 let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?;946 let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?;
tests/regress_classes.rsmodified+31 -32
@@ -9,12 +9,11 @@ use axum::http::StatusCode;
9 use common::{Res, app_and_db, create_course, login_as, me_id, send, total};9 use common::{Res, app_and_db, create_course, login_as, me_id, send, total};
10 use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};10 use hezarfen_backend::constant::{MAX_CLASS_COURSES, MAX_CLASS_MEMBERS};
11 use hezarfen_backend::database::Database;11 use hezarfen_backend::database::Database;
12-use hezarfen_backend::domain::class_course::ClassCourse;12+use hezarfen_backend::domain::class_group::ClassName;
13-use hezarfen_backend::domain::class_group::{ClassGroup, ClassName};
14-use hezarfen_backend::domain::class_member::ClassMember;
15 use hezarfen_backend::domain::course::CourseId;13 use hezarfen_backend::domain::course::CourseId;
16 use hezarfen_backend::domain::user::UserId;14 use hezarfen_backend::domain::user::UserId;
17 use hezarfen_backend::error::AppError;15 use hezarfen_backend::error::AppError;
16+use hezarfen_backend::service::{class_course, class_group, class_member};
18 use serde_json::json;17 use serde_json::json;
19 18
20 /// One counter, re-read out of the store — never off a response body.19 /// 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) {
59 async fn an_attach_onto_a_deleted_course_writes_no_link() {58 async fn an_attach_onto_a_deleted_course_writes_no_link() {
60 let (_app, db) = app_and_db().await;59 let (_app, db) = app_and_db().await;
61 let manager = UserId::from_key("manager");60 let manager = UserId::from_key("manager");
62- let class = ClassGroup::create(61+ let class = class_group::create(
62+ &db,
63 &manager,63 &manager,
64 ClassName::try_new("9-A").unwrap(),64 ClassName::try_new("9-A").unwrap(),
65 None,65 None,
66 None,66 None,
67 None,67 None,
68- &db,
69 )68 )
70 .await69 .await
71 .unwrap();70 .unwrap();
@@ -73,7 +72,7 @@ async fn an_attach_onto_a_deleted_course_writes_no_link() {
73 // leaves behind.72 // leaves behind.
74 let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");73 let ghost = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
75 74
76- let refused = ClassCourse::attach(class.get_id(), &ghost, &manager, &db).await;75+ let refused = class_course::attach(&db, class.get_id(), &ghost, &manager).await;
77 assert!(76 assert!(
78 refused.is_err(),77 refused.is_err(),
79 "attaching a course that is gone must be refused: {refused:?}"78 "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() {
506 async fn a_roster_is_ordered_by_when_a_student_was_added() {505 async fn a_roster_is_ordered_by_when_a_student_was_added() {
507 let (_app, db) = app_and_db().await;506 let (_app, db) = app_and_db().await;
508 let manager = UserId::from_key("manager");507 let manager = UserId::from_key("manager");
509- let class = ClassGroup::create(508+ let class = class_group::create(
509+ &db,
510 &manager,510 &manager,
511 ClassName::try_new("9-A").unwrap(),511 ClassName::try_new("9-A").unwrap(),
512 None,512 None,
513 None,513 None,
514 None,514 None,
515- &db,
516 )515 )
517 .await516 .await
518 .unwrap()517 .unwrap()
@@ -525,13 +524,13 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
525 // which is the very order under test.524 // which is the very order under test.
526 let added = ["a", "c", "b"];525 let added = ["a", "c", "b"];
527 for key in added {526 for key in added {
528- ClassMember::add(&class, &UserId::from_key(key), &manager, &db)527+ class_member::add(&db, &class, &UserId::from_key(key), &manager)
529 .await528 .await
530 .unwrap();529 .unwrap();
531 tokio::time::sleep(std::time::Duration::from_millis(2)).await;530 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
532 }531 }
533 532
534- let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db)533+ let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
535 .await534 .await
536 .unwrap();535 .unwrap();
537 let order: Vec<&str> = roster536 let order: Vec<&str> = roster
@@ -554,7 +553,7 @@ async fn a_roster_is_ordered_by_when_a_student_was_added() {
554 .unwrap()553 .unwrap()
555 .check()554 .check()
556 .unwrap();555 .unwrap();
557- let (roster, _) = ClassMember::list_for_class(&class, None, 0, &db)556+ let (roster, _) = class_member::list_for_class(&db, &class, None, 0)
558 .await557 .await
559 .unwrap();558 .unwrap();
560 assert_eq!(559 assert_eq!(
@@ -574,13 +573,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
574 let (app, db) = app_and_db().await;573 let (app, db) = app_and_db().await;
575 let manager_cookie = login_as(&app, &db, "manager", "manager").await;574 let manager_cookie = login_as(&app, &db, "manager", "manager").await;
576 let manager = UserId::from_key(&me_id(&app, &manager_cookie).await);575 let manager = UserId::from_key(&me_id(&app, &manager_cookie).await);
577- let class = ClassGroup::create(576+ let class = class_group::create(
577+ &db,
578 &manager,578 &manager,
579 ClassName::try_new("9-A").unwrap(),579 ClassName::try_new("9-A").unwrap(),
580 None,580 None,
581 None,581 None,
582 None,582 None,
583- &db,
584 )583 )
585 .await584 .await
586 .unwrap()585 .unwrap()
@@ -596,13 +595,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
596 ));595 ));
597 }596 }
598 for course in courses.iter().rev() {597 for course in courses.iter().rev() {
599- ClassCourse::attach(&class, course, &manager, &db)598+ class_course::attach(&db, &class, course, &manager)
600 .await599 .await
601 .unwrap();600 .unwrap();
602 tokio::time::sleep(std::time::Duration::from_millis(2)).await;601 tokio::time::sleep(std::time::Duration::from_millis(2)).await;
603 }602 }
604 603
605- let (attached, _) = ClassCourse::list_for_class(&class, None, 0, &db)604+ let (attached, _) = class_course::list_for_class(&db, &class, None, 0)
606 .await605 .await
607 .unwrap();606 .unwrap();
608 let order: Vec<&str> = attached607 let order: Vec<&str> = attached
@@ -628,13 +627,13 @@ async fn a_class_course_list_is_ordered_by_when_it_was_attached() {
628 async fn a_class_refuses_the_member_past_its_ceiling() {627 async fn a_class_refuses_the_member_past_its_ceiling() {
629 let (_app, db) = app_and_db().await;628 let (_app, db) = app_and_db().await;
630 let manager = UserId::from_key("manager");629 let manager = UserId::from_key("manager");
631- let class = ClassGroup::create(630+ let class = class_group::create(
631+ &db,
632 &manager,632 &manager,
633 ClassName::try_new("9-A").unwrap(),633 ClassName::try_new("9-A").unwrap(),
634 None,634 None,
635 None,635 None,
636 None,636 None,
637- &db,
638 )637 )
639 .await638 .await
640 .unwrap()639 .unwrap()
@@ -648,10 +647,10 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
648 .check()647 .check()
649 .unwrap();648 .unwrap();
650 649
651- ClassMember::add(&class, &UserId::from_key("last"), &manager, &db)650+ class_member::add(&db, &class, &UserId::from_key("last"), &manager)
652 .await651 .await
653 .expect("the place under the ceiling is still free");652 .expect("the place under the ceiling is still free");
654- let refused = ClassMember::add(&class, &UserId::from_key("over"), &manager, &db).await;653+ let refused = class_member::add(&db, &class, &UserId::from_key("over"), &manager).await;
655 assert!(654 assert!(
656 matches!(refused, Err(AppError::ConflictCoded { code, ref message })655 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
657 if code == "class_at_roster_ceiling"656 if code == "class_at_roster_ceiling"
@@ -675,7 +674,7 @@ async fn a_class_refuses_the_member_past_its_ceiling() {
675 .unwrap()674 .unwrap()
676 .check()675 .check()
677 .unwrap();676 .unwrap();
678- let gone = ClassMember::add(&class, &UserId::from_key("ghost"), &manager, &db).await;677+ let gone = class_member::add(&db, &class, &UserId::from_key("ghost"), &manager).await;
679 assert!(678 assert!(
680 matches!(gone, Err(AppError::NotFound)),679 matches!(gone, Err(AppError::NotFound)),
681 "a class that is gone is a 404: {gone:?}"680 "a class that is gone is a 404: {gone:?}"
@@ -697,13 +696,13 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
697 let (app, db) = app_and_db().await;696 let (app, db) = app_and_db().await;
698 let cookie = login_as(&app, &db, "manager", "manager").await;697 let cookie = login_as(&app, &db, "manager", "manager").await;
699 let manager = UserId::from_key(&me_id(&app, &cookie).await);698 let manager = UserId::from_key(&me_id(&app, &cookie).await);
700- let class = ClassGroup::create(699+ let class = class_group::create(
700+ &db,
701 &manager,701 &manager,
702 ClassName::try_new("9-A").unwrap(),702 ClassName::try_new("9-A").unwrap(),
703 None,703 None,
704 None,704 None,
705 None,705 None,
706- &db,
707 )706 )
708 .await707 .await
709 .unwrap()708 .unwrap()
@@ -718,7 +717,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
718 .check()717 .check()
719 .unwrap();718 .unwrap();
720 719
721- let refused = ClassCourse::attach(&class, &algebra, &manager, &db).await;720+ let refused = class_course::attach(&db, &class, &algebra, &manager).await;
722 assert!(721 assert!(
723 matches!(refused, Err(AppError::ConflictCoded { code, ref message })722 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
724 if code == "class_roster_too_large"723 if code == "class_roster_too_large"
@@ -745,7 +744,7 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
745 .unwrap()744 .unwrap()
746 .check()745 .check()
747 .unwrap();746 .unwrap();
748- ClassCourse::attach(&class, &algebra, &manager, &db)747+ class_course::attach(&db, &class, &algebra, &manager)
749 .await748 .await
750 .expect("a class exactly at the ceiling is still a bounded transaction");749 .expect("a class exactly at the ceiling is still a bounded transaction");
751 }750 }
@@ -756,13 +755,13 @@ async fn a_class_over_the_other_axis_ceiling_attaches_nothing() {
756 async fn a_class_over_the_course_ceiling_takes_no_member() {755 async fn a_class_over_the_course_ceiling_takes_no_member() {
757 let (_app, db) = app_and_db().await;756 let (_app, db) = app_and_db().await;
758 let manager = UserId::from_key("manager");757 let manager = UserId::from_key("manager");
759- let class = ClassGroup::create(758+ let class = class_group::create(
759+ &db,
760 &manager,760 &manager,
761 ClassName::try_new("9-B").unwrap(),761 ClassName::try_new("9-B").unwrap(),
762 None,762 None,
763 None,763 None,
764 None,764 None,
765- &db,
766 )765 )
767 .await766 .await
768 .unwrap()767 .unwrap()
@@ -776,7 +775,7 @@ async fn a_class_over_the_course_ceiling_takes_no_member() {
776 .check()775 .check()
777 .unwrap();776 .unwrap();
778 777
779- let refused = ClassMember::add(&class, &UserId::from_key("ali"), &manager, &db).await;778+ let refused = class_member::add(&db, &class, &UserId::from_key("ali"), &manager).await;
780 assert!(779 assert!(
781 matches!(refused, Err(AppError::ConflictCoded { code, ref message })780 matches!(refused, Err(AppError::ConflictCoded { code, ref message })
782 if code == "class_course_list_too_large"781 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() {
1764 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);1763 let algebra = CourseId::from_key(&create_course(&app, &staff, "algebra").await);
1765 let mut made = Vec::new();1764 let mut made = Vec::new();
1766 for name in ["9-B", "9-A"] {1765 for name in ["9-B", "9-A"] {
1767- let class = ClassGroup::create(1766+ let class = class_group::create(
1767+ &db,
1768 &manager,1768 &manager,
1769 ClassName::try_new(name).unwrap(),1769 ClassName::try_new(name).unwrap(),
1770 None,1770 None,
1771 None,1771 None,
1772 None,1772 None,
1773- &db,
1774 )1773 )
1775 .await1774 .await
1776 .unwrap();1775 .unwrap();
1777 let class = class.get_id().clone();1776 let class = class.get_id().clone();
1778- ClassMember::add(&class, &student, &manager, &db)1777+ class_member::add(&db, &class, &student, &manager)
1779 .await1778 .await
1780 .unwrap();1779 .unwrap();
1781- ClassCourse::attach(&class, &algebra, &manager, &db)1780+ class_course::attach(&db, &class, &algebra, &manager)
1782 .await1781 .await
1783 .unwrap();1782 .unwrap();
1784 made.push(class);1783 made.push(class);
@@ -1806,7 +1805,7 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() {
1806 .check()1805 .check()
1807 .unwrap();1806 .unwrap();
1808 1807
1809- ClassCourse::detach(&owner, &algebra, &db).await.unwrap();1808+ class_course::detach(&db, &owner, &algebra).await.unwrap();
1810 assert_eq!(1809 assert_eq!(
1811 rows("SELECT VALUE id FROM enrollment", &db).await,1810 rows("SELECT VALUE id FROM enrollment", &db).await,
1812 0,1811 0,
tests/regress_role_sweep.rsmodified+7 -7
@@ -22,14 +22,14 @@ use axum::http::StatusCode;
22 use common::{app_and_db, login_as, me_id, send};22 use common::{app_and_db, login_as, me_id, send};
23 use hezarfen_backend::database::Database;23 use hezarfen_backend::database::Database;
24 use hezarfen_backend::db::enrollment;24 use hezarfen_backend::db::enrollment;
25-use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName};25+use hezarfen_backend::domain::class_group::{ClassGroupId, ClassName};
26-use hezarfen_backend::domain::class_member::ClassMember;
27 use hezarfen_backend::domain::course::CourseId;26 use hezarfen_backend::domain::course::CourseId;
28 use hezarfen_backend::domain::event::EventId;27 use hezarfen_backend::domain::event::EventId;
29 use hezarfen_backend::domain::role::Role;28 use hezarfen_backend::domain::role::Role;
30 use hezarfen_backend::domain::timestamp::Timestamp;29 use hezarfen_backend::domain::timestamp::Timestamp;
31 use hezarfen_backend::domain::user::UserId;30 use hezarfen_backend::domain::user::UserId;
32 use hezarfen_backend::service::registration;31 use hezarfen_backend::service::registration;
32+use hezarfen_backend::service::{class_group, class_member};
33 use serde_json::json;33 use serde_json::json;
34 34
35 /// How many rows `sql` selects ids for.35 /// How many rows `sql` selects ids for.
@@ -321,13 +321,13 @@ async fn a_class(db: &Database) -> ClassGroupId {
321 }321 }
322 322
323 async fn a_class_named(name: &str, db: &Database) -> ClassGroupId {323 async fn a_class_named(name: &str, db: &Database) -> ClassGroupId {
324- ClassGroup::create(324+ class_group::create(
325+ db,
325 &UserId::from_key("manager"),326 &UserId::from_key("manager"),
326 ClassName::try_new(name).unwrap(),327 ClassName::try_new(name).unwrap(),
327 None,328 None,
328 None,329 None,
329 None,330 None,
330- db,
331 )331 )
332 .await332 .await
333 .unwrap()333 .unwrap()
@@ -342,7 +342,7 @@ async fn a_membership_is_refused_once_the_student_is_demoted() {
342 let class = a_class(&db).await;342 let class = a_class(&db).await;
343 demote(&student, Role::Parent, &db).await;343 demote(&student, Role::Parent, &db).await;
344 344
345- let refused = ClassMember::add(&class, &student, &UserId::from_key("manager"), &db).await;345+ let refused = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;
346 assert!(346 assert!(
347 refused.is_err(),347 refused.is_err(),
348 "only students belong to a class: {refused:?}"348 "only students belong to a class: {refused:?}"
@@ -363,13 +363,13 @@ async fn a_membership_never_survives_the_demotion_it_raced() {
363 let class = a_class(&db).await;363 let class = a_class(&db).await;
364 // The bait: a membership the sweep will delete, which holds it open.364 // The bait: a membership the sweep will delete, which holds it open.
365 let earlier = a_class_named("9-B", &db).await;365 let earlier = a_class_named("9-B", &db).await;
366- ClassMember::add(&earlier, &student, &UserId::from_key("manager"), &db)366+ class_member::add(&db, &earlier, &student, &UserId::from_key("manager"))
367 .await367 .await
368 .unwrap();368 .unwrap();
369 hold_the_sweep("class_member", &db).await;369 hold_the_sweep("class_member", &db).await;
370 370
371 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;371 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
372- let joined = ClassMember::add(&class, &student, &UserId::from_key("manager"), &db).await;372+ let joined = class_member::add(&db, &class, &student, &UserId::from_key("manager")).await;
373 still_running(&demoting);373 still_running(&demoting);
374 demoting.await.unwrap();374 demoting.await.unwrap();
375 375