forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/fee_attendance'

Browse files at this commit

08aa13eab28a49f02102a0484b0161ba30d7af3aAhmet Kaan GümüşParent: b0e9ab846cb63d
# Conflicts:
#	src/db/mod.rs
#	src/domain/attendance.rs
#	src/domain/event.rs
#	src/domain/session_attendance.rs
#	src/service/mod.rs
#	src/web/payments.rs
#	src/web/sessions.rs

23 changed files +2046 -1683

src/database.rsmodified+18 -9
@@ -604,7 +604,8 @@ mod tests {
604 /// the backfill is the whole of the stale-data story, not a nicety.604 /// the backfill is the whole of the stale-data story, not a nicety.
605 #[tokio::test]605 #[tokio::test]
606 async fn a_plan_assigned_before_the_counter_existed_is_still_refused() {606 async fn a_plan_assigned_before_the_counter_existed_is_still_refused() {
607- use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName};607+ use crate::db::fee_plan;
608+ use crate::domain::fee_plan::{FeePlanId, FeePlanName};
608 use crate::error::AppError;609 use crate::error::AppError;
609 610
610 let db = super::init_mem().await.unwrap();611 let db = super::init_mem().await.unwrap();
@@ -644,28 +645,36 @@ mod tests {
644 645
645 // The load-bearing half: the seeded plan is frozen, and the untouched646 // The load-bearing half: the seeded plan is frozen, and the untouched
646 // one is not.647 // one is not.
647- let used = FeePlan::read(&FeePlanId::from_key("used"), &db)648+ let used = fee_plan::read(&db, &FeePlanId::from_key("used"))
648 .await649 .await
649 .unwrap()650 .unwrap()
650 .unwrap();651 .unwrap();
651 assert!(matches!(652 assert!(matches!(
652- used.clone()653+ fee_plan::update(
653- .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)654+ &db,
655+ used.clone(),
656+ Some(FeePlanName::try_new("Edited").unwrap()),
657+ None
658+ )
654 .await,659 .await,
655 Err(AppError::Conflict(_))660 Err(AppError::Conflict(_))
656 ));661 ));
657- assert!(!used.delete(&db).await.unwrap());662+ assert!(!fee_plan::delete(&db, used).await.unwrap());
658- let free = FeePlan::read(&FeePlanId::from_key("free"), &db)663+ let free = fee_plan::read(&db, &FeePlanId::from_key("free"))
659 .await664 .await
660 .unwrap()665 .unwrap()
661 .unwrap();666 .unwrap();
662 assert!(667 assert!(
663- free.clone()668+ fee_plan::update(
664- .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db)669+ &db,
670+ free.clone(),
671+ Some(FeePlanName::try_new("Edited").unwrap()),
672+ None
673+ )
665 .await674 .await
666 .is_ok()675 .is_ok()
667 );676 );
668- assert!(free.delete(&db).await.unwrap());677+ assert!(fee_plan::delete(&db, free).await.unwrap());
669 }678 }
670 679
671 /// Stale-data path for the 2026-08-02 board-roster repair. `set_role`680 /// Stale-data path for the 2026-08-02 board-roster repair. `set_role`
src/db/attendance.rsadded+212 -0
@@ -0,0 +1,212 @@
1+//! The `attendance` table: event roll call. Every write is a single
2+//! transaction whose gates ride inside it (the event-existence proof), so
3+//! the whole module is the persistence half; the workflow that decides it
4+//! lives in [`crate::service::attendance`].
5+
6+use surrealdb::types::SurrealValue;
7+
8+use crate::constant::REGISTRATION_COUNT_FIELD;
9+use crate::database::{Database, transaction_with_retry};
10+use crate::db::page::PagedList;
11+use crate::domain::attendance::{Attendance, AttendanceId, AttendanceStatus};
12+use crate::domain::event::EventId;
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+/// Record (or overwrite) `user`'s status for `event`. One row per (event,
17+/// user), keyed by a deterministic composite id so this is a single atomic
18+/// UPSERT — concurrent marks for the same pair can no longer both insert and
19+/// collide on the unique index (a 500); they converge on the one row.
20+///
21+/// The event's existence is proved *inside* the write, the twin of the gate
22+/// in [`crate::db::session_attendance::mark`]: the handler's event read sits
23+/// several round trips in front of this, so a bare upsert left a mark on an
24+/// event [`crate::domain::event::Event`]'s cascade
25+/// (`DELETE attendance WHERE event = $ev`) had already swept — counted
26+/// forever in `GET /attendance/{user}` on an event no page shows. Reading
27+/// the event here would not have closed it either: SurrealDB 3.2.3
28+/// conflict-checks write sets, not read sets, so the proof has to *move* a
29+/// value on the event row. It is the bump-and-restore of
30+/// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the
31+/// event already carries: matching nothing is the existence gate, writing
32+/// the key the delete removes is the collision, and the restore is by
33+/// captured value (`NONE` included) so no seat is spent or freed.
34+///
35+/// Admissible for [`transaction_with_retry`]: no statement can answer
36+/// "already exists" — the `UPSERT`'s composite id is bijective with the
37+/// `attendance_event_user` unique tuple, so it resolves onto the row it
38+/// names instead of colliding with it.
39+pub async fn mark(
40+ db: &Database,
41+ event: &EventId,
42+ user: &UserId,
43+ status: AttendanceStatus,
44+ marked_by: &UserId,
45+) -> Result<Attendance, AppError> {
46+ let attendance = Attendance {
47+ id: AttendanceId::composite(event, user),
48+ event: event.clone(),
49+ user: user.clone(),
50+ status,
51+ marked_by: marked_by.clone(),
52+ };
53+ let (mut result, mut errors) = transaction_with_retry(
54+ db,
55+ &format!(
56+ "BEGIN TRANSACTION;
57+ LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev);
58+ LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} =
59+ ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
60+ IF array::len($alive) = 0 {{ THROW 'event_missing' }};
61+ UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was;
62+ LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
63+ RETURN $after;
64+ COMMIT TRANSACTION;"
65+ ),
66+ &[
67+ ("ev".into(), event.record().into_value()),
68+ ("id".into(), attendance.id.record().into_value()),
69+ ("row".into(), attendance.into_value()),
70+ ],
71+ &["event_missing"],
72+ )
73+ .await?;
74+ // An aborted transaction errors every slot and only the THROW's own
75+ // slot names the marker.
76+ if errors
77+ .values()
78+ .any(|error| error.to_string().contains("event_missing"))
79+ {
80+ return Err(AppError::NotFound);
81+ }
82+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
83+ return Err(error.into());
84+ }
85+ // The trailing `RETURN` is always the last statement before `COMMIT`.
86+ let slot = result.num_statements().saturating_sub(2);
87+ result
88+ .take::<Vec<Attendance>>(slot)?
89+ .into_iter()
90+ .next()
91+ .ok_or_else(|| AppError::Internal("failed to mark attendance".into()))
92+}
93+
94+pub async fn list_for_event(
95+ db: &Database,
96+ event: &EventId,
97+ limit: Option<i64>,
98+ offset: i64,
99+) -> Result<(Vec<Attendance>, i64), AppError> {
100+ PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC")
101+ .bind("ev", event.record())
102+ .run(limit, offset, db)
103+ .await
104+}
105+
106+/// Every event-attendance row recorded for `user` — the events half of the
107+/// attendance report.
108+pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Attendance>, AppError> {
109+ let mut result = db
110+ .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC")
111+ .bind(("usr", user.record()))
112+ .await?
113+ .check()?;
114+ Ok(result.take::<Vec<Attendance>>(0)?)
115+}
116+
117+pub async fn remove(
118+ db: &Database,
119+ event: &EventId,
120+ user: &UserId,
121+) -> Result<Option<Attendance>, AppError> {
122+ let mut result = db
123+ .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE")
124+ .bind(("ev", event.record()))
125+ .bind(("usr", user.record()))
126+ .await?
127+ .check()?;
128+ Ok(result.take::<Vec<Attendance>>(0)?.into_iter().next())
129+}
130+
131+#[cfg(test)]
132+mod tests {
133+ use super::*;
134+ use crate::domain::settings::Settings;
135+
136+ /// The session twin's race, one table over
137+ /// ([`crate::db::session_attendance::mark`]): a
138+ /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and
139+ /// the event's delete sweeps its attendance rows before removing the row, so
140+ /// the `SLEEP` lands exactly between the sweep and the commit — the window
141+ /// where a bare upsert wrote a mark nothing would ever sweep again.
142+ ///
143+ /// Real server, and `#[ignore]`d for it: the subject is the store's
144+ /// conflict detection, which `init_mem`'s embedded engine does not have —
145+ /// it commits both writes and answers `Ok` to each, so this passes there on
146+ /// broken code. Mutation-tested: turning the claim back into a read
147+ /// (`SELECT VALUE id FROM $ev`) turns it red.
148+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
149+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
150+ async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
151+ use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle};
152+ let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;
153+ db.query(
154+ "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \
155+ THEN { SLEEP 1s; };",
156+ )
157+ .await
158+ .unwrap()
159+ .check()
160+ .unwrap();
161+
162+ let allowed: Vec<String> = Settings::defaults().get_attendance_statuses().to_vec();
163+ let marker = UserId::from_key("t");
164+ let (mut swept, mut orphans) = (0, 0);
165+ for round in 0..4 {
166+ let event = Event::create(
167+ &marker,
168+ EventTitle::try_new("gezi").unwrap(),
169+ EventDescription::try_new("").unwrap(),
170+ EventAudience::School,
171+ None,
172+ None,
173+ &db,
174+ )
175+ .await
176+ .unwrap();
177+ let id = event.get_id().clone();
178+ let drop_it = {
179+ let db = db.clone();
180+ tokio::spawn(async move { event.delete(&db).await })
181+ };
182+ // The mark starts inside the held window: the sweep has run and the
183+ // event row is gone but uncommitted.
184+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
185+ let marked = {
186+ let (db, id, marker) = (db.clone(), id.clone(), marker.clone());
187+ let student = UserId::from_key(&format!("s{round}"));
188+ let status = AttendanceStatus::try_new("present", &allowed).unwrap();
189+ tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await })
190+ };
191+ let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
192+ assert!(
193+ !matches!(marked, Err(AppError::Db(_))),
194+ "round {round}: a raced mark must be answered, not 500: {marked:?}"
195+ );
196+
197+ // Stored state is the whole verdict; a return value is not evidence.
198+ if Event::read(&id, &db).await.unwrap().is_none() {
199+ swept += 1;
200+ orphans += list_for_event(&db, &id, None, 0).await.unwrap().0.len();
201+ } else if drop_it.is_ok() {
202+ panic!("round {round}: the delete reported success but the event is still there");
203+ }
204+ }
205+ eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event");
206+ assert!(
207+ swept > 0,
208+ "no round ever deleted the event, so the window was never reached"
209+ );
210+ assert_eq!(orphans, 0, "a mark outlived its event");
211+ }
212+}
src/db/course_session.rsmodified+1 -1
@@ -99,7 +99,7 @@ pub async fn update(
99 /// Delete the session and cascade-remove its roll-call rows, in one99 /// Delete the session and cascade-remove its roll-call rows, in one
100 /// transaction: as two unbatched queries a failure between them stranded100 /// transaction: as two unbatched queries a failure between them stranded
101 /// roll-call rows on a session that was already gone. The other half of101 /// roll-call rows on a session that was already gone. The other half of
102-/// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`],102+/// that invariant is [`crate::db::session_attendance::mark`],
103 /// which proves the session still exists inside its own write — a103 /// which proves the session still exists inside its own write — a
104 /// transaction here cannot stop a mark that commits *after* this one.104 /// transaction here cannot stop a mark that commits *after* this one.
105 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {105 pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> {
src/db/fee_plan.rsadded+164 -0
@@ -0,0 +1,164 @@
1+//! The `fee_plan` table: the create, the reads, and the guarded edit and
2+//! delete. Both guards are conditional single-record writes on the plan's own
3+//! refcount — the WHERE clause *is* the assigned-plan freeze rule — so they
4+//! live here whole. The web-facing doors are [`crate::service::fee_plan`].
5+
6+use surrealdb::types::SurrealValue;
7+
8+use crate::constant::FEE_PLAN_UNASSIGNED_GUARD;
9+use crate::database::{Database, write_with_retry};
10+use crate::db::field_update::FieldUpdate;
11+use crate::db::page::PagedList;
12+use crate::domain::fee_plan::{
13+ FeePlan, FeePlanId, FeePlanName, Installment, validate_installments,
14+};
15+use crate::domain::timestamp::Timestamp;
16+use crate::domain::user::UserId;
17+use crate::error::AppError;
18+
19+pub async fn create(
20+ db: &Database,
21+ name: FeePlanName,
22+ installments: Vec<Installment>,
23+ created_by: &UserId,
24+) -> Result<FeePlan, AppError> {
25+ validate_installments(&installments)?;
26+ let plan = FeePlan {
27+ id: FeePlanId::generate(),
28+ name,
29+ installments,
30+ created_by: created_by.clone(),
31+ created_at: Timestamp::now(),
32+ };
33+ let created: Option<FeePlan> = db.create(plan.id.record()).content(plan).await?;
34+ created.ok_or_else(|| AppError::Internal("failed to create fee plan".into()))
35+}
36+
37+pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> {
38+ Ok(db.select(id.record()).await?)
39+}
40+
41+/// Every plan, newest first — a school runs a handful.
42+pub async fn list_all(
43+ db: &Database,
44+ limit: Option<i64>,
45+ offset: i64,
46+) -> Result<(Vec<FeePlan>, i64), AppError> {
47+ PagedList::new("fee_plan", "ORDER BY created_at DESC, id DESC")
48+ .run(limit, offset, db)
49+ .await
50+}
51+
52+/// Write only the fields the PATCH carried — `None` means the request
53+/// omitted it, so the column is left alone rather than re-stated from the
54+/// snapshot this struct was read into. `Err(Conflict)` = refused, nothing
55+/// was written: somebody is already on the plan.
56+///
57+/// Editing a plan never moves money: charges are frozen copies of the
58+/// installments as they stood when the plan was assigned. That is exactly
59+/// why an assigned plan may not be edited at all — the plan and the charges
60+/// raised from it would tell different stories. The roster is the plan's own
61+/// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same
62+/// transaction as the assignment row, so the check and the write are one
63+/// conditional `UPDATE` on one record: an assign racing this either claims
64+/// first (and the edit is refused) or claims after (and bills the edited
65+/// plan, which it re-reads). A `SELECT`-then-write could be, and was,
66+/// stepped over in the gap between the two.
67+pub async fn update(
68+ db: &Database,
69+ plan: FeePlan,
70+ name: Option<FeePlanName>,
71+ installments: Option<Vec<Installment>>,
72+) -> Result<FeePlan, AppError> {
73+ if let Some(installments) = &installments {
74+ validate_installments(installments)?;
75+ }
76+ let edited = FieldUpdate::new(plan.id.record())
77+ .set("name", name)
78+ .set("installments", installments)
79+ .guard(
80+ FEE_PLAN_UNASSIGNED_GUARD,
81+ AppError::Conflict("an assigned plan cannot be edited"),
82+ )
83+ .run::<FeePlan>(db)
84+ .await;
85+ // Still assigned or already gone: the guarded `UPDATE` cannot tell those
86+ // apart either (it reports the refusal it was given), so — exactly as
87+ // [`crate::db::fee_plan::delete`] does — only the refusal path pays for the read
88+ // that can. A plan deleted in the window since the handler read it must
89+ // not be refused as "assigned": it never was.
90+ if matches!(edited, Err(AppError::Conflict(_))) && read(db, &plan.id).await?.is_none() {
91+ return Err(AppError::NotFound);
92+ }
93+ edited
94+}
95+
96+/// Delete the plan, but only while nobody is on it. `false` = refused,
97+/// nothing was written; `Err(NotFound)` keeps the answer a concurrent
98+/// *delete* gives. Same one-record guard as [`update`], and the
99+/// same reason — the charges an assignment raised name this plan, and a
100+/// school's financial history keeps its references.
101+///
102+/// Retried while the store answers "conflict, retry": the guard reads a
103+/// counter an assign *writes*, so the two contend on this one record by
104+/// design — and a delete that loses that round has written nothing, so
105+/// re-sending it is the whole of the recovery. Without the retry an
106+/// ordinary raced delete answers 500 instead of the 404 or 409 it owes.
107+pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> {
108+ let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE");
109+ let deleted: Vec<FeePlan> =
110+ write_with_retry(db, &sql, &[("plan".into(), plan.id.record().into_value())]).await?;
111+ if !deleted.is_empty() {
112+ return Ok(true);
113+ }
114+ // Still assigned or already gone: the one statement cannot tell those
115+ // apart, and only the refusal path pays for the read that can.
116+ match read(db, &plan.id).await? {
117+ Some(_) => Ok(false),
118+ None => Err(AppError::NotFound),
119+ }
120+}
121+
122+#[cfg(test)]
123+mod tests {
124+ use super::*;
125+ use crate::domain::payment_ledger::LedgerAmount;
126+
127+ /// The embedded-object DDL (`installments.*.amount_minor`) proved against
128+ /// the engine: SCHEMAFULL rejects any nested key it was not told about, so
129+ /// a plan that writes and reads back unchanged is what says the declared
130+ /// shape and the stored one agree. A past due date is legal on purpose.
131+ #[tokio::test]
132+ async fn installments_survive_a_round_trip_through_the_schema() {
133+ let db = crate::database::init_mem().await.unwrap();
134+ let manager = UserId::from_key("mgr1");
135+ let installments = vec![
136+ Installment::new(
137+ LedgerAmount::try_new(150_000).unwrap(),
138+ Timestamp::from_millis(1_000),
139+ ),
140+ Installment::new(
141+ LedgerAmount::try_new(250_000).unwrap(),
142+ Timestamp::from_millis(2_000),
143+ ),
144+ ];
145+ let plan = create(
146+ &db,
147+ FeePlanName::try_new("Yearly").unwrap(),
148+ installments.clone(),
149+ &manager,
150+ )
151+ .await
152+ .unwrap();
153+
154+ let stored = read(&db, plan.get_id()).await.unwrap().unwrap();
155+ assert_eq!(stored.get_installments(), installments.as_slice());
156+ assert_eq!(stored.get_name().as_str(), "Yearly");
157+
158+ // And a PATCH of the array lands whole.
159+ let edited = update(&db, stored, None, Some(vec![installments[0].clone()]))
160+ .await
161+ .unwrap();
162+ assert_eq!(edited.get_installments().len(), 1);
163+ }
164+}
src/db/fee_plan_assignment.rsadded+64 -0
@@ -0,0 +1,64 @@
1+//! The `fee_plan_assignment` table: the reads over placements. The row is
2+//! written by [`crate::service::fee_plan_assignment::assign`], whose claim
3+//! ([`crate::db::cap::claim_and_create`]) is the write that freezes the plan.
4+
5+use surrealdb::types::RecordId;
6+
7+use crate::database::Database;
8+use crate::db::page::PagedList;
9+use crate::domain::fee_plan::FeePlanId;
10+use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
11+use crate::domain::user::UserId;
12+use crate::error::AppError;
13+
14+pub async fn read(
15+ db: &Database,
16+ id: &FeePlanAssignmentId,
17+) -> Result<Option<FeePlanAssignment>, AppError> {
18+ Ok(db.select(id.record()).await?)
19+}
20+
21+/// Who is on this plan, newest first.
22+pub async fn list_for_plan(
23+ db: &Database,
24+ plan: &FeePlanId,
25+ limit: Option<i64>,
26+ offset: i64,
27+) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
28+ PagedList::new(
29+ "fee_plan_assignment WHERE plan = $plan",
30+ "ORDER BY created_at DESC, id DESC",
31+ )
32+ .bind("plan", plan.record())
33+ .run(limit, offset, db)
34+ .await
35+}
36+
37+/// Is anybody on this plan? A scan, and no longer a guard: the edit and
38+/// delete guards read the plan's own refcount, which no concurrent assign
39+/// can be behind. Kept because a *test* asserting the rows and the counter
40+/// agree is the only thing that would catch the counter drifting.
41+pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> {
42+ let mut result = db
43+ .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1")
44+ .bind(("plan", plan.record()))
45+ .await?
46+ .check()?;
47+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
48+}
49+
50+/// Which plans a student is on — one student may hold several.
51+pub async fn list_for_student(
52+ db: &Database,
53+ student: &UserId,
54+ limit: Option<i64>,
55+ offset: i64,
56+) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
57+ PagedList::new(
58+ "fee_plan_assignment WHERE student = $student",
59+ "ORDER BY created_at DESC, id DESC",
60+ )
61+ .bind("student", student.record())
62+ .run(limit, offset, db)
63+ .await
64+}
src/db/mod.rsmodified+4 -0
@@ -1,6 +1,7 @@
1 //! The only layer that executes queries.1 //! The only layer that executes queries.
2 pub mod appointment;2 pub mod appointment;
3 pub mod appointment_slot;3 pub mod appointment_slot;
4+pub mod attendance;
4 pub mod badge;5 pub mod badge;
5 pub mod builder;6 pub mod builder;
6 pub mod cap;7 pub mod cap;
@@ -15,6 +16,8 @@ pub mod event;
15 pub mod exam;16 pub mod exam;
16 pub mod exam_attempt;17 pub mod exam_attempt;
17 pub mod exam_question;18 pub mod exam_question;
19+pub mod fee_plan;
20+pub mod fee_plan_assignment;
18 pub mod field_update;21 pub mod field_update;
19 pub mod meal_attendance;22 pub mod meal_attendance;
20 pub mod meal_booking;23 pub mod meal_booking;
@@ -31,6 +34,7 @@ pub mod profile;
31 pub mod rag_output;34 pub mod rag_output;
32 pub mod registration;35 pub mod registration;
33 pub mod session;36 pub mod session;
37+pub mod session_attendance;
34 pub mod settings;38 pub mod settings;
35 pub mod subject;39 pub mod subject;
36 pub mod term;40 pub mod term;
src/db/session_attendance.rsadded+705 -0
@@ -0,0 +1,705 @@
1+//! The `session_attendance` table: the lesson roll call and the two badge
2+//! counters its mark and remove move. Every write is a single transaction
3+//! whose gates ride inside it; the target-eligibility rules (staff rows are
4+//! management's, only students attend, enrollment) are
5+//! [`crate::service::session_attendance`]'s to judge before calling here.
6+
7+use surrealdb::types::SurrealValue;
8+
9+use crate::constant::{
10+ LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
11+};
12+use crate::database::{Database, transaction_with_retry};
13+use crate::db::page::PagedList;
14+use crate::domain::attendance::AttendanceStatus;
15+use crate::domain::course_session::{CourseSession, CourseSessionId};
16+use crate::domain::session_attendance::{
17+ SessionAttendance, SessionAttendanceId, counts_as_attended,
18+};
19+use crate::domain::timestamp::Timestamp;
20+use crate::domain::user::UserId;
21+use crate::error::AppError;
22+
23+/// Record (or overwrite) `user`'s status for the session. One row per
24+/// (session, user), keyed by a deterministic composite id so this is a
25+/// single atomic UPSERT — concurrent marks converge on the one row.
26+///
27+/// The "session still exists" gate rides in the same transaction as the
28+/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the
29+/// caller's pre-flight read sits four round trips in front of this write,
30+/// so a delete landing in that gap used to leave a roll-call row on a
31+/// session that was gone — and that row was *unremovable*, its only delete
32+/// route 404ing on the vanished session while the attendance report went
33+/// on counting it. A deleted session reads NONE, which is falsy, so the
34+/// gate is written as an explicit `IS NONE` (see
35+/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the
36+/// session's `teacher` — required on every row, so NONE means "no row" just
37+/// as `id` did — because the counter below needs that teacher anyway, and
38+/// one read serves both.
39+///
40+/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write
41+/// sets, not read sets, so that gate alone only closes the *sequential*
42+/// order (delete committed, then the mark arrives). To make the two really
43+/// collide, this transaction also *writes* the session row, unconditionally
44+/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`]
45+/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`].
46+/// Unconditional is the whole point: the credit branch below writes that
47+/// column already, but it fires only for the first roll call of a lesson
48+/// that has begun, so a future-dated sheet and every re-mark of a counted
49+/// one touched nothing at all and committed happily beside
50+/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do
51+/// either — an `UPDATE` that leaves the document unchanged is elided and
52+/// never enters the write set — hence bump first, then either stamp
53+/// (credit branch) or put back exactly what was found, `NONE` included, so
54+/// the row is byte-identical and the once-per-lesson rule is untouched.
55+///
56+/// Sound to re-send while the store answers "conflict, retry": the gate
57+/// reads the record a delete writes, so the two contend by design, and the
58+/// UPSERT cannot legitimately answer "already exists" — its composite id is
59+/// bijective with the `session_attendance_session_user` unique tuple, so
60+/// the index entry can only point at the row the id already names.
61+///
62+/// Two badge counters move in this same transaction, both of them read
63+/// from the store rather than taken on the caller's word:
64+///
65+/// - `lessons_attended_total`, on the person marked, as a *delta* rather
66+/// than an increment, because this is an upsert: a re-mark that changes
67+/// nothing must change nothing, and a teacher's correction must move it
68+/// back down. `$was` is read before the upsert overwrites it (`NONE` when
69+/// the pair has no row yet), so it writes only on a real crossing of the
70+/// attended line, and only for a **student** — attending lessons is a
71+/// student's badge, the same student-only rule enrolling and sitting an
72+/// exam already carry, so a teacher marked present in their own lesson
73+/// moves it in neither direction. The live `role` decides that, not the
74+/// role someone held when the row was written.
75+/// - `lessons_held_total`, on the *session's* teacher, exactly once per
76+/// session: the first roll call taken stamps
77+/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
78+/// the stamp and credits nothing. It counts lessons that actually
79+/// happened — scheduling one and cancelling it earns nothing, which is
80+/// why the credit does not live in `crate::db::course_session::create`. Two
81+/// simultaneous first marks both write the lesson row, so the store's own
82+/// conflict detection (and `transaction_with_retry` behind it) is what
83+/// keeps the stamp from being set twice.
84+///
85+/// "Actually happened" is a clock reading, not a request count: the
86+/// credit waits for the lesson's own `starts_at` to arrive. Roll call is
87+/// deliberately *not* time-gated — a teacher may open the sheet early and
88+/// is never refused — so without this a teacher could schedule two
89+/// hundred lessons for next week, mark one student in each, and hold two
90+/// hundred lessons this afternoon. Because the stamp is written only on
91+/// the branch that credits, a sheet opened early and touched again after
92+/// the bell still credits exactly once, then; a sheet never touched
93+/// again credits never, which is the deliberate cost of not storing a
94+/// promise the passage of time would have to redeem on its own.
95+///
96+/// `lessons_attended_total` is *not* gated the same way, and the
97+/// asymmetry is on purpose: it is a delta off the row's stored status,
98+/// which carries no record of whether the credit was ever taken, so a
99+/// gate would refund at the correction what the early mark never
100+/// credited — a student's real lessons eaten by someone else's farm. It
101+/// is also nobody's self-service: only a teacher can mark a student, so
102+/// the counter cannot be moved by the person it decorates.
103+///
104+/// Both are floored/guarded rather than trusting the column to exist: a row
105+/// written before these columns carries none of them.
106+//
107+// corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
108+// attendance with future-dated lessons. Closing it needs the credit stamped
109+// on the roll-call row itself and refunded off that stamp — the same column
110+// the live-role note on `remove` below wants, and the shape
111+// `counted_on_time` already uses for homework. One column closes both;
112+// neither is worth it until a real complaint names one.
113+pub async fn mark(
114+ db: &Database,
115+ session: &CourseSession,
116+ user: &UserId,
117+ status: AttendanceStatus,
118+ marked_by: &UserId,
119+) -> Result<SessionAttendance, AppError> {
120+ let attended = counts_as_attended(&status);
121+ let delta: i64 = if attended { 1 } else { -1 };
122+ let attendance = SessionAttendance {
123+ id: SessionAttendanceId::composite(session.get_id(), user),
124+ session: session.get_id().clone(),
125+ course: session.get_course().clone(),
126+ user: user.clone(),
127+ status,
128+ marked_by: marked_by.clone(),
129+ };
130+ let (mut written, mut errors) = transaction_with_retry(
131+ db,
132+ &format!(
133+ "BEGIN TRANSACTION;
134+ LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);
135+ IF $teacher IS NONE {{ THROW 'session_missing' }};
136+ LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);
137+ LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);
138+ LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
139+ LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);
140+ LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
141+ IF $student AND $was != $now {{
142+ UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
143+ math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])
144+ }};
145+ UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;
146+ IF ($counted IS NONE) AND $begun {{
147+ UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;
148+ UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =
149+ ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1
150+ }} ELSE {{
151+ UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted
152+ }};
153+ RETURN $after;
154+ COMMIT TRANSACTION;"
155+ ),
156+ &[
157+ // `$session` is SurrealDB's own protected variable (the auth
158+ // session): binding that name errors the whole query.
159+ ("sess".into(), session.get_id().record().into_value()),
160+ ("id".into(), attendance.id.record().into_value()),
161+ ("usr".into(), user.record().into_value()),
162+ ("now".into(), attended.into_value()),
163+ ("delta".into(), delta.into_value()),
164+ ("stamp".into(), Timestamp::now().into_value()),
165+ ("row".into(), attendance.into_value()),
166+ ],
167+ &["session_missing"],
168+ )
169+ .await?;
170+ // An aborted transaction errors every slot and only the THROW's own
171+ // slot names the marker, so a refusal is read by marker while a lost
172+ // round was already re-sent — never reported as a 500.
173+ if errors
174+ .values()
175+ .any(|error| error.to_string().contains("session_missing"))
176+ {
177+ return Err(AppError::NotFound);
178+ }
179+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
180+ return Err(error.into());
181+ }
182+ // The trailing `RETURN` is always the last statement before `COMMIT`,
183+ // so its slot follows the statement count instead of a hand-kept one.
184+ let slot = written.num_statements().saturating_sub(2);
185+ written
186+ .take::<Vec<SessionAttendance>>(slot)?
187+ .into_iter()
188+ .next()
189+ .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))
190+}
191+
192+pub async fn list_for_session(
193+ db: &Database,
194+ session: &CourseSessionId,
195+ limit: Option<i64>,
196+ offset: i64,
197+) -> Result<(Vec<SessionAttendance>, i64), AppError> {
198+ PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")
199+ .bind("s", session.record())
200+ .run(limit, offset, db)
201+ .await
202+}
203+
204+/// Every roll-call row ever recorded for `user` — the session half of the
205+/// attendance report. Deliberately not filtered by current enrollment:
206+/// attendance is a historical record, so unenrolling hides marks (report
207+/// semantics) but never absences.
208+pub async fn list_for_user(
209+ db: &Database,
210+ user: &UserId,
211+) -> Result<Vec<SessionAttendance>, AppError> {
212+ let mut result = db
213+ .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")
214+ .bind(("usr", user.record()))
215+ .await?
216+ .check()?;
217+ Ok(result.take::<Vec<SessionAttendance>>(0)?)
218+}
219+
220+/// Clearing a row the student was counted for gives the count back, in the
221+/// delete's own transaction — the other direction of the delta in
222+/// [`mark`], so a row that never existed and a row that
223+/// was withdrawn leave the same number behind. Only *this* route decrements:
224+/// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of
225+/// its own and never comes through here, which is the ruling
226+/// `exam_sat_total` already carries — deleting the lesson does not un-attend
227+/// it. `lessons_held_total` is never given back either: the lesson was
228+/// taken, and clearing one student's row does not un-take it.
229+///
230+/// Student-only on the same terms as the mark, and read from the store for
231+/// the same reason.
232+///
233+/// Sound to re-send: neither statement can answer "already exists".
234+//
235+// corner-cut: both ends read the *live* role, so a student promoted between
236+// being marked present and having that row corrected leaves the counter one
237+// high (the credit landed as a student, the refund is refused as staff).
238+// Upgrade path is stamping the credit on the roll-call row itself and
239+// refunding off that stamp, the way `counted_on_time` works for homework —
240+// not worth a column until a promotion mid-term is a real complaint.
241+pub async fn remove(
242+ db: &Database,
243+ session: &CourseSessionId,
244+ user: &UserId,
245+) -> Result<Option<SessionAttendance>, AppError> {
246+ let (mut result, mut errors) = transaction_with_retry(
247+ db,
248+ &format!(
249+ "BEGIN TRANSACTION;
250+ LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
251+ LET $gone = (DELETE session_attendance
252+ WHERE session = $s AND user = $usr RETURN BEFORE);
253+ IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{
254+ UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
255+ math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])
256+ }};
257+ RETURN $gone;
258+ COMMIT TRANSACTION;"
259+ ),
260+ &[
261+ ("s".into(), session.record().into_value()),
262+ ("usr".into(), user.record().into_value()),
263+ ],
264+ &[],
265+ )
266+ .await?;
267+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
268+ return Err(error.into());
269+ }
270+ // The trailing `RETURN` is always the last statement before `COMMIT`.
271+ let slot = result.num_statements().saturating_sub(2);
272+ Ok(result
273+ .take::<Vec<SessionAttendance>>(slot)?
274+ .into_iter()
275+ .next())
276+}
277+
278+#[cfg(test)]
279+mod tests {
280+ use super::*;
281+ use crate::constant::DEFAULT_ATTENDANCE_STATUSES;
282+ use crate::database::init_mem;
283+ use crate::domain::badge::BadgeStats;
284+ use crate::domain::course_session::SessionTopic;
285+ use crate::domain::role::Role;
286+
287+ /// A user row carrying its role — the counters are `UPDATE`s on one (which
288+ /// writes nothing at all to a record that does not exist), and the live
289+ /// role is what decides whether the attended counter moves.
290+ async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
291+ let user = UserId::from_key(key);
292+ db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role")
293+ .bind(("usr", user.record()))
294+ .bind(("name", key.to_string()))
295+ .bind(("role", role))
296+ .await
297+ .unwrap()
298+ .check()
299+ .unwrap();
300+ user
301+ }
302+
303+ async fn a_student(key: &str, db: &Database) -> UserId {
304+ a_user(key, Role::Student, db).await
305+ }
306+
307+ async fn a_teacher(key: &str, db: &Database) -> UserId {
308+ a_user(key, Role::Teacher, db).await
309+ }
310+
311+ async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession {
312+ crate::db::course_session::create(
313+ db,
314+ &crate::db::course::a_test_course(db).await,
315+ teacher,
316+ SessionTopic::try_new("limits").unwrap(),
317+ Timestamp::from_millis(starts_at),
318+ None,
319+ )
320+ .await
321+ .unwrap()
322+ }
323+
324+ /// A lesson long since begun — every test but the gate's own wants one.
325+ async fn a_session(teacher: &UserId, db: &Database) -> CourseSession {
326+ a_session_at(teacher, 1, db).await
327+ }
328+
329+ /// A status this school allows — the four core ones plus a school-added
330+ /// `online`, which is exactly the open half of the set.
331+ fn status(value: &str) -> AttendanceStatus {
332+ let allowed: Vec<String> = DEFAULT_ATTENDANCE_STATUSES
333+ .iter()
334+ .map(|s| s.to_string())
335+ .chain(["online".to_string()])
336+ .collect();
337+ AttendanceStatus::try_new(value, &allowed).unwrap()
338+ }
339+
340+ /// The two counters as the badge rules read them, off the stored row.
341+ async fn attended(user: &UserId, db: &Database) -> i64 {
342+ BadgeStats::load(user, db)
343+ .await
344+ .unwrap()
345+ .get_lessons_attended()
346+ }
347+
348+ async fn held(user: &UserId, db: &Database) -> i64 {
349+ BadgeStats::load(user, db).await.unwrap().get_lessons_held()
350+ }
351+
352+ /// The whole transition table in one pass: an upsert may only move the
353+ /// counter when the mark crosses the attended line, in either direction, so
354+ /// a re-mark and a swap within the same class are both no-ops.
355+ #[tokio::test]
356+ async fn the_counter_follows_every_crossing_and_no_other_move() {
357+ let db = init_mem().await.unwrap();
358+ let teacher = a_teacher("t", &db).await;
359+ let student = a_student("s", &db).await;
360+ let session = a_session(&teacher, &db).await;
361+ let mark = async |value: &str, db: &Database| {
362+ super::mark(db, &session, &student, status(value), &teacher)
363+ .await
364+ .unwrap();
365+ };
366+
367+ for (value, expected, why) in [
368+ ("present", 1, "first mark counts"),
369+ ("present", 1, "re-marking the same status changes nothing"),
370+ ("late", 1, "late is attending too, so no crossing"),
371+ ("absent", 0, "a correction gives the count back"),
372+ ("absent", 0, "and does not keep giving it back"),
373+ ("late", 1, "absent -> late crosses back up"),
374+ ("excused", 0, "excused is neutral: a crossing down"),
375+ ("online", 0, "a school-added status stays neutral"),
376+ ("present", 1, "…and crossing up from one still counts"),
377+ ("online", 0, "…as does crossing down to one"),
378+ ] {
379+ mark(value, &db).await;
380+ assert_eq!(attended(&student, &db).await, expected, "{why}");
381+ }
382+ assert_eq!(attended(&teacher, &db).await, 0, "credited the marker");
383+ // Ten marks, one lesson: correcting a roll call is not holding another.
384+ assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice");
385+ }
386+
387+ /// The lesson is credited to its teacher when the roll call is *taken*, and
388+ /// once: the whole roster, and every later correction, ride the same stamp.
389+ #[tokio::test]
390+ async fn the_first_roll_call_counts_the_lesson_once() {
391+ let db = init_mem().await.unwrap();
392+ let teacher = a_teacher("t", &db).await;
393+ let other = a_teacher("o", &db).await;
394+ let session = a_session(&teacher, &db).await;
395+ assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing");
396+
397+ for key in ["s1", "s2", "s3"] {
398+ let student = a_student(key, &db).await;
399+ mark(&db, &session, &student, status("present"), &teacher)
400+ .await
401+ .unwrap();
402+ assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again");
403+ }
404+ assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher");
405+
406+ // A second lesson is a second count — the stamp is per session.
407+ let second = a_session(&teacher, &db).await;
408+ let student = a_student("s4", &db).await;
409+ mark(&db, &second, &student, status("present"), &teacher)
410+ .await
411+ .unwrap();
412+ assert_eq!(held(&teacher, &db).await, 2);
413+ }
414+
415+ /// A lesson is held when its own time comes, not when the sheet is opened.
416+ /// Roll call is never refused early, so ungated a teacher could schedule
417+ /// two hundred lessons for next week and hold all of them this afternoon.
418+ #[tokio::test]
419+ async fn a_lesson_that_has_not_started_holds_nothing_yet() {
420+ let db = init_mem().await.unwrap();
421+ let teacher = a_teacher("t", &db).await;
422+ let student = a_student("s", &db).await;
423+ let next_week =
424+ a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await;
425+
426+ mark(&db, &next_week, &student, status("present"), &teacher)
427+ .await
428+ .unwrap();
429+ assert_eq!(held(&teacher, &db).await, 0, "next week's lesson, today");
430+ // The mark itself stands — opening the sheet early is not an error.
431+ assert_eq!(attended(&student, &db).await, 1);
432+
433+ // The bell rings. The same sheet, touched again, credits now — and
434+ // only once: nothing backfills, so the stamp is the whole guard.
435+ db.query("UPDATE $sess SET starts_at = 1")
436+ .bind(("sess", next_week.get_id().record()))
437+ .await
438+ .unwrap()
439+ .check()
440+ .unwrap();
441+ for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] {
442+ mark(&db, &next_week, &student, status(status_value), &teacher)
443+ .await
444+ .unwrap();
445+ assert_eq!(held(&teacher, &db).await, 1, "{why}");
446+ }
447+ }
448+
449+ /// Attending lessons is a student's badge. A teacher marked present in
450+ /// their own lesson (which management does, not the teacher) moves nothing
451+ /// for them as an attendee — while the roll call itself still counts as a
452+ /// lesson held.
453+ #[tokio::test]
454+ async fn a_teacher_marked_present_earns_nothing_for_attending() {
455+ let db = init_mem().await.unwrap();
456+ let teacher = a_teacher("t", &db).await;
457+ let session = a_session(&teacher, &db).await;
458+
459+ mark(&db, &session, &teacher, status("present"), &teacher)
460+ .await
461+ .unwrap();
462+ assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson");
463+ assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken");
464+
465+ // And the correction direction is just as closed: nothing was taken, so
466+ // nothing may be given back.
467+ mark(&db, &session, &teacher, status("absent"), &teacher)
468+ .await
469+ .unwrap();
470+ assert_eq!(attended(&teacher, &db).await, 0);
471+ remove(&db, session.get_id(), &teacher)
472+ .await
473+ .unwrap()
474+ .expect("the row was there");
475+ assert_eq!(attended(&teacher, &db).await, 0);
476+ assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened");
477+ }
478+
479+ /// Two lessons are two counts — the counter is per row, not per student.
480+ #[tokio::test]
481+ async fn each_lesson_counts_once_for_the_student_marked() {
482+ let db = init_mem().await.unwrap();
483+ let teacher = a_teacher("t", &db).await;
484+ let student = a_student("s", &db).await;
485+ let other = a_student("o", &db).await;
486+ for _ in 0..2 {
487+ let session = a_session(&teacher, &db).await;
488+ mark(&db, &session, &student, status("present"), &teacher)
489+ .await
490+ .unwrap();
491+ }
492+ assert_eq!(attended(&student, &db).await, 2);
493+ assert_eq!(attended(&other, &db).await, 0, "credited the wrong student");
494+ }
495+
496+ /// Removing the row is the other direction of the delta, and only for a row
497+ /// that was counted.
498+ #[tokio::test]
499+ async fn removing_a_row_gives_back_only_what_it_took() {
500+ let db = init_mem().await.unwrap();
501+ let teacher = a_teacher("t", &db).await;
502+ let student = a_student("s", &db).await;
503+
504+ let counted = a_session(&teacher, &db).await;
505+ mark(&db, &counted, &student, status("present"), &teacher)
506+ .await
507+ .unwrap();
508+ let neutral = a_session(&teacher, &db).await;
509+ mark(&db, &neutral, &student, status("absent"), &teacher)
510+ .await
511+ .unwrap();
512+ assert_eq!(attended(&student, &db).await, 1);
513+
514+ remove(&db, neutral.get_id(), &student)
515+ .await
516+ .unwrap()
517+ .expect("the absent row was there");
518+ assert_eq!(attended(&student, &db).await, 1, "absent took nothing");
519+ remove(&db, counted.get_id(), &student)
520+ .await
521+ .unwrap()
522+ .expect("the present row was there");
523+ assert_eq!(attended(&student, &db).await, 0);
524+ assert!(
525+ remove(&db, counted.get_id(), &student)
526+ .await
527+ .unwrap()
528+ .is_none(),
529+ "nothing left to remove"
530+ );
531+ assert_eq!(attended(&student, &db).await, 0, "and nothing to give back");
532+ assert_eq!(
533+ held(&teacher, &db).await,
534+ 2,
535+ "clearing a row un-held a lesson"
536+ );
537+ }
538+
539+ /// The floor: however the corrections and removals interleave, and whatever
540+ /// a stale row starts from, the counter never goes negative.
541+ #[tokio::test]
542+ async fn the_counter_never_goes_below_zero() {
543+ let db = init_mem().await.unwrap();
544+ let teacher = a_teacher("t", &db).await;
545+ let student = a_student("s", &db).await;
546+
547+ // Ten counted lessons whose counter was never credited — the stale-data
548+ // case, an account that predates the column. Every one of them is now
549+ // corrected away, which is ten decrements against a zero.
550+ let mut sessions = Vec::new();
551+ for _ in 0..10 {
552+ let session = a_session(&teacher, &db).await;
553+ mark(&db, &session, &student, status("present"), &teacher)
554+ .await
555+ .unwrap();
556+ sessions.push(session);
557+ }
558+ db.query(format!(
559+ "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0"
560+ ))
561+ .bind(("usr", student.record()))
562+ .await
563+ .unwrap()
564+ .check()
565+ .unwrap();
566+
567+ for session in &sessions {
568+ mark(&db, session, &student, status("absent"), &teacher)
569+ .await
570+ .unwrap();
571+ remove(&db, session.get_id(), &student).await.unwrap();
572+ assert!(attended(&student, &db).await >= 0);
573+ }
574+ assert_eq!(attended(&student, &db).await, 0, "floored, never negative");
575+ }
576+
577+ /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own
578+ /// — it never reaches [`remove`] — so the count stands,
579+ /// the ruling every other counter here carries.
580+ #[tokio::test]
581+ async fn deleting_the_session_leaves_the_counters_alone() {
582+ let db = init_mem().await.unwrap();
583+ let teacher = a_teacher("t", &db).await;
584+ let student = a_student("s", &db).await;
585+ let session = a_session(&teacher, &db).await;
586+ mark(&db, &session, &student, status("present"), &teacher)
587+ .await
588+ .unwrap();
589+
590+ crate::db::course_session::delete(&db, session)
591+ .await
592+ .unwrap();
593+ assert_eq!(attended(&student, &db).await, 1, "the cascade decremented");
594+ assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented");
595+ }
596+
597+ /// A mark on a session that is already gone is refused, so it cannot leave
598+ /// a count behind either.
599+ #[tokio::test]
600+ async fn a_refused_mark_moves_nothing() {
601+ let db = init_mem().await.unwrap();
602+ let teacher = a_teacher("t", &db).await;
603+ let student = a_student("s", &db).await;
604+ let session = a_session(&teacher, &db).await;
605+ let ghost = session.clone();
606+ crate::db::course_session::delete(&db, session)
607+ .await
608+ .unwrap();
609+
610+ assert!(matches!(
611+ mark(&db, &ghost, &student, status("present"), &teacher).await,
612+ Err(AppError::NotFound)
613+ ));
614+ assert_eq!(attended(&student, &db).await, 0);
615+ assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson");
616+ }
617+
618+ /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT`
619+ /// on `course_session` fires inside the delete's own transaction, and
620+ /// [`crate::db::course_session::delete`] sweeps its children before removing the row,
621+ /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is
622+ /// written after the sweep has run, and used to commit straight past it.
623+ ///
624+ /// The two flavors raced are the ones the credit branch never wrote for — a
625+ /// lesson that has not begun, and a student with no row yet on a lesson
626+ /// already counted. A re-mark of a row that *exists* was never in danger:
627+ /// the cascade and the upsert write that child's own key and collide there.
628+ ///
629+ /// Real server, and `#[ignore]`d for it: the subject is the store's
630+ /// conflict detection, which [`init_mem`]'s embedded engine does not have —
631+ /// it commits both writes and answers `Ok` to each, so this passes there on
632+ /// broken code. Mutation-tested: dropping the unconditional
633+ /// `UPDATE $sess` from `mark` turns it red.
634+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
635+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
636+ async fn a_mark_written_inside_a_delete_never_outlives_the_session() {
637+ let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await;
638+ db.query(
639+ "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \
640+ THEN { SLEEP 1s; };",
641+ )
642+ .await
643+ .unwrap()
644+ .check()
645+ .unwrap();
646+
647+ let teacher = a_teacher("t", &db).await;
648+ let (mut swept, mut orphans) = (0, 0);
649+ for (round, already_counted) in [false, true, false, true].into_iter().enumerate() {
650+ let session = if already_counted {
651+ // Counted by somebody else's mark, so this one credits nothing.
652+ let session = a_session(&teacher, &db).await;
653+ let first = a_student(&format!("f{round}"), &db).await;
654+ mark(&db, &session, &first, status("present"), &teacher)
655+ .await
656+ .unwrap();
657+ session
658+ } else {
659+ a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await
660+ };
661+ let id = session.get_id().clone();
662+ let ghost = session.clone();
663+ let drop_it = {
664+ let db = db.clone();
665+ tokio::spawn(async move { crate::db::course_session::delete(&db, session).await })
666+ };
667+ // The mark starts inside the held window: the sweep has run and the
668+ // session row is gone but uncommitted — which is exactly what a
669+ // read of that session still believes.
670+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
671+ let marked = {
672+ let (db, teacher) = (db.clone(), teacher.clone());
673+ let student = a_student(&format!("s{round}"), &db).await;
674+ tokio::spawn(async move {
675+ mark(&db, &ghost, &student, status("present"), &teacher).await
676+ })
677+ };
678+ let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
679+ assert!(
680+ !matches!(marked, Err(AppError::Db(_))),
681+ "round {round}: a raced mark must be answered, not 500: {marked:?}"
682+ );
683+
684+ // Stored state is the whole verdict; a return value is not evidence.
685+ if crate::db::course_session::read(&db, &id)
686+ .await
687+ .unwrap()
688+ .is_none()
689+ {
690+ swept += 1;
691+ orphans += list_for_session(&db, &id, None, 0).await.unwrap().0.len();
692+ } else if drop_it.is_ok() {
693+ panic!("round {round}: the delete reported success but the session is still there");
694+ }
695+ }
696+ eprintln!(
697+ "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session"
698+ );
699+ assert!(
700+ swept > 0,
701+ "no round ever deleted the session, so the window was never reached"
702+ );
703+ assert_eq!(orphans, 0, "a roll call outlived its session");
704+ }
705+}
src/domain/attendance.rsmodified+7 -209
@@ -1,11 +1,9 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD};3+use crate::constant::ATTENDANCE_TABLE;
4-use crate::database::{Database, transaction_with_retry};
5-use crate::db::page::PagedList;
6 use crate::domain::event::EventId;4 use crate::domain::event::EventId;
7 use crate::domain::user::UserId;5 use crate::domain::user::UserId;
8-use crate::error::{AppError, ValidationError};6+use crate::error::ValidationError;
9 7
10 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]8 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
11 pub struct AttendanceId(RecordId);9 pub struct AttendanceId(RecordId);
@@ -59,11 +57,11 @@ impl AttendanceStatus {
59 57
60 #[derive(Debug, Clone, SurrealValue)]58 #[derive(Debug, Clone, SurrealValue)]
61 pub struct Attendance {59 pub struct Attendance {
62- id: AttendanceId,60+ pub(crate) id: AttendanceId,
63- event: EventId,61+ pub(crate) event: EventId,
64- user: UserId,62+ pub(crate) user: UserId,
65- status: AttendanceStatus,63+ pub(crate) status: AttendanceStatus,
66- marked_by: UserId,64+ pub(crate) marked_by: UserId,
67 }65 }
68 66
69 impl Attendance {67 impl Attendance {
@@ -86,121 +84,6 @@ impl Attendance {
86 pub fn get_marked_by(&self) -> &UserId {84 pub fn get_marked_by(&self) -> &UserId {
87 &self.marked_by85 &self.marked_by
88 }86 }
89-
90- /// Record (or overwrite) `user`'s status for `event`. One row per (event,
91- /// user), keyed by a deterministic composite id so this is a single atomic
92- /// UPSERT — concurrent marks for the same pair can no longer both insert and
93- /// collide on the unique index (a 500); they converge on the one row.
94- ///
95- /// The event's existence is proved *inside* the write, the twin of the gate
96- /// in [`crate::domain::session_attendance::SessionAttendance::mark`]: the
97- /// handler's event read sits several round trips in front of this, so a
98- /// bare upsert left a mark on an event [`crate::domain::event::Event`]'s
99- /// cascade (`DELETE attendance WHERE event = $ev`) had already swept —
100- /// counted forever in `GET /attendance/{user}` on an event no page shows.
101- /// Reading the event here would not have closed it either: SurrealDB 3.2.3
102- /// conflict-checks write sets, not read sets, so the proof has to *move* a
103- /// value on the event row. It is the bump-and-restore of
104- /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the
105- /// event already carries: matching nothing is the existence gate, writing
106- /// the key the delete removes is the collision, and the restore is by
107- /// captured value (`NONE` included) so no seat is spent or freed.
108- ///
109- /// Admissible for [`transaction_with_retry`]: no statement can answer
110- /// "already exists" — the `UPSERT`'s composite id is bijective with the
111- /// `attendance_event_user` unique tuple, so it resolves onto the row it
112- /// names instead of colliding with it.
113- pub async fn mark(
114- event: &EventId,
115- user: &UserId,
116- status: AttendanceStatus,
117- marked_by: &UserId,
118- db: &Database,
119- ) -> Result<Attendance, AppError> {
120- let attendance = Attendance {
121- id: AttendanceId::composite(event, user),
122- event: event.clone(),
123- user: user.clone(),
124- status,
125- marked_by: marked_by.clone(),
126- };
127- let (mut result, mut errors) = transaction_with_retry(
128- db,
129- &format!(
130- "BEGIN TRANSACTION;
131- LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev);
132- LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} =
133- ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
134- IF array::len($alive) = 0 {{ THROW 'event_missing' }};
135- UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was;
136- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
137- RETURN $after;
138- COMMIT TRANSACTION;"
139- ),
140- &[
141- ("ev".into(), event.record().into_value()),
142- ("id".into(), attendance.id.record().into_value()),
143- ("row".into(), attendance.into_value()),
144- ],
145- &["event_missing"],
146- )
147- .await?;
148- // An aborted transaction errors every slot and only the THROW's own
149- // slot names the marker.
150- if errors
151- .values()
152- .any(|error| error.to_string().contains("event_missing"))
153- {
154- return Err(AppError::NotFound);
155- }
156- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
157- return Err(error.into());
158- }
159- // The trailing `RETURN` is always the last statement before `COMMIT`.
160- let slot = result.num_statements().saturating_sub(2);
161- result
162- .take::<Vec<Attendance>>(slot)?
163- .into_iter()
164- .next()
165- .ok_or_else(|| AppError::Internal("failed to mark attendance".into()))
166- }
167-
168- pub async fn list_for_event(
169- event: &EventId,
170- limit: Option<i64>,
171- offset: i64,
172- db: &Database,
173- ) -> Result<(Vec<Attendance>, i64), AppError> {
174- PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC")
175- .bind("ev", event.record())
176- .run(limit, offset, db)
177- .await
178- }
179-
180- /// Every event-attendance row recorded for `user` — the events half of the
181- /// attendance report.
182- pub async fn list_for_user(user: &UserId, db: &Database) -> Result<Vec<Attendance>, AppError> {
183- let mut result = db
184- .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC")
185- .bind(("usr", user.record()))
186- .await?
187- .check()?;
188- Ok(result.take::<Vec<Attendance>>(0)?)
189- }
190-
191- pub async fn remove(
192- event: &EventId,
193- user: &UserId,
194- db: &Database,
195- ) -> Result<Option<Attendance>, AppError> {
196- let mut result = db
197- .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE")
198- .bind(("ev", event.record()))
199- .bind(("usr", user.record()))
200- .await?
201- .check()?;
202- Ok(result.take::<Vec<Attendance>>(0)?.into_iter().next())
203- }
204 }87 }
205 88
206 #[cfg(test)]89 #[cfg(test)]
@@ -230,89 +113,4 @@ mod tests {
230 .collect();113 .collect();
231 assert!(AttendanceStatus::try_new("online", &extended).is_ok());114 assert!(AttendanceStatus::try_new("online", &extended).is_ok());
232 }115 }
233-
234- /// The session twin's race, one table over
235- /// ([`crate::domain::session_attendance::SessionAttendance`]): a
236- /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and
237- /// [`crate::db::event::delete`] sweeps its attendance rows before removing the row, so
238- /// the `SLEEP` lands exactly between the sweep and the commit — the window
239- /// where a bare upsert wrote a mark nothing would ever sweep again.
240- ///
241- /// Real server, and `#[ignore]`d for it: the subject is the store's
242- /// conflict detection, which `init_mem`'s embedded engine does not have —
243- /// it commits both writes and answers `Ok` to each, so this passes there on
244- /// broken code. Mutation-tested: turning the claim back into a read
245- /// (`SELECT VALUE id FROM $ev`) turns it red.
246- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
247- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
248- async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
249- use crate::domain::event::{EventAudience, EventDescription, EventTitle};
250- let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;
251- db.query(
252- "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \
253- THEN { SLEEP 1s; };",
254- )
255- .await
256- .unwrap()
257- .check()
258- .unwrap();
259-
260- let allowed: Vec<String> = crate::domain::settings::Settings::defaults()
261- .get_attendance_statuses()
262- .to_vec();
263- let marker = UserId::from_key("t");
264- let (mut swept, mut orphans) = (0, 0);
265- for round in 0..4 {
266- let event = crate::db::event::create(
267- &db,
268- &marker,
269- EventTitle::try_new("gezi").unwrap(),
270- EventDescription::try_new("").unwrap(),
271- EventAudience::School,
272- None,
273- None,
274- )
275- .await
276- .unwrap();
277- let id = event.get_id().clone();
278- let drop_it = {
279- let db = db.clone();
280- tokio::spawn(async move { crate::db::event::delete(&db, event).await })
281- };
282- // The mark starts inside the held window: the sweep has run and the
283- // event row is gone but uncommitted.
284- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
285- let marked = {
286- let (db, id, marker) = (db.clone(), id.clone(), marker.clone());
287- let student = UserId::from_key(&format!("s{round}"));
288- let status = AttendanceStatus::try_new("present", &allowed).unwrap();
289- tokio::spawn(
290- async move { Attendance::mark(&id, &student, status, &marker, &db).await },
291- )
292- };
293- let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
294- assert!(
295- !matches!(marked, Err(AppError::Db(_))),
296- "round {round}: a raced mark must be answered, not 500: {marked:?}"
297- );
298-
299- // Stored state is the whole verdict; a return value is not evidence.
300- if crate::db::event::read(&db, &id).await.unwrap().is_none() {
301- swept += 1;
302- orphans += Attendance::list_for_event(&id, None, 0, &db)
303- .await
304- .unwrap()
305- .0
306- .len();
307- } else if drop_it.is_ok() {
308- panic!("round {round}: the delete reported success but the event is still there");
309- }
310- }
311- eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event");
312- assert!(
313- swept > 0,
314- "no round ever deleted the event, so the window was never reached"
315- );
316- assert_eq!(orphans, 0, "a mark outlived its event");
317- }
318 }116 }
src/domain/fee_plan.rsmodified+7 -155
@@ -16,17 +16,12 @@
16 16
17 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};17 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
18 18
19-use crate::constant::{19+use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN};
20- FEE_PLAN_TABLE, FEE_PLAN_UNASSIGNED_GUARD, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN,
21-};
22-use crate::database::{Database, write_with_retry};
23-use crate::db::field_update::FieldUpdate;
24 use crate::domain::monotonic_id::next_ulid;20 use crate::domain::monotonic_id::next_ulid;
25-use crate::db::page::PagedList;
26 use crate::domain::payment_ledger::LedgerAmount;21 use crate::domain::payment_ledger::LedgerAmount;
27 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
28 use crate::domain::user::UserId;23 use crate::domain::user::UserId;
29-use crate::error::{AppError, ValidationError};24+use crate::error::ValidationError;
30 use crate::validate::validate_required;25 use crate::validate::validate_required;
31 26
32 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]27 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -108,11 +103,11 @@ pub fn validate_installments(installments: &[Installment]) -> Result<(), Validat
108 103
109 #[derive(Debug, Clone, SurrealValue)]104 #[derive(Debug, Clone, SurrealValue)]
110 pub struct FeePlan {105 pub struct FeePlan {
111- id: FeePlanId,106+ pub(crate) id: FeePlanId,
112- name: FeePlanName,107+ pub(crate) name: FeePlanName,
113- installments: Vec<Installment>,108+ pub(crate) installments: Vec<Installment>,
114- created_by: UserId,109+ pub(crate) created_by: UserId,
115- created_at: Timestamp,110+ pub(crate) created_at: Timestamp,
116 }111 }
117 112
118 impl FeePlan {113 impl FeePlan {
@@ -135,110 +130,6 @@ impl FeePlan {
135 pub fn get_created_at(&self) -> Timestamp {130 pub fn get_created_at(&self) -> Timestamp {
136 self.created_at131 self.created_at
137 }132 }
138-
139- pub async fn create(
140- name: FeePlanName,
141- installments: Vec<Installment>,
142- created_by: &UserId,
143- db: &Database,
144- ) -> Result<FeePlan, AppError> {
145- validate_installments(&installments)?;
146- let plan = FeePlan {
147- id: FeePlanId::generate(),
148- name,
149- installments,
150- created_by: created_by.clone(),
151- created_at: Timestamp::now(),
152- };
153- let created: Option<FeePlan> = db.create(plan.id.record()).content(plan).await?;
154- created.ok_or_else(|| AppError::Internal("failed to create fee plan".into()))
155- }
156-
157- pub async fn read(id: &FeePlanId, db: &Database) -> Result<Option<FeePlan>, AppError> {
158- Ok(db.select(id.record()).await?)
159- }
160-
161- /// Every plan, newest first — a school runs a handful.
162- pub async fn list_all(
163- limit: Option<i64>,
164- offset: i64,
165- db: &Database,
166- ) -> Result<(Vec<FeePlan>, i64), AppError> {
167- PagedList::new("fee_plan", "ORDER BY created_at DESC, id DESC")
168- .run(limit, offset, db)
169- .await
170- }
171-
172- /// Write only the fields the PATCH carried — `None` means the request
173- /// omitted it, so the column is left alone rather than re-stated from the
174- /// snapshot this struct was read into. `Err(Conflict)` = refused, nothing
175- /// was written: somebody is already on the plan.
176- ///
177- /// Editing a plan never moves money: charges are frozen copies of the
178- /// installments as they stood when the plan was assigned. That is exactly
179- /// why an assigned plan may not be edited at all — the plan and the charges
180- /// raised from it would tell different stories. The roster is the plan's own
181- /// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same
182- /// transaction as the assignment row, so the check and the write are one
183- /// conditional `UPDATE` on one record: an assign racing this either claims
184- /// first (and the edit is refused) or claims after (and bills the edited
185- /// plan, which it re-reads). A `SELECT`-then-write could be, and was,
186- /// stepped over in the gap between the two.
187- pub async fn update(
188- self,
189- name: Option<FeePlanName>,
190- installments: Option<Vec<Installment>>,
191- db: &Database,
192- ) -> Result<FeePlan, AppError> {
193- if let Some(installments) = &installments {
194- validate_installments(installments)?;
195- }
196- let edited = FieldUpdate::new(self.id.record())
197- .set("name", name)
198- .set("installments", installments)
199- .guard(
200- FEE_PLAN_UNASSIGNED_GUARD,
201- AppError::Conflict("an assigned plan cannot be edited"),
202- )
203- .run::<FeePlan>(db)
204- .await;
205- // Still assigned or already gone: the guarded `UPDATE` cannot tell those
206- // apart either (it reports the refusal it was given), so — exactly as
207- // [`FeePlan::delete`] does — only the refusal path pays for the read
208- // that can. A plan deleted in the window since the handler read it must
209- // not be refused as "assigned": it never was.
210- if matches!(edited, Err(AppError::Conflict(_))) && Self::read(&self.id, db).await?.is_none()
211- {
212- return Err(AppError::NotFound);
213- }
214- edited
215- }
216-
217- /// Delete the plan, but only while nobody is on it. `false` = refused,
218- /// nothing was written; `Err(NotFound)` keeps the answer a concurrent
219- /// *delete* gives. Same one-record guard as [`FeePlan::update`], and the
220- /// same reason — the charges an assignment raised name this plan, and a
221- /// school's financial history keeps its references.
222- ///
223- /// Retried while the store answers "conflict, retry": the guard reads a
224- /// counter an assign *writes*, so the two contend on this one record by
225- /// design — and a delete that loses that round has written nothing, so
226- /// re-sending it is the whole of the recovery. Without the retry an
227- /// ordinary raced delete answers 500 instead of the 404 or 409 it owes.
228- pub async fn delete(self, db: &Database) -> Result<bool, AppError> {
229- let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE");
230- let deleted: Vec<FeePlan> =
231- write_with_retry(db, &sql, &[("plan".into(), self.id.record().into_value())]).await?;
232- if !deleted.is_empty() {
233- return Ok(true);
234- }
235- // Still assigned or already gone: the one statement cannot tell those
236- // apart, and only the refusal path pays for the read that can.
237- match Self::read(&self.id, db).await? {
238- Some(_) => Ok(false),
239- None => Err(AppError::NotFound),
240- }
241- }
242 }133 }
243 134
244 #[cfg(test)]135 #[cfg(test)]
@@ -267,43 +158,4 @@ mod tests {
267 assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok());158 assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok());
268 assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err());159 assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err());
269 }160 }
270-
271- /// The embedded-object DDL (`installments.*.amount_minor`) proved against
272- /// the engine: SCHEMAFULL rejects any nested key it was not told about, so
273- /// a plan that writes and reads back unchanged is what says the declared
274- /// shape and the stored one agree. A past due date is legal on purpose.
275- #[tokio::test]
276- async fn installments_survive_a_round_trip_through_the_schema() {
277- let db = crate::database::init_mem().await.unwrap();
278- let manager = UserId::from_key("mgr1");
279- let installments = vec![
280- Installment::new(
281- LedgerAmount::try_new(150_000).unwrap(),
282- Timestamp::from_millis(1_000),
283- ),
284- Installment::new(
285- LedgerAmount::try_new(250_000).unwrap(),
286- Timestamp::from_millis(2_000),
287- ),
288- ];
289- let plan = FeePlan::create(
290- FeePlanName::try_new("Yearly").unwrap(),
291- installments.clone(),
292- &manager,
293- &db,
294- )
295- .await
296- .unwrap();
297-
298- let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap();
299- assert_eq!(stored.get_installments(), installments.as_slice());
300- assert_eq!(stored.get_name().as_str(), "Yearly");
301-
302- // And a PATCH of the array lands whole.
303- let edited = stored
304- .update(None, Some(vec![installments[0].clone()]), &db)
305- .await
306- .unwrap();
307- assert_eq!(edited.get_installments().len(), 1);
308- }
309 }161 }
src/domain/fee_plan_assignment.rsmodified+7 -424
@@ -17,15 +17,10 @@
17 17
18 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};18 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
19 19
20-use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE};20+use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE;
21-use crate::database::Database;21+use crate::domain::fee_plan::FeePlanId;
22-use crate::db::cap::{self, Claimed};
23-use crate::db::page::PagedList;
24-use crate::db::payment_ledger;
25-use crate::domain::fee_plan::{FeePlan, FeePlanId};
26 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
27 use crate::domain::user::UserId;23 use crate::domain::user::UserId;
28-use crate::error::AppError;
29 24
30 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]25 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
31 pub struct FeePlanAssignmentId(RecordId);26 pub struct FeePlanAssignmentId(RecordId);
@@ -60,11 +55,11 @@ impl FeePlanAssignmentId {
60 55
61 #[derive(Debug, Clone, SurrealValue)]56 #[derive(Debug, Clone, SurrealValue)]
62 pub struct FeePlanAssignment {57 pub struct FeePlanAssignment {
63- id: FeePlanAssignmentId,58+ pub(crate) id: FeePlanAssignmentId,
64- plan: FeePlanId,59+ pub(crate) plan: FeePlanId,
65- student: UserId,60+ pub(crate) student: UserId,
66- assigned_by: UserId,61+ pub(crate) assigned_by: UserId,
67- created_at: Timestamp,62+ pub(crate) created_at: Timestamp,
68 }63 }
69 64
70 impl FeePlanAssignment {65 impl FeePlanAssignment {
@@ -87,416 +82,4 @@ impl FeePlanAssignment {
87 pub fn get_created_at(&self) -> Timestamp {82 pub fn get_created_at(&self) -> Timestamp {
88 self.created_at83 self.created_at
89 }84 }
90-
91- /// Place `plan` on `student` and bill it. Returns the assignment and
92- /// whether it was *already* there, so the web layer can answer a replay
93- /// honestly instead of pretending it just happened.
94- ///
95- /// The row and the plan's assignment refcount are written in **one**
96- /// transaction ([`cap::claim_and_create`]): that increment is what makes the
97- /// plan un-editable and un-deletable, and it has to be indivisible from the
98- /// row it counts, or an edit could slip between the two. A plan the counter
99- /// cannot be claimed on is one a concurrent delete already removed, which is
100- /// the same `404` the handler's own lookup would have given.
101- ///
102- /// The installments are then re-read **from the stored plan**, not taken
103- /// from the caller's snapshot: the claim is the moment the plan freezes, and
104- /// an edit that landed between the handler's read and that claim is
105- /// legitimate. Billing the snapshot would raise charges from a schedule the
106- /// plan no longer shows — precisely the divergence the 409 exists to
107- /// prevent.
108- ///
109- /// The charges are appended after the row, never before: each one is keyed
110- /// by (assignment, installment number), so this loop is safe to re-enter
111- /// from the top — which is exactly what a repeated assign does, and the
112- /// only way a half-written assignment ever gets its missing lines.
113- pub async fn assign(
114- plan: &FeePlan,
115- student: &UserId,
116- assigned_by: &UserId,
117- db: &Database,
118- ) -> Result<(FeePlanAssignment, bool), AppError> {
119- let id = FeePlanAssignmentId::composite(plan.get_id(), student);
120- let row = FeePlanAssignment {
121- id: id.clone(),
122- plan: plan.get_id().clone(),
123- student: student.clone(),
124- assigned_by: assigned_by.clone(),
125- created_at: Timestamp::now(),
126- };
127- let claimed = cap::claim_and_create(
128- &plan.get_id().record(),
129- FEE_PLAN_ASSIGNMENT_COUNT_FIELD,
130- cap::UNLIMITED,
131- &id.record(),
132- &row,
133- db,
134- )
135- .await?;
136- let (assignment, existed) = match claimed {
137- Claimed::Made(created) => (created, false),
138- // Someone assigned this pair first — their row is the answer, and
139- // the charges below are keyed the same, so continuing here can only
140- // *complete* the billing. Their claim already counts this row.
141- Claimed::Duplicate => (Self::require(&id, db).await?, true),
142- // The counter is uncapped, so the only miss is a plan that is gone.
143- Claimed::Full => return Err(AppError::NotFound),
144- };
145- // Frozen as of the claim above: no edit can land past it any more.
146- let plan = FeePlan::read(plan.get_id(), db)
147- .await?
148- .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?;
149- for (index, installment) in plan.get_installments().iter().enumerate() {
150- payment_ledger::charge_for_installment(
151- db,
152- &assignment,
153- index + 1,
154- installment,
155- assigned_by,
156- )
157- .await?;
158- }
159- Ok((assignment, existed))
160- }
161-
162- async fn require(
163- id: &FeePlanAssignmentId,
164- db: &Database,
165- ) -> Result<FeePlanAssignment, AppError> {
166- Self::read(id, db)
167- .await?
168- .ok_or_else(|| AppError::Internal("failed to assign the fee plan".into()))
169- }
170-
171- pub async fn read(
172- id: &FeePlanAssignmentId,
173- db: &Database,
174- ) -> Result<Option<FeePlanAssignment>, AppError> {
175- Ok(db.select(id.record()).await?)
176- }
177-
178- /// Who is on this plan, newest first.
179- pub async fn list_for_plan(
180- plan: &FeePlanId,
181- limit: Option<i64>,
182- offset: i64,
183- db: &Database,
184- ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
185- PagedList::new(
186- "fee_plan_assignment WHERE plan = $plan",
187- "ORDER BY created_at DESC, id DESC",
188- )
189- .bind("plan", plan.record())
190- .run(limit, offset, db)
191- .await
192- }
193-
194- /// Is anybody on this plan? A scan, and no longer a guard: the edit and
195- /// delete guards read the plan's own refcount, which no concurrent assign
196- /// can be behind. Kept because a *test* asserting the rows and the counter
197- /// agree is the only thing that would catch the counter drifting.
198- pub async fn exists_for_plan(plan: &FeePlanId, db: &Database) -> Result<bool, AppError> {
199- let mut result = db
200- .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1")
201- .bind(("plan", plan.record()))
202- .await?
203- .check()?;
204- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
205- }
206-
207- /// Which plans a student is on — one student may hold several.
208- pub async fn list_for_student(
209- student: &UserId,
210- limit: Option<i64>,
211- offset: i64,
212- db: &Database,
213- ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
214- PagedList::new(
215- "fee_plan_assignment WHERE student = $student",
216- "ORDER BY created_at DESC, id DESC",
217- )
218- .bind("student", student.record())
219- .run(limit, offset, db)
220- .await
221- }
222-}
223-
224-#[cfg(test)]
225-mod tests {
226- use super::*;
227- use crate::domain::fee_plan::{FeePlanName, Installment};
228- use crate::domain::payment_ledger::{LedgerAmount, PaymentLedgerKind};
229-
230- /// The invariant the whole module exists for: assigning bills every
231- /// installment once, and assigning *again* bills nothing — the second call
232- /// must not double a family's debt.
233- #[tokio::test]
234- async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {
235- let db = crate::database::init_mem().await.unwrap();
236- let manager = UserId::from_key("mgr1");
237- let student = UserId::from_key("stu1");
238- let plan = FeePlan::create(
239- FeePlanName::try_new("Yearly").unwrap(),
240- vec![
241- Installment::new(
242- LedgerAmount::try_new(150_000).unwrap(),
243- Timestamp::from_millis(1_000),
244- ),
245- Installment::new(
246- LedgerAmount::try_new(250_000).unwrap(),
247- Timestamp::from_millis(2_000),
248- ),
249- ],
250- &manager,
251- &db,
252- )
253- .await
254- .unwrap();
255-
256- let (_, existed) = FeePlanAssignment::assign(&plan, &student, &manager, &db)
257- .await
258- .unwrap();
259- assert!(!existed);
260- assert_eq!(
261- payment_ledger::balance_of(&db, &student).await.unwrap(),
262- -400_000,
263- "both installments must be owed"
264- );
265-
266- let (_, existed) = FeePlanAssignment::assign(&plan, &student, &manager, &db)
267- .await
268- .unwrap();
269- assert!(
270- existed,
271- "the second assign is a replay, not a new placement"
272- );
273- let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
274- .await
275- .unwrap();
276- assert_eq!(lines.len(), 2, "a replay may not append a single line");
277- assert!(
278- lines
279- .iter()
280- .all(|l| l.get_kind() == PaymentLedgerKind::Charge)
281- );
282- assert_eq!(
283- payment_ledger::balance_of(&db, &student).await.unwrap(),
284- -400_000
285- );
286- assert!(
287- FeePlanAssignment::exists_for_plan(plan.get_id(), &db)
288- .await
289- .unwrap()
290- );
291- }
292-
293- /// The race the refcount exists for: an edit and an assign, both licensed
294- /// by the same instant.
295- ///
296- /// "Neither lands" is *not* the invariant — the two are legal in one order
297- /// (edit, then assign the edited plan) and illegal in the other. What may
298- /// never happen is the money and the plan disagreeing: the charges raised
299- /// must be copies of the schedule the plan actually ends up carrying, and
300- /// once anybody is on the plan no further edit or delete may land at all.
301- ///
302- /// Asserted against the **stored** state, never against which call returned
303- /// `Ok`: a winner's word is not evidence about what the store kept.
304- /// The one thing the *returned* values are good for is the second
305- /// invariant: neither racer may answer 500. Losing a single-record round to
306- /// a rival is the ordinary way this guard works, and the loser's recovery is
307- /// to re-send, not to fail the request.
308- ///
309- /// Multi-threaded on purpose: on the single-threaded runtime the two tasks
310- /// interleave only at await points and the store never reports a conflict at
311- /// all, which is how a version of this test watched a 45-in-50 500 rate and
312- /// passed.
313- ///
314- /// Real server, and `#[ignore]`d rather than falling back to `init_mem`:
315- /// the embedded engine drops one of two concurrent writes to a record and
316- /// answers `Ok` to both, which fails this very assertion out of nowhere
317- /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in
318- /// 10 000 rounds on the server). See [`crate::database::init_test_server`].
319- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
320- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
321- async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() {
322- let (db, _serialized) = crate::database::init_test_server("edit_race").await;
323- let mut reached = 0;
324- for round in 0..20 {
325- let manager = UserId::from_key("mgr1");
326- let student = UserId::from_key(&format!("stu{round}"));
327- let plan = FeePlan::create(
328- FeePlanName::try_new("Yearly").unwrap(),
329- vec![Installment::new(
330- LedgerAmount::try_new(100).unwrap(),
331- Timestamp::from_millis(1_000),
332- )],
333- &manager,
334- &db,
335- )
336- .await
337- .unwrap();
338-
339- let edit = {
340- let (plan, db) = (plan.clone(), db.clone());
341- tokio::spawn(async move {
342- plan.update(
343- None,
344- Some(vec![Installment::new(
345- LedgerAmount::try_new(999).unwrap(),
346- Timestamp::from_millis(2_000),
347- )]),
348- &db,
349- )
350- .await
351- })
352- };
353- let assign = {
354- let (plan, db, manager, student) =
355- (plan.clone(), db.clone(), manager.clone(), student.clone());
356- tokio::spawn(async move {
357- FeePlanAssignment::assign(&plan, &student, &manager, &db).await
358- })
359- };
360- let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap());
361- assert!(
362- !matches!(edit, Err(AppError::Db(_))),
363- "a raced edit must be refused, not 500: {edit:?}"
364- );
365- assert!(
366- !matches!(assign, Err(AppError::Db(_))),
367- "a raced assign must retry, not 500: {assign:?}"
368- );
369-
370- let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap();
371- let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db)
372- .await
373- .unwrap();
374- if assigned {
375- reached += 1;
376- // The counter is what refuses every later edit, so it has to
377- // agree with the rows it stands for.
378- let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
379- .await
380- .unwrap();
381- assert_eq!(lines.len(), 1, "one installment, one charge");
382- assert_eq!(
383- lines[0].get_amount_minor().as_minor(),
384- stored.get_installments()[0].get_amount_minor().as_minor(),
385- "the charge must be a copy of the plan as it now stands"
386- );
387- assert!(
388- plan.clone().update(None, None, &db).await.is_ok(),
389- "an empty PATCH writes nothing, so it is not refused"
390- );
391- assert!(
392- matches!(
393- plan.clone()
394- .update(Some(FeePlanName::try_new("Nope").unwrap()), None, &db)
395- .await,
396- Err(AppError::Conflict(_))
397- ),
398- "an assigned plan stays frozen afterwards"
399- );
400- assert!(
401- !plan.clone().delete(&db).await.unwrap(),
402- "and it cannot be deleted either"
403- );
404- }
405- }
406- // Every assertion above sits behind "the assign landed", so a run where
407- // it never did asserts nothing at all — the failure this counter turns
408- // into a loud one.
409- assert!(reached > 0, "no round ever placed the assignment");
410- }
411-
412- /// The other half, and here "never both" *is* the invariant: a delete and
413- /// an assign racing must never leave a live assignment — with the charges
414- /// it billed — pointing at a plan that is gone. Stored state again, and a
415- /// real server again, for the same reasons.
416- ///
417- /// Both orderings are forced, because the interesting one does not happen on
418- /// its own: with both racers released together the assign wins ~24 rounds in
419- /// 25, so a run that only ever saw that ordering never tested a delete
420- /// landing first at all. Half the rounds therefore hold the assign back by a
421- /// beat, and the two counters below fail the test if either ordering went
422- /// unseen. Neither racer may answer 500 here either — this is the pair that
423- /// contends hardest, both writing the plan record itself.
424- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
425- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
426- async fn a_delete_racing_an_assign_never_orphans_an_assignment() {
427- let (db, _serialized) = crate::database::init_test_server("delete_race").await;
428- let (mut deleted_first, mut assigned_first) = (0, 0);
429- for round in 0..20 {
430- let hold_back_the_assign = round % 2 == 0;
431- let manager = UserId::from_key("mgr1");
432- let student = UserId::from_key(&format!("stu{round}"));
433- let plan = FeePlan::create(
434- FeePlanName::try_new("Yearly").unwrap(),
435- vec![Installment::new(
436- LedgerAmount::try_new(100).unwrap(),
437- Timestamp::from_millis(1_000),
438- )],
439- &manager,
440- &db,
441- )
442- .await
443- .unwrap();
444-
445- let head_start = std::time::Duration::from_millis(5);
446- let drop_it = {
447- let (plan, db) = (plan.clone(), db.clone());
448- tokio::spawn(async move {
449- if !hold_back_the_assign {
450- tokio::time::sleep(head_start).await;
451- }
452- plan.delete(&db).await
453- })
454- };
455- let assign = {
456- let (plan, db, manager, student) =
457- (plan.clone(), db.clone(), manager.clone(), student.clone());
458- tokio::spawn(async move {
459- if hold_back_the_assign {
460- tokio::time::sleep(head_start).await;
461- }
462- FeePlanAssignment::assign(&plan, &student, &manager, &db).await
463- })
464- };
465- let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap());
466- assert!(
467- !matches!(drop_it, Err(AppError::Db(_))),
468- "a raced delete must retry, not 500: {drop_it:?}"
469- );
470- assert!(
471- !matches!(assign, Err(AppError::Db(_))),
472- "a raced assign must retry, not 500: {assign:?}"
473- );
474-
475- let gone = FeePlan::read(plan.get_id(), &db).await.unwrap().is_none();
476- let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db)
477- .await
478- .unwrap();
479- deleted_first += usize::from(gone);
480- assigned_first += usize::from(assigned);
481- assert!(
482- !(gone && assigned),
483- "an assignment may not outlive the plan it names"
484- );
485- let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
486- .await
487- .unwrap();
488- assert!(
489- !(gone && !lines.is_empty()),
490- "and neither may the charges it raised"
491- );
492- }
493- // The premise, not a nicety: "never both" is trivially true in a run
494- // where one of the two never landed, so a run that only saw one
495- // ordering has proven nothing and says so.
496- assert!(deleted_first > 0, "no round ever let the delete land first");
497- assert!(
498- assigned_first > 0,
499- "no round ever let the assign land first"
500- );
501- }
502 }85 }
src/domain/session_attendance.rsmodified+9 -709
@@ -1,17 +1,10 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{3+use crate::constant::SESSION_ATTENDANCE_TABLE;
4- LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
5- SESSION_ATTENDANCE_TABLE,
6-};
7-use crate::database::{Database, transaction_with_retry};
8-use crate::db::page::PagedList;
9 use crate::domain::attendance::AttendanceStatus;4 use crate::domain::attendance::AttendanceStatus;
10 use crate::domain::course::CourseId;5 use crate::domain::course::CourseId;
11-use crate::domain::course_session::{CourseSession, CourseSessionId};6+use crate::domain::course_session::CourseSessionId;
12-use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
14-use crate::error::AppError;
15 8
16 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]9 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
17 pub struct SessionAttendanceId(RecordId);10 pub struct SessionAttendanceId(RecordId);
@@ -52,7 +45,7 @@ impl SessionAttendanceId {
52 /// drops one of the core four, so `present` and `late` can never be renamed45 /// drops one of the core four, so `present` and `late` can never be renamed
53 /// away. The SQL below repeats them — they are one rule in two languages, and46 /// away. The SQL below repeats them — they are one rule in two languages, and
54 /// the transition test is what pins them together.47 /// the transition test is what pins them together.
55-fn counts_as_attended(status: &AttendanceStatus) -> bool {48+pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool {
56 matches!(status.as_str(), "present" | "late")49 matches!(status.as_str(), "present" | "late")
57 }50 }
58 51
@@ -61,12 +54,12 @@ fn counts_as_attended(status: &AttendanceStatus) -> bool {
61 /// (`WHERE user = $u`) with no join.54 /// (`WHERE user = $u`) with no join.
62 #[derive(Debug, Clone, SurrealValue)]55 #[derive(Debug, Clone, SurrealValue)]
63 pub struct SessionAttendance {56 pub struct SessionAttendance {
64- id: SessionAttendanceId,57+ pub(crate) id: SessionAttendanceId,
65- session: CourseSessionId,58+ pub(crate) session: CourseSessionId,
66- course: CourseId,59+ pub(crate) course: CourseId,
67- user: UserId,60+ pub(crate) user: UserId,
68- status: AttendanceStatus,61+ pub(crate) status: AttendanceStatus,
69- marked_by: UserId,62+ pub(crate) marked_by: UserId,
70 }63 }
71 64
72 impl SessionAttendance {65 impl SessionAttendance {
@@ -93,697 +86,4 @@ impl SessionAttendance {
93 pub fn get_marked_by(&self) -> &UserId {86 pub fn get_marked_by(&self) -> &UserId {
94 &self.marked_by87 &self.marked_by
95 }88 }
96-
97- /// Record (or overwrite) `user`'s status for the session. One row per
98- /// (session, user), keyed by a deterministic composite id so this is a
99- /// single atomic UPSERT — concurrent marks converge on the one row.
100- ///
101- /// The "session still exists" gate rides in the same transaction as the
102- /// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the
103- /// caller's pre-flight read sits four round trips in front of this write,
104- /// so a delete landing in that gap used to leave a roll-call row on a
105- /// session that was gone — and that row was *unremovable*, its only delete
106- /// route 404ing on the vanished session while the attendance report went
107- /// on counting it. A deleted session reads NONE, which is falsy, so the
108- /// gate is written as an explicit `IS NONE` (see
109- /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the
110- /// session's `teacher` — required on every row, so NONE means "no row" just
111- /// as `id` did — because the counter below needs that teacher anyway, and
112- /// one read serves both.
113- ///
114- /// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write
115- /// sets, not read sets, so that gate alone only closes the *sequential*
116- /// order (delete committed, then the mark arrives). To make the two really
117- /// collide, this transaction also *writes* the session row, unconditionally
118- /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`]
119- /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`].
120- /// Unconditional is the whole point: the credit branch below writes that
121- /// column already, but it fires only for the first roll call of a lesson
122- /// that has begun, so a future-dated sheet and every re-mark of a counted
123- /// one touched nothing at all and committed happily beside
124- /// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do
125- /// either — an `UPDATE` that leaves the document unchanged is elided and
126- /// never enters the write set — hence bump first, then either stamp
127- /// (credit branch) or put back exactly what was found, `NONE` included, so
128- /// the row is byte-identical and the once-per-lesson rule is untouched.
129- ///
130- /// Sound to re-send while the store answers "conflict, retry": the gate
131- /// reads the record a delete writes, so the two contend by design, and the
132- /// UPSERT cannot legitimately answer "already exists" — its composite id is
133- /// bijective with the `session_attendance_session_user` unique tuple, so
134- /// the index entry can only point at the row the id already names.
135- ///
136- /// Two badge counters move in this same transaction, both of them read
137- /// from the store rather than taken on the caller's word:
138- ///
139- /// - `lessons_attended_total`, on the person marked, as a *delta* rather
140- /// than an increment, because this is an upsert: a re-mark that changes
141- /// nothing must change nothing, and a teacher's correction must move it
142- /// back down. `$was` is read before the upsert overwrites it (`NONE` when
143- /// the pair has no row yet), so it writes only on a real crossing of the
144- /// attended line, and only for a **student** — attending lessons is a
145- /// student's badge, the same student-only rule enrolling and sitting an
146- /// exam already carry, so a teacher marked present in their own lesson
147- /// moves it in neither direction. The live `role` decides that, not the
148- /// role someone held when the row was written.
149- /// - `lessons_held_total`, on the *session's* teacher, exactly once per
150- /// session: the first roll call taken stamps
151- /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
152- /// the stamp and credits nothing. It counts lessons that actually
153- /// happened — scheduling one and cancelling it earns nothing, which is
154- /// why the credit does not live in `crate::db::course_session::create`. Two
155- /// simultaneous first marks both write the lesson row, so the store's own
156- /// conflict detection (and `transaction_with_retry` behind it) is what
157- /// keeps the stamp from being set twice.
158- ///
159- /// "Actually happened" is a clock reading, not a request count: the
160- /// credit waits for the lesson's own `starts_at` to arrive. Roll call is
161- /// deliberately *not* time-gated — a teacher may open the sheet early and
162- /// is never refused — so without this a teacher could schedule two
163- /// hundred lessons for next week, mark one student in each, and hold two
164- /// hundred lessons this afternoon. Because the stamp is written only on
165- /// the branch that credits, a sheet opened early and touched again after
166- /// the bell still credits exactly once, then; a sheet never touched
167- /// again credits never, which is the deliberate cost of not storing a
168- /// promise the passage of time would have to redeem on its own.
169- ///
170- /// `lessons_attended_total` is *not* gated the same way, and the
171- /// asymmetry is on purpose: it is a delta off the row's stored status,
172- /// which carries no record of whether the credit was ever taken, so a
173- /// gate would refund at the correction what the early mark never
174- /// credited — a student's real lessons eaten by someone else's farm. It
175- /// is also nobody's self-service: only a teacher can mark a student, so
176- /// the counter cannot be moved by the person it decorates.
177- ///
178- /// Both are floored/guarded rather than trusting the column to exist: a row
179- /// written before these columns carries none of them.
180- //
181- // corner-cut: that asymmetry leaves a teacher able to inflate a *student's*
182- // attendance with future-dated lessons. Closing it needs the credit stamped
183- // on the roll-call row itself and refunded off that stamp — the same column
184- // the live-role note on `remove` below wants, and the shape
185- // `counted_on_time` already uses for homework. One column closes both;
186- // neither is worth it until a real complaint names one.
187- pub async fn mark(
188- session: &CourseSession,
189- user: &UserId,
190- status: AttendanceStatus,
191- marked_by: &UserId,
192- db: &Database,
193- ) -> Result<SessionAttendance, AppError> {
194- let attended = counts_as_attended(&status);
195- let delta: i64 = if attended { 1 } else { -1 };
196- let attendance = SessionAttendance {
197- id: SessionAttendanceId::composite(session.get_id(), user),
198- session: session.get_id().clone(),
199- course: session.get_course().clone(),
200- user: user.clone(),
201- status,
202- marked_by: marked_by.clone(),
203- };
204- let (mut written, mut errors) = transaction_with_retry(
205- db,
206- &format!(
207- "BEGIN TRANSACTION;
208- LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);
209- IF $teacher IS NONE {{ THROW 'session_missing' }};
210- LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);
211- LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp);
212- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
213- LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);
214- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
215- IF $student AND $was != $now {{
216- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
217- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])
218- }};
219- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1;
220- IF ($counted IS NONE) AND $begun {{
221- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;
222- UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =
223- ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1
224- }} ELSE {{
225- UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted
226- }};
227- RETURN $after;
228- COMMIT TRANSACTION;"
229- ),
230- &[
231- // `$session` is SurrealDB's own protected variable (the auth
232- // session): binding that name errors the whole query.
233- ("sess".into(), session.get_id().record().into_value()),
234- ("id".into(), attendance.id.record().into_value()),
235- ("usr".into(), user.record().into_value()),
236- ("now".into(), attended.into_value()),
237- ("delta".into(), delta.into_value()),
238- ("stamp".into(), Timestamp::now().into_value()),
239- ("row".into(), attendance.into_value()),
240- ],
241- &["session_missing"],
242- )
243- .await?;
244- // An aborted transaction errors every slot and only the THROW's own
245- // slot names the marker, so a refusal is read by marker while a lost
246- // round was already re-sent — never reported as a 500.
247- if errors
248- .values()
249- .any(|error| error.to_string().contains("session_missing"))
250- {
251- return Err(AppError::NotFound);
252- }
253- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
254- return Err(error.into());
255- }
256- // The trailing `RETURN` is always the last statement before `COMMIT`,
257- // so its slot follows the statement count instead of a hand-kept one.
258- let slot = written.num_statements().saturating_sub(2);
259- written
260- .take::<Vec<SessionAttendance>>(slot)?
261- .into_iter()
262- .next()
263- .ok_or_else(|| AppError::Internal("failed to mark session attendance".into()))
264- }
265-
266- pub async fn list_for_session(
267- session: &CourseSessionId,
268- limit: Option<i64>,
269- offset: i64,
270- db: &Database,
271- ) -> Result<(Vec<SessionAttendance>, i64), AppError> {
272- PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC")
273- .bind("s", session.record())
274- .run(limit, offset, db)
275- .await
276- }
277-
278- /// Every roll-call row ever recorded for `user` — the session half of the
279- /// attendance report. Deliberately not filtered by current enrollment:
280- /// attendance is a historical record, so unenrolling hides marks (report
281- /// semantics) but never absences.
282- pub async fn list_for_user(
283- user: &UserId,
284- db: &Database,
285- ) -> Result<Vec<SessionAttendance>, AppError> {
286- let mut result = db
287- .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC")
288- .bind(("usr", user.record()))
289- .await?
290- .check()?;
291- Ok(result.take::<Vec<SessionAttendance>>(0)?)
292- }
293-
294- /// Clearing a row the student was counted for gives the count back, in the
295- /// delete's own transaction — the other direction of the delta in
296- /// [`SessionAttendance::mark`], so a row that never existed and a row that
297- /// was withdrawn leave the same number behind. Only *this* route decrements:
298- /// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of
299- /// its own and never comes through here, which is the ruling
300- /// `exam_sat_total` already carries — deleting the lesson does not un-attend
301- /// it. `lessons_held_total` is never given back either: the lesson was
302- /// taken, and clearing one student's row does not un-take it.
303- ///
304- /// Student-only on the same terms as the mark, and read from the store for
305- /// the same reason.
306- ///
307- /// Sound to re-send: neither statement can answer "already exists".
308- //
309- // corner-cut: both ends read the *live* role, so a student promoted between
310- // being marked present and having that row corrected leaves the counter one
311- // high (the credit landed as a student, the refund is refused as staff).
312- // Upgrade path is stamping the credit on the roll-call row itself and
313- // refunding off that stamp, the way `counted_on_time` works for homework —
314- // not worth a column until a promotion mid-term is a real complaint.
315- pub async fn remove(
316- session: &CourseSessionId,
317- user: &UserId,
318- db: &Database,
319- ) -> Result<Option<SessionAttendance>, AppError> {
320- let (mut result, mut errors) = transaction_with_retry(
321- db,
322- &format!(
323- "BEGIN TRANSACTION;
324- LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
325- LET $gone = (DELETE session_attendance
326- WHERE session = $s AND user = $usr RETURN BEFORE);
327- IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{
328- UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
329- math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])
330- }};
331- RETURN $gone;
332- COMMIT TRANSACTION;"
333- ),
334- &[
335- ("s".into(), session.record().into_value()),
336- ("usr".into(), user.record().into_value()),
337- ],
338- &[],
339- )
340- .await?;
341- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
342- return Err(error.into());
343- }
344- // The trailing `RETURN` is always the last statement before `COMMIT`.
345- let slot = result.num_statements().saturating_sub(2);
346- Ok(result
347- .take::<Vec<SessionAttendance>>(slot)?
348- .into_iter()
349- .next())
350- }
351-}
352-
353-#[cfg(test)]
354-mod tests {
355- use super::*;
356- use crate::constant::DEFAULT_ATTENDANCE_STATUSES;
357- use crate::database::init_mem;
358- use crate::domain::course_session::SessionTopic;
359- use crate::domain::role::Role;
360-
361- /// A user row carrying its role — the counters are `UPDATE`s on one (which
362- /// writes nothing at all to a record that does not exist), and the live
363- /// role is what decides whether the attended counter moves.
364- async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
365- let user = UserId::from_key(key);
366- db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role")
367- .bind(("usr", user.record()))
368- .bind(("name", key.to_string()))
369- .bind(("role", role))
370- .await
371- .unwrap()
372- .check()
373- .unwrap();
374- user
375- }
376-
377- async fn a_student(key: &str, db: &Database) -> UserId {
378- a_user(key, Role::Student, db).await
379- }
380-
381- async fn a_teacher(key: &str, db: &Database) -> UserId {
382- a_user(key, Role::Teacher, db).await
383- }
384-
385- async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession {
386- crate::db::course_session::create(
387- db,
388- &crate::db::course::a_test_course(db).await,
389- teacher,
390- SessionTopic::try_new("limits").unwrap(),
391- Timestamp::from_millis(starts_at),
392- None,
393- )
394- .await
395- .unwrap()
396- }
397-
398- /// A lesson long since begun — every test but the gate's own wants one.
399- async fn a_session(teacher: &UserId, db: &Database) -> CourseSession {
400- a_session_at(teacher, 1, db).await
401- }
402-
403- /// A status this school allows — the four core ones plus a school-added
404- /// `online`, which is exactly the open half of the set.
405- fn status(value: &str) -> AttendanceStatus {
406- let allowed: Vec<String> = DEFAULT_ATTENDANCE_STATUSES
407- .iter()
408- .map(|s| s.to_string())
409- .chain(["online".to_string()])
410- .collect();
411- AttendanceStatus::try_new(value, &allowed).unwrap()
412- }
413-
414- /// The two counters as the badge rules read them, off the stored row.
415- async fn attended(user: &UserId, db: &Database) -> i64 {
416- crate::db::badge::load(db, user)
417- .await
418- .unwrap()
419- .get_lessons_attended()
420- }
421-
422- async fn held(user: &UserId, db: &Database) -> i64 {
423- crate::db::badge::load(db, user)
424- .await
425- .unwrap()
426- .get_lessons_held()
427- }
428-
429- /// The whole transition table in one pass: an upsert may only move the
430- /// counter when the mark crosses the attended line, in either direction, so
431- /// a re-mark and a swap within the same class are both no-ops.
432- #[tokio::test]
433- async fn the_counter_follows_every_crossing_and_no_other_move() {
434- let db = init_mem().await.unwrap();
435- let teacher = a_teacher("t", &db).await;
436- let student = a_student("s", &db).await;
437- let session = a_session(&teacher, &db).await;
438- let mark = async |value: &str, db: &Database| {
439- SessionAttendance::mark(&session, &student, status(value), &teacher, db)
440- .await
441- .unwrap();
442- };
443-
444- for (value, expected, why) in [
445- ("present", 1, "first mark counts"),
446- ("present", 1, "re-marking the same status changes nothing"),
447- ("late", 1, "late is attending too, so no crossing"),
448- ("absent", 0, "a correction gives the count back"),
449- ("absent", 0, "and does not keep giving it back"),
450- ("late", 1, "absent -> late crosses back up"),
451- ("excused", 0, "excused is neutral: a crossing down"),
452- ("online", 0, "a school-added status stays neutral"),
453- ("present", 1, "…and crossing up from one still counts"),
454- ("online", 0, "…as does crossing down to one"),
455- ] {
456- mark(value, &db).await;
457- assert_eq!(attended(&student, &db).await, expected, "{why}");
458- }
459- assert_eq!(attended(&teacher, &db).await, 0, "credited the marker");
460- // Ten marks, one lesson: correcting a roll call is not holding another.
461- assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice");
462- }
463-
464- /// The lesson is credited to its teacher when the roll call is *taken*, and
465- /// once: the whole roster, and every later correction, ride the same stamp.
466- #[tokio::test]
467- async fn the_first_roll_call_counts_the_lesson_once() {
468- let db = init_mem().await.unwrap();
469- let teacher = a_teacher("t", &db).await;
470- let other = a_teacher("o", &db).await;
471- let session = a_session(&teacher, &db).await;
472- assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing");
473-
474- for key in ["s1", "s2", "s3"] {
475- let student = a_student(key, &db).await;
476- SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
477- .await
478- .unwrap();
479- assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again");
480- }
481- assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher");
482-
483- // A second lesson is a second count — the stamp is per session.
484- let second = a_session(&teacher, &db).await;
485- let student = a_student("s4", &db).await;
486- SessionAttendance::mark(&second, &student, status("present"), &teacher, &db)
487- .await
488- .unwrap();
489- assert_eq!(held(&teacher, &db).await, 2);
490- }
491-
492- /// A lesson is held when its own time comes, not when the sheet is opened.
493- /// Roll call is never refused early, so ungated a teacher could schedule
494- /// two hundred lessons for next week and hold all of them this afternoon.
495- #[tokio::test]
496- async fn a_lesson_that_has_not_started_holds_nothing_yet() {
497- let db = init_mem().await.unwrap();
498- let teacher = a_teacher("t", &db).await;
499- let student = a_student("s", &db).await;
500- let next_week =
501- a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await;
502-
503- SessionAttendance::mark(&next_week, &student, status("present"), &teacher, &db)
504- .await
505- .unwrap();
506- assert_eq!(held(&teacher, &db).await, 0, "next week's lesson, today");
507- // The mark itself stands — opening the sheet early is not an error.
508- assert_eq!(attended(&student, &db).await, 1);
509-
510- // The bell rings. The same sheet, touched again, credits now — and
511- // only once: nothing backfills, so the stamp is the whole guard.
512- db.query("UPDATE $sess SET starts_at = 1")
513- .bind(("sess", next_week.get_id().record()))
514- .await
515- .unwrap()
516- .check()
517- .unwrap();
518- for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] {
519- SessionAttendance::mark(&next_week, &student, status(status_value), &teacher, &db)
520- .await
521- .unwrap();
522- assert_eq!(held(&teacher, &db).await, 1, "{why}");
523- }
524- }
525-
526- /// Attending lessons is a student's badge. A teacher marked present in
527- /// their own lesson (which management does, not the teacher) moves nothing
528- /// for them as an attendee — while the roll call itself still counts as a
529- /// lesson held.
530- #[tokio::test]
531- async fn a_teacher_marked_present_earns_nothing_for_attending() {
532- let db = init_mem().await.unwrap();
533- let teacher = a_teacher("t", &db).await;
534- let session = a_session(&teacher, &db).await;
535-
536- SessionAttendance::mark(&session, &teacher, status("present"), &teacher, &db)
537- .await
538- .unwrap();
539- assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson");
540- assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken");
541-
542- // And the correction direction is just as closed: nothing was taken, so
543- // nothing may be given back.
544- SessionAttendance::mark(&session, &teacher, status("absent"), &teacher, &db)
545- .await
546- .unwrap();
547- assert_eq!(attended(&teacher, &db).await, 0);
548- SessionAttendance::remove(session.get_id(), &teacher, &db)
549- .await
550- .unwrap()
551- .expect("the row was there");
552- assert_eq!(attended(&teacher, &db).await, 0);
553- assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened");
554- }
555-
556- /// Two lessons are two counts — the counter is per row, not per student.
557- #[tokio::test]
558- async fn each_lesson_counts_once_for_the_student_marked() {
559- let db = init_mem().await.unwrap();
560- let teacher = a_teacher("t", &db).await;
561- let student = a_student("s", &db).await;
562- let other = a_student("o", &db).await;
563- for _ in 0..2 {
564- let session = a_session(&teacher, &db).await;
565- SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
566- .await
567- .unwrap();
568- }
569- assert_eq!(attended(&student, &db).await, 2);
570- assert_eq!(attended(&other, &db).await, 0, "credited the wrong student");
571- }
572-
573- /// Removing the row is the other direction of the delta, and only for a row
574- /// that was counted.
575- #[tokio::test]
576- async fn removing_a_row_gives_back_only_what_it_took() {
577- let db = init_mem().await.unwrap();
578- let teacher = a_teacher("t", &db).await;
579- let student = a_student("s", &db).await;
580-
581- let counted = a_session(&teacher, &db).await;
582- SessionAttendance::mark(&counted, &student, status("present"), &teacher, &db)
583- .await
584- .unwrap();
585- let neutral = a_session(&teacher, &db).await;
586- SessionAttendance::mark(&neutral, &student, status("absent"), &teacher, &db)
587- .await
588- .unwrap();
589- assert_eq!(attended(&student, &db).await, 1);
590-
591- SessionAttendance::remove(neutral.get_id(), &student, &db)
592- .await
593- .unwrap()
594- .expect("the absent row was there");
595- assert_eq!(attended(&student, &db).await, 1, "absent took nothing");
596- SessionAttendance::remove(counted.get_id(), &student, &db)
597- .await
598- .unwrap()
599- .expect("the present row was there");
600- assert_eq!(attended(&student, &db).await, 0);
601- assert!(
602- SessionAttendance::remove(counted.get_id(), &student, &db)
603- .await
604- .unwrap()
605- .is_none(),
606- "nothing left to remove"
607- );
608- assert_eq!(attended(&student, &db).await, 0, "and nothing to give back");
609- assert_eq!(
610- held(&teacher, &db).await,
611- 2,
612- "clearing a row un-held a lesson"
613- );
614- }
615-
616- /// The floor: however the corrections and removals interleave, and whatever
617- /// a stale row starts from, the counter never goes negative.
618- #[tokio::test]
619- async fn the_counter_never_goes_below_zero() {
620- let db = init_mem().await.unwrap();
621- let teacher = a_teacher("t", &db).await;
622- let student = a_student("s", &db).await;
623-
624- // Ten counted lessons whose counter was never credited — the stale-data
625- // case, an account that predates the column. Every one of them is now
626- // corrected away, which is ten decrements against a zero.
627- let mut sessions = Vec::new();
628- for _ in 0..10 {
629- let session = a_session(&teacher, &db).await;
630- SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
631- .await
632- .unwrap();
633- sessions.push(session);
634- }
635- db.query(format!(
636- "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0"
637- ))
638- .bind(("usr", student.record()))
639- .await
640- .unwrap()
641- .check()
642- .unwrap();
643-
644- for session in &sessions {
645- SessionAttendance::mark(session, &student, status("absent"), &teacher, &db)
646- .await
647- .unwrap();
648- SessionAttendance::remove(session.get_id(), &student, &db)
649- .await
650- .unwrap();
651- assert!(attended(&student, &db).await >= 0);
652- }
653- assert_eq!(attended(&student, &db).await, 0, "floored, never negative");
654- }
655-
656- /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own
657- /// — it never reaches [`SessionAttendance::remove`] — so the count stands,
658- /// the ruling every other counter here carries.
659- #[tokio::test]
660- async fn deleting_the_session_leaves_the_counters_alone() {
661- let db = init_mem().await.unwrap();
662- let teacher = a_teacher("t", &db).await;
663- let student = a_student("s", &db).await;
664- let session = a_session(&teacher, &db).await;
665- SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
666- .await
667- .unwrap();
668-
669- crate::db::course_session::delete(&db, session)
670- .await
671- .unwrap();
672- assert_eq!(attended(&student, &db).await, 1, "the cascade decremented");
673- assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented");
674- }
675-
676- /// A mark on a session that is already gone is refused, so it cannot leave
677- /// a count behind either.
678- #[tokio::test]
679- async fn a_refused_mark_moves_nothing() {
680- let db = init_mem().await.unwrap();
681- let teacher = a_teacher("t", &db).await;
682- let student = a_student("s", &db).await;
683- let session = a_session(&teacher, &db).await;
684- let ghost = session.clone();
685- crate::db::course_session::delete(&db, session)
686- .await
687- .unwrap();
688-
689- assert!(matches!(
690- SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await,
691- Err(AppError::NotFound)
692- ));
693- assert_eq!(attended(&student, &db).await, 0);
694- assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson");
695- }
696-
697- /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT`
698- /// on `course_session` fires inside the delete's own transaction, and
699- /// [`crate::db::course_session::delete`] sweeps its children before removing the row,
700- /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is
701- /// written after the sweep has run, and used to commit straight past it.
702- ///
703- /// The two flavors raced are the ones the credit branch never wrote for — a
704- /// lesson that has not begun, and a student with no row yet on a lesson
705- /// already counted. A re-mark of a row that *exists* was never in danger:
706- /// the cascade and the upsert write that child's own key and collide there.
707- ///
708- /// Real server, and `#[ignore]`d for it: the subject is the store's
709- /// conflict detection, which [`init_mem`]'s embedded engine does not have —
710- /// it commits both writes and answers `Ok` to each, so this passes there on
711- /// broken code. Mutation-tested: dropping the unconditional
712- /// `UPDATE $sess` from `mark` turns it red.
713- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
714- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
715- async fn a_mark_written_inside_a_delete_never_outlives_the_session() {
716- let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await;
717- db.query(
718- "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \
719- THEN { SLEEP 1s; };",
720- )
721- .await
722- .unwrap()
723- .check()
724- .unwrap();
725-
726- let teacher = a_teacher("t", &db).await;
727- let (mut swept, mut orphans) = (0, 0);
728- for (round, already_counted) in [false, true, false, true].into_iter().enumerate() {
729- let session = if already_counted {
730- // Counted by somebody else's mark, so this one credits nothing.
731- let session = a_session(&teacher, &db).await;
732- let first = a_student(&format!("f{round}"), &db).await;
733- SessionAttendance::mark(&session, &first, status("present"), &teacher, &db)
734- .await
735- .unwrap();
736- session
737- } else {
738- a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await
739- };
740- let id = session.get_id().clone();
741- let ghost = session.clone();
742- let drop_it = {
743- let db = db.clone();
744- tokio::spawn(async move { crate::db::course_session::delete(&db, session).await })
745- };
746- // The mark starts inside the held window: the sweep has run and the
747- // session row is gone but uncommitted — which is exactly what a
748- // read of that session still believes.
749- tokio::time::sleep(std::time::Duration::from_millis(300)).await;
750- let marked = {
751- let (db, teacher) = (db.clone(), teacher.clone());
752- let student = a_student(&format!("s{round}"), &db).await;
753- tokio::spawn(async move {
754- SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db)
755- .await
756- })
757- };
758- let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap());
759- assert!(
760- !matches!(marked, Err(AppError::Db(_))),
761- "round {round}: a raced mark must be answered, not 500: {marked:?}"
762- );
763-
764- // Stored state is the whole verdict; a return value is not evidence.
765- if crate::db::course_session::read(&db, &id)
766- .await
767- .unwrap()
768- .is_none()
769- {
770- swept += 1;
771- orphans += SessionAttendance::list_for_session(&id, None, 0, &db)
772- .await
773- .unwrap()
774- .0
775- .len();
776- } else if drop_it.is_ok() {
777- panic!("round {round}: the delete reported success but the session is still there");
778- }
779- }
780- eprintln!(
781- "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session"
782- );
783- assert!(
784- swept > 0,
785- "no round ever deleted the session, so the window was never reached"
786- );
787- assert_eq!(orphans, 0, "a roll call outlived its session");
788- }
789 }89 }
src/service/attendance.rsadded+48 -0
@@ -0,0 +1,48 @@
1+//! Event roll-call doors for the web layer. The mark is one atomic
2+//! transaction whose existence gate rides inside the write
3+//! ([`crate::db::attendance::mark`]), so this module is thin
4+//! pass-throughs; the event's audience gate is judged by the web layer
5+//! against the event it already read.
6+
7+use crate::database::Database;
8+use crate::db::attendance;
9+use crate::domain::attendance::{Attendance, AttendanceStatus};
10+use crate::domain::event::EventId;
11+use crate::domain::user::UserId;
12+use crate::error::AppError;
13+
14+/// Record (or overwrite) `user`'s status for `event`.
15+pub async fn mark(
16+ db: &Database,
17+ event: &EventId,
18+ user: &UserId,
19+ status: AttendanceStatus,
20+ marked_by: &UserId,
21+) -> Result<Attendance, AppError> {
22+ attendance::mark(db, event, user, status, marked_by).await
23+}
24+
25+/// A page of the event's roll call, newest id first.
26+pub async fn list_for_event(
27+ db: &Database,
28+ event: &EventId,
29+ limit: Option<i64>,
30+ offset: i64,
31+) -> Result<(Vec<Attendance>, i64), AppError> {
32+ attendance::list_for_event(db, event, limit, offset).await
33+}
34+
35+/// Every event-attendance row recorded for `user` — the events half of the
36+/// attendance report.
37+pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Attendance>, AppError> {
38+ attendance::list_for_user(db, user).await
39+}
40+
41+/// Clear one row; `None` = there was none.
42+pub async fn remove(
43+ db: &Database,
44+ event: &EventId,
45+ user: &UserId,
46+) -> Result<Option<Attendance>, AppError> {
47+ attendance::remove(db, event, user).await
48+}
src/service/fee_plan.rsadded+53 -0
@@ -0,0 +1,53 @@
1+//! Fee-plan doors for the web layer. Every write here is a single guarded
2+//! statement in [`crate::db::fee_plan`] — the assigned-plan freeze is the
3+//! store's own, decided as the write lands — so this module is thin
4+//! pass-throughs; the manager+ gate is the web layer's extractor.
5+
6+use crate::database::Database;
7+use crate::db::fee_plan;
8+use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+/// Write a fee plan: a name and the installments it is paid in. Creating one
13+/// bills nobody — assigning it does.
14+pub async fn create(
15+ db: &Database,
16+ name: FeePlanName,
17+ installments: Vec<Installment>,
18+ created_by: &UserId,
19+) -> Result<FeePlan, AppError> {
20+ fee_plan::create(db, name, installments, created_by).await
21+}
22+
23+/// The plan, for callers that only inspect it.
24+pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> {
25+ fee_plan::read(db, id).await
26+}
27+
28+/// Every plan, newest first.
29+pub async fn list_all(
30+ db: &Database,
31+ limit: Option<i64>,
32+ offset: i64,
33+) -> Result<(Vec<FeePlan>, i64), AppError> {
34+ fee_plan::list_all(db, limit, offset).await
35+}
36+
37+/// Edit a plan's name and/or schedule. `Err(Conflict)` = refused, nothing was
38+/// written: somebody is already on the plan (and `Err(NotFound)` = the plan
39+/// is gone, so the refusal is not "assigned" but "deleted").
40+pub async fn update(
41+ db: &Database,
42+ plan: FeePlan,
43+ name: Option<FeePlanName>,
44+ installments: Option<Vec<Installment>>,
45+) -> Result<FeePlan, AppError> {
46+ fee_plan::update(db, plan, name, installments).await
47+}
48+
49+/// Delete the plan while nobody is on it. `false` = refused: somebody is on
50+/// it, and a school's financial history keeps its references.
51+pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> {
52+ fee_plan::delete(db, plan).await
53+}
src/service/fee_plan_assignment.rsadded+507 -0
@@ -0,0 +1,507 @@
1+//! The assign workflow: placing a plan on a student and billing it — the
2+//! moment the plan becomes money owed — plus the batch loop and the bounds
3+//! one assign request may carry. The queries live in
4+//! [`crate::db::fee_plan_assignment`]; the ledger appends in
5+//! [`crate::db::payment_ledger`].
6+//!
7+//! The row is keyed `<plan>_<student>`, and every charge it raises is keyed
8+//! from that same key plus the installment number, so the whole operation is
9+//! idempotent **by identity**: assigning twice writes nothing the second time,
10+//! however the two requests interleave, and an assign cut short after three of
11+//! twelve charges landed completes itself when it is repeated. No scan decides
12+//! "has this been billed yet?" — a scan can be slipped past by a concurrent
13+//! writer, and the cost of that mistake here is a double-billed family.
14+
15+use crate::constant::{
16+ FEE_PLAN_ASSIGNMENT_COUNT_FIELD, MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES,
17+};
18+use crate::database::Database;
19+use crate::db::cap::{self, Claimed};
20+use crate::db::{fee_plan, fee_plan_assignment, payment_ledger};
21+use crate::domain::fee_plan::FeePlan;
22+use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
23+use crate::domain::role::Role;
24+use crate::domain::timestamp::Timestamp;
25+use crate::domain::user::UserId;
26+use crate::error::{AppError, ValidationError};
27+
28+/// Place `plan` on `student` and bill it. Returns the assignment and
29+/// whether it was *already* there, so the web layer can answer a replay
30+/// honestly instead of pretending it just happened.
31+///
32+/// The row and the plan's assignment refcount are written in **one**
33+/// transaction ([`cap::claim_and_create`]): that increment is what makes the
34+/// plan un-editable and un-deletable, and it has to be indivisible from the
35+/// row it counts, or an edit could slip between the two. A plan the counter
36+/// cannot be claimed on is one a concurrent delete already removed, which is
37+/// the same `404` the handler's own lookup would have given.
38+///
39+/// The installments are then re-read **from the stored plan**, not taken
40+/// from the caller's snapshot: the claim is the moment the plan freezes, and
41+/// an edit that landed between the handler's read and that claim is
42+/// legitimate. Billing the snapshot would raise charges from a schedule the
43+/// plan no longer shows — precisely the divergence the 409 exists to
44+/// prevent.
45+///
46+/// The charges are appended after the row, never before: each one is keyed
47+/// by (assignment, installment number), so this loop is safe to re-enter
48+/// from the top — which is exactly what a repeated assign does, and the
49+/// only way a half-written assignment ever gets its missing lines.
50+pub async fn assign(
51+ db: &Database,
52+ plan: &FeePlan,
53+ student: &UserId,
54+ assigned_by: &UserId,
55+) -> Result<(FeePlanAssignment, bool), AppError> {
56+ let id = FeePlanAssignmentId::composite(plan.get_id(), student);
57+ let row = FeePlanAssignment {
58+ id: id.clone(),
59+ plan: plan.get_id().clone(),
60+ student: student.clone(),
61+ assigned_by: assigned_by.clone(),
62+ created_at: Timestamp::now(),
63+ };
64+ let claimed = cap::claim_and_create(
65+ &plan.get_id().record(),
66+ FEE_PLAN_ASSIGNMENT_COUNT_FIELD,
67+ cap::UNLIMITED,
68+ &id.record(),
69+ &row,
70+ db,
71+ )
72+ .await?;
73+ let (assignment, existed) = match claimed {
74+ Claimed::Made(created) => (created, false),
75+ // Someone assigned this pair first — their row is the answer, and
76+ // the charges below are keyed the same, so continuing here can only
77+ // *complete* the billing. Their claim already counts this row.
78+ Claimed::Duplicate => (require(&id, db).await?, true),
79+ // The counter is uncapped, so the only miss is a plan that is gone.
80+ Claimed::Full => return Err(AppError::NotFound),
81+ };
82+ // Frozen as of the claim above: no edit can land past it any more.
83+ let plan = fee_plan::read(db, plan.get_id())
84+ .await?
85+ .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?;
86+ for (index, installment) in plan.get_installments().iter().enumerate() {
87+ payment_ledger::charge_for_installment(
88+ db,
89+ &assignment,
90+ index + 1,
91+ installment,
92+ assigned_by,
93+ )
94+ .await?;
95+ }
96+ Ok((assignment, existed))
97+}
98+
99+async fn require(id: &FeePlanAssignmentId, db: &Database) -> Result<FeePlanAssignment, AppError> {
100+ fee_plan_assignment::read(db, id)
101+ .await?
102+ .ok_or_else(|| AppError::Internal("failed to assign the fee plan".into()))
103+}
104+
105+/// What one student in an assign batch came to. The web layer spells these
106+/// as its response statuses.
107+#[derive(Debug, Clone, PartialEq, Eq)]
108+pub enum Outcome {
109+ /// Placed and billed now.
110+ Assigned,
111+ /// A replay: the student was already on this plan, nothing billed again.
112+ AlreadyAssigned,
113+ /// Refused for this student alone — the batch carries on.
114+ Rejected(&'static str),
115+}
116+
117+/// Place one plan on a batch of students, which is what turns it into money
118+/// owed: every installment is appended as a charge line right away, each with
119+/// its own due date. Returns one outcome per student, in the order sent.
120+///
121+/// Only students carry a fee record, so any other target is rejected. One bad
122+/// id never loses the rest of the batch: the outcome reports each student
123+/// separately.
124+///
125+/// Placing the first student **freezes** the plan: it can no longer be edited
126+/// or deleted. The installments billed are read back from the stored plan at
127+/// that instant, so an edit that landed a moment earlier is the one billed,
128+/// never the version this request first looked at. A plan deleted while the
129+/// batch is running is `Rejected` from that student on — a per-student
130+/// outcome like any other, so the students it already billed stay in the
131+/// report.
132+///
133+/// One request is bounded by the **charges it would raise**, not by the head
134+/// count alone: `student_ids × installments` may not exceed 3 000 (200
135+/// students up to a 15-installment plan; 50 at a time on a 60-installment
136+/// one). Past that the whole call is a `400` telling the caller to split the
137+/// batch — nothing is written, because a money route that billed half a batch
138+/// and gave up would leave a bursar guessing which families were charged.
139+pub async fn assign_batch(
140+ db: &Database,
141+ plan_key: &str,
142+ assigner: &UserId,
143+ student_ids: Vec<String>,
144+) -> Result<Vec<(String, Outcome)>, AppError> {
145+ if student_ids.len() > MAX_FEE_PLAN_ASSIGN_STUDENTS {
146+ return Err(AppError::Validation(ValidationError::Invalid {
147+ field: "student_ids",
148+ reason: "may name at most 200 students",
149+ }));
150+ }
151+ let plan = fee_plan::read(db, &crate::domain::fee_plan::FeePlanId::from_key(plan_key))
152+ .await?
153+ .ok_or(AppError::NotFound)?;
154+ // The student cap alone cannot see the schedule: every student named
155+ // appends *every* installment, so what really bounds this request is the
156+ // product. Refused whole and before anything is written — a batch this API
157+ // billed only part of would leave a bursar guessing which families were
158+ // charged.
159+ if student_ids
160+ .len()
161+ .saturating_mul(plan.get_installments().len())
162+ > MAX_FEE_PLAN_ASSIGN_WRITES
163+ {
164+ return Err(AppError::Validation(ValidationError::Invalid {
165+ field: "student_ids",
166+ reason: "too many charges for one request: students × installments \
167+ may not exceed 3000, so split the batch",
168+ }));
169+ }
170+ let mut outcomes = Vec::with_capacity(student_ids.len());
171+ for student_id in student_ids {
172+ let student = UserId::from_key(&student_id);
173+ // A fee record belongs to a student; billing anyone else is a typo, and
174+ // a typo here is money against the wrong person.
175+ let is_student = crate::db::user::read(db, &student)
176+ .await?
177+ .is_some_and(|user| user.get_role() == Role::Student);
178+ let outcome = if is_student {
179+ match assign(db, &plan, &student, assigner).await {
180+ Ok((_, true)) => Outcome::AlreadyAssigned,
181+ Ok((_, false)) => Outcome::Assigned,
182+ // The plan was deleted mid-batch. That is a per-student outcome
183+ // like any other, not a reason to throw away the report for the
184+ // students this batch already billed — their charges are
185+ // written and the caller has to be told about them.
186+ Err(AppError::NotFound) => Outcome::Rejected("no such plan"),
187+ Err(err) => return Err(err),
188+ }
189+ } else {
190+ Outcome::Rejected("no such student")
191+ };
192+ outcomes.push((student_id, outcome));
193+ }
194+ Ok(outcomes)
195+}
196+
197+/// The placement, for callers that only inspect it.
198+pub async fn read(
199+ db: &Database,
200+ id: &FeePlanAssignmentId,
201+) -> Result<Option<FeePlanAssignment>, AppError> {
202+ fee_plan_assignment::read(db, id).await
203+}
204+
205+/// Who is on this plan, newest first.
206+pub async fn list_for_plan(
207+ db: &Database,
208+ plan: &crate::domain::fee_plan::FeePlanId,
209+ limit: Option<i64>,
210+ offset: i64,
211+) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
212+ fee_plan_assignment::list_for_plan(db, plan, limit, offset).await
213+}
214+
215+/// Which plans a student is on.
216+pub async fn list_for_student(
217+ db: &Database,
218+ student: &UserId,
219+ limit: Option<i64>,
220+ offset: i64,
221+) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
222+ fee_plan_assignment::list_for_student(db, student, limit, offset).await
223+}
224+
225+#[cfg(test)]
226+mod tests {
227+ use super::*;
228+ use crate::database::init_mem;
229+ use crate::domain::fee_plan::{FeePlanName, Installment};
230+ use crate::domain::payment_ledger::LedgerAmount;
231+
232+ async fn a_plan(db: &Database, installments: Vec<Installment>) -> FeePlan {
233+ fee_plan::create(
234+ db,
235+ FeePlanName::try_new("Yearly").unwrap(),
236+ installments,
237+ &UserId::from_key("mgr1"),
238+ )
239+ .await
240+ .unwrap()
241+ }
242+
243+ /// The invariant the whole module exists for: assigning bills every
244+ /// installment once, and assigning *again* bills nothing — the second call
245+ /// must not double a family's debt.
246+ #[tokio::test]
247+ async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {
248+ let db = init_mem().await.unwrap();
249+ let manager = UserId::from_key("mgr1");
250+ let student = UserId::from_key("stu1");
251+ let plan = a_plan(
252+ &db,
253+ vec![
254+ Installment::new(
255+ LedgerAmount::try_new(150_000).unwrap(),
256+ Timestamp::from_millis(1_000),
257+ ),
258+ Installment::new(
259+ LedgerAmount::try_new(250_000).unwrap(),
260+ Timestamp::from_millis(2_000),
261+ ),
262+ ],
263+ )
264+ .await;
265+
266+ let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap();
267+ assert!(!existed);
268+ assert_eq!(
269+ payment_ledger::balance_of(&db, &student).await.unwrap(),
270+ -400_000,
271+ "both installments must be owed"
272+ );
273+
274+ let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap();
275+ assert!(
276+ existed,
277+ "the second assign is a replay, not a new placement"
278+ );
279+ let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
280+ .await
281+ .unwrap();
282+ assert_eq!(lines.len(), 2, "a replay may not append a single line");
283+ assert!(
284+ lines
285+ .iter()
286+ .all(|l| l.get_kind() == crate::domain::payment_ledger::PaymentLedgerKind::Charge)
287+ );
288+ assert_eq!(
289+ payment_ledger::balance_of(&db, &student).await.unwrap(),
290+ -400_000
291+ );
292+ assert!(
293+ fee_plan_assignment::exists_for_plan(&db, plan.get_id())
294+ .await
295+ .unwrap()
296+ );
297+ }
298+
299+ /// The race the refcount exists for: an edit and an assign, both licensed
300+ /// by the same instant.
301+ ///
302+ /// "Neither lands" is *not* the invariant — the two are legal in one order
303+ /// (edit, then assign the edited plan) and illegal in the other. What may
304+ /// never happen is the money and the plan disagreeing: the charges raised
305+ /// must be copies of the schedule the plan actually ends up carrying, and
306+ /// once anybody is on the plan no further edit or delete may land at all.
307+ ///
308+ /// Asserted against the **stored** state, never against which call returned
309+ /// `Ok`: a winner's word is not evidence about what the store kept.
310+ /// The one thing the *returned* values are good for is the second
311+ /// invariant: neither racer may answer 500. Losing a single-record round to
312+ /// a rival is the ordinary way this guard works, and the loser's recovery is
313+ /// to re-send, not to fail the request.
314+ ///
315+ /// Multi-threaded on purpose: on the single-threaded runtime the two tasks
316+ /// interleave only at await points and the store never reports a conflict at
317+ /// all, which is how a version of this test watched a 45-in-50 500 rate and
318+ /// passed.
319+ ///
320+ /// Real server, and `#[ignore]`d rather than falling back to `init_mem`:
321+ /// the embedded engine drops one of two concurrent writes to a record and
322+ /// answers `Ok` to both, which fails this very assertion out of nowhere
323+ /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in
324+ /// 10 000 rounds on the server). See [`crate::database::init_test_server`].
325+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
326+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
327+ async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() {
328+ let (db, _serialized) = crate::database::init_test_server("edit_race").await;
329+ let mut reached = 0;
330+ for round in 0..20 {
331+ let manager = UserId::from_key("mgr1");
332+ let student = UserId::from_key(&format!("stu{round}"));
333+ let plan = a_plan(
334+ &db,
335+ vec![Installment::new(
336+ LedgerAmount::try_new(100).unwrap(),
337+ Timestamp::from_millis(1_000),
338+ )],
339+ )
340+ .await;
341+
342+ let edit = {
343+ let (plan, db) = (plan.clone(), db.clone());
344+ tokio::spawn(async move {
345+ fee_plan::update(
346+ &db,
347+ plan,
348+ None,
349+ Some(vec![Installment::new(
350+ LedgerAmount::try_new(999).unwrap(),
351+ Timestamp::from_millis(2_000),
352+ )]),
353+ )
354+ .await
355+ })
356+ };
357+ let assign = {
358+ let (db, plan, manager, student) =
359+ (db.clone(), plan.clone(), manager.clone(), student.clone());
360+ tokio::spawn(async move { assign(&db, &plan, &student, &manager).await })
361+ };
362+ let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap());
363+ assert!(
364+ !matches!(edit, Err(AppError::Db(_))),
365+ "a raced edit must be refused, not 500: {edit:?}"
366+ );
367+ assert!(
368+ !matches!(assign, Err(AppError::Db(_))),
369+ "a raced assign must retry, not 500: {assign:?}"
370+ );
371+
372+ let stored = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap();
373+ let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id())
374+ .await
375+ .unwrap();
376+ if assigned {
377+ reached += 1;
378+ // The counter is what refuses every later edit, so it has to
379+ // agree with the rows it stands for.
380+ let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
381+ .await
382+ .unwrap();
383+ assert_eq!(lines.len(), 1, "one installment, one charge");
384+ assert_eq!(
385+ lines[0].get_amount_minor().as_minor(),
386+ stored.get_installments()[0].get_amount_minor().as_minor(),
387+ "the charge must be a copy of the plan as it now stands"
388+ );
389+ assert!(
390+ fee_plan::update(&db, plan.clone(), None, None)
391+ .await
392+ .is_ok(),
393+ "an empty PATCH writes nothing, so it is not refused"
394+ );
395+ assert!(
396+ matches!(
397+ fee_plan::update(
398+ &db,
399+ plan.clone(),
400+ Some(FeePlanName::try_new("Nope").unwrap()),
401+ None
402+ )
403+ .await,
404+ Err(AppError::Conflict(_))
405+ ),
406+ "an assigned plan stays frozen afterwards"
407+ );
408+ assert!(
409+ !fee_plan::delete(&db, plan.clone()).await.unwrap(),
410+ "and it cannot be deleted either"
411+ );
412+ }
413+ }
414+ // Every assertion above sits behind "the assign landed", so a run where
415+ // it never did asserts nothing at all — the failure this counter turns
416+ // into a loud one.
417+ assert!(reached > 0, "no round ever placed the assignment");
418+ }
419+
420+ /// The other half, and here "never both" *is* the invariant: a delete and
421+ /// an assign racing must never leave a live assignment — with the charges
422+ /// it billed — pointing at a plan that is gone. Stored state again, and a
423+ /// real server again, for the same reasons.
424+ ///
425+ /// Both orderings are forced, because the interesting one does not happen on
426+ /// its own: with both racers released together the assign wins ~24 rounds in
427+ /// 25, so a run that only ever saw that ordering never tested a delete
428+ /// landing first at all. Half the rounds therefore hold the assign back by a
429+ /// beat, and the two counters below fail the test if either ordering went
430+ /// unseen. Neither racer may answer 500 here either — this is the pair that
431+ /// contends hardest, both writing the plan record itself.
432+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
433+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
434+ async fn a_delete_racing_an_assign_never_orphans_an_assignment() {
435+ let (db, _serialized) = crate::database::init_test_server("delete_race").await;
436+ let (mut deleted_first, mut assigned_first) = (0, 0);
437+ for round in 0..20 {
438+ let hold_back_the_assign = round % 2 == 0;
439+ let manager = UserId::from_key("mgr1");
440+ let student = UserId::from_key(&format!("stu{round}"));
441+ let plan = a_plan(
442+ &db,
443+ vec![Installment::new(
444+ LedgerAmount::try_new(100).unwrap(),
445+ Timestamp::from_millis(1_000),
446+ )],
447+ )
448+ .await;
449+
450+ let head_start = std::time::Duration::from_millis(5);
451+ let drop_it = {
452+ let (db, plan) = (db.clone(), plan.clone());
453+ tokio::spawn(async move {
454+ if !hold_back_the_assign {
455+ tokio::time::sleep(head_start).await;
456+ }
457+ fee_plan::delete(&db, plan).await
458+ })
459+ };
460+ let assign = {
461+ let (db, plan, manager, student) =
462+ (db.clone(), plan.clone(), manager.clone(), student.clone());
463+ tokio::spawn(async move {
464+ if hold_back_the_assign {
465+ tokio::time::sleep(head_start).await;
466+ }
467+ assign(&db, &plan, &student, &manager).await
468+ })
469+ };
470+ let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap());
471+ assert!(
472+ !matches!(drop_it, Err(AppError::Db(_))),
473+ "a raced delete must retry, not 500: {drop_it:?}"
474+ );
475+ assert!(
476+ !matches!(assign, Err(AppError::Db(_))),
477+ "a raced assign must retry, not 500: {assign:?}"
478+ );
479+
480+ let gone = fee_plan::read(&db, plan.get_id()).await.unwrap().is_none();
481+ let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id())
482+ .await
483+ .unwrap();
484+ deleted_first += usize::from(gone);
485+ assigned_first += usize::from(assigned);
486+ assert!(
487+ !(gone && assigned),
488+ "an assignment may not outlive the plan it names"
489+ );
490+ let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
491+ .await
492+ .unwrap();
493+ assert!(
494+ !(gone && !lines.is_empty()),
495+ "and neither may the charges it raised"
496+ );
497+ }
498+ // The premise, not a nicety: "never both" is trivially true in a run
499+ // where one of the two never landed, so a run that only saw one
500+ // ordering has proven nothing and says so.
501+ assert!(deleted_first > 0, "no round ever let the delete land first");
502+ assert!(
503+ assigned_first > 0,
504+ "no round ever let the assign land first"
505+ );
506+ }
507+}
src/service/mod.rsmodified+4 -0
@@ -2,6 +2,7 @@
2 //! SurrealQL text.2 //! SurrealQL text.
3 pub mod appointment;3 pub mod appointment;
4 pub mod appointment_slot;4 pub mod appointment_slot;
5+pub mod attendance;
5 pub mod badge;6 pub mod badge;
6 pub mod builder;7 pub mod builder;
7 pub mod chatbot_message;8 pub mod chatbot_message;
@@ -15,6 +16,8 @@ pub mod event;
15 pub mod exam;16 pub mod exam;
16 pub mod exam_attempt;17 pub mod exam_attempt;
17 pub mod exam_question;18 pub mod exam_question;
19+pub mod fee_plan;
20+pub mod fee_plan_assignment;
18 pub mod meal_attendance;21 pub mod meal_attendance;
19 pub mod meal_booking;22 pub mod meal_booking;
20 pub mod meal_ledger;23 pub mod meal_ledger;
@@ -28,6 +31,7 @@ pub mod profile;
28 pub mod rag_output;31 pub mod rag_output;
29 pub mod registration;32 pub mod registration;
30 pub mod session;33 pub mod session;
34+pub mod session_attendance;
31 pub mod settings;35 pub mod settings;
32 pub mod subject;36 pub mod subject;
33 pub mod term;37 pub mod term;
src/service/payment_ledger.rsmodified+10 -10
@@ -348,23 +348,23 @@ mod tests {
348 348
349 /// Raise one charge of `amount` on a fresh student, and hand it back.349 /// Raise one charge of `amount` on a fresh student, and hand it back.
350 async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) {350 async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) {
351- use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment};351+ use crate::db::fee_plan;
352- use crate::domain::fee_plan_assignment::FeePlanAssignment;352+ use crate::domain::fee_plan::{FeePlanName, Installment};
353 353
354 let manager = UserId::from_key("mgr1");354 let manager = UserId::from_key("mgr1");
355 let student = UserId::from_key("stu1");355 let student = UserId::from_key("stu1");
356- let plan = FeePlan::create(356+ let plan = fee_plan::create(
357+ db,
357 FeePlanName::try_new("Yearly").unwrap(),358 FeePlanName::try_new("Yearly").unwrap(),
358 vec![Installment::new(359 vec![Installment::new(
359 LedgerAmount::try_new(amount).unwrap(),360 LedgerAmount::try_new(amount).unwrap(),
360 Timestamp::from_millis(1_000),361 Timestamp::from_millis(1_000),
361 )],362 )],
362 &manager,363 &manager,
363- db,
364 )364 )
365 .await365 .await
366 .unwrap();366 .unwrap();
367- FeePlanAssignment::assign(&plan, &student, &manager, db)367+ crate::service::fee_plan_assignment::assign(db, &plan, &student, &manager)
368 .await368 .await
369 .unwrap();369 .unwrap();
370 let (lines, _) = payment_ledger::list_for_student(db, &student, None, 0)370 let (lines, _) = payment_ledger::list_for_student(db, &student, None, 0)
@@ -546,24 +546,24 @@ mod tests {
546 /// reversal may point at a line of the wrong kind.546 /// reversal may point at a line of the wrong kind.
547 #[tokio::test]547 #[tokio::test]
548 async fn payments_are_capped_by_the_line_they_target() {548 async fn payments_are_capped_by_the_line_they_target() {
549- use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment};549+ use crate::db::fee_plan;
550- use crate::domain::fee_plan_assignment::FeePlanAssignment;550+ use crate::domain::fee_plan::{FeePlanName, Installment};
551 551
552 let db = crate::database::init_mem().await.unwrap();552 let db = crate::database::init_mem().await.unwrap();
553 let manager = UserId::from_key("mgr1");553 let manager = UserId::from_key("mgr1");
554 let student = UserId::from_key("stu1");554 let student = UserId::from_key("stu1");
555- let plan = FeePlan::create(555+ let plan = fee_plan::create(
556+ &db,
556 FeePlanName::try_new("Yearly").unwrap(),557 FeePlanName::try_new("Yearly").unwrap(),
557 vec![Installment::new(558 vec![Installment::new(
558 LedgerAmount::try_new(10_000).unwrap(),559 LedgerAmount::try_new(10_000).unwrap(),
559 Timestamp::from_millis(1_000),560 Timestamp::from_millis(1_000),
560 )],561 )],
561 &manager,562 &manager,
562- &db,
563 )563 )
564 .await564 .await
565 .unwrap();565 .unwrap();
566- FeePlanAssignment::assign(&plan, &student, &manager, &db)566+ crate::service::fee_plan_assignment::assign(&db, &plan, &student, &manager)
567 .await567 .await
568 .unwrap();568 .unwrap();
569 let (charges, _) = payment_ledger::list_for_student(&db, &student, None, 0)569 let (charges, _) = payment_ledger::list_for_student(&db, &student, None, 0)
src/service/session_attendance.rsadded+137 -0
@@ -0,0 +1,137 @@
1+//! The roll-call workflows: taking and clearing a lesson's roll call, with
2+//! the target-eligibility rules every roll-call path shares — a staff row is
3+//! management's to write (the session's own teacher is marked and cleared
4+//! only by manager+), only students attend lessons, and a non-teacher target
5+//! must be enrolled in the course. The queries and the badge-counter
6+//! transactions live in [`crate::db::session_attendance`]; who may take a
7+//! roll call at all (the session's teacher or a course manager) is the web
8+//! layer's authorization, judged against the session and course it loaded.
9+
10+use crate::database::Database;
11+use crate::db::session_attendance;
12+use crate::domain::attendance::AttendanceStatus;
13+use crate::domain::badge;
14+use crate::domain::course_session::CourseSession;
15+use crate::domain::role::Role;
16+use crate::domain::session_attendance::SessionAttendance;
17+use crate::domain::user::{User, UserId};
18+use crate::error::{AppError, ValidationError};
19+
20+/// Record `target`'s roll-call state for the session — the target-eligibility
21+/// gates plus the mark. Returns the written row and the target's user row as
22+/// the gates judged it (the response joins both people).
23+///
24+/// - The session's own teacher is marked only by manager+: staff presence is
25+/// management's call, so a teacher can't mark themselves present.
26+/// - Everyone else on a lesson's roster is an enrolled student. Only students
27+/// attend classes; checking the live role keeps a stale enrollment (left by
28+/// a promotion) from putting staff on the roll.
29+///
30+/// A badge is a decoration on top of the roll call: losing one to a
31+/// transient database error must never fail the mark, and the next counter
32+/// move re-runs this and heals it. Both people the mark can credit are
33+/// synced — the person marked (`lessons_attended`) and the lesson's teacher
34+/// (`lessons_held`, on the first roll call only). The teacher's runs on every
35+/// mark rather than only that first one: `sync` is add-only and idempotent,
36+/// so the extra calls cost one record read and are what heals a first sync
37+/// that failed, and knowing here whether the credit landed would mean
38+/// widening the write's return type for nothing.
39+pub async fn mark(
40+ db: &Database,
41+ session: &CourseSession,
42+ marker: &User,
43+ target: &UserId,
44+ status: AttendanceStatus,
45+) -> Result<(SessionAttendance, User), AppError> {
46+ // Target user must exist.
47+ let target_user = crate::db::user::read(db, target)
48+ .await?
49+ .ok_or(AppError::Validation(ValidationError::Invalid {
50+ field: "user_id",
51+ reason: "target user does not exist",
52+ }))?;
53+
54+ if session.is_teacher(target) {
55+ // The session teacher's own presence is recorded by management.
56+ if !marker.get_role().at_least(Role::Manager) {
57+ return Err(AppError::Forbidden(
58+ "marking the session's teacher requires manager role or higher",
59+ ));
60+ }
61+ } else {
62+ // Everyone else on a lesson's roster is an enrolled student. Only
63+ // students attend classes; checking the live role keeps a stale
64+ // enrollment (left by a promotion) from putting staff on the roll.
65+ if target_user.get_role() != Role::Student {
66+ return Err(AppError::Validation(ValidationError::Invalid {
67+ field: "user_id",
68+ reason: "only students can be marked present in a lesson",
69+ }));
70+ }
71+ if crate::db::enrollment::read_for_user(db, session.get_course(), target)
72+ .await?
73+ .is_none()
74+ {
75+ return Err(AppError::Validation(ValidationError::Invalid {
76+ field: "user_id",
77+ reason: "target user is not enrolled in this course",
78+ }));
79+ }
80+ }
81+
82+ let attendance = session_attendance::mark(db, session, target, status, marker.get_id()).await?;
83+ for who in [target, session.get_teacher()] {
84+ if let Err(err) = badge::sync(who, db).await {
85+ tracing::warn!("failed to sync badges for {}: {err}", who.key());
86+ }
87+ }
88+ Ok((attendance, target_user))
89+}
90+
91+/// List a session's roll call, paged.
92+pub async fn list_for_session(
93+ db: &Database,
94+ session: &crate::domain::course_session::CourseSessionId,
95+ limit: Option<i64>,
96+ offset: i64,
97+) -> Result<(Vec<SessionAttendance>, i64), AppError> {
98+ session_attendance::list_for_session(db, session, limit, offset).await
99+}
100+
101+/// Every roll-call row ever recorded for `user` — the session half of the
102+/// attendance report.
103+pub async fn list_for_user(
104+ db: &Database,
105+ user: &UserId,
106+) -> Result<Vec<SessionAttendance>, AppError> {
107+ session_attendance::list_for_user(db, user).await
108+}
109+
110+/// Clear `target`'s roll-call row from the session, with the one gate the
111+/// mark does not have: a staff row is management's to remove, keyed on the
112+/// *target's live role* rather than on `is_teacher` — reassigning a
113+/// session's teacher used to hand the incoming teacher, an ordinary one, the
114+/// outgoing teacher's staff row to delete without the manager+ this guard
115+/// exists to require. A target whose user row is gone can only be a
116+/// student's stale row (marking checks the role at write time), so it stays
117+/// the session teacher's to clear.
118+///
119+/// `Err(NotFound)` when there was no row to remove.
120+pub async fn remove(
121+ db: &Database,
122+ session: &CourseSession,
123+ remover: &User,
124+ target: &UserId,
125+) -> Result<SessionAttendance, AppError> {
126+ let staff_row = crate::db::user::read(db, target)
127+ .await?
128+ .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher));
129+ if staff_row && !remover.get_role().at_least(Role::Manager) {
130+ return Err(AppError::Forbidden(
131+ "removing a staff roll-call row requires manager role or higher",
132+ ));
133+ }
134+ session_attendance::remove(db, session.get_id(), target)
135+ .await?
136+ .ok_or(AppError::NotFound)
137+}
src/web/attendance.rsmodified+3 -3
@@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter;
9 use utoipa_axum::routes;9 use utoipa_axum::routes;
10 10
11 use crate::database::Database;11 use crate::database::Database;
12-use crate::domain::attendance::{Attendance, AttendanceStatus};12+use crate::domain::attendance::AttendanceStatus;
13 use crate::domain::course::{Course, CourseId};13 use crate::domain::course::{Course, CourseId};
14 use crate::domain::role::Role;14 use crate::domain::role::Role;
15 use crate::domain::session_attendance::SessionAttendance;15 use crate::domain::session_attendance::SessionAttendance;
@@ -104,8 +104,8 @@ async fn build_report(
104 viewer: Option<&User>,104 viewer: Option<&User>,
105 db: &Database,105 db: &Database,
106 ) -> Result<AttendanceReport, AppError> {106 ) -> Result<AttendanceReport, AppError> {
107- let events = Attendance::list_for_user(user, db).await?;107+ let events = crate::service::attendance::list_for_user(db, user).await?;
108- let sessions = SessionAttendance::list_for_user(user, db).await?;108+ let sessions = crate::service::session_attendance::list_for_user(db, user).await?;
109 109
110 // Group session rows by course, preserving first-seen (newest-first) order.110 // Group session rows by course, preserving first-seen (newest-first) order.
111 let mut course_ids: Vec<CourseId> = Vec::new();111 let mut course_ids: Vec<CourseId> = Vec::new();
src/web/events.rsmodified+11 -5
@@ -540,7 +540,8 @@ async fn mark(
540 }));540 }));
541 }541 }
542 542
543- let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?;543+ let attendance =
544+ crate::service::attendance::mark(&st.db, &event_id, &target, status, user.get_id()).await?;
544 let people = PersonRef::map_of(&[&target_user, &user]);545 let people = PersonRef::map_of(&[&target_user, &user]);
545 Ok(Json(AttendanceResponse::new(&attendance, &people)))546 Ok(Json(AttendanceResponse::new(&attendance, &people)))
546 }547 }
@@ -575,7 +576,8 @@ async fn list_attendance(
575 service::event::read(&st.db, &event_id)576 service::event::read(&st.db, &event_id)
576 .await?577 .await?
577 .ok_or(AppError::NotFound)?;578 .ok_or(AppError::NotFound)?;
578- let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?;579+ let (rows, total) =
580+ crate::service::attendance::list_for_event(&st.db, &event_id, limit, offset).await?;
579 // Join people onto the page alone — the lookup shrinks with the window.581 // Join people onto the page alone — the lookup shrinks with the window.
580 let people = person_map(582 let people = person_map(
581 rows.iter()583 rows.iter()
@@ -612,8 +614,12 @@ async fn remove_attendance(
612 _teacher: RequireTeacher,614 _teacher: RequireTeacher,
613 Path((id, target)): Path<(String, String)>,615 Path((id, target)): Path<(String, String)>,
614 ) -> Result<StatusCode, AppError> {616 ) -> Result<StatusCode, AppError> {
615- let removed =617+ let removed = crate::service::attendance::remove(
616- Attendance::remove(&EventId::from_key(&id), &UserId::from_key(&target), &st.db).await?;618+ &st.db,
619+ &EventId::from_key(&id),
620+ &UserId::from_key(&target),
621+ )
622+ .await?;
617 if removed.is_none() {623 if removed.is_none() {
618 return Err(AppError::NotFound);624 return Err(AppError::NotFound);
619 }625 }
@@ -671,7 +677,7 @@ async fn roster(
671 let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?;677 let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?;
672 // ULID keys sort by creation instant — a stable order keeps pages coherent.678 // ULID keys sort by creation instant — a stable order keeps pages coherent.
673 members.sort_by(|a, b| a.key().cmp(b.key()));679 members.sort_by(|a, b| a.key().cmp(b.key()));
674- let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?;680+ let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?;
675 let by_user: HashMap<&str, &Attendance> = marks681 let by_user: HashMap<&str, &Attendance> = marks
676 .iter()682 .iter()
677 .map(|attendance| (attendance.get_user().key(), attendance))683 .map(|attendance| (attendance.get_user().key(), attendance))
src/web/payments.rsmodified+31 -60
@@ -23,10 +23,9 @@ use utoipa::ToSchema;
23 use utoipa_axum::router::OpenApiRouter;23 use utoipa_axum::router::OpenApiRouter;
24 use utoipa_axum::routes;24 use utoipa_axum::routes;
25 25
26-use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES};
27 use crate::database::Database;26 use crate::database::Database;
28 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};27 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};
29-use crate::domain::fee_plan_assignment::FeePlanAssignment;28+use crate::domain::parent_link::ParentLink;
30 use crate::domain::payment_ledger::{29 use crate::domain::payment_ledger::{
31 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,30 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
32 PaymentRequestKey,31 PaymentRequestKey,
@@ -163,7 +162,7 @@ async fn plan_responses(
163 }162 }
164 163
165 async fn require_plan(id: &str, db: &Database) -> Result<FeePlan, AppError> {164 async fn require_plan(id: &str, db: &Database) -> Result<FeePlan, AppError> {
166- FeePlan::read(&FeePlanId::from_key(id), db)165+ service::fee_plan::read(db, &FeePlanId::from_key(id))
167 .await?166 .await?
168 .ok_or(AppError::NotFound)167 .ok_or(AppError::NotFound)
169 }168 }
@@ -189,11 +188,11 @@ async fn create_plan(
189 RequireManager(manager): RequireManager,188 RequireManager(manager): RequireManager,
190 Json(req): Json<CreateFeePlan>,189 Json(req): Json<CreateFeePlan>,
191 ) -> Result<(StatusCode, Json<FeePlanResponse>), AppError> {190 ) -> Result<(StatusCode, Json<FeePlanResponse>), AppError> {
192- let plan = FeePlan::create(191+ let plan = service::fee_plan::create(
192+ &st.db,
193 FeePlanName::try_new(&req.name)?,193 FeePlanName::try_new(&req.name)?,
194 InstallmentBody::list(req.installments)?,194 InstallmentBody::list(req.installments)?,
195 manager.get_id(),195 manager.get_id(),
196- &st.db,
197 )196 )
198 .await?;197 .await?;
199 let people = PersonRef::map_of(&[&manager]);198 let people = PersonRef::map_of(&[&manager]);
@@ -224,7 +223,7 @@ async fn list_plans(
224 Query(page): Query<PageParams>,223 Query(page): Query<PageParams>,
225 ) -> Result<Json<Page<FeePlanResponse>>, AppError> {224 ) -> Result<Json<Page<FeePlanResponse>>, AppError> {
226 let (limit, offset) = page.resolve()?;225 let (limit, offset) = page.resolve()?;
227- let (rows, total) = FeePlan::list_all(limit, offset, &st.db).await?;226+ let (rows, total) = service::fee_plan::list_all(&st.db, limit, offset).await?;
228 let items = plan_responses(&rows, &st.db).await?;227 let items = plan_responses(&rows, &st.db).await?;
229 Ok(Json(Page::new(items, total, limit, offset)))228 Ok(Json(Page::new(items, total, limit, offset)))
230 }229 }
@@ -291,7 +290,7 @@ async fn update_plan(
291 let plan = require_plan(&id, &st.db).await?;290 let plan = require_plan(&id, &st.db).await?;
292 let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?;291 let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?;
293 let installments = req.installments.map(InstallmentBody::list).transpose()?;292 let installments = req.installments.map(InstallmentBody::list).transpose()?;
294- let plan = plan.update(name, installments, &st.db).await?;293+ let plan = service::fee_plan::update(&st.db, plan, name, installments).await?;
295 let items = plan_responses(std::slice::from_ref(&plan), &st.db).await?;294 let items = plan_responses(std::slice::from_ref(&plan), &st.db).await?;
296 Ok(Json(295 Ok(Json(
297 items.into_iter().next().expect("one plan in, one out"),296 items.into_iter().next().expect("one plan in, one out"),
@@ -323,7 +322,7 @@ async fn delete_plan(
323 Path(id): Path<String>,322 Path(id): Path<String>,
324 ) -> Result<StatusCode, AppError> {323 ) -> Result<StatusCode, AppError> {
325 let plan = require_plan(&id, &st.db).await?;324 let plan = require_plan(&id, &st.db).await?;
326- if !plan.delete(&st.db).await? {325+ if !service::fee_plan::delete(&st.db, plan).await? {
327 return Err(AppError::Conflict("an assigned plan cannot be deleted"));326 return Err(AppError::Conflict("an assigned plan cannot be deleted"));
328 }327 }
329 Ok(StatusCode::NO_CONTENT)328 Ok(StatusCode::NO_CONTENT)
@@ -405,59 +404,30 @@ async fn assign_plan(
405 Path(id): Path<String>,404 Path(id): Path<String>,
406 Json(req): Json<AssignFeePlan>,405 Json(req): Json<AssignFeePlan>,
407 ) -> Result<Json<Vec<AssignmentOutcome>>, AppError> {406 ) -> Result<Json<Vec<AssignmentOutcome>>, AppError> {
408- if req.student_ids.len() > MAX_FEE_PLAN_ASSIGN_STUDENTS {407+ let outcomes =
409- return Err(AppError::Validation(ValidationError::Invalid {408+ service::fee_plan_assignment::assign_batch(&st.db, &id, manager.get_id(), req.student_ids)
410- field: "student_ids",409+ .await?;
411- reason: "may name at most 200 students",410+ Ok(Json(
412- }));411+ outcomes
413- }412+ .into_iter()
414- let plan = require_plan(&id, &st.db).await?;413+ .map(|(student_id, outcome)| {
415- // The student cap alone cannot see the schedule: every student named414+ let (status, reason) = match outcome {
416- // appends *every* installment, so what really bounds this request is the415+ service::fee_plan_assignment::Outcome::Assigned => ("assigned", None),
417- // product. Refused whole and before anything is written — a batch this API416+ service::fee_plan_assignment::Outcome::AlreadyAssigned => {
418- // billed only part of would leave a bursar guessing which families were417+ ("already_assigned", None)
419- // charged.
420- if req
421- .student_ids
422- .len()
423- .saturating_mul(plan.get_installments().len())
424- > MAX_FEE_PLAN_ASSIGN_WRITES
425- {
426- return Err(AppError::Validation(ValidationError::Invalid {
427- field: "student_ids",
428- reason: "too many charges for one request: students × installments \
429- may not exceed 3000, so split the batch",
430- }));
431 }418 }
432- let mut outcomes = Vec::with_capacity(req.student_ids.len());419+ service::fee_plan_assignment::Outcome::Rejected(reason) => {
433- for student_id in req.student_ids {420+ ("rejected", Some(reason))
434- let student = UserId::from_key(&student_id);
435- // A fee record belongs to a student; billing anyone else is a typo, and
436- // a typo here is money against the wrong person.
437- let is_student = crate::service::user::read(&st.db, &student)
438- .await?
439- .is_some_and(|user| user.get_role() == Role::Student);
440- let (status, reason) = if is_student {
441- match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await {
442- Ok((_, true)) => ("already_assigned", None),
443- Ok((_, false)) => ("assigned", None),
444- // The plan was deleted mid-batch. That is a per-student outcome
445- // like any other, not a reason to throw away the report for the
446- // students this batch already billed — their charges are
447- // written and the caller has to be told about them.
448- Err(AppError::NotFound) => ("rejected", Some("no such plan")),
449- Err(err) => return Err(err),
450 }421 }
451- } else {
452- ("rejected", Some("no such student"))
453 };422 };
454- outcomes.push(AssignmentOutcome {423+ AssignmentOutcome {
455 student_id,424 student_id,
456 status,425 status,
457 reason,426 reason,
458- });
459 }427 }
460- Ok(Json(outcomes))428+ })
429+ .collect(),
430+ ))
461 }431 }
462 432
463 /// Who is on this plan, newest first. Paged via `?limit=&offset=`; returns a433 /// Who is on this plan, newest first. Paged via `?limit=&offset=`; returns a
@@ -485,7 +455,7 @@ async fn list_plan_assignments(
485 let (limit, offset) = page.resolve()?;455 let (limit, offset) = page.resolve()?;
486 let plan = require_plan(&id, &st.db).await?;456 let plan = require_plan(&id, &st.db).await?;
487 let (rows, total) =457 let (rows, total) =
488- FeePlanAssignment::list_for_plan(plan.get_id(), limit, offset, &st.db).await?;458+ service::fee_plan_assignment::list_for_plan(&st.db, plan.get_id(), limit, offset).await?;
489 let people = person_map(459 let people = person_map(
490 rows.iter()460 rows.iter()
491 .flat_map(|row| [row.get_student().clone(), row.get_assigned_by().clone()]),461 .flat_map(|row| [row.get_student().clone(), row.get_assigned_by().clone()]),
@@ -905,13 +875,14 @@ async fn statement_response(
905 };875 };
906 876
907 // A charge names its assignment, and the assignment names the plan.877 // A charge names its assignment, and the assignment names the plan.
908- let (assignments, _) = FeePlanAssignment::list_for_student(student, None, 0, db).await?;878+ let (assignments, _) =
879+ service::fee_plan_assignment::list_for_student(db, student, None, 0).await?;
909 let mut plan_names: HashMap<String, Option<String>> = HashMap::new();880 let mut plan_names: HashMap<String, Option<String>> = HashMap::new();
910 let mut plan_of: HashMap<&str, &FeePlanId> = HashMap::new();881 let mut plan_of: HashMap<&str, &FeePlanId> = HashMap::new();
911 for assignment in &assignments {882 for assignment in &assignments {
912 let plan = assignment.get_plan();883 let plan = assignment.get_plan();
913 if !plan_names.contains_key(plan.key()) {884 if !plan_names.contains_key(plan.key()) {
914- let name = FeePlan::read(plan, db)885+ let name = service::fee_plan::read(db, plan)
915 .await?886 .await?
916 .map(|plan| plan.get_name().as_str().to_string());887 .map(|plan| plan.get_name().as_str().to_string());
917 plan_names.insert(plan.key().to_string(), name);888 plan_names.insert(plan.key().to_string(), name);
@@ -1119,7 +1090,8 @@ mod tests {
1119 let manager = UserId::from_key("mgr1");1090 let manager = UserId::from_key("mgr1");
1120 let student = UserId::from_key("stu1");1091 let student = UserId::from_key("stu1");
1121 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;1092 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;
1122- let plan = FeePlan::create(1093+ let plan = service::fee_plan::create(
1094+ &db,
1123 FeePlanName::try_new("Yearly").unwrap(),1095 FeePlanName::try_new("Yearly").unwrap(),
1124 vec![1096 vec![
1125 // Already due, and only part paid — the overdue row.1097 // Already due, and only part paid — the overdue row.
@@ -1133,11 +1105,10 @@ mod tests {
1133 ),1105 ),
1134 ],1106 ],
1135 &manager,1107 &manager,
1136- &db,
1137 )1108 )
1138 .await1109 .await
1139 .unwrap();1110 .unwrap();
1140- FeePlanAssignment::assign(&plan, &student, &manager, &db)1111+ service::fee_plan_assignment::assign(&db, &plan, &student, &manager)
1141 .await1112 .await
1142 .unwrap();1113 .unwrap();
1143 1114
src/web/sessions.rsmodified+6 -72
@@ -18,7 +18,7 @@ use crate::domain::role::Role;
18 use crate::domain::session_attendance::SessionAttendance;18 use crate::domain::session_attendance::SessionAttendance;
19 use crate::domain::timestamp::Timestamp;19 use crate::domain::timestamp::Timestamp;
20 use crate::domain::user::{User, UserId};20 use crate::domain::user::{User, UserId};
21-use crate::error::{AppError, ErrorResponse, ValidationError};21+use crate::error::{AppError, ErrorResponse};
22 use crate::service;22 use crate::service;
23 use crate::state::AppState;23 use crate::state::AppState;
24 24
@@ -295,58 +295,8 @@ async fn mark_roll_call(
295 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;295 let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?;
296 let target = UserId::from_key(&req.user_id);296 let target = UserId::from_key(&req.user_id);
297 297
298- // Target user must exist.298+ let (attendance, target_user) =
299- let Some(target_user) = crate::service::user::read(&st.db, &target).await? else {299+ service::session_attendance::mark(&st.db, &session, &user, &target, status).await?;
300- return Err(AppError::Validation(ValidationError::Invalid {
301- field: "user_id",
302- reason: "target user does not exist",
303- }));
304- };
305-
306- if session.is_teacher(&target) {
307- // The session teacher's own presence is recorded by management.
308- if !user.get_role().at_least(Role::Manager) {
309- return Err(AppError::Forbidden(
310- "marking the session's teacher requires manager role or higher",
311- ));
312- }
313- } else {
314- // Everyone else on a lesson's roster is an enrolled student. Only
315- // students attend classes; checking the live role keeps a stale
316- // enrollment (left by a promotion) from putting staff on the roll.
317- if target_user.get_role() != Role::Student {
318- return Err(AppError::Validation(ValidationError::Invalid {
319- field: "user_id",
320- reason: "only students can be marked present in a lesson",
321- }));
322- }
323- if service::enrollment::read_for_user(&st.db, session.get_course(), &target)
324- .await?
325- .is_none()
326- {
327- return Err(AppError::Validation(ValidationError::Invalid {
328- field: "user_id",
329- reason: "target user is not enrolled in this course",
330- }));
331- }
332- }
333-
334- let attendance =
335- SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?;
336- // A badge is a decoration on top of the roll call: losing one to a
337- // transient database error must never fail the mark, and the next counter
338- // move re-runs this and heals it. Both people the mark can credit are
339- // synced — the person marked (`lessons_attended`) and the lesson's teacher
340- // (`lessons_held`, on the first roll call only). The teacher's runs on every
341- // mark rather than only that first one: `sync` is add-only and idempotent,
342- // so the extra calls cost one record read and are what heals a first sync
343- // that failed, and knowing here whether the credit landed would mean
344- // widening `mark`'s return type for nothing.
345- for who in [&target, session.get_teacher()] {
346- if let Err(err) = service::badge::sync(&st.db, who).await {
347- tracing::warn!("failed to sync badges for {}: {err}", who.key());
348- }
349- }
350 let people = PersonRef::map_of(&[&target_user, &user]);300 let people = PersonRef::map_of(&[&target_user, &user]);
351 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))301 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))
352 }302 }
@@ -383,7 +333,8 @@ async fn list_roll_call(
383 ));333 ));
384 }334 }
385 let (rows, total) =335 let (rows, total) =
386- SessionAttendance::list_for_session(session.get_id(), limit, offset, &st.db).await?;336+ service::session_attendance::list_for_session(&st.db, session.get_id(), limit, offset)
337+ .await?;
387 // Join people onto the page alone — the lookup shrinks with the window.338 // Join people onto the page alone — the lookup shrinks with the window.
388 let people = person_map(339 let people = person_map(
389 rows.iter()340 rows.iter()
@@ -431,23 +382,6 @@ async fn remove_roll_call(
431 }382 }
432 crate::service::course::require_open(&st.db, &course).await?;383 crate::service::course::require_open(&st.db, &course).await?;
433 let target = UserId::from_key(&target);384 let target = UserId::from_key(&target);
434- // A staff row is management's to remove, keyed on the *target's live role*385+ service::session_attendance::remove(&st.db, &session, &user, &target).await?;
435- // rather than on `is_teacher`: reassigning a session's teacher used to hand
436- // the incoming teacher — an ordinary one — the outgoing teacher's staff row
437- // to delete without the manager+ this guard exists to require. A target
438- // whose user row is gone can only be a student's stale row (marking checks
439- // the role at write time), so it stays the session teacher's to clear.
440- let staff_row = crate::service::user::read(&st.db, &target)
441- .await?
442- .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher));
443- if staff_row && !user.get_role().at_least(Role::Manager) {
444- return Err(AppError::Forbidden(
445- "removing a staff roll-call row requires manager role or higher",
446- ));
447- }
448- let removed = SessionAttendance::remove(session.get_id(), &target, &st.db).await?;
449- if removed.is_none() {
450- return Err(AppError::NotFound);
451- }
452 Ok(StatusCode::NO_CONTENT)386 Ok(StatusCode::NO_CONTENT)
453 }387 }
tests/regress_attendance.rsmodified+11 -10
@@ -13,12 +13,13 @@ mod common;
13 use axum::http::StatusCode;13 use axum::http::StatusCode;
14 use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send};14 use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send};
15 use hezarfen_backend::database::Database;15 use hezarfen_backend::database::Database;
16+use hezarfen_backend::db::attendance;
16 use hezarfen_backend::db::course_session;17 use hezarfen_backend::db::course_session;
18+use hezarfen_backend::db::session_attendance;
17 use hezarfen_backend::db::settings;19 use hezarfen_backend::db::settings;
18-use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus};20+use hezarfen_backend::domain::attendance::AttendanceStatus;
19 use hezarfen_backend::domain::course_session::CourseSessionId;21 use hezarfen_backend::domain::course_session::CourseSessionId;
20 use hezarfen_backend::domain::event::EventId;22 use hezarfen_backend::domain::event::EventId;
21-use hezarfen_backend::domain::session_attendance::SessionAttendance;
22 use hezarfen_backend::domain::timestamp::Timestamp;23 use hezarfen_backend::domain::timestamp::Timestamp;
23 use hezarfen_backend::domain::user::UserId;24 use hezarfen_backend::domain::user::UserId;
24 use hezarfen_backend::error::AppError;25 use hezarfen_backend::error::AppError;
@@ -130,7 +131,7 @@ async fn reassigning_the_teacher_does_not_unlock_the_old_teachers_staff_row() {
130 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);131 assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
131 132
132 // The row is still there, and a manager still clears it.133 // The row is still there, and a manager still clears it.
133- let rows = SessionAttendance::list_for_user(&UserId::from_key(&t1_id), &db)134+ let rows = session_attendance::list_for_user(&db, &UserId::from_key(&t1_id))
134 .await135 .await
135 .unwrap();136 .unwrap();
136 assert_eq!(rows.len(), 1, "the staff row survived the refused delete");137 assert_eq!(rows.len(), 1, "the staff row survived the refused delete");
@@ -216,7 +217,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() {
216 .await;217 .await;
217 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);218 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
218 assert!(219 assert!(
219- SessionAttendance::list_for_user(&ali_ref, &db)220+ session_attendance::list_for_user(&db, &ali_ref)
220 .await221 .await
221 .unwrap()222 .unwrap()
222 .is_empty(),223 .is_empty(),
@@ -226,12 +227,12 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() {
226 // Then the mark arrives, still believing in its snapshot.227 // Then the mark arrives, still believing in its snapshot.
227 let school = settings::load(&db).await.unwrap();228 let school = settings::load(&db).await.unwrap();
228 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();229 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();
229- let marked = SessionAttendance::mark(230+ let marked = session_attendance::mark(
231+ &db,
230 &snapshot,232 &snapshot,
231 &ali_ref,233 &ali_ref,
232 status,234 status,
233 &UserId::from_key(&hoca_id),235 &UserId::from_key(&hoca_id),
234- &db,
235 )236 )
236 .await;237 .await;
237 assert!(238 assert!(
@@ -240,7 +241,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() {
240 );241 );
241 // The stored state is the assertion — the return value is not trusted.242 // The stored state is the assertion — the return value is not trusted.
242 assert!(243 assert!(
243- SessionAttendance::list_for_user(&ali_ref, &db)244+ session_attendance::list_for_user(&db, &ali_ref)
244 .await245 .await
245 .unwrap()246 .unwrap()
246 .is_empty(),247 .is_empty(),
@@ -385,7 +386,7 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() {
385 .await;386 .await;
386 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);387 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
387 assert!(388 assert!(
388- Attendance::list_for_user(&ali_ref, &db)389+ attendance::list_for_user(&db, &ali_ref)
389 .await390 .await
390 .unwrap()391 .unwrap()
391 .is_empty(),392 .is_empty(),
@@ -396,14 +397,14 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() {
396 let school = settings::load(&db).await.unwrap();397 let school = settings::load(&db).await.unwrap();
397 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();398 let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap();
398 let marked =399 let marked =
399- Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await;400+ attendance::mark(&db, &EventId::from_key(&event), &ali_ref, status, &hoca_ref).await;
400 assert!(401 assert!(
401 matches!(marked, Err(AppError::NotFound)),402 matches!(marked, Err(AppError::NotFound)),
402 "a mark on a deleted event is a 404, got {marked:?}"403 "a mark on a deleted event is a 404, got {marked:?}"
403 );404 );
404 // The stored state is the assertion — the return value is not trusted.405 // The stored state is the assertion — the return value is not trusted.
405 assert!(406 assert!(
406- Attendance::list_for_user(&ali_ref, &db)407+ attendance::list_for_user(&db, &ali_ref)
407 .await408 .await
408 .unwrap()409 .unwrap()
409 .is_empty(),410 .is_empty(),
tests/regress_payments.rsmodified+27 -16
@@ -15,12 +15,13 @@ mod common;
15 use axum::http::StatusCode;15 use axum::http::StatusCode;
16 use common::{app_and_db, id_of, login, login_as, me_id, send};16 use common::{app_and_db, id_of, login, login_as, me_id, send};
17 use hezarfen_backend::constant::{MAX_FEE_PLAN_ASSIGN_WRITES, MAX_LEDGER_APPLIED_LINES};17 use hezarfen_backend::constant::{MAX_FEE_PLAN_ASSIGN_WRITES, MAX_LEDGER_APPLIED_LINES};
18-use hezarfen_backend::domain::fee_plan::{FeePlan, FeePlanName, Installment};18+use hezarfen_backend::db::fee_plan;
19-use hezarfen_backend::domain::fee_plan_assignment::FeePlanAssignment;19+use hezarfen_backend::domain::fee_plan::{FeePlanName, Installment};
20 use hezarfen_backend::domain::payment_ledger::LedgerAmount;20 use hezarfen_backend::domain::payment_ledger::LedgerAmount;
21 use hezarfen_backend::domain::timestamp::Timestamp;21 use hezarfen_backend::domain::timestamp::Timestamp;
22 use hezarfen_backend::domain::user::UserId;22 use hezarfen_backend::domain::user::UserId;
23 use hezarfen_backend::error::AppError;23 use hezarfen_backend::error::AppError;
24+use hezarfen_backend::service::fee_plan_assignment;
24 use serde_json::{Value, json};25 use serde_json::{Value, json};
25 26
26 /// A plan of `installments`, as the manager writes it.27 /// A plan of `installments`, as the manager writes it.
@@ -220,7 +221,7 @@ async fn a_negative_due_date_is_refused_on_both_write_paths() {
220 /// deleted, and only then does the guarded `UPDATE` run. It matched nothing —221 /// deleted, and only then does the guarded `UPDATE` run. It matched nothing —
221 /// because the row is gone, not because anyone is on the plan — and the answer222 /// because the row is gone, not because anyone is on the plan — and the answer
222 /// was `409 "an assigned plan cannot be edited"` about a plan that never was.223 /// was `409 "an assigned plan cannot be edited"` about a plan that never was.
223-/// `FeePlan::delete` already pays for the read that tells the two apart on its224+/// `db::fee_plan::delete` already pays for the read that tells the two apart on its
224 /// refusal path; the edit now does too, and a genuinely assigned plan is still225 /// refusal path; the edit now does too, and a genuinely assigned plan is still
225 /// the `409` it always was.226 /// the `409` it always was.
226 #[tokio::test]227 #[tokio::test]
@@ -233,20 +234,27 @@ async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() {
233 Timestamp::from_millis(1_000),234 Timestamp::from_millis(1_000),
234 )]235 )]
235 };236 };
236- let plan = FeePlan::create(237+ let plan = fee_plan::create(
238+ &db,
237 FeePlanName::try_new("Yearly").unwrap(),239 FeePlanName::try_new("Yearly").unwrap(),
238 one(),240 one(),
239 &manager,241 &manager,
240- &db,
241 )242 )
242 .await243 .await
243 .unwrap();244 .unwrap();
244 245
245 // The handler's snapshot, taken before the delete lands.246 // The handler's snapshot, taken before the delete lands.
246- let read = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap();247+ let read = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap();
247- assert!(plan.delete(&db).await.unwrap(), "nobody is on it");248+ assert!(
248- let refused = read249+ fee_plan::delete(&db, plan).await.unwrap(),
249- .update(Some(FeePlanName::try_new("Renamed").unwrap()), None, &db)250+ "nobody is on it"
251+ );
252+ let refused = fee_plan::update(
253+ &db,
254+ read,
255+ Some(FeePlanName::try_new("Renamed").unwrap()),
256+ None,
257+ )
250 .await258 .await
251 .unwrap_err();259 .unwrap_err();
252 assert!(260 assert!(
@@ -256,27 +264,30 @@ async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() {
256 264
257 // The genuine refusal is untouched: a plan somebody is actually on still265 // The genuine refusal is untouched: a plan somebody is actually on still
258 // answers 409, and its schedule is not edited.266 // answers 409, and its schedule is not edited.
259- let plan = FeePlan::create(267+ let plan = fee_plan::create(
268+ &db,
260 FeePlanName::try_new("Yearly").unwrap(),269 FeePlanName::try_new("Yearly").unwrap(),
261 one(),270 one(),
262 &manager,271 &manager,
263- &db,
264 )272 )
265 .await273 .await
266 .unwrap();274 .unwrap();
267- FeePlanAssignment::assign(&plan, &UserId::from_key("del_stu"), &manager, &db)275+ fee_plan_assignment::assign(&db, &plan, &UserId::from_key("del_stu"), &manager)
268 .await276 .await
269 .unwrap();277 .unwrap();
270- let refused = plan278+ let refused = fee_plan::update(
271- .clone()279+ &db,
272- .update(Some(FeePlanName::try_new("Renamed").unwrap()), None, &db)280+ plan.clone(),
281+ Some(FeePlanName::try_new("Renamed").unwrap()),
282+ None,
283+ )
273 .await284 .await
274 .unwrap_err();285 .unwrap_err();
275 assert!(286 assert!(
276 matches!(refused, AppError::Conflict(_)),287 matches!(refused, AppError::Conflict(_)),
277 "an assigned plan is still refused as assigned: {refused}"288 "an assigned plan is still refused as assigned: {refused}"
278 );289 );
279- let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap();290+ let stored = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap();
280 assert_eq!(stored.get_name().as_str(), "Yearly", "nothing was written");291 assert_eq!(stored.get_name().as_str(), "Yearly", "nothing was written");
281 }292 }
282 293