forge
Explore
Log in

Don't you dare go Hollow

🏫 add class groups and enrollment provenance

Browse files at this commit

4715b083462d9b41237efb8a598ab722330e9bb2Ahmet Kaan GümüşParent: 0a82a9b
  • feat
    • 🏫 add class groups and enrollment provenance
Show full message
feat: 🏫 add class groups and enrollment provenance
README.mdmodified+4 -1
@@ -2764,7 +2764,10 @@ src/
2764 course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson)2764 course_session.rs CourseSessionId · SessionTopic · CourseSession (a course's lesson)
2765 session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user)2765 session_attendance.rs SessionAttendanceId · SessionAttendance (roll call; one row per session+user)
2766 work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction)2766 work_entry.rs WorkEntryId · WorkEntry (staff stint; one open per user by construction)
2767- enrollment.rs EnrollmentId · Enrollment (one row per course+user)2767+ enrollment.rs EnrollmentId · Enrollment (one row per course+user; `source`
2768+ names the class that pumped it, absent when hand-placed)
2769+ class_group.rs ClassGroupId · ClassName · ClassGrade · ClassGroup (a şube;
2770+ deletable only with no members and no attached courses)
2768 exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight ·2771 exam.rs ExamId · ExamTitle · ExamDescription · ExamKind · ExamWeight ·
2769 ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course)2772 ExamMode · ExamDuration · ExamSchedule · Exam (belongs to a course)
2770 exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts)2773 exam_attempt.rs ExamAttemptId · AttemptStatus · ExamAttempt (numbered sittings per exam+user, metered by max_attempts)
src/domain/class_group.rsadded+493 -0
@@ -0,0 +1,493 @@
1+//! A class (şube): a named set of students the school manages as one, so a
2+//! course attach enrolls the whole set at once. The membership and the
3+//! attachments live in their own tables (`class_member`, `class_course`) and are
4+//! counted on this row — a class may only be deleted at zero on both, the same
5+//! stored guard shape courses and terms use.
6+//!
7+//! 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* column
9+//! ([`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 share
11+//! of it on the next migration.
12+
13+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14+
15+use crate::constant::{
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::domain::cap;
21+use crate::domain::field_update::FieldUpdate;
22+use crate::domain::monotonic_id::next_ulid;
23+use crate::domain::page::PagedList;
24+use crate::domain::term::TermId;
25+use crate::domain::user::UserId;
26+use crate::error::{AppError, ValidationError};
27+use crate::validate::{validate_optional, validate_required};
28+
29+/// The `THROW` marker the delete guard aborts with — a class that still holds
30+/// students or courses, or a class row that is no longer there.
31+const LINKS_MARK: &str = "class_links";
32+
33+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
34+pub struct ClassGroupId(RecordId);
35+
36+impl ClassGroupId {
37+ pub fn generate() -> Self {
38+ Self(RecordId::new(CLASS_GROUP_TABLE, next_ulid().to_string()))
39+ }
40+
41+ pub fn from_key(key: &str) -> Self {
42+ Self(RecordId::new(CLASS_GROUP_TABLE, key))
43+ }
44+
45+ pub fn record(&self) -> RecordId {
46+ self.0.clone()
47+ }
48+
49+ pub fn key(&self) -> &str {
50+ match &self.0.key {
51+ RecordIdKey::String(key) => key,
52+ _ => "",
53+ }
54+ }
55+}
56+
57+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
58+pub struct ClassName(String);
59+
60+impl ClassName {
61+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
62+ validate_required("name", value, MAX_CLASS_NAME_LEN)?;
63+ Ok(Self(value.to_string()))
64+ }
65+
66+ pub fn as_str(&self) -> &str {
67+ &self.0
68+ }
69+}
70+
71+/// The school's own label for the year a class sits in ("9", "10-A",
72+/// "anaokulu"). Free text on purpose — no school's grade ladder is the next
73+/// one's — and optional: a club-shaped class has no grade at all.
74+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
75+pub struct ClassGrade(String);
76+
77+impl ClassGrade {
78+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
79+ validate_optional("grade", value, MAX_CLASS_GRADE_LEN)?;
80+ Ok(Self(value.to_string()))
81+ }
82+
83+ pub fn as_str(&self) -> &str {
84+ &self.0
85+ }
86+}
87+
88+/// One class. `creator` is who made it; the two refcounts behind the delete
89+/// guard are database-side columns only, so no whole-row save can clobber one
90+/// (see [`crate::domain::cap`]).
91+#[derive(Debug, Clone, SurrealValue)]
92+pub struct ClassGroup {
93+ id: ClassGroupId,
94+ creator: UserId,
95+ name: ClassName,
96+ grade: Option<ClassGrade>,
97+ term: Option<TermId>,
98+}
99+
100+impl ClassGroup {
101+ pub fn get_id(&self) -> &ClassGroupId {
102+ &self.id
103+ }
104+
105+ pub fn get_creator(&self) -> &UserId {
106+ &self.creator
107+ }
108+
109+ pub fn get_name(&self) -> &ClassName {
110+ &self.name
111+ }
112+
113+ pub fn get_grade(&self) -> Option<&ClassGrade> {
114+ self.grade.as_ref()
115+ }
116+
117+ pub fn get_term(&self) -> Option<&TermId> {
118+ self.term.as_ref()
119+ }
120+
121+ pub fn is_creator(&self, user: &UserId) -> bool {
122+ &self.creator == user
123+ }
124+
125+ /// Create the class, claiming a reference on the term it links (if any)
126+ /// *before* the row is written: the claim is a conditional write on the term
127+ /// row, so it fails when the term is already gone and it makes the term
128+ /// undeletable the instant this link exists.
129+ pub async fn create(
130+ creator: &UserId,
131+ name: ClassName,
132+ grade: Option<ClassGrade>,
133+ term: Option<TermId>,
134+ db: &Database,
135+ ) -> Result<ClassGroup, AppError> {
136+ if let Some(term) = &term {
137+ claim_term(term, db).await?;
138+ }
139+ let claimed = term.clone();
140+ let class = ClassGroup {
141+ id: ClassGroupId::generate(),
142+ creator: creator.clone(),
143+ name,
144+ grade,
145+ term,
146+ };
147+ let created: Result<Option<ClassGroup>, _> =
148+ db.create(class.id.record()).content(class).await;
149+ match created {
150+ Ok(Some(created)) => Ok(created),
151+ other => {
152+ // The link never landed, so the reference has to go back.
153+ if let Some(term) = &claimed {
154+ cap::release(&term.record(), TERM_CLASS_COUNT_FIELD, db).await?;
155+ }
156+ match other {
157+ Err(err) => Err(err.into()),
158+ _ => Err(AppError::Internal("failed to create class".into())),
159+ }
160+ }
161+ }
162+ }
163+
164+ pub async fn read(id: &ClassGroupId, db: &Database) -> Result<Option<ClassGroup>, AppError> {
165+ Ok(db.select(id.record()).await?)
166+ }
167+
168+ /// Every class, newest first.
169+ pub async fn list_all(
170+ limit: Option<i64>,
171+ offset: i64,
172+ db: &Database,
173+ ) -> Result<(Vec<ClassGroup>, i64), AppError> {
174+ PagedList::new("class_group", "ORDER BY id DESC")
175+ .run(limit, offset, db)
176+ .await
177+ }
178+
179+ /// Write only the fields the PATCH carried — `None` means the request
180+ /// omitted it, so the column is left alone rather than re-stated from the
181+ /// snapshot this struct was read into. `grade` and `term` are nullable, so
182+ /// they take the outer/inner `Option<Option<_>>`: `None` = omitted (keep),
183+ /// `Some(None)` = clear.
184+ ///
185+ /// A term move is claim-then-write-then-release, in that order, exactly as
186+ /// in [`crate::domain::course::Course::update`]: the new term is made
187+ /// undeletable before the link points at it, and the old one is only let go
188+ /// once the link has actually moved off it.
189+ pub async fn update(
190+ self,
191+ name: Option<ClassName>,
192+ grade: Option<Option<ClassGrade>>,
193+ term: Option<Option<TermId>>,
194+ db: &Database,
195+ ) -> Result<ClassGroup, AppError> {
196+ let claimed = match &term {
197+ Some(Some(new)) if Some(new) != self.term.as_ref() => {
198+ claim_term(new, db).await?;
199+ Some(new.clone())
200+ }
201+ _ => None,
202+ };
203+ let updated = FieldUpdate::new(self.id.record())
204+ .set("name", name)
205+ .set("grade", grade)
206+ .set("term", term.map(|term| term.map(|term| term.record())))
207+ .run::<ClassGroup>(db)
208+ .await;
209+ match updated {
210+ Ok(updated) => {
211+ // The stored row is the authority on where the link ended up —
212+ // a PATCH that carried no `term_id` leaves it untouched.
213+ if let Some(old) = &self.term
214+ && updated.term.as_ref() != Some(old)
215+ {
216+ cap::release(&old.record(), TERM_CLASS_COUNT_FIELD, db).await?;
217+ }
218+ Ok(updated)
219+ }
220+ Err(err) => {
221+ if let Some(new) = &claimed {
222+ cap::release(&new.record(), TERM_CLASS_COUNT_FIELD, db).await?;
223+ }
224+ Err(err)
225+ }
226+ }
227+ }
228+
229+ /// Delete the class and give its term reference back. Nothing cascades: a
230+ /// class that still holds students or courses is refused outright, because
231+ /// dropping it silently would leave the enrollments it pumped behind with
232+ /// nothing left to sweep them.
233+ ///
234+ /// `false` = refused, nothing was written. Both counts are read off the
235+ /// class's own row, so the check and the delete are one conditional write on
236+ /// one record — a member or attach racing this either claims first (and the
237+ /// delete is refused) or finds the row gone (and is refused itself).
238+ /// `Err(NotFound)` keeps the answer a concurrent *delete* used to get.
239+ pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
240+ // Parenthesized `??` throughout: `n ?? 0 = 0` parses as `n ?? (0 = 0)`,
241+ // which is truthy for every row and would delete a class still in use.
242+ let sql = format!(
243+ "BEGIN TRANSACTION;
244+ LET $gone = (DELETE $class WHERE ({CLASS_MEMBER_COUNT_FIELD} ?? 0) = 0 \
245+ AND ({CLASS_COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE);
246+ IF array::len($gone) = 0 {{ THROW '{LINKS_MARK}' }};
247+ FOR $row IN $gone {{
248+ IF $row.term != NONE {{
249+ UPDATE $row.term SET {TERM_CLASS_COUNT_FIELD} = \
250+ math::max([({TERM_CLASS_COUNT_FIELD} ?? 0) - 1, 0]);
251+ }};
252+ }};
253+ COMMIT TRANSACTION;"
254+ );
255+ // An aborted transaction errors *every* slot, most with a generic "not
256+ // executed" — only the THROW's own slot names the marker, and a lost
257+ // round is re-sent rather than reported (see [`transaction_with_retry`]).
258+ let (_, mut errors) = transaction_with_retry(
259+ db,
260+ &sql,
261+ &[("class".into(), self.id.record().into_value())],
262+ &[LINKS_MARK],
263+ )
264+ .await?;
265+ if errors
266+ .values()
267+ .any(|error| error.to_string().contains(LINKS_MARK))
268+ {
269+ // Still linked or already gone: the guard cannot tell those apart,
270+ // and only the refusal path pays for the extra read that can.
271+ return match Self::read(&self.id, db).await? {
272+ Some(_) => Ok(false),
273+ None => Err(AppError::NotFound),
274+ };
275+ }
276+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
277+ return Err(error.into());
278+ }
279+ Ok(true)
280+ }
281+}
282+
283+/// Take a reference on `term` for a class about to link it. The conditional
284+/// write doubles as the existence check — the class half of
285+/// [`crate::domain::course`]'s `claim_term`, against the class column.
286+async fn claim_term(term: &TermId, db: &Database) -> Result<(), AppError> {
287+ if cap::claim(&term.record(), TERM_CLASS_COUNT_FIELD, cap::UNLIMITED, db).await? {
288+ return Ok(());
289+ }
290+ Err(AppError::Validation(ValidationError::Invalid {
291+ field: "term_id",
292+ reason: "term does not exist",
293+ }))
294+}
295+
296+#[cfg(test)]
297+mod tests {
298+ use super::*;
299+ use crate::domain::term::{Term, TermName};
300+
301+ async fn class_on(term: Option<TermId>, db: &Database) -> ClassGroup {
302+ ClassGroup::create(
303+ &UserId::from_key("manager"),
304+ ClassName::try_new("9-A").unwrap(),
305+ None,
306+ term,
307+ db,
308+ )
309+ .await
310+ .unwrap()
311+ }
312+
313+ async fn a_term(db: &Database) -> Term {
314+ let at = crate::domain::timestamp::Timestamp::from_millis;
315+ Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), db)
316+ .await
317+ .unwrap()
318+ }
319+
320+ /// The stored counter, re-read — never off a return value, which the
321+ /// in-memory engine forges wins on (see [`crate::domain::cap`]).
322+ async fn stored_count(sql: &str, db: &Database) -> i64 {
323+ let mut result = db.query(sql).await.unwrap().check().unwrap();
324+ result
325+ .take::<Vec<i64>>(0)
326+ .unwrap()
327+ .first()
328+ .copied()
329+ .unwrap()
330+ }
331+
332+ /// How many rows `sql` selects ids for.
333+ async fn rows(sql: &str, db: &Database) -> usize {
334+ let mut result = db.query(sql).await.unwrap().check().unwrap();
335+ result.take::<Vec<RecordId>>(0).unwrap().len()
336+ }
337+
338+ #[test]
339+ fn name_is_required_and_grade_is_optional() {
340+ assert!(ClassName::try_new("9-A").is_ok());
341+ assert!(ClassName::try_new("").is_err());
342+ assert!(ClassName::try_new(" ").is_err());
343+ assert!(ClassName::try_new(&"x".repeat(MAX_CLASS_NAME_LEN + 1)).is_err());
344+ assert!(ClassGrade::try_new("").is_ok());
345+ assert!(ClassGrade::try_new("anaokulu").is_ok());
346+ assert!(ClassGrade::try_new(&"x".repeat(MAX_CLASS_GRADE_LEN + 1)).is_err());
347+ }
348+
349+ /// The bite test for the class half of the term delete guard: a term is
350+ /// undeletable while a *class* links it, on its own column, and every way
351+ /// that link can end gives the reference back. Claiming into `course_count`
352+ /// instead would pass the first assert and fail the roundtrip through boot.
353+ #[tokio::test]
354+ async fn a_term_is_deletable_only_once_no_class_links_it() {
355+ let db = crate::database::init_mem().await.unwrap();
356+ let term = a_term(&db).await;
357+
358+ let linked = class_on(Some(term.get_id().clone()), &db).await;
359+ let patched = class_on(Some(term.get_id().clone()), &db).await;
360+ assert_eq!(
361+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
362+ 2,
363+ "classes must count on class_count, not course_count"
364+ );
365+ assert_eq!(
366+ stored_count("SELECT VALUE course_count ?? 0 FROM term", &db).await,
367+ 0,
368+ "the courses' counter is seeded from course rows and must stay untouched"
369+ );
370+ assert!(
371+ !term.clone().delete(&db).await.unwrap(),
372+ "two linked classes must refuse the delete"
373+ );
374+
375+ patched.update(None, None, Some(None), &db).await.unwrap();
376+ assert!(
377+ !term.clone().delete(&db).await.unwrap(),
378+ "one link is still one link"
379+ );
380+
381+ assert!(linked.delete(&db).await.unwrap());
382+ assert!(
383+ term.clone().delete(&db).await.unwrap(),
384+ "the last link gone, the term may go"
385+ );
386+ }
387+
388+ /// The bite test for the class delete guard, both arms: either count above
389+ /// zero refuses, having written nothing — the term reference least of all,
390+ /// which a refusal that released it would strand.
391+ #[tokio::test]
392+ async fn a_class_with_members_or_courses_refuses_to_delete() {
393+ for field in [CLASS_MEMBER_COUNT_FIELD, CLASS_COURSE_COUNT_FIELD] {
394+ let db = crate::database::init_mem().await.unwrap();
395+ let term = a_term(&db).await;
396+ let class = class_on(Some(term.get_id().clone()), &db).await;
397+ db.query(format!("UPDATE $class SET {field} = 1"))
398+ .bind(("class", class.get_id().record()))
399+ .await
400+ .unwrap()
401+ .check()
402+ .unwrap();
403+
404+ assert!(
405+ !class.clone().delete(&db).await.unwrap(),
406+ "{field} above zero must refuse the delete"
407+ );
408+ assert!(
409+ ClassGroup::read(class.get_id(), &db)
410+ .await
411+ .unwrap()
412+ .is_some(),
413+ "a refused delete may write nothing"
414+ );
415+ assert_eq!(
416+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
417+ 1,
418+ "…the term reference least of all"
419+ );
420+
421+ // Back to zero, and the same class deletes and releases the term.
422+ db.query(format!("UPDATE $class SET {field} = 0"))
423+ .bind(("class", class.get_id().record()))
424+ .await
425+ .unwrap()
426+ .check()
427+ .unwrap();
428+ assert!(class.clone().delete(&db).await.unwrap());
429+ assert_eq!(
430+ stored_count("SELECT VALUE class_count ?? 0 FROM term", &db).await,
431+ 0
432+ );
433+ let again = class.delete(&db).await;
434+ assert!(
435+ matches!(again, Err(AppError::NotFound)),
436+ "a second delete is a 404, not a refusal: {again:?}"
437+ );
438+ }
439+ }
440+
441+ /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course
442+ /// takes its `class_course` attachments with it and gives each class its
443+ /// count back, or the classes would be undeletable forever over rows that
444+ /// point at nothing.
445+ #[tokio::test]
446+ async fn deleting_a_course_sweeps_its_class_attachments() {
447+ use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle};
448+
449+ let db = crate::database::init_mem().await.unwrap();
450+ let manager = UserId::from_key("manager");
451+ let course = Course::create(
452+ &manager,
453+ CourseTitle::try_new("algebra").unwrap(),
454+ CourseDescription::try_new("").unwrap(),
455+ CourseKind::course(),
456+ None,
457+ None,
458+ &db,
459+ )
460+ .await
461+ .unwrap();
462+ let class = class_on(None, &db).await;
463+ db.query(format!(
464+ "CREATE class_course SET class = $class, course = $course, attached_by = $usr;
465+ UPDATE $class SET {CLASS_COURSE_COUNT_FIELD} = 1;"
466+ ))
467+ .bind(("class", class.get_id().record()))
468+ .bind(("course", course.get_id().record()))
469+ .bind(("usr", manager.record()))
470+ .await
471+ .unwrap()
472+ .check()
473+ .unwrap();
474+
475+ assert!(course.delete(&db).await.unwrap());
476+ assert_eq!(
477+ rows("SELECT VALUE id FROM class_course", &db).await,
478+ 0,
479+ "the attachment rows must go with the course"
480+ );
481+ assert_eq!(
482+ stored_count(
483+ &format!("SELECT VALUE {CLASS_COURSE_COUNT_FIELD} ?? 0 FROM class_group"),
484+ &db
485+ )
486+ .await,
487+ 0,
488+ "…and each class must get its count back"
489+ );
490+ // Which is the whole point: the class is deletable again.
491+ assert!(class.delete(&db).await.unwrap());
492+ }
493+}
src/domain/course.rsmodified+10 -3
@@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 use ulid::Ulid;2 use ulid::Ulid;
3 3
4 use crate::constant::{4 use crate::constant::{
5- COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, MAX_COURSE_DESCRIPTION_LEN,5+ CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD,
6- MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD,6+ MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD,
7 };7 };
8 use crate::database::{Database, transaction_with_retry};8 use crate::database::{Database, transaction_with_retry};
9 use crate::domain::cap;9 use crate::domain::cap;
@@ -386,7 +386,9 @@ impl Course {
386 /// Delete the course and cascade-remove everything inside it: results,386 /// Delete the course and cascade-remove everything inside it: results,
387 /// attempts, answers, and question/answer images of its exams, its387 /// attempts, answers, and question/answer images of its exams, its
388 /// homework with their submissions, submission files, and grades, its388 /// homework with their submissions, submission files, and grades, its
389- /// enrollments, its sessions with their roll call, its subjects, and the389+ /// enrollments, the class attachments that pumped some of them (each class
390+ /// gets its count back, or it would be undeletable over rows pointing at
391+ /// nothing), its sessions with their roll call, its subjects, and the
390 /// exams themselves. The children go in one transaction so a crash can't392 /// exams themselves. The children go in one transaction so a crash can't
391 /// leave an exam pointing at a deleted course. The image and393 /// leave an exam pointing at a deleted course. The image and
392 /// homework-file *blobs* are the web layer's to remove — it collects394 /// homework-file *blobs* are the web layer's to remove — it collects
@@ -429,6 +431,11 @@ impl Course {
429 DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course));431 DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course));
430 DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);432 DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
431 DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);433 DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
434+ LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE);
435+ FOR $row IN ($detached ?? []) {{
436+ UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \
437+ math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]);
438+ }};
432 DELETE session_attendance WHERE course = $course;439 DELETE session_attendance WHERE course = $course;
433 DELETE course_session WHERE course = $course;440 DELETE course_session WHERE course = $course;
434 DELETE enrollment WHERE course = $course;441 DELETE enrollment WHERE course = $course;
src/domain/enrollment.rsmodified+85 -0
@@ -3,6 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};3 use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE};
4 use crate::database::Database;4 use crate::database::Database;
5 use crate::domain::cap;5 use crate::domain::cap;
6+use crate::domain::class_group::ClassGroupId;
6 use crate::domain::course::{Course, CourseId};7 use crate::domain::course::{Course, CourseId};
7 use crate::domain::page::PagedList;8 use crate::domain::page::PagedList;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
@@ -37,12 +38,19 @@ impl EnrollmentId {
37 38
38 /// A user's membership in a course. Grading requires it; removing it hides the39 /// A user's membership in a course. Grading requires it; removing it hides the
39 /// user's marks from the report but never deletes result rows.40 /// user's marks from the report but never deletes result rows.
41+///
42+/// `source` names the class ([`crate::domain::class_group::ClassGroup`]) that
43+/// pumped this row, and is absent when a human placed the student directly —
44+/// every row written before classes existed, and every row placed by hand since.
45+/// Absence *is* the meaning, so nothing backfills it: a class sweep may only take
46+/// back the rows it wrote.
40 #[derive(Debug, Clone, SurrealValue)]47 #[derive(Debug, Clone, SurrealValue)]
41 pub struct Enrollment {48 pub struct Enrollment {
42 id: EnrollmentId,49 id: EnrollmentId,
43 course: CourseId,50 course: CourseId,
44 user: UserId,51 user: UserId,
45 enrolled_by: UserId,52 enrolled_by: UserId,
53+ source: Option<ClassGroupId>,
46 }54 }
47 55
48 impl Enrollment {56 impl Enrollment {
@@ -62,6 +70,11 @@ impl Enrollment {
62 &self.enrolled_by70 &self.enrolled_by
63 }71 }
64 72
73+ /// The class that pumped this row, or `None` for a hand-placed one.
74+ pub fn get_source(&self) -> Option<&ClassGroupId> {
75+ self.source.as_ref()
76+ }
77+
65 /// Enroll (idempotently) `user` into `course`. One row per (course, user),78 /// Enroll (idempotently) `user` into `course`. One row per (course, user),
66 /// keyed by a deterministic composite id, so concurrent enrolls of the same79 /// keyed by a deterministic composite id, so concurrent enrolls of the same
67 /// pair converge on one row instead of racing the unique index into a 500:80 /// pair converge on one row instead of racing the unique index into a 500:
@@ -92,6 +105,9 @@ impl Enrollment {
92 course: course.clone(),105 course: course.clone(),
93 user: user.clone(),106 user: user.clone(),
94 enrolled_by: enrolled_by.clone(),107 enrolled_by: enrolled_by.clone(),
108+ // Hand-placed: no source key at all is written, which is what makes
109+ // a class sweep unable to take this row back.
110+ source: None,
95 };111 };
96 // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has112 // CREATE, not UPSERT, and in the seat's own transaction: a duplicate has
97 // to be *seen*, or the pair's second writer would keep the seat it113 // to be *seen*, or the pair's second writer would keep the seat it
@@ -189,3 +205,72 @@ impl Enrollment {
189 Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())205 Ok(result.take::<Vec<Enrollment>>(3)?.into_iter().next())
190 }206 }
191 }207 }
208+
209+#[cfg(test)]
210+mod tests {
211+ use super::*;
212+
213+ /// The database strips `NONE`-valued optional columns, and every enrollment
214+ /// row written before classes existed has no `source` key at all — both must
215+ /// decode as a hand-placed row, never as a decode error that 500s a roster.
216+ #[tokio::test]
217+ async fn enrollment_decodes_without_source_key() {
218+ use surrealdb::types::Value;
219+
220+ let class = crate::domain::class_group::ClassGroupId::from_key("9a");
221+ let course = CourseId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8T");
222+ let student = UserId::from_key("01J8XZ0K3Q8G7X2M4N5P6R7S8U");
223+ let enrollment = Enrollment {
224+ id: EnrollmentId::composite(&course, &student),
225+ course,
226+ user: student,
227+ enrolled_by: UserId::from_key("mgr"),
228+ source: Some(class.clone()),
229+ };
230+ assert_eq!(enrollment.get_source(), Some(&class));
231+
232+ let Value::Object(mut object) = enrollment.into_value() else {
233+ panic!("an enrollment must encode as an object");
234+ };
235+ object.remove("source");
236+ let decoded = Enrollment::from_value(Value::Object(object)).unwrap();
237+ assert_eq!(decoded.get_source(), None);
238+ }
239+
240+ /// And the other half of "absence is the meaning": a hand-placed enrollment
241+ /// must store *no* source key, or a class sweep would take back a row it
242+ /// never wrote. Asserted on the stored row, not the returned one.
243+ #[tokio::test]
244+ async fn a_hand_placed_enrollment_stores_no_source_key() {
245+ use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle};
246+
247+ let db = crate::database::init_mem().await.unwrap();
248+ let teacher = UserId::from_key("teacher");
249+ let course = Course::create(
250+ &teacher,
251+ CourseTitle::try_new("algebra").unwrap(),
252+ CourseDescription::try_new("").unwrap(),
253+ CourseKind::course(),
254+ None,
255+ None,
256+ &db,
257+ )
258+ .await
259+ .unwrap();
260+ Enrollment::enroll(course.get_id(), &UserId::from_key("student"), &teacher, &db)
261+ .await
262+ .unwrap();
263+
264+ let mut result = db
265+ .query("SELECT VALUE 'source' IN object::keys($this) FROM enrollment")
266+ .await
267+ .unwrap()
268+ .check()
269+ .unwrap();
270+ assert_eq!(
271+ result.take::<Vec<bool>>(0).unwrap(),
272+ vec![false],
273+ "a hand-placed row may carry no source key"
274+ );
275+ }
276+}
src/domain/mod.rsmodified+1 -0
@@ -13,6 +13,7 @@ pub mod board_stroke;
13 pub mod cap;13 pub mod cap;
14 pub mod chatbot_message;14 pub mod chatbot_message;
15 pub mod chatbot_thread;15 pub mod chatbot_thread;
16+pub mod class_group;
16 pub mod course;17 pub mod course;
17 pub mod course_session;18 pub mod course_session;
18 pub mod dietary_profile;19 pub mod dietary_profile;
src/domain/term.rsmodified+11 -4
@@ -9,7 +9,7 @@
9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};9 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
10 use ulid::Ulid;10 use ulid::Ulid;
11 11
12-use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_TABLE};12+use crate::constant::{COURSE_COUNT_FIELD, MAX_TERM_NAME_LEN, TERM_CLASS_COUNT_FIELD, TERM_TABLE};
13 use crate::database::{Database, write_with_retry};13 use crate::database::{Database, write_with_retry};
14 use crate::domain::field_update::FieldUpdate;14 use crate::domain::field_update::FieldUpdate;
15 use crate::domain::page::PagedList;15 use crate::domain::page::PagedList;
@@ -133,8 +133,8 @@ impl Term {
133 .await133 .await
134 }134 }
135 135
136- /// Delete the term, but only while no course links it — nothing here136+ /// Delete the term, but only while no course *and no class* links it —
137- /// unlinks or cascades. `false` = refused, nothing was written.137+ /// nothing here unlinks or cascades. `false` = refused, nothing was written.
138 ///138 ///
139 /// The roster of linking courses is the term's own `course_count`139 /// The roster of linking courses is the term's own `course_count`
140 /// refcount, claimed by [`crate::domain::course::Course::create`] and140 /// refcount, claimed by [`crate::domain::course::Course::create`] and
@@ -143,8 +143,15 @@ impl Term {
143 /// claims first (and the delete is refused) or finds the row gone (and is143 /// claims first (and the delete is refused) or finds the row gone (and is
144 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`144 /// refused itself, with the same 400 the lookup gives). `Err(NotFound)`
145 /// keeps the answer a concurrent *delete* used to get.145 /// keeps the answer a concurrent *delete* used to get.
146+ ///
147+ /// Classes ([`crate::domain::class_group::ClassGroup`]) link a term the same
148+ /// way and count on `class_count` — a column of their own, because
149+ /// `course_count` is seeded at boot from the course rows alone.
146 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {150 pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
147- let sql = format!("DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE");151+ let sql = format!(
152+ "DELETE $term WHERE ({COURSE_COUNT_FIELD} ?? 0) = 0 \
153+ AND ({TERM_CLASS_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE"
154+ );
148 // Through the retry, because the guard reads the very column a course155 // Through the retry, because the guard reads the very column a course
149 // create claims: a lost round writes nothing, and re-sending it is what156 // create claims: a lost round writes nothing, and re-sending it is what
150 // keeps the answer the 404 or 409 it owes instead of a 500.157 // keeps the answer the 404 or 409 it owes instead of a 500.