diff --git a/src/database.rs b/src/database.rs index 26cf28c..84f2784 100644 --- a/src/database.rs +++ b/src/database.rs @@ -604,7 +604,8 @@ mod tests { /// the backfill is the whole of the stale-data story, not a nicety. #[tokio::test] async fn a_plan_assigned_before_the_counter_existed_is_still_refused() { - use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName}; + use crate::db::fee_plan; + use crate::domain::fee_plan::{FeePlanId, FeePlanName}; use crate::error::AppError; let db = super::init_mem().await.unwrap(); @@ -644,28 +645,36 @@ mod tests { // The load-bearing half: the seeded plan is frozen, and the untouched // one is not. - let used = FeePlan::read(&FeePlanId::from_key("used"), &db) + let used = fee_plan::read(&db, &FeePlanId::from_key("used")) .await .unwrap() .unwrap(); assert!(matches!( - used.clone() - .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) - .await, + fee_plan::update( + &db, + used.clone(), + Some(FeePlanName::try_new("Edited").unwrap()), + None + ) + .await, Err(AppError::Conflict(_)) )); - assert!(!used.delete(&db).await.unwrap()); - let free = FeePlan::read(&FeePlanId::from_key("free"), &db) + assert!(!fee_plan::delete(&db, used).await.unwrap()); + let free = fee_plan::read(&db, &FeePlanId::from_key("free")) .await .unwrap() .unwrap(); assert!( - free.clone() - .update(Some(FeePlanName::try_new("Edited").unwrap()), None, &db) - .await - .is_ok() + fee_plan::update( + &db, + free.clone(), + Some(FeePlanName::try_new("Edited").unwrap()), + None + ) + .await + .is_ok() ); - assert!(free.delete(&db).await.unwrap()); + assert!(fee_plan::delete(&db, free).await.unwrap()); } /// Stale-data path for the 2026-08-02 board-roster repair. `set_role` diff --git a/src/db/attendance.rs b/src/db/attendance.rs new file mode 100644 index 0000000..34db397 --- /dev/null +++ b/src/db/attendance.rs @@ -0,0 +1,212 @@ +//! The `attendance` table: event roll call. Every write is a single +//! transaction whose gates ride inside it (the event-existence proof), so +//! the whole module is the persistence half; the workflow that decides it +//! lives in [`crate::service::attendance`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::REGISTRATION_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::db::page::PagedList; +use crate::domain::attendance::{Attendance, AttendanceId, AttendanceStatus}; +use crate::domain::event::EventId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Record (or overwrite) `user`'s status for `event`. One row per (event, +/// user), keyed by a deterministic composite id so this is a single atomic +/// UPSERT — concurrent marks for the same pair can no longer both insert and +/// collide on the unique index (a 500); they converge on the one row. +/// +/// The event's existence is proved *inside* the write, the twin of the gate +/// in [`crate::db::session_attendance::mark`]: the handler's event read sits +/// several round trips in front of this, so a bare upsert left a mark on an +/// event [`crate::domain::event::Event`]'s cascade +/// (`DELETE attendance WHERE event = $ev`) had already swept — counted +/// forever in `GET /attendance/{user}` on an event no page shows. Reading +/// the event here would not have closed it either: SurrealDB 3.2.3 +/// conflict-checks write sets, not read sets, so the proof has to *move* a +/// value on the event row. It is the bump-and-restore of +/// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the +/// event already carries: matching nothing is the existence gate, writing +/// the key the delete removes is the collision, and the restore is by +/// captured value (`NONE` included) so no seat is spent or freed. +/// +/// Admissible for [`transaction_with_retry`]: no statement can answer +/// "already exists" — the `UPSERT`'s composite id is bijective with the +/// `attendance_event_user` unique tuple, so it resolves onto the row it +/// names instead of colliding with it. +pub async fn mark( + db: &Database, + event: &EventId, + user: &UserId, + status: AttendanceStatus, + marked_by: &UserId, +) -> Result { + let attendance = Attendance { + id: AttendanceId::composite(event, user), + event: event.clone(), + user: user.clone(), + status, + marked_by: marked_by.clone(), + }; + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev); + LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = + ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); + IF array::len($alive) = 0 {{ THROW 'event_missing' }}; + UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was; + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + ("ev".into(), event.record().into_value()), + ("id".into(), attendance.id.record().into_value()), + ("row".into(), attendance.into_value()), + ], + &["event_missing"], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker. + if errors + .values() + .any(|error| error.to_string().contains("event_missing")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to mark attendance".into())) +} + +pub async fn list_for_event( + db: &Database, + event: &EventId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC") + .bind("ev", event.record()) + .run(limit, offset, db) + .await +} + +/// Every event-attendance row recorded for `user` — the events half of the +/// attendance report. +pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn remove( + db: &Database, + event: &EventId, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE") + .bind(("ev", event.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::settings::Settings; + + /// The session twin's race, one table over + /// ([`crate::db::session_attendance::mark`]): a + /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and + /// the event's delete sweeps its attendance rows before removing the row, so + /// the `SLEEP` lands exactly between the sweep and the commit — the window + /// where a bare upsert wrote a mark nothing would ever sweep again. + /// + /// Real server, and `#[ignore]`d for it: the subject is the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: turning the claim back into a read + /// (`SELECT VALUE id FROM $ev`) turns it red. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_mark_written_inside_a_delete_never_outlives_the_event() { + use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle}; + let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let allowed: Vec = Settings::defaults().get_attendance_statuses().to_vec(); + let marker = UserId::from_key("t"); + let (mut swept, mut orphans) = (0, 0); + for round in 0..4 { + let event = Event::create( + &marker, + EventTitle::try_new("gezi").unwrap(), + EventDescription::try_new("").unwrap(), + EventAudience::School, + None, + None, + &db, + ) + .await + .unwrap(); + let id = event.get_id().clone(); + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { event.delete(&db).await }) + }; + // The mark starts inside the held window: the sweep has run and the + // event row is gone but uncommitted. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let marked = { + let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); + let student = UserId::from_key(&format!("s{round}")); + let status = AttendanceStatus::try_new("present", &allowed).unwrap(); + tokio::spawn(async move { mark(&db, &id, &student, status, &marker).await }) + }; + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); + assert!( + !matches!(marked, Err(AppError::Db(_))), + "round {round}: a raced mark must be answered, not 500: {marked:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if Event::read(&id, &db).await.unwrap().is_none() { + swept += 1; + orphans += list_for_event(&db, &id, None, 0).await.unwrap().0.len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the event is still there"); + } + } + eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event"); + assert!( + swept > 0, + "no round ever deleted the event, so the window was never reached" + ); + assert_eq!(orphans, 0, "a mark outlived its event"); + } +} diff --git a/src/db/course_session.rs b/src/db/course_session.rs index 4e6a6b2..ff7aea7 100644 --- a/src/db/course_session.rs +++ b/src/db/course_session.rs @@ -99,7 +99,7 @@ pub async fn update( /// Delete the session and cascade-remove its roll-call rows, in one /// transaction: as two unbatched queries a failure between them stranded /// roll-call rows on a session that was already gone. The other half of -/// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], +/// that invariant is [`crate::db::session_attendance::mark`], /// which proves the session still exists inside its own write — a /// transaction here cannot stop a mark that commits *after* this one. pub async fn delete(db: &Database, session: CourseSession) -> Result { diff --git a/src/db/fee_plan.rs b/src/db/fee_plan.rs new file mode 100644 index 0000000..4810bd2 --- /dev/null +++ b/src/db/fee_plan.rs @@ -0,0 +1,164 @@ +//! The `fee_plan` table: the create, the reads, and the guarded edit and +//! delete. Both guards are conditional single-record writes on the plan's own +//! refcount — the WHERE clause *is* the assigned-plan freeze rule — so they +//! live here whole. The web-facing doors are [`crate::service::fee_plan`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::FEE_PLAN_UNASSIGNED_GUARD; +use crate::database::{Database, write_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::fee_plan::{ + FeePlan, FeePlanId, FeePlanName, Installment, validate_installments, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn create( + db: &Database, + name: FeePlanName, + installments: Vec, + created_by: &UserId, +) -> Result { + validate_installments(&installments)?; + let plan = FeePlan { + id: FeePlanId::generate(), + name, + installments, + created_by: created_by.clone(), + created_at: Timestamp::now(), + }; + let created: Option = db.create(plan.id.record()).content(plan).await?; + created.ok_or_else(|| AppError::Internal("failed to create fee plan".into())) +} + +pub async fn read(db: &Database, id: &FeePlanId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every plan, newest first — a school runs a handful. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("fee_plan", "ORDER BY created_at DESC, id DESC") + .run(limit, offset, db) + .await +} + +/// Write only the fields the PATCH carried — `None` means the request +/// omitted it, so the column is left alone rather than re-stated from the +/// snapshot this struct was read into. `Err(Conflict)` = refused, nothing +/// was written: somebody is already on the plan. +/// +/// Editing a plan never moves money: charges are frozen copies of the +/// installments as they stood when the plan was assigned. That is exactly +/// why an assigned plan may not be edited at all — the plan and the charges +/// raised from it would tell different stories. The roster is the plan's own +/// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same +/// transaction as the assignment row, so the check and the write are one +/// conditional `UPDATE` on one record: an assign racing this either claims +/// first (and the edit is refused) or claims after (and bills the edited +/// plan, which it re-reads). A `SELECT`-then-write could be, and was, +/// stepped over in the gap between the two. +pub async fn update( + db: &Database, + plan: FeePlan, + name: Option, + installments: Option>, +) -> Result { + if let Some(installments) = &installments { + validate_installments(installments)?; + } + let edited = FieldUpdate::new(plan.id.record()) + .set("name", name) + .set("installments", installments) + .guard( + FEE_PLAN_UNASSIGNED_GUARD, + AppError::Conflict("an assigned plan cannot be edited"), + ) + .run::(db) + .await; + // Still assigned or already gone: the guarded `UPDATE` cannot tell those + // apart either (it reports the refusal it was given), so — exactly as + // [`crate::db::fee_plan::delete`] does — only the refusal path pays for the read + // that can. A plan deleted in the window since the handler read it must + // not be refused as "assigned": it never was. + if matches!(edited, Err(AppError::Conflict(_))) && read(db, &plan.id).await?.is_none() { + return Err(AppError::NotFound); + } + edited +} + +/// Delete the plan, but only while nobody is on it. `false` = refused, +/// nothing was written; `Err(NotFound)` keeps the answer a concurrent +/// *delete* gives. Same one-record guard as [`update`], and the +/// same reason — the charges an assignment raised name this plan, and a +/// school's financial history keeps its references. +/// +/// Retried while the store answers "conflict, retry": the guard reads a +/// counter an assign *writes*, so the two contend on this one record by +/// design — and a delete that loses that round has written nothing, so +/// re-sending it is the whole of the recovery. Without the retry an +/// ordinary raced delete answers 500 instead of the 404 or 409 it owes. +pub async fn delete(db: &Database, plan: FeePlan) -> Result { + let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE"); + let deleted: Vec = + write_with_retry(db, &sql, &[("plan".into(), plan.id.record().into_value())]).await?; + if !deleted.is_empty() { + return Ok(true); + } + // Still assigned or already gone: the one statement cannot tell those + // apart, and only the refusal path pays for the read that can. + match read(db, &plan.id).await? { + Some(_) => Ok(false), + None => Err(AppError::NotFound), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::payment_ledger::LedgerAmount; + + /// The embedded-object DDL (`installments.*.amount_minor`) proved against + /// the engine: SCHEMAFULL rejects any nested key it was not told about, so + /// a plan that writes and reads back unchanged is what says the declared + /// shape and the stored one agree. A past due date is legal on purpose. + #[tokio::test] + async fn installments_survive_a_round_trip_through_the_schema() { + let db = crate::database::init_mem().await.unwrap(); + let manager = UserId::from_key("mgr1"); + let installments = vec![ + Installment::new( + LedgerAmount::try_new(150_000).unwrap(), + Timestamp::from_millis(1_000), + ), + Installment::new( + LedgerAmount::try_new(250_000).unwrap(), + Timestamp::from_millis(2_000), + ), + ]; + let plan = create( + &db, + FeePlanName::try_new("Yearly").unwrap(), + installments.clone(), + &manager, + ) + .await + .unwrap(); + + let stored = read(&db, plan.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_installments(), installments.as_slice()); + assert_eq!(stored.get_name().as_str(), "Yearly"); + + // And a PATCH of the array lands whole. + let edited = update(&db, stored, None, Some(vec![installments[0].clone()])) + .await + .unwrap(); + assert_eq!(edited.get_installments().len(), 1); + } +} diff --git a/src/db/fee_plan_assignment.rs b/src/db/fee_plan_assignment.rs new file mode 100644 index 0000000..87ca89c --- /dev/null +++ b/src/db/fee_plan_assignment.rs @@ -0,0 +1,64 @@ +//! The `fee_plan_assignment` table: the reads over placements. The row is +//! written by [`crate::service::fee_plan_assignment::assign`], whose claim +//! ([`crate::db::cap::claim_and_create`]) is the write that freezes the plan. + +use surrealdb::types::RecordId; + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::domain::fee_plan::FeePlanId; +use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn read( + db: &Database, + id: &FeePlanAssignmentId, +) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Who is on this plan, newest first. +pub async fn list_for_plan( + db: &Database, + plan: &FeePlanId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "fee_plan_assignment WHERE plan = $plan", + "ORDER BY created_at DESC, id DESC", + ) + .bind("plan", plan.record()) + .run(limit, offset, db) + .await +} + +/// Is anybody on this plan? A scan, and no longer a guard: the edit and +/// delete guards read the plan's own refcount, which no concurrent assign +/// can be behind. Kept because a *test* asserting the rows and the counter +/// agree is the only thing that would catch the counter drifting. +pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result { + let mut result = db + .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") + .bind(("plan", plan.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) +} + +/// Which plans a student is on — one student may hold several. +pub async fn list_for_student( + db: &Database, + student: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "fee_plan_assignment WHERE student = $student", + "ORDER BY created_at DESC, id DESC", + ) + .bind("student", student.record()) + .run(limit, offset, db) + .await +} diff --git a/src/db/mod.rs b/src/db/mod.rs index ddf9d5f..450cc1c 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,6 +1,7 @@ //! The only layer that executes queries. pub mod appointment; pub mod appointment_slot; +pub mod attendance; pub mod badge; pub mod builder; pub mod cap; @@ -15,6 +16,8 @@ pub mod event; pub mod exam; pub mod exam_attempt; pub mod exam_question; +pub mod fee_plan; +pub mod fee_plan_assignment; pub mod field_update; pub mod meal_attendance; pub mod meal_booking; @@ -31,6 +34,7 @@ pub mod profile; pub mod rag_output; pub mod registration; pub mod session; +pub mod session_attendance; pub mod settings; pub mod subject; pub mod term; diff --git a/src/db/session_attendance.rs b/src/db/session_attendance.rs new file mode 100644 index 0000000..f7f3064 --- /dev/null +++ b/src/db/session_attendance.rs @@ -0,0 +1,705 @@ +//! The `session_attendance` table: the lesson roll call and the two badge +//! counters its mark and remove move. Every write is a single transaction +//! whose gates ride inside it; the target-eligibility rules (staff rows are +//! management's, only students attend, enrollment) are +//! [`crate::service::session_attendance`]'s to judge before calling here. + +use surrealdb::types::SurrealValue; + +use crate::constant::{ + LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::db::page::PagedList; +use crate::domain::attendance::AttendanceStatus; +use crate::domain::course_session::{CourseSession, CourseSessionId}; +use crate::domain::session_attendance::{ + SessionAttendance, SessionAttendanceId, counts_as_attended, +}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Record (or overwrite) `user`'s status for the session. One row per +/// (session, user), keyed by a deterministic composite id so this is a +/// single atomic UPSERT — concurrent marks converge on the one row. +/// +/// The "session still exists" gate rides in the same transaction as the +/// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the +/// caller's pre-flight read sits four round trips in front of this write, +/// so a delete landing in that gap used to leave a roll-call row on a +/// session that was gone — and that row was *unremovable*, its only delete +/// route 404ing on the vanished session while the attendance report went +/// on counting it. A deleted session reads NONE, which is falsy, so the +/// gate is written as an explicit `IS NONE` (see +/// [`crate::domain::exam_result::ExamResult::grade`]). It reads the +/// session's `teacher` — required on every row, so NONE means "no row" just +/// as `id` did — because the counter below needs that teacher anyway, and +/// one read serves both. +/// +/// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write +/// sets, not read sets, so that gate alone only closes the *sequential* +/// order (delete committed, then the mark arrives). To make the two really +/// collide, this transaction also *writes* the session row, unconditionally +/// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] +/// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. +/// Unconditional is the whole point: the credit branch below writes that +/// column already, but it fires only for the first roll call of a lesson +/// that has begun, so a future-dated sheet and every re-mark of a counted +/// one touched nothing at all and committed happily beside +/// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do +/// either — an `UPDATE` that leaves the document unchanged is elided and +/// never enters the write set — hence bump first, then either stamp +/// (credit branch) or put back exactly what was found, `NONE` included, so +/// the row is byte-identical and the once-per-lesson rule is untouched. +/// +/// Sound to re-send while the store answers "conflict, retry": the gate +/// reads the record a delete writes, so the two contend by design, and the +/// UPSERT cannot legitimately answer "already exists" — its composite id is +/// bijective with the `session_attendance_session_user` unique tuple, so +/// the index entry can only point at the row the id already names. +/// +/// Two badge counters move in this same transaction, both of them read +/// from the store rather than taken on the caller's word: +/// +/// - `lessons_attended_total`, on the person marked, as a *delta* rather +/// than an increment, because this is an upsert: a re-mark that changes +/// nothing must change nothing, and a teacher's correction must move it +/// back down. `$was` is read before the upsert overwrites it (`NONE` when +/// the pair has no row yet), so it writes only on a real crossing of the +/// attended line, and only for a **student** — attending lessons is a +/// student's badge, the same student-only rule enrolling and sitting an +/// exam already carry, so a teacher marked present in their own lesson +/// moves it in neither direction. The live `role` decides that, not the +/// role someone held when the row was written. +/// - `lessons_held_total`, on the *session's* teacher, exactly once per +/// session: the first roll call taken stamps +/// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees +/// the stamp and credits nothing. It counts lessons that actually +/// happened — scheduling one and cancelling it earns nothing, which is +/// why the credit does not live in `crate::db::course_session::create`. Two +/// simultaneous first marks both write the lesson row, so the store's own +/// conflict detection (and `transaction_with_retry` behind it) is what +/// keeps the stamp from being set twice. +/// +/// "Actually happened" is a clock reading, not a request count: the +/// credit waits for the lesson's own `starts_at` to arrive. Roll call is +/// deliberately *not* time-gated — a teacher may open the sheet early and +/// is never refused — so without this a teacher could schedule two +/// hundred lessons for next week, mark one student in each, and hold two +/// hundred lessons this afternoon. Because the stamp is written only on +/// the branch that credits, a sheet opened early and touched again after +/// the bell still credits exactly once, then; a sheet never touched +/// again credits never, which is the deliberate cost of not storing a +/// promise the passage of time would have to redeem on its own. +/// +/// `lessons_attended_total` is *not* gated the same way, and the +/// asymmetry is on purpose: it is a delta off the row's stored status, +/// which carries no record of whether the credit was ever taken, so a +/// gate would refund at the correction what the early mark never +/// credited — a student's real lessons eaten by someone else's farm. It +/// is also nobody's self-service: only a teacher can mark a student, so +/// the counter cannot be moved by the person it decorates. +/// +/// Both are floored/guarded rather than trusting the column to exist: a row +/// written before these columns carries none of them. +// +// corner-cut: that asymmetry leaves a teacher able to inflate a *student's* +// attendance with future-dated lessons. Closing it needs the credit stamped +// on the roll-call row itself and refunded off that stamp — the same column +// the live-role note on `remove` below wants, and the shape +// `counted_on_time` already uses for homework. One column closes both; +// neither is worth it until a real complaint names one. +pub async fn mark( + db: &Database, + session: &CourseSession, + user: &UserId, + status: AttendanceStatus, + marked_by: &UserId, +) -> Result { + let attended = counts_as_attended(&status); + let delta: i64 = if attended { 1 } else { -1 }; + let attendance = SessionAttendance { + id: SessionAttendanceId::composite(session.get_id(), user), + session: session.get_id().clone(), + course: session.get_course().clone(), + user: user.clone(), + status, + marked_by: marked_by.clone(), + }; + let (mut written, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $teacher = (SELECT VALUE teacher FROM ONLY $sess); + IF $teacher IS NONE {{ THROW 'session_missing' }}; + LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess); + LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp); + LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); + LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']); + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + IF $student AND $was != $now {{ + UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = + math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) + }}; + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; + IF ($counted IS NONE) AND $begun {{ + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; + UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = + ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 + }} ELSE {{ + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted + }}; + RETURN $after; + COMMIT TRANSACTION;" + ), + &[ + // `$session` is SurrealDB's own protected variable (the auth + // session): binding that name errors the whole query. + ("sess".into(), session.get_id().record().into_value()), + ("id".into(), attendance.id.record().into_value()), + ("usr".into(), user.record().into_value()), + ("now".into(), attended.into_value()), + ("delta".into(), delta.into_value()), + ("stamp".into(), Timestamp::now().into_value()), + ("row".into(), attendance.into_value()), + ], + &["session_missing"], + ) + .await?; + // An aborted transaction errors every slot and only the THROW's own + // slot names the marker, so a refusal is read by marker while a lost + // round was already re-sent — never reported as a 500. + if errors + .values() + .any(|error| error.to_string().contains("session_missing")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept one. + let slot = written.num_statements().saturating_sub(2); + written + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) +} + +pub async fn list_for_session( + db: &Database, + session: &CourseSessionId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC") + .bind("s", session.record()) + .run(limit, offset, db) + .await +} + +/// Every roll-call row ever recorded for `user` — the session half of the +/// attendance report. Deliberately not filtered by current enrollment: +/// attendance is a historical record, so unenrolling hides marks (report +/// semantics) but never absences. +pub async fn list_for_user( + db: &Database, + user: &UserId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Clearing a row the student was counted for gives the count back, in the +/// delete's own transaction — the other direction of the delta in +/// [`mark`], so a row that never existed and a row that +/// was withdrawn leave the same number behind. Only *this* route decrements: +/// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of +/// its own and never comes through here, which is the ruling +/// `exam_sat_total` already carries — deleting the lesson does not un-attend +/// it. `lessons_held_total` is never given back either: the lesson was +/// taken, and clearing one student's row does not un-take it. +/// +/// Student-only on the same terms as the mark, and read from the store for +/// the same reason. +/// +/// Sound to re-send: neither statement can answer "already exists". +// +// corner-cut: both ends read the *live* role, so a student promoted between +// being marked present and having that row corrected leaves the counter one +// high (the credit landed as a student, the refund is refused as staff). +// Upgrade path is stamping the credit on the roll-call row itself and +// refunding off that stamp, the way `counted_on_time` works for homework — +// not worth a column until a promotion mid-term is a real complaint. +pub async fn remove( + db: &Database, + session: &CourseSessionId, + user: &UserId, +) -> Result, AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); + LET $gone = (DELETE session_attendance + WHERE session = $s AND user = $usr RETURN BEFORE); + IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{ + UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = + math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + &[ + ("s".into(), session.record().into_value()), + ("usr".into(), user.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); + Ok(result + .take::>(slot)? + .into_iter() + .next()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::DEFAULT_ATTENDANCE_STATUSES; + use crate::database::init_mem; + use crate::domain::badge::BadgeStats; + use crate::domain::course_session::SessionTopic; + use crate::domain::role::Role; + + /// A user row carrying its role — the counters are `UPDATE`s on one (which + /// writes nothing at all to a record that does not exist), and the live + /// role is what decides whether the attended counter moves. + async fn a_user(key: &str, role: Role, db: &Database) -> UserId { + let user = UserId::from_key(key); + db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role") + .bind(("usr", user.record())) + .bind(("name", key.to_string())) + .bind(("role", role)) + .await + .unwrap() + .check() + .unwrap(); + user + } + + async fn a_student(key: &str, db: &Database) -> UserId { + a_user(key, Role::Student, db).await + } + + async fn a_teacher(key: &str, db: &Database) -> UserId { + a_user(key, Role::Teacher, db).await + } + + async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { + crate::db::course_session::create( + db, + &crate::db::course::a_test_course(db).await, + teacher, + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(starts_at), + None, + ) + .await + .unwrap() + } + + /// A lesson long since begun — every test but the gate's own wants one. + async fn a_session(teacher: &UserId, db: &Database) -> CourseSession { + a_session_at(teacher, 1, db).await + } + + /// A status this school allows — the four core ones plus a school-added + /// `online`, which is exactly the open half of the set. + fn status(value: &str) -> AttendanceStatus { + let allowed: Vec = DEFAULT_ATTENDANCE_STATUSES + .iter() + .map(|s| s.to_string()) + .chain(["online".to_string()]) + .collect(); + AttendanceStatus::try_new(value, &allowed).unwrap() + } + + /// The two counters as the badge rules read them, off the stored row. + async fn attended(user: &UserId, db: &Database) -> i64 { + BadgeStats::load(user, db) + .await + .unwrap() + .get_lessons_attended() + } + + async fn held(user: &UserId, db: &Database) -> i64 { + BadgeStats::load(user, db).await.unwrap().get_lessons_held() + } + + /// The whole transition table in one pass: an upsert may only move the + /// counter when the mark crosses the attended line, in either direction, so + /// a re-mark and a swap within the same class are both no-ops. + #[tokio::test] + async fn the_counter_follows_every_crossing_and_no_other_move() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + let mark = async |value: &str, db: &Database| { + super::mark(db, &session, &student, status(value), &teacher) + .await + .unwrap(); + }; + + for (value, expected, why) in [ + ("present", 1, "first mark counts"), + ("present", 1, "re-marking the same status changes nothing"), + ("late", 1, "late is attending too, so no crossing"), + ("absent", 0, "a correction gives the count back"), + ("absent", 0, "and does not keep giving it back"), + ("late", 1, "absent -> late crosses back up"), + ("excused", 0, "excused is neutral: a crossing down"), + ("online", 0, "a school-added status stays neutral"), + ("present", 1, "…and crossing up from one still counts"), + ("online", 0, "…as does crossing down to one"), + ] { + mark(value, &db).await; + assert_eq!(attended(&student, &db).await, expected, "{why}"); + } + assert_eq!(attended(&teacher, &db).await, 0, "credited the marker"); + // Ten marks, one lesson: correcting a roll call is not holding another. + assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice"); + } + + /// The lesson is credited to its teacher when the roll call is *taken*, and + /// once: the whole roster, and every later correction, ride the same stamp. + #[tokio::test] + async fn the_first_roll_call_counts_the_lesson_once() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let other = a_teacher("o", &db).await; + let session = a_session(&teacher, &db).await; + assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing"); + + for key in ["s1", "s2", "s3"] { + let student = a_student(key, &db).await; + mark(&db, &session, &student, status("present"), &teacher) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again"); + } + assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher"); + + // A second lesson is a second count — the stamp is per session. + let second = a_session(&teacher, &db).await; + let student = a_student("s4", &db).await; + mark(&db, &second, &student, status("present"), &teacher) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 2); + } + + /// A lesson is held when its own time comes, not when the sheet is opened. + /// Roll call is never refused early, so ungated a teacher could schedule + /// two hundred lessons for next week and hold all of them this afternoon. + #[tokio::test] + async fn a_lesson_that_has_not_started_holds_nothing_yet() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let next_week = + a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await; + + mark(&db, &next_week, &student, status("present"), &teacher) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 0, "next week's lesson, today"); + // The mark itself stands — opening the sheet early is not an error. + assert_eq!(attended(&student, &db).await, 1); + + // The bell rings. The same sheet, touched again, credits now — and + // only once: nothing backfills, so the stamp is the whole guard. + db.query("UPDATE $sess SET starts_at = 1") + .bind(("sess", next_week.get_id().record())) + .await + .unwrap() + .check() + .unwrap(); + for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { + mark(&db, &next_week, &student, status(status_value), &teacher) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 1, "{why}"); + } + } + + /// Attending lessons is a student's badge. A teacher marked present in + /// their own lesson (which management does, not the teacher) moves nothing + /// for them as an attendee — while the roll call itself still counts as a + /// lesson held. + #[tokio::test] + async fn a_teacher_marked_present_earns_nothing_for_attending() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let session = a_session(&teacher, &db).await; + + mark(&db, &session, &teacher, status("present"), &teacher) + .await + .unwrap(); + assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson"); + assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken"); + + // And the correction direction is just as closed: nothing was taken, so + // nothing may be given back. + mark(&db, &session, &teacher, status("absent"), &teacher) + .await + .unwrap(); + assert_eq!(attended(&teacher, &db).await, 0); + remove(&db, session.get_id(), &teacher) + .await + .unwrap() + .expect("the row was there"); + assert_eq!(attended(&teacher, &db).await, 0); + assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened"); + } + + /// Two lessons are two counts — the counter is per row, not per student. + #[tokio::test] + async fn each_lesson_counts_once_for_the_student_marked() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let other = a_student("o", &db).await; + for _ in 0..2 { + let session = a_session(&teacher, &db).await; + mark(&db, &session, &student, status("present"), &teacher) + .await + .unwrap(); + } + assert_eq!(attended(&student, &db).await, 2); + assert_eq!(attended(&other, &db).await, 0, "credited the wrong student"); + } + + /// Removing the row is the other direction of the delta, and only for a row + /// that was counted. + #[tokio::test] + async fn removing_a_row_gives_back_only_what_it_took() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + + let counted = a_session(&teacher, &db).await; + mark(&db, &counted, &student, status("present"), &teacher) + .await + .unwrap(); + let neutral = a_session(&teacher, &db).await; + mark(&db, &neutral, &student, status("absent"), &teacher) + .await + .unwrap(); + assert_eq!(attended(&student, &db).await, 1); + + remove(&db, neutral.get_id(), &student) + .await + .unwrap() + .expect("the absent row was there"); + assert_eq!(attended(&student, &db).await, 1, "absent took nothing"); + remove(&db, counted.get_id(), &student) + .await + .unwrap() + .expect("the present row was there"); + assert_eq!(attended(&student, &db).await, 0); + assert!( + remove(&db, counted.get_id(), &student) + .await + .unwrap() + .is_none(), + "nothing left to remove" + ); + assert_eq!(attended(&student, &db).await, 0, "and nothing to give back"); + assert_eq!( + held(&teacher, &db).await, + 2, + "clearing a row un-held a lesson" + ); + } + + /// The floor: however the corrections and removals interleave, and whatever + /// a stale row starts from, the counter never goes negative. + #[tokio::test] + async fn the_counter_never_goes_below_zero() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + + // Ten counted lessons whose counter was never credited — the stale-data + // case, an account that predates the column. Every one of them is now + // corrected away, which is ten decrements against a zero. + let mut sessions = Vec::new(); + for _ in 0..10 { + let session = a_session(&teacher, &db).await; + mark(&db, &session, &student, status("present"), &teacher) + .await + .unwrap(); + sessions.push(session); + } + db.query(format!( + "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0" + )) + .bind(("usr", student.record())) + .await + .unwrap() + .check() + .unwrap(); + + for session in &sessions { + mark(&db, session, &student, status("absent"), &teacher) + .await + .unwrap(); + remove(&db, session.get_id(), &student).await.unwrap(); + assert!(attended(&student, &db).await >= 0); + } + assert_eq!(attended(&student, &db).await, 0, "floored, never negative"); + } + + /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own + /// — it never reaches [`remove`] — so the count stands, + /// the ruling every other counter here carries. + #[tokio::test] + async fn deleting_the_session_leaves_the_counters_alone() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + mark(&db, &session, &student, status("present"), &teacher) + .await + .unwrap(); + + crate::db::course_session::delete(&db, session) + .await + .unwrap(); + assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); + assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); + } + + /// A mark on a session that is already gone is refused, so it cannot leave + /// a count behind either. + #[tokio::test] + async fn a_refused_mark_moves_nothing() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + let ghost = session.clone(); + crate::db::course_session::delete(&db, session) + .await + .unwrap(); + + assert!(matches!( + mark(&db, &ghost, &student, status("present"), &teacher).await, + Err(AppError::NotFound) + )); + assert_eq!(attended(&student, &db).await, 0); + assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); + } + + /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` + /// on `course_session` fires inside the delete's own transaction, and + /// [`crate::db::course_session::delete`] sweeps its children before removing the row, + /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is + /// written after the sweep has run, and used to commit straight past it. + /// + /// The two flavors raced are the ones the credit branch never wrote for — a + /// lesson that has not begun, and a student with no row yet on a lesson + /// already counted. A re-mark of a row that *exists* was never in danger: + /// the cascade and the upsert write that child's own key and collide there. + /// + /// Real server, and `#[ignore]`d for it: the subject is the store's + /// conflict detection, which [`init_mem`]'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, so this passes there on + /// broken code. Mutation-tested: dropping the unconditional + /// `UPDATE $sess` from `mark` turns it red. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_mark_written_inside_a_delete_never_outlives_the_session() { + let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let teacher = a_teacher("t", &db).await; + let (mut swept, mut orphans) = (0, 0); + for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { + let session = if already_counted { + // Counted by somebody else's mark, so this one credits nothing. + let session = a_session(&teacher, &db).await; + let first = a_student(&format!("f{round}"), &db).await; + mark(&db, &session, &first, status("present"), &teacher) + .await + .unwrap(); + session + } else { + a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await + }; + let id = session.get_id().clone(); + let ghost = session.clone(); + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { crate::db::course_session::delete(&db, session).await }) + }; + // The mark starts inside the held window: the sweep has run and the + // session row is gone but uncommitted — which is exactly what a + // read of that session still believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let marked = { + let (db, teacher) = (db.clone(), teacher.clone()); + let student = a_student(&format!("s{round}"), &db).await; + tokio::spawn(async move { + mark(&db, &ghost, &student, status("present"), &teacher).await + }) + }; + let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); + assert!( + !matches!(marked, Err(AppError::Db(_))), + "round {round}: a raced mark must be answered, not 500: {marked:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if crate::db::course_session::read(&db, &id) + .await + .unwrap() + .is_none() + { + swept += 1; + orphans += list_for_session(&db, &id, None, 0).await.unwrap().0.len(); + } else if drop_it.is_ok() { + panic!("round {round}: the delete reported success but the session is still there"); + } + } + eprintln!( + "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" + ); + assert!( + swept > 0, + "no round ever deleted the session, so the window was never reached" + ); + assert_eq!(orphans, 0, "a roll call outlived its session"); + } +} diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 3dc2688..6649f48 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -1,11 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::page::PagedList; +use crate::constant::ATTENDANCE_TABLE; use crate::domain::event::EventId; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct AttendanceId(RecordId); @@ -59,11 +57,11 @@ impl AttendanceStatus { #[derive(Debug, Clone, SurrealValue)] pub struct Attendance { - id: AttendanceId, - event: EventId, - user: UserId, - status: AttendanceStatus, - marked_by: UserId, + pub(crate) id: AttendanceId, + pub(crate) event: EventId, + pub(crate) user: UserId, + pub(crate) status: AttendanceStatus, + pub(crate) marked_by: UserId, } impl Attendance { @@ -86,121 +84,6 @@ impl Attendance { pub fn get_marked_by(&self) -> &UserId { &self.marked_by } - - /// Record (or overwrite) `user`'s status for `event`. One row per (event, - /// user), keyed by a deterministic composite id so this is a single atomic - /// UPSERT — concurrent marks for the same pair can no longer both insert and - /// collide on the unique index (a 500); they converge on the one row. - /// - /// The event's existence is proved *inside* the write, the twin of the gate - /// in [`crate::domain::session_attendance::SessionAttendance::mark`]: the - /// handler's event read sits several round trips in front of this, so a - /// bare upsert left a mark on an event [`crate::domain::event::Event`]'s - /// cascade (`DELETE attendance WHERE event = $ev`) had already swept — - /// counted forever in `GET /attendance/{user}` on an event no page shows. - /// Reading the event here would not have closed it either: SurrealDB 3.2.3 - /// conflict-checks write sets, not read sets, so the proof has to *move* a - /// value on the event row. It is the bump-and-restore of - /// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the - /// event already carries: matching nothing is the existence gate, writing - /// the key the delete removes is the collision, and the restore is by - /// captured value (`NONE` included) so no seat is spent or freed. - /// - /// Admissible for [`transaction_with_retry`]: no statement can answer - /// "already exists" — the `UPSERT`'s composite id is bijective with the - /// `attendance_event_user` unique tuple, so it resolves onto the row it - /// names instead of colliding with it. - pub async fn mark( - event: &EventId, - user: &UserId, - status: AttendanceStatus, - marked_by: &UserId, - db: &Database, - ) -> Result { - let attendance = Attendance { - id: AttendanceId::composite(event, user), - event: event.clone(), - user: user.clone(), - status, - marked_by: marked_by.clone(), - }; - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev); - LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = - ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'event_missing' }}; - UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was; - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("ev".into(), event.record().into_value()), - ("id".into(), attendance.id.record().into_value()), - ("row".into(), attendance.into_value()), - ], - &["event_missing"], - ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker. - if errors - .values() - .any(|error| error.to_string().contains("event_missing")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to mark attendance".into())) - } - - pub async fn list_for_event( - event: &EventId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC") - .bind("ev", event.record()) - .run(limit, offset, db) - .await - } - - /// Every event-attendance row recorded for `user` — the events half of the - /// attendance report. - pub async fn list_for_user(user: &UserId, db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn remove( - event: &EventId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE") - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } } #[cfg(test)] @@ -230,89 +113,4 @@ mod tests { .collect(); assert!(AttendanceStatus::try_new("online", &extended).is_ok()); } - - /// The session twin's race, one table over - /// ([`crate::domain::session_attendance::SessionAttendance`]): a - /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and - /// [`crate::db::event::delete`] sweeps its attendance rows before removing the row, so - /// the `SLEEP` lands exactly between the sweep and the commit — the window - /// where a bare upsert wrote a mark nothing would ever sweep again. - /// - /// Real server, and `#[ignore]`d for it: the subject is the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, so this passes there on - /// broken code. Mutation-tested: turning the claim back into a read - /// (`SELECT VALUE id FROM $ev`) turns it red. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_mark_written_inside_a_delete_never_outlives_the_event() { - use crate::domain::event::{EventAudience, EventDescription, EventTitle}; - let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let allowed: Vec = crate::domain::settings::Settings::defaults() - .get_attendance_statuses() - .to_vec(); - let marker = UserId::from_key("t"); - let (mut swept, mut orphans) = (0, 0); - for round in 0..4 { - let event = crate::db::event::create( - &db, - &marker, - EventTitle::try_new("gezi").unwrap(), - EventDescription::try_new("").unwrap(), - EventAudience::School, - None, - None, - ) - .await - .unwrap(); - let id = event.get_id().clone(); - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { crate::db::event::delete(&db, event).await }) - }; - // The mark starts inside the held window: the sweep has run and the - // event row is gone but uncommitted. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let marked = { - let (db, id, marker) = (db.clone(), id.clone(), marker.clone()); - let student = UserId::from_key(&format!("s{round}")); - let status = AttendanceStatus::try_new("present", &allowed).unwrap(); - tokio::spawn( - async move { Attendance::mark(&id, &student, status, &marker, &db).await }, - ) - }; - let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); - assert!( - !matches!(marked, Err(AppError::Db(_))), - "round {round}: a raced mark must be answered, not 500: {marked:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if crate::db::event::read(&db, &id).await.unwrap().is_none() { - swept += 1; - orphans += Attendance::list_for_event(&id, None, 0, &db) - .await - .unwrap() - .0 - .len(); - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the event is still there"); - } - } - eprintln!("Event::delete raced by a mark: {swept}/4 rounds deleted the event"); - assert!( - swept > 0, - "no round ever deleted the event, so the window was never reached" - ); - assert_eq!(orphans, 0, "a mark outlived its event"); - } } diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index 55a1bd9..a3d074e 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -16,17 +16,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - FEE_PLAN_TABLE, FEE_PLAN_UNASSIGNED_GUARD, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN, -}; -use crate::database::{Database, write_with_retry}; -use crate::db::field_update::FieldUpdate; +use crate::constant::{FEE_PLAN_TABLE, MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::payment_ledger::LedgerAmount; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -108,11 +103,11 @@ pub fn validate_installments(installments: &[Installment]) -> Result<(), Validat #[derive(Debug, Clone, SurrealValue)] pub struct FeePlan { - id: FeePlanId, - name: FeePlanName, - installments: Vec, - created_by: UserId, - created_at: Timestamp, + pub(crate) id: FeePlanId, + pub(crate) name: FeePlanName, + pub(crate) installments: Vec, + pub(crate) created_by: UserId, + pub(crate) created_at: Timestamp, } impl FeePlan { @@ -135,110 +130,6 @@ impl FeePlan { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - pub async fn create( - name: FeePlanName, - installments: Vec, - created_by: &UserId, - db: &Database, - ) -> Result { - validate_installments(&installments)?; - let plan = FeePlan { - id: FeePlanId::generate(), - name, - installments, - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let created: Option = db.create(plan.id.record()).content(plan).await?; - created.ok_or_else(|| AppError::Internal("failed to create fee plan".into())) - } - - pub async fn read(id: &FeePlanId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every plan, newest first — a school runs a handful. - pub async fn list_all( - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("fee_plan", "ORDER BY created_at DESC, id DESC") - .run(limit, offset, db) - .await - } - - /// Write only the fields the PATCH carried — `None` means the request - /// omitted it, so the column is left alone rather than re-stated from the - /// snapshot this struct was read into. `Err(Conflict)` = refused, nothing - /// was written: somebody is already on the plan. - /// - /// Editing a plan never moves money: charges are frozen copies of the - /// installments as they stood when the plan was assigned. That is exactly - /// why an assigned plan may not be edited at all — the plan and the charges - /// raised from it would tell different stories. The roster is the plan's own - /// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same - /// transaction as the assignment row, so the check and the write are one - /// conditional `UPDATE` on one record: an assign racing this either claims - /// first (and the edit is refused) or claims after (and bills the edited - /// plan, which it re-reads). A `SELECT`-then-write could be, and was, - /// stepped over in the gap between the two. - pub async fn update( - self, - name: Option, - installments: Option>, - db: &Database, - ) -> Result { - if let Some(installments) = &installments { - validate_installments(installments)?; - } - let edited = FieldUpdate::new(self.id.record()) - .set("name", name) - .set("installments", installments) - .guard( - FEE_PLAN_UNASSIGNED_GUARD, - AppError::Conflict("an assigned plan cannot be edited"), - ) - .run::(db) - .await; - // Still assigned or already gone: the guarded `UPDATE` cannot tell those - // apart either (it reports the refusal it was given), so — exactly as - // [`FeePlan::delete`] does — only the refusal path pays for the read - // that can. A plan deleted in the window since the handler read it must - // not be refused as "assigned": it never was. - if matches!(edited, Err(AppError::Conflict(_))) && Self::read(&self.id, db).await?.is_none() - { - return Err(AppError::NotFound); - } - edited - } - - /// Delete the plan, but only while nobody is on it. `false` = refused, - /// nothing was written; `Err(NotFound)` keeps the answer a concurrent - /// *delete* gives. Same one-record guard as [`FeePlan::update`], and the - /// same reason — the charges an assignment raised name this plan, and a - /// school's financial history keeps its references. - /// - /// Retried while the store answers "conflict, retry": the guard reads a - /// counter an assign *writes*, so the two contend on this one record by - /// design — and a delete that loses that round has written nothing, so - /// re-sending it is the whole of the recovery. Without the retry an - /// ordinary raced delete answers 500 instead of the 404 or 409 it owes. - pub async fn delete(self, db: &Database) -> Result { - let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE"); - let deleted: Vec = - write_with_retry(db, &sql, &[("plan".into(), self.id.record().into_value())]).await?; - if !deleted.is_empty() { - return Ok(true); - } - // Still assigned or already gone: the one statement cannot tell those - // apart, and only the refusal path pays for the read that can. - match Self::read(&self.id, db).await? { - Some(_) => Ok(false), - None => Err(AppError::NotFound), - } - } } #[cfg(test)] @@ -267,43 +158,4 @@ mod tests { assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok()); assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err()); } - - /// The embedded-object DDL (`installments.*.amount_minor`) proved against - /// the engine: SCHEMAFULL rejects any nested key it was not told about, so - /// a plan that writes and reads back unchanged is what says the declared - /// shape and the stored one agree. A past due date is legal on purpose. - #[tokio::test] - async fn installments_survive_a_round_trip_through_the_schema() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("mgr1"); - let installments = vec![ - Installment::new( - LedgerAmount::try_new(150_000).unwrap(), - Timestamp::from_millis(1_000), - ), - Installment::new( - LedgerAmount::try_new(250_000).unwrap(), - Timestamp::from_millis(2_000), - ), - ]; - let plan = FeePlan::create( - FeePlanName::try_new("Yearly").unwrap(), - installments.clone(), - &manager, - &db, - ) - .await - .unwrap(); - - let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_installments(), installments.as_slice()); - assert_eq!(stored.get_name().as_str(), "Yearly"); - - // And a PATCH of the array lands whole. - let edited = stored - .update(None, Some(vec![installments[0].clone()]), &db) - .await - .unwrap(); - assert_eq!(edited.get_installments().len(), 1); - } } diff --git a/src/domain/fee_plan_assignment.rs b/src/domain/fee_plan_assignment.rs index bd4cc12..7462433 100644 --- a/src/domain/fee_plan_assignment.rs +++ b/src/domain/fee_plan_assignment.rs @@ -17,15 +17,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE}; -use crate::database::Database; -use crate::db::cap::{self, Claimed}; -use crate::db::page::PagedList; -use crate::db::payment_ledger; -use crate::domain::fee_plan::{FeePlan, FeePlanId}; +use crate::constant::FEE_PLAN_ASSIGNMENT_TABLE; +use crate::domain::fee_plan::FeePlanId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct FeePlanAssignmentId(RecordId); @@ -60,11 +55,11 @@ impl FeePlanAssignmentId { #[derive(Debug, Clone, SurrealValue)] pub struct FeePlanAssignment { - id: FeePlanAssignmentId, - plan: FeePlanId, - student: UserId, - assigned_by: UserId, - created_at: Timestamp, + pub(crate) id: FeePlanAssignmentId, + pub(crate) plan: FeePlanId, + pub(crate) student: UserId, + pub(crate) assigned_by: UserId, + pub(crate) created_at: Timestamp, } impl FeePlanAssignment { @@ -87,416 +82,4 @@ impl FeePlanAssignment { pub fn get_created_at(&self) -> Timestamp { self.created_at } - - /// Place `plan` on `student` and bill it. Returns the assignment and - /// whether it was *already* there, so the web layer can answer a replay - /// honestly instead of pretending it just happened. - /// - /// The row and the plan's assignment refcount are written in **one** - /// transaction ([`cap::claim_and_create`]): that increment is what makes the - /// plan un-editable and un-deletable, and it has to be indivisible from the - /// row it counts, or an edit could slip between the two. A plan the counter - /// cannot be claimed on is one a concurrent delete already removed, which is - /// the same `404` the handler's own lookup would have given. - /// - /// The installments are then re-read **from the stored plan**, not taken - /// from the caller's snapshot: the claim is the moment the plan freezes, and - /// an edit that landed between the handler's read and that claim is - /// legitimate. Billing the snapshot would raise charges from a schedule the - /// plan no longer shows — precisely the divergence the 409 exists to - /// prevent. - /// - /// The charges are appended after the row, never before: each one is keyed - /// by (assignment, installment number), so this loop is safe to re-enter - /// from the top — which is exactly what a repeated assign does, and the - /// only way a half-written assignment ever gets its missing lines. - pub async fn assign( - plan: &FeePlan, - student: &UserId, - assigned_by: &UserId, - db: &Database, - ) -> Result<(FeePlanAssignment, bool), AppError> { - let id = FeePlanAssignmentId::composite(plan.get_id(), student); - let row = FeePlanAssignment { - id: id.clone(), - plan: plan.get_id().clone(), - student: student.clone(), - assigned_by: assigned_by.clone(), - created_at: Timestamp::now(), - }; - let claimed = cap::claim_and_create( - &plan.get_id().record(), - FEE_PLAN_ASSIGNMENT_COUNT_FIELD, - cap::UNLIMITED, - &id.record(), - &row, - db, - ) - .await?; - let (assignment, existed) = match claimed { - Claimed::Made(created) => (created, false), - // Someone assigned this pair first — their row is the answer, and - // the charges below are keyed the same, so continuing here can only - // *complete* the billing. Their claim already counts this row. - Claimed::Duplicate => (Self::require(&id, db).await?, true), - // The counter is uncapped, so the only miss is a plan that is gone. - Claimed::Full => return Err(AppError::NotFound), - }; - // Frozen as of the claim above: no edit can land past it any more. - let plan = FeePlan::read(plan.get_id(), db) - .await? - .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; - for (index, installment) in plan.get_installments().iter().enumerate() { - payment_ledger::charge_for_installment( - db, - &assignment, - index + 1, - installment, - assigned_by, - ) - .await?; - } - Ok((assignment, existed)) - } - - async fn require( - id: &FeePlanAssignmentId, - db: &Database, - ) -> Result { - Self::read(id, db) - .await? - .ok_or_else(|| AppError::Internal("failed to assign the fee plan".into())) - } - - pub async fn read( - id: &FeePlanAssignmentId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Who is on this plan, newest first. - pub async fn list_for_plan( - plan: &FeePlanId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "fee_plan_assignment WHERE plan = $plan", - "ORDER BY created_at DESC, id DESC", - ) - .bind("plan", plan.record()) - .run(limit, offset, db) - .await - } - - /// Is anybody on this plan? A scan, and no longer a guard: the edit and - /// delete guards read the plan's own refcount, which no concurrent assign - /// can be behind. Kept because a *test* asserting the rows and the counter - /// agree is the only thing that would catch the counter drifting. - pub async fn exists_for_plan(plan: &FeePlanId, db: &Database) -> Result { - let mut result = db - .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") - .bind(("plan", plan.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) - } - - /// Which plans a student is on — one student may hold several. - pub async fn list_for_student( - student: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "fee_plan_assignment WHERE student = $student", - "ORDER BY created_at DESC, id DESC", - ) - .bind("student", student.record()) - .run(limit, offset, db) - .await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::domain::fee_plan::{FeePlanName, Installment}; - use crate::domain::payment_ledger::{LedgerAmount, PaymentLedgerKind}; - - /// The invariant the whole module exists for: assigning bills every - /// installment once, and assigning *again* bills nothing — the second call - /// must not double a family's debt. - #[tokio::test] - async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { - let db = crate::database::init_mem().await.unwrap(); - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key("stu1"); - let plan = FeePlan::create( - FeePlanName::try_new("Yearly").unwrap(), - vec![ - Installment::new( - LedgerAmount::try_new(150_000).unwrap(), - Timestamp::from_millis(1_000), - ), - Installment::new( - LedgerAmount::try_new(250_000).unwrap(), - Timestamp::from_millis(2_000), - ), - ], - &manager, - &db, - ) - .await - .unwrap(); - - let (_, existed) = FeePlanAssignment::assign(&plan, &student, &manager, &db) - .await - .unwrap(); - assert!(!existed); - assert_eq!( - payment_ledger::balance_of(&db, &student).await.unwrap(), - -400_000, - "both installments must be owed" - ); - - let (_, existed) = FeePlanAssignment::assign(&plan, &student, &manager, &db) - .await - .unwrap(); - assert!( - existed, - "the second assign is a replay, not a new placement" - ); - let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) - .await - .unwrap(); - assert_eq!(lines.len(), 2, "a replay may not append a single line"); - assert!( - lines - .iter() - .all(|l| l.get_kind() == PaymentLedgerKind::Charge) - ); - assert_eq!( - payment_ledger::balance_of(&db, &student).await.unwrap(), - -400_000 - ); - assert!( - FeePlanAssignment::exists_for_plan(plan.get_id(), &db) - .await - .unwrap() - ); - } - - /// The race the refcount exists for: an edit and an assign, both licensed - /// by the same instant. - /// - /// "Neither lands" is *not* the invariant — the two are legal in one order - /// (edit, then assign the edited plan) and illegal in the other. What may - /// never happen is the money and the plan disagreeing: the charges raised - /// must be copies of the schedule the plan actually ends up carrying, and - /// once anybody is on the plan no further edit or delete may land at all. - /// - /// Asserted against the **stored** state, never against which call returned - /// `Ok`: a winner's word is not evidence about what the store kept. - /// The one thing the *returned* values are good for is the second - /// invariant: neither racer may answer 500. Losing a single-record round to - /// a rival is the ordinary way this guard works, and the loser's recovery is - /// to re-send, not to fail the request. - /// - /// Multi-threaded on purpose: on the single-threaded runtime the two tasks - /// interleave only at await points and the store never reports a conflict at - /// all, which is how a version of this test watched a 45-in-50 500 rate and - /// passed. - /// - /// Real server, and `#[ignore]`d rather than falling back to `init_mem`: - /// the embedded engine drops one of two concurrent writes to a record and - /// answers `Ok` to both, which fails this very assertion out of nowhere - /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in - /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { - let (db, _serialized) = crate::database::init_test_server("edit_race").await; - let mut reached = 0; - for round in 0..20 { - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key(&format!("stu{round}")); - let plan = FeePlan::create( - FeePlanName::try_new("Yearly").unwrap(), - vec![Installment::new( - LedgerAmount::try_new(100).unwrap(), - Timestamp::from_millis(1_000), - )], - &manager, - &db, - ) - .await - .unwrap(); - - let edit = { - let (plan, db) = (plan.clone(), db.clone()); - tokio::spawn(async move { - plan.update( - None, - Some(vec![Installment::new( - LedgerAmount::try_new(999).unwrap(), - Timestamp::from_millis(2_000), - )]), - &db, - ) - .await - }) - }; - let assign = { - let (plan, db, manager, student) = - (plan.clone(), db.clone(), manager.clone(), student.clone()); - tokio::spawn(async move { - FeePlanAssignment::assign(&plan, &student, &manager, &db).await - }) - }; - let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap()); - assert!( - !matches!(edit, Err(AppError::Db(_))), - "a raced edit must be refused, not 500: {edit:?}" - ); - assert!( - !matches!(assign, Err(AppError::Db(_))), - "a raced assign must retry, not 500: {assign:?}" - ); - - let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); - let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) - .await - .unwrap(); - if assigned { - reached += 1; - // The counter is what refuses every later edit, so it has to - // agree with the rows it stands for. - let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) - .await - .unwrap(); - assert_eq!(lines.len(), 1, "one installment, one charge"); - assert_eq!( - lines[0].get_amount_minor().as_minor(), - stored.get_installments()[0].get_amount_minor().as_minor(), - "the charge must be a copy of the plan as it now stands" - ); - assert!( - plan.clone().update(None, None, &db).await.is_ok(), - "an empty PATCH writes nothing, so it is not refused" - ); - assert!( - matches!( - plan.clone() - .update(Some(FeePlanName::try_new("Nope").unwrap()), None, &db) - .await, - Err(AppError::Conflict(_)) - ), - "an assigned plan stays frozen afterwards" - ); - assert!( - !plan.clone().delete(&db).await.unwrap(), - "and it cannot be deleted either" - ); - } - } - // Every assertion above sits behind "the assign landed", so a run where - // it never did asserts nothing at all — the failure this counter turns - // into a loud one. - assert!(reached > 0, "no round ever placed the assignment"); - } - - /// The other half, and here "never both" *is* the invariant: a delete and - /// an assign racing must never leave a live assignment — with the charges - /// it billed — pointing at a plan that is gone. Stored state again, and a - /// real server again, for the same reasons. - /// - /// Both orderings are forced, because the interesting one does not happen on - /// its own: with both racers released together the assign wins ~24 rounds in - /// 25, so a run that only ever saw that ordering never tested a delete - /// landing first at all. Half the rounds therefore hold the assign back by a - /// beat, and the two counters below fail the test if either ordering went - /// unseen. Neither racer may answer 500 here either — this is the pair that - /// contends hardest, both writing the plan record itself. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_delete_racing_an_assign_never_orphans_an_assignment() { - let (db, _serialized) = crate::database::init_test_server("delete_race").await; - let (mut deleted_first, mut assigned_first) = (0, 0); - for round in 0..20 { - let hold_back_the_assign = round % 2 == 0; - let manager = UserId::from_key("mgr1"); - let student = UserId::from_key(&format!("stu{round}")); - let plan = FeePlan::create( - FeePlanName::try_new("Yearly").unwrap(), - vec![Installment::new( - LedgerAmount::try_new(100).unwrap(), - Timestamp::from_millis(1_000), - )], - &manager, - &db, - ) - .await - .unwrap(); - - let head_start = std::time::Duration::from_millis(5); - let drop_it = { - let (plan, db) = (plan.clone(), db.clone()); - tokio::spawn(async move { - if !hold_back_the_assign { - tokio::time::sleep(head_start).await; - } - plan.delete(&db).await - }) - }; - let assign = { - let (plan, db, manager, student) = - (plan.clone(), db.clone(), manager.clone(), student.clone()); - tokio::spawn(async move { - if hold_back_the_assign { - tokio::time::sleep(head_start).await; - } - FeePlanAssignment::assign(&plan, &student, &manager, &db).await - }) - }; - let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap()); - assert!( - !matches!(drop_it, Err(AppError::Db(_))), - "a raced delete must retry, not 500: {drop_it:?}" - ); - assert!( - !matches!(assign, Err(AppError::Db(_))), - "a raced assign must retry, not 500: {assign:?}" - ); - - let gone = FeePlan::read(plan.get_id(), &db).await.unwrap().is_none(); - let assigned = FeePlanAssignment::exists_for_plan(plan.get_id(), &db) - .await - .unwrap(); - deleted_first += usize::from(gone); - assigned_first += usize::from(assigned); - assert!( - !(gone && assigned), - "an assignment may not outlive the plan it names" - ); - let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) - .await - .unwrap(); - assert!( - !(gone && !lines.is_empty()), - "and neither may the charges it raised" - ); - } - // The premise, not a nicety: "never both" is trivially true in a run - // where one of the two never landed, so a run that only saw one - // ordering has proven nothing and says so. - assert!(deleted_first > 0, "no round ever let the delete land first"); - assert!( - assigned_first > 0, - "no round ever let the assign land first" - ); - } } diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index e14b312..0d90b6d 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -1,17 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, - SESSION_ATTENDANCE_TABLE, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::page::PagedList; +use crate::constant::SESSION_ATTENDANCE_TABLE; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; -use crate::domain::course_session::{CourseSession, CourseSessionId}; -use crate::domain::timestamp::Timestamp; +use crate::domain::course_session::CourseSessionId; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct SessionAttendanceId(RecordId); @@ -52,7 +45,7 @@ impl SessionAttendanceId { /// drops one of the core four, so `present` and `late` can never be renamed /// away. The SQL below repeats them — they are one rule in two languages, and /// the transition test is what pins them together. -fn counts_as_attended(status: &AttendanceStatus) -> bool { +pub(crate) fn counts_as_attended(status: &AttendanceStatus) -> bool { matches!(status.as_str(), "present" | "late") } @@ -61,12 +54,12 @@ fn counts_as_attended(status: &AttendanceStatus) -> bool { /// (`WHERE user = $u`) with no join. #[derive(Debug, Clone, SurrealValue)] pub struct SessionAttendance { - id: SessionAttendanceId, - session: CourseSessionId, - course: CourseId, - user: UserId, - status: AttendanceStatus, - marked_by: UserId, + pub(crate) id: SessionAttendanceId, + pub(crate) session: CourseSessionId, + pub(crate) course: CourseId, + pub(crate) user: UserId, + pub(crate) status: AttendanceStatus, + pub(crate) marked_by: UserId, } impl SessionAttendance { @@ -93,697 +86,4 @@ impl SessionAttendance { pub fn get_marked_by(&self) -> &UserId { &self.marked_by } - - /// Record (or overwrite) `user`'s status for the session. One row per - /// (session, user), keyed by a deterministic composite id so this is a - /// single atomic UPSERT — concurrent marks converge on the one row. - /// - /// The "session still exists" gate rides in the same transaction as the - /// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the - /// caller's pre-flight read sits four round trips in front of this write, - /// so a delete landing in that gap used to leave a roll-call row on a - /// session that was gone — and that row was *unremovable*, its only delete - /// route 404ing on the vanished session while the attendance report went - /// on counting it. A deleted session reads NONE, which is falsy, so the - /// gate is written as an explicit `IS NONE` (see - /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the - /// session's `teacher` — required on every row, so NONE means "no row" just - /// as `id` did — because the counter below needs that teacher anyway, and - /// one read serves both. - /// - /// A read is not a claim, though: SurrealDB 3.2.3 conflict-checks write - /// sets, not read sets, so that gate alone only closes the *sequential* - /// order (delete committed, then the mark arrives). To make the two really - /// collide, this transaction also *writes* the session row, unconditionally - /// — the bump-and-restore of [`crate::domain::exam_answer::ExamAnswer::save`] - /// on the one column this write already owns, [`LESSON_COUNTED_AT_FIELD`]. - /// Unconditional is the whole point: the credit branch below writes that - /// column already, but it fires only for the first roll call of a lesson - /// that has begun, so a future-dated sheet and every re-mark of a counted - /// one touched nothing at all and committed happily beside - /// `DELETE /sessions/{id}`. Re-stating the value verbatim would not do - /// either — an `UPDATE` that leaves the document unchanged is elided and - /// never enters the write set — hence bump first, then either stamp - /// (credit branch) or put back exactly what was found, `NONE` included, so - /// the row is byte-identical and the once-per-lesson rule is untouched. - /// - /// Sound to re-send while the store answers "conflict, retry": the gate - /// reads the record a delete writes, so the two contend by design, and the - /// UPSERT cannot legitimately answer "already exists" — its composite id is - /// bijective with the `session_attendance_session_user` unique tuple, so - /// the index entry can only point at the row the id already names. - /// - /// Two badge counters move in this same transaction, both of them read - /// from the store rather than taken on the caller's word: - /// - /// - `lessons_attended_total`, on the person marked, as a *delta* rather - /// than an increment, because this is an upsert: a re-mark that changes - /// nothing must change nothing, and a teacher's correction must move it - /// back down. `$was` is read before the upsert overwrites it (`NONE` when - /// the pair has no row yet), so it writes only on a real crossing of the - /// attended line, and only for a **student** — attending lessons is a - /// student's badge, the same student-only rule enrolling and sitting an - /// exam already carry, so a teacher marked present in their own lesson - /// moves it in neither direction. The live `role` decides that, not the - /// role someone held when the row was written. - /// - `lessons_held_total`, on the *session's* teacher, exactly once per - /// session: the first roll call taken stamps - /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees - /// the stamp and credits nothing. It counts lessons that actually - /// happened — scheduling one and cancelling it earns nothing, which is - /// why the credit does not live in `crate::db::course_session::create`. Two - /// simultaneous first marks both write the lesson row, so the store's own - /// conflict detection (and `transaction_with_retry` behind it) is what - /// keeps the stamp from being set twice. - /// - /// "Actually happened" is a clock reading, not a request count: the - /// credit waits for the lesson's own `starts_at` to arrive. Roll call is - /// deliberately *not* time-gated — a teacher may open the sheet early and - /// is never refused — so without this a teacher could schedule two - /// hundred lessons for next week, mark one student in each, and hold two - /// hundred lessons this afternoon. Because the stamp is written only on - /// the branch that credits, a sheet opened early and touched again after - /// the bell still credits exactly once, then; a sheet never touched - /// again credits never, which is the deliberate cost of not storing a - /// promise the passage of time would have to redeem on its own. - /// - /// `lessons_attended_total` is *not* gated the same way, and the - /// asymmetry is on purpose: it is a delta off the row's stored status, - /// which carries no record of whether the credit was ever taken, so a - /// gate would refund at the correction what the early mark never - /// credited — a student's real lessons eaten by someone else's farm. It - /// is also nobody's self-service: only a teacher can mark a student, so - /// the counter cannot be moved by the person it decorates. - /// - /// Both are floored/guarded rather than trusting the column to exist: a row - /// written before these columns carries none of them. - // - // corner-cut: that asymmetry leaves a teacher able to inflate a *student's* - // attendance with future-dated lessons. Closing it needs the credit stamped - // on the roll-call row itself and refunded off that stamp — the same column - // the live-role note on `remove` below wants, and the shape - // `counted_on_time` already uses for homework. One column closes both; - // neither is worth it until a real complaint names one. - pub async fn mark( - session: &CourseSession, - user: &UserId, - status: AttendanceStatus, - marked_by: &UserId, - db: &Database, - ) -> Result { - let attended = counts_as_attended(&status); - let delta: i64 = if attended { 1 } else { -1 }; - let attendance = SessionAttendance { - id: SessionAttendanceId::composite(session.get_id(), user), - session: session.get_id().clone(), - course: session.get_course().clone(), - user: user.clone(), - status, - marked_by: marked_by.clone(), - }; - let (mut written, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $teacher = (SELECT VALUE teacher FROM ONLY $sess); - IF $teacher IS NONE {{ THROW 'session_missing' }}; - LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess); - LET $begun = ((SELECT VALUE starts_at FROM ONLY $sess) <= $stamp); - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']); - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - IF $student AND $was != $now {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) - }}; - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = ({LESSON_COUNTED_AT_FIELD} ?? 0) + 1; - IF ($counted IS NONE) AND $begun {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; - UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = - ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 - }} ELSE {{ - UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $counted - }}; - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - // `$session` is SurrealDB's own protected variable (the auth - // session): binding that name errors the whole query. - ("sess".into(), session.get_id().record().into_value()), - ("id".into(), attendance.id.record().into_value()), - ("usr".into(), user.record().into_value()), - ("now".into(), attended.into_value()), - ("delta".into(), delta.into_value()), - ("stamp".into(), Timestamp::now().into_value()), - ("row".into(), attendance.into_value()), - ], - &["session_missing"], - ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker, so a refusal is read by marker while a lost - // round was already re-sent — never reported as a 500. - if errors - .values() - .any(|error| error.to_string().contains("session_missing")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count instead of a hand-kept one. - let slot = written.num_statements().saturating_sub(2); - written - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) - } - - pub async fn list_for_session( - session: &CourseSessionId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new("session_attendance WHERE session = $s", "ORDER BY id DESC") - .bind("s", session.record()) - .run(limit, offset, db) - .await - } - - /// Every roll-call row ever recorded for `user` — the session half of the - /// attendance report. Deliberately not filtered by current enrollment: - /// attendance is a historical record, so unenrolling hides marks (report - /// semantics) but never absences. - pub async fn list_for_user( - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Clearing a row the student was counted for gives the count back, in the - /// delete's own transaction — the other direction of the delta in - /// [`SessionAttendance::mark`], so a row that never existed and a row that - /// was withdrawn leave the same number behind. Only *this* route decrements: - /// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of - /// its own and never comes through here, which is the ruling - /// `exam_sat_total` already carries — deleting the lesson does not un-attend - /// it. `lessons_held_total` is never given back either: the lesson was - /// taken, and clearing one student's row does not un-take it. - /// - /// Student-only on the same terms as the mark, and read from the store for - /// the same reason. - /// - /// Sound to re-send: neither statement can answer "already exists". - // - // corner-cut: both ends read the *live* role, so a student promoted between - // being marked present and having that row corrected leaves the counter one - // high (the credit landed as a student, the refund is refused as staff). - // Upgrade path is stamping the credit on the roll-call row itself and - // refunding off that stamp, the way `counted_on_time` works for homework — - // not worth a column until a promotion mid-term is a real complaint. - pub async fn remove( - session: &CourseSessionId, - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); - LET $gone = (DELETE session_attendance - WHERE session = $s AND user = $usr RETURN BEFORE); - IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{ - UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = - math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0]) - }}; - RETURN $gone; - COMMIT TRANSACTION;" - ), - &[ - ("s".into(), session.record().into_value()), - ("usr".into(), user.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - Ok(result - .take::>(slot)? - .into_iter() - .next()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::constant::DEFAULT_ATTENDANCE_STATUSES; - use crate::database::init_mem; - use crate::domain::course_session::SessionTopic; - use crate::domain::role::Role; - - /// A user row carrying its role — the counters are `UPDATE`s on one (which - /// writes nothing at all to a record that does not exist), and the live - /// role is what decides whether the attended counter moves. - async fn a_user(key: &str, role: Role, db: &Database) -> UserId { - let user = UserId::from_key(key); - db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role") - .bind(("usr", user.record())) - .bind(("name", key.to_string())) - .bind(("role", role)) - .await - .unwrap() - .check() - .unwrap(); - user - } - - async fn a_student(key: &str, db: &Database) -> UserId { - a_user(key, Role::Student, db).await - } - - async fn a_teacher(key: &str, db: &Database) -> UserId { - a_user(key, Role::Teacher, db).await - } - - async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { - crate::db::course_session::create( - db, - &crate::db::course::a_test_course(db).await, - teacher, - SessionTopic::try_new("limits").unwrap(), - Timestamp::from_millis(starts_at), - None, - ) - .await - .unwrap() - } - - /// A lesson long since begun — every test but the gate's own wants one. - async fn a_session(teacher: &UserId, db: &Database) -> CourseSession { - a_session_at(teacher, 1, db).await - } - - /// A status this school allows — the four core ones plus a school-added - /// `online`, which is exactly the open half of the set. - fn status(value: &str) -> AttendanceStatus { - let allowed: Vec = DEFAULT_ATTENDANCE_STATUSES - .iter() - .map(|s| s.to_string()) - .chain(["online".to_string()]) - .collect(); - AttendanceStatus::try_new(value, &allowed).unwrap() - } - - /// The two counters as the badge rules read them, off the stored row. - async fn attended(user: &UserId, db: &Database) -> i64 { - crate::db::badge::load(db, user) - .await - .unwrap() - .get_lessons_attended() - } - - async fn held(user: &UserId, db: &Database) -> i64 { - crate::db::badge::load(db, user) - .await - .unwrap() - .get_lessons_held() - } - - /// The whole transition table in one pass: an upsert may only move the - /// counter when the mark crosses the attended line, in either direction, so - /// a re-mark and a swap within the same class are both no-ops. - #[tokio::test] - async fn the_counter_follows_every_crossing_and_no_other_move() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - let session = a_session(&teacher, &db).await; - let mark = async |value: &str, db: &Database| { - SessionAttendance::mark(&session, &student, status(value), &teacher, db) - .await - .unwrap(); - }; - - for (value, expected, why) in [ - ("present", 1, "first mark counts"), - ("present", 1, "re-marking the same status changes nothing"), - ("late", 1, "late is attending too, so no crossing"), - ("absent", 0, "a correction gives the count back"), - ("absent", 0, "and does not keep giving it back"), - ("late", 1, "absent -> late crosses back up"), - ("excused", 0, "excused is neutral: a crossing down"), - ("online", 0, "a school-added status stays neutral"), - ("present", 1, "…and crossing up from one still counts"), - ("online", 0, "…as does crossing down to one"), - ] { - mark(value, &db).await; - assert_eq!(attended(&student, &db).await, expected, "{why}"); - } - assert_eq!(attended(&teacher, &db).await, 0, "credited the marker"); - // Ten marks, one lesson: correcting a roll call is not holding another. - assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice"); - } - - /// The lesson is credited to its teacher when the roll call is *taken*, and - /// once: the whole roster, and every later correction, ride the same stamp. - #[tokio::test] - async fn the_first_roll_call_counts_the_lesson_once() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let other = a_teacher("o", &db).await; - let session = a_session(&teacher, &db).await; - assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing"); - - for key in ["s1", "s2", "s3"] { - let student = a_student(key, &db).await; - SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) - .await - .unwrap(); - assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again"); - } - assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher"); - - // A second lesson is a second count — the stamp is per session. - let second = a_session(&teacher, &db).await; - let student = a_student("s4", &db).await; - SessionAttendance::mark(&second, &student, status("present"), &teacher, &db) - .await - .unwrap(); - assert_eq!(held(&teacher, &db).await, 2); - } - - /// A lesson is held when its own time comes, not when the sheet is opened. - /// Roll call is never refused early, so ungated a teacher could schedule - /// two hundred lessons for next week and hold all of them this afternoon. - #[tokio::test] - async fn a_lesson_that_has_not_started_holds_nothing_yet() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - let next_week = - a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await; - - SessionAttendance::mark(&next_week, &student, status("present"), &teacher, &db) - .await - .unwrap(); - assert_eq!(held(&teacher, &db).await, 0, "next week's lesson, today"); - // The mark itself stands — opening the sheet early is not an error. - assert_eq!(attended(&student, &db).await, 1); - - // The bell rings. The same sheet, touched again, credits now — and - // only once: nothing backfills, so the stamp is the whole guard. - db.query("UPDATE $sess SET starts_at = 1") - .bind(("sess", next_week.get_id().record())) - .await - .unwrap() - .check() - .unwrap(); - for (status_value, why) in [("late", "the bell rang"), ("present", "held twice")] { - SessionAttendance::mark(&next_week, &student, status(status_value), &teacher, &db) - .await - .unwrap(); - assert_eq!(held(&teacher, &db).await, 1, "{why}"); - } - } - - /// Attending lessons is a student's badge. A teacher marked present in - /// their own lesson (which management does, not the teacher) moves nothing - /// for them as an attendee — while the roll call itself still counts as a - /// lesson held. - #[tokio::test] - async fn a_teacher_marked_present_earns_nothing_for_attending() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let session = a_session(&teacher, &db).await; - - SessionAttendance::mark(&session, &teacher, status("present"), &teacher, &db) - .await - .unwrap(); - assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson"); - assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken"); - - // And the correction direction is just as closed: nothing was taken, so - // nothing may be given back. - SessionAttendance::mark(&session, &teacher, status("absent"), &teacher, &db) - .await - .unwrap(); - assert_eq!(attended(&teacher, &db).await, 0); - SessionAttendance::remove(session.get_id(), &teacher, &db) - .await - .unwrap() - .expect("the row was there"); - assert_eq!(attended(&teacher, &db).await, 0); - assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened"); - } - - /// Two lessons are two counts — the counter is per row, not per student. - #[tokio::test] - async fn each_lesson_counts_once_for_the_student_marked() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - let other = a_student("o", &db).await; - for _ in 0..2 { - let session = a_session(&teacher, &db).await; - SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) - .await - .unwrap(); - } - assert_eq!(attended(&student, &db).await, 2); - assert_eq!(attended(&other, &db).await, 0, "credited the wrong student"); - } - - /// Removing the row is the other direction of the delta, and only for a row - /// that was counted. - #[tokio::test] - async fn removing_a_row_gives_back_only_what_it_took() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - - let counted = a_session(&teacher, &db).await; - SessionAttendance::mark(&counted, &student, status("present"), &teacher, &db) - .await - .unwrap(); - let neutral = a_session(&teacher, &db).await; - SessionAttendance::mark(&neutral, &student, status("absent"), &teacher, &db) - .await - .unwrap(); - assert_eq!(attended(&student, &db).await, 1); - - SessionAttendance::remove(neutral.get_id(), &student, &db) - .await - .unwrap() - .expect("the absent row was there"); - assert_eq!(attended(&student, &db).await, 1, "absent took nothing"); - SessionAttendance::remove(counted.get_id(), &student, &db) - .await - .unwrap() - .expect("the present row was there"); - assert_eq!(attended(&student, &db).await, 0); - assert!( - SessionAttendance::remove(counted.get_id(), &student, &db) - .await - .unwrap() - .is_none(), - "nothing left to remove" - ); - assert_eq!(attended(&student, &db).await, 0, "and nothing to give back"); - assert_eq!( - held(&teacher, &db).await, - 2, - "clearing a row un-held a lesson" - ); - } - - /// The floor: however the corrections and removals interleave, and whatever - /// a stale row starts from, the counter never goes negative. - #[tokio::test] - async fn the_counter_never_goes_below_zero() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - - // Ten counted lessons whose counter was never credited — the stale-data - // case, an account that predates the column. Every one of them is now - // corrected away, which is ten decrements against a zero. - let mut sessions = Vec::new(); - for _ in 0..10 { - let session = a_session(&teacher, &db).await; - SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) - .await - .unwrap(); - sessions.push(session); - } - db.query(format!( - "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0" - )) - .bind(("usr", student.record())) - .await - .unwrap() - .check() - .unwrap(); - - for session in &sessions { - SessionAttendance::mark(session, &student, status("absent"), &teacher, &db) - .await - .unwrap(); - SessionAttendance::remove(session.get_id(), &student, &db) - .await - .unwrap(); - assert!(attended(&student, &db).await >= 0); - } - assert_eq!(attended(&student, &db).await, 0, "floored, never negative"); - } - - /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own - /// — it never reaches [`SessionAttendance::remove`] — so the count stands, - /// the ruling every other counter here carries. - #[tokio::test] - async fn deleting_the_session_leaves_the_counters_alone() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - let session = a_session(&teacher, &db).await; - SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) - .await - .unwrap(); - - crate::db::course_session::delete(&db, session) - .await - .unwrap(); - assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); - assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); - } - - /// A mark on a session that is already gone is refused, so it cannot leave - /// a count behind either. - #[tokio::test] - async fn a_refused_mark_moves_nothing() { - let db = init_mem().await.unwrap(); - let teacher = a_teacher("t", &db).await; - let student = a_student("s", &db).await; - let session = a_session(&teacher, &db).await; - let ghost = session.clone(); - crate::db::course_session::delete(&db, session) - .await - .unwrap(); - - assert!(matches!( - SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await, - Err(AppError::NotFound) - )); - assert_eq!(attended(&student, &db).await, 0); - assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); - } - - /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` - /// on `course_session` fires inside the delete's own transaction, and - /// [`crate::db::course_session::delete`] sweeps its children before removing the row, - /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is - /// written after the sweep has run, and used to commit straight past it. - /// - /// The two flavors raced are the ones the credit branch never wrote for — a - /// lesson that has not begun, and a student with no row yet on a lesson - /// already counted. A re-mark of a row that *exists* was never in danger: - /// the cascade and the upsert write that child's own key and collide there. - /// - /// Real server, and `#[ignore]`d for it: the subject is the store's - /// conflict detection, which [`init_mem`]'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, so this passes there on - /// broken code. Mutation-tested: dropping the unconditional - /// `UPDATE $sess` from `mark` turns it red. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_mark_written_inside_a_delete_never_outlives_the_session() { - let (db, _serialized) = crate::database::init_test_server("session_attendance_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE course_session WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let teacher = a_teacher("t", &db).await; - let (mut swept, mut orphans) = (0, 0); - for (round, already_counted) in [false, true, false, true].into_iter().enumerate() { - let session = if already_counted { - // Counted by somebody else's mark, so this one credits nothing. - let session = a_session(&teacher, &db).await; - let first = a_student(&format!("f{round}"), &db).await; - SessionAttendance::mark(&session, &first, status("present"), &teacher, &db) - .await - .unwrap(); - session - } else { - a_session_at(&teacher, Timestamp::now().as_millis() + 604_800_000, &db).await - }; - let id = session.get_id().clone(); - let ghost = session.clone(); - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { crate::db::course_session::delete(&db, session).await }) - }; - // The mark starts inside the held window: the sweep has run and the - // session row is gone but uncommitted — which is exactly what a - // read of that session still believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let marked = { - let (db, teacher) = (db.clone(), teacher.clone()); - let student = a_student(&format!("s{round}"), &db).await; - tokio::spawn(async move { - SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db) - .await - }) - }; - let (drop_it, marked) = (drop_it.await.unwrap(), marked.await.unwrap()); - assert!( - !matches!(marked, Err(AppError::Db(_))), - "round {round}: a raced mark must be answered, not 500: {marked:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if crate::db::course_session::read(&db, &id) - .await - .unwrap() - .is_none() - { - swept += 1; - orphans += SessionAttendance::list_for_session(&id, None, 0, &db) - .await - .unwrap() - .0 - .len(); - } else if drop_it.is_ok() { - panic!("round {round}: the delete reported success but the session is still there"); - } - } - eprintln!( - "CourseSession::delete raced by a roll call: {swept}/4 rounds deleted the session" - ); - assert!( - swept > 0, - "no round ever deleted the session, so the window was never reached" - ); - assert_eq!(orphans, 0, "a roll call outlived its session"); - } } diff --git a/src/service/attendance.rs b/src/service/attendance.rs new file mode 100644 index 0000000..82a4118 --- /dev/null +++ b/src/service/attendance.rs @@ -0,0 +1,48 @@ +//! Event roll-call doors for the web layer. The mark is one atomic +//! transaction whose existence gate rides inside the write +//! ([`crate::db::attendance::mark`]), so this module is thin +//! pass-throughs; the event's audience gate is judged by the web layer +//! against the event it already read. + +use crate::database::Database; +use crate::db::attendance; +use crate::domain::attendance::{Attendance, AttendanceStatus}; +use crate::domain::event::EventId; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Record (or overwrite) `user`'s status for `event`. +pub async fn mark( + db: &Database, + event: &EventId, + user: &UserId, + status: AttendanceStatus, + marked_by: &UserId, +) -> Result { + attendance::mark(db, event, user, status, marked_by).await +} + +/// A page of the event's roll call, newest id first. +pub async fn list_for_event( + db: &Database, + event: &EventId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + attendance::list_for_event(db, event, limit, offset).await +} + +/// Every event-attendance row recorded for `user` — the events half of the +/// attendance report. +pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { + attendance::list_for_user(db, user).await +} + +/// Clear one row; `None` = there was none. +pub async fn remove( + db: &Database, + event: &EventId, + user: &UserId, +) -> Result, AppError> { + attendance::remove(db, event, user).await +} diff --git a/src/service/fee_plan.rs b/src/service/fee_plan.rs new file mode 100644 index 0000000..89d781b --- /dev/null +++ b/src/service/fee_plan.rs @@ -0,0 +1,53 @@ +//! Fee-plan doors for the web layer. Every write here is a single guarded +//! statement in [`crate::db::fee_plan`] — the assigned-plan freeze is the +//! store's own, decided as the write lands — so this module is thin +//! pass-throughs; the manager+ gate is the web layer's extractor. + +use crate::database::Database; +use crate::db::fee_plan; +use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment}; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Write a fee plan: a name and the installments it is paid in. Creating one +/// bills nobody — assigning it does. +pub async fn create( + db: &Database, + name: FeePlanName, + installments: Vec, + created_by: &UserId, +) -> Result { + fee_plan::create(db, name, installments, created_by).await +} + +/// The plan, for callers that only inspect it. +pub async fn read(db: &Database, id: &FeePlanId) -> Result, AppError> { + fee_plan::read(db, id).await +} + +/// Every plan, newest first. +pub async fn list_all( + db: &Database, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + fee_plan::list_all(db, limit, offset).await +} + +/// Edit a plan's name and/or schedule. `Err(Conflict)` = refused, nothing was +/// written: somebody is already on the plan (and `Err(NotFound)` = the plan +/// is gone, so the refusal is not "assigned" but "deleted"). +pub async fn update( + db: &Database, + plan: FeePlan, + name: Option, + installments: Option>, +) -> Result { + fee_plan::update(db, plan, name, installments).await +} + +/// Delete the plan while nobody is on it. `false` = refused: somebody is on +/// it, and a school's financial history keeps its references. +pub async fn delete(db: &Database, plan: FeePlan) -> Result { + fee_plan::delete(db, plan).await +} diff --git a/src/service/fee_plan_assignment.rs b/src/service/fee_plan_assignment.rs new file mode 100644 index 0000000..4a4f725 --- /dev/null +++ b/src/service/fee_plan_assignment.rs @@ -0,0 +1,507 @@ +//! The assign workflow: placing a plan on a student and billing it — the +//! moment the plan becomes money owed — plus the batch loop and the bounds +//! one assign request may carry. The queries live in +//! [`crate::db::fee_plan_assignment`]; the ledger appends in +//! [`crate::db::payment_ledger`]. +//! +//! The row is keyed `_`, and every charge it raises is keyed +//! from that same key plus the installment number, so the whole operation is +//! idempotent **by identity**: assigning twice writes nothing the second time, +//! however the two requests interleave, and an assign cut short after three of +//! twelve charges landed completes itself when it is repeated. No scan decides +//! "has this been billed yet?" — a scan can be slipped past by a concurrent +//! writer, and the cost of that mistake here is a double-billed family. + +use crate::constant::{ + FEE_PLAN_ASSIGNMENT_COUNT_FIELD, MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES, +}; +use crate::database::Database; +use crate::db::cap::{self, Claimed}; +use crate::db::{fee_plan, fee_plan_assignment, payment_ledger}; +use crate::domain::fee_plan::FeePlan; +use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId}; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// Place `plan` on `student` and bill it. Returns the assignment and +/// whether it was *already* there, so the web layer can answer a replay +/// honestly instead of pretending it just happened. +/// +/// The row and the plan's assignment refcount are written in **one** +/// transaction ([`cap::claim_and_create`]): that increment is what makes the +/// plan un-editable and un-deletable, and it has to be indivisible from the +/// row it counts, or an edit could slip between the two. A plan the counter +/// cannot be claimed on is one a concurrent delete already removed, which is +/// the same `404` the handler's own lookup would have given. +/// +/// The installments are then re-read **from the stored plan**, not taken +/// from the caller's snapshot: the claim is the moment the plan freezes, and +/// an edit that landed between the handler's read and that claim is +/// legitimate. Billing the snapshot would raise charges from a schedule the +/// plan no longer shows — precisely the divergence the 409 exists to +/// prevent. +/// +/// The charges are appended after the row, never before: each one is keyed +/// by (assignment, installment number), so this loop is safe to re-enter +/// from the top — which is exactly what a repeated assign does, and the +/// only way a half-written assignment ever gets its missing lines. +pub async fn assign( + db: &Database, + plan: &FeePlan, + student: &UserId, + assigned_by: &UserId, +) -> Result<(FeePlanAssignment, bool), AppError> { + let id = FeePlanAssignmentId::composite(plan.get_id(), student); + let row = FeePlanAssignment { + id: id.clone(), + plan: plan.get_id().clone(), + student: student.clone(), + assigned_by: assigned_by.clone(), + created_at: Timestamp::now(), + }; + let claimed = cap::claim_and_create( + &plan.get_id().record(), + FEE_PLAN_ASSIGNMENT_COUNT_FIELD, + cap::UNLIMITED, + &id.record(), + &row, + db, + ) + .await?; + let (assignment, existed) = match claimed { + Claimed::Made(created) => (created, false), + // Someone assigned this pair first — their row is the answer, and + // the charges below are keyed the same, so continuing here can only + // *complete* the billing. Their claim already counts this row. + Claimed::Duplicate => (require(&id, db).await?, true), + // The counter is uncapped, so the only miss is a plan that is gone. + Claimed::Full => return Err(AppError::NotFound), + }; + // Frozen as of the claim above: no edit can land past it any more. + let plan = fee_plan::read(db, plan.get_id()) + .await? + .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; + for (index, installment) in plan.get_installments().iter().enumerate() { + payment_ledger::charge_for_installment( + db, + &assignment, + index + 1, + installment, + assigned_by, + ) + .await?; + } + Ok((assignment, existed)) +} + +async fn require(id: &FeePlanAssignmentId, db: &Database) -> Result { + fee_plan_assignment::read(db, id) + .await? + .ok_or_else(|| AppError::Internal("failed to assign the fee plan".into())) +} + +/// What one student in an assign batch came to. The web layer spells these +/// as its response statuses. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// Placed and billed now. + Assigned, + /// A replay: the student was already on this plan, nothing billed again. + AlreadyAssigned, + /// Refused for this student alone — the batch carries on. + Rejected(&'static str), +} + +/// Place one plan on a batch of students, which is what turns it into money +/// owed: every installment is appended as a charge line right away, each with +/// its own due date. Returns one outcome per student, in the order sent. +/// +/// Only students carry a fee record, so any other target is rejected. One bad +/// id never loses the rest of the batch: the outcome reports each student +/// separately. +/// +/// Placing the first student **freezes** the plan: it can no longer be edited +/// or deleted. The installments billed are read back from the stored plan at +/// that instant, so an edit that landed a moment earlier is the one billed, +/// never the version this request first looked at. A plan deleted while the +/// batch is running is `Rejected` from that student on — a per-student +/// outcome like any other, so the students it already billed stay in the +/// report. +/// +/// One request is bounded by the **charges it would raise**, not by the head +/// count alone: `student_ids × installments` may not exceed 3 000 (200 +/// students up to a 15-installment plan; 50 at a time on a 60-installment +/// one). Past that the whole call is a `400` telling the caller to split the +/// batch — nothing is written, because a money route that billed half a batch +/// and gave up would leave a bursar guessing which families were charged. +pub async fn assign_batch( + db: &Database, + plan_key: &str, + assigner: &UserId, + student_ids: Vec, +) -> Result, AppError> { + if student_ids.len() > MAX_FEE_PLAN_ASSIGN_STUDENTS { + return Err(AppError::Validation(ValidationError::Invalid { + field: "student_ids", + reason: "may name at most 200 students", + })); + } + let plan = fee_plan::read(db, &crate::domain::fee_plan::FeePlanId::from_key(plan_key)) + .await? + .ok_or(AppError::NotFound)?; + // The student cap alone cannot see the schedule: every student named + // appends *every* installment, so what really bounds this request is the + // product. Refused whole and before anything is written — a batch this API + // billed only part of would leave a bursar guessing which families were + // charged. + if student_ids + .len() + .saturating_mul(plan.get_installments().len()) + > MAX_FEE_PLAN_ASSIGN_WRITES + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "student_ids", + reason: "too many charges for one request: students × installments \ + may not exceed 3000, so split the batch", + })); + } + let mut outcomes = Vec::with_capacity(student_ids.len()); + for student_id in student_ids { + let student = UserId::from_key(&student_id); + // A fee record belongs to a student; billing anyone else is a typo, and + // a typo here is money against the wrong person. + let is_student = crate::db::user::read(db, &student) + .await? + .is_some_and(|user| user.get_role() == Role::Student); + let outcome = if is_student { + match assign(db, &plan, &student, assigner).await { + Ok((_, true)) => Outcome::AlreadyAssigned, + Ok((_, false)) => Outcome::Assigned, + // The plan was deleted mid-batch. That is a per-student outcome + // like any other, not a reason to throw away the report for the + // students this batch already billed — their charges are + // written and the caller has to be told about them. + Err(AppError::NotFound) => Outcome::Rejected("no such plan"), + Err(err) => return Err(err), + } + } else { + Outcome::Rejected("no such student") + }; + outcomes.push((student_id, outcome)); + } + Ok(outcomes) +} + +/// The placement, for callers that only inspect it. +pub async fn read( + db: &Database, + id: &FeePlanAssignmentId, +) -> Result, AppError> { + fee_plan_assignment::read(db, id).await +} + +/// Who is on this plan, newest first. +pub async fn list_for_plan( + db: &Database, + plan: &crate::domain::fee_plan::FeePlanId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + fee_plan_assignment::list_for_plan(db, plan, limit, offset).await +} + +/// Which plans a student is on. +pub async fn list_for_student( + db: &Database, + student: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + fee_plan_assignment::list_for_student(db, student, limit, offset).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::init_mem; + use crate::domain::fee_plan::{FeePlanName, Installment}; + use crate::domain::payment_ledger::LedgerAmount; + + async fn a_plan(db: &Database, installments: Vec) -> FeePlan { + fee_plan::create( + db, + FeePlanName::try_new("Yearly").unwrap(), + installments, + &UserId::from_key("mgr1"), + ) + .await + .unwrap() + } + + /// The invariant the whole module exists for: assigning bills every + /// installment once, and assigning *again* bills nothing — the second call + /// must not double a family's debt. + #[tokio::test] + async fn assigning_bills_every_installment_and_a_replay_bills_nothing() { + let db = init_mem().await.unwrap(); + let manager = UserId::from_key("mgr1"); + let student = UserId::from_key("stu1"); + let plan = a_plan( + &db, + vec![ + Installment::new( + LedgerAmount::try_new(150_000).unwrap(), + Timestamp::from_millis(1_000), + ), + Installment::new( + LedgerAmount::try_new(250_000).unwrap(), + Timestamp::from_millis(2_000), + ), + ], + ) + .await; + + let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap(); + assert!(!existed); + assert_eq!( + payment_ledger::balance_of(&db, &student).await.unwrap(), + -400_000, + "both installments must be owed" + ); + + let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap(); + assert!( + existed, + "the second assign is a replay, not a new placement" + ); + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) + .await + .unwrap(); + assert_eq!(lines.len(), 2, "a replay may not append a single line"); + assert!( + lines + .iter() + .all(|l| l.get_kind() == crate::domain::payment_ledger::PaymentLedgerKind::Charge) + ); + assert_eq!( + payment_ledger::balance_of(&db, &student).await.unwrap(), + -400_000 + ); + assert!( + fee_plan_assignment::exists_for_plan(&db, plan.get_id()) + .await + .unwrap() + ); + } + + /// The race the refcount exists for: an edit and an assign, both licensed + /// by the same instant. + /// + /// "Neither lands" is *not* the invariant — the two are legal in one order + /// (edit, then assign the edited plan) and illegal in the other. What may + /// never happen is the money and the plan disagreeing: the charges raised + /// must be copies of the schedule the plan actually ends up carrying, and + /// once anybody is on the plan no further edit or delete may land at all. + /// + /// Asserted against the **stored** state, never against which call returned + /// `Ok`: a winner's word is not evidence about what the store kept. + /// The one thing the *returned* values are good for is the second + /// invariant: neither racer may answer 500. Losing a single-record round to + /// a rival is the ordinary way this guard works, and the loser's recovery is + /// to re-send, not to fail the request. + /// + /// Multi-threaded on purpose: on the single-threaded runtime the two tasks + /// interleave only at await points and the store never reports a conflict at + /// all, which is how a version of this test watched a 45-in-50 500 rate and + /// passed. + /// + /// Real server, and `#[ignore]`d rather than falling back to `init_mem`: + /// the embedded engine drops one of two concurrent writes to a record and + /// answers `Ok` to both, which fails this very assertion out of nowhere + /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in + /// 10 000 rounds on the server). See [`crate::database::init_test_server`]. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() { + let (db, _serialized) = crate::database::init_test_server("edit_race").await; + let mut reached = 0; + for round in 0..20 { + let manager = UserId::from_key("mgr1"); + let student = UserId::from_key(&format!("stu{round}")); + let plan = a_plan( + &db, + vec![Installment::new( + LedgerAmount::try_new(100).unwrap(), + Timestamp::from_millis(1_000), + )], + ) + .await; + + let edit = { + let (plan, db) = (plan.clone(), db.clone()); + tokio::spawn(async move { + fee_plan::update( + &db, + plan, + None, + Some(vec![Installment::new( + LedgerAmount::try_new(999).unwrap(), + Timestamp::from_millis(2_000), + )]), + ) + .await + }) + }; + let assign = { + let (db, plan, manager, student) = + (db.clone(), plan.clone(), manager.clone(), student.clone()); + tokio::spawn(async move { assign(&db, &plan, &student, &manager).await }) + }; + let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap()); + assert!( + !matches!(edit, Err(AppError::Db(_))), + "a raced edit must be refused, not 500: {edit:?}" + ); + assert!( + !matches!(assign, Err(AppError::Db(_))), + "a raced assign must retry, not 500: {assign:?}" + ); + + let stored = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap(); + let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id()) + .await + .unwrap(); + if assigned { + reached += 1; + // The counter is what refuses every later edit, so it has to + // agree with the rows it stands for. + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) + .await + .unwrap(); + assert_eq!(lines.len(), 1, "one installment, one charge"); + assert_eq!( + lines[0].get_amount_minor().as_minor(), + stored.get_installments()[0].get_amount_minor().as_minor(), + "the charge must be a copy of the plan as it now stands" + ); + assert!( + fee_plan::update(&db, plan.clone(), None, None) + .await + .is_ok(), + "an empty PATCH writes nothing, so it is not refused" + ); + assert!( + matches!( + fee_plan::update( + &db, + plan.clone(), + Some(FeePlanName::try_new("Nope").unwrap()), + None + ) + .await, + Err(AppError::Conflict(_)) + ), + "an assigned plan stays frozen afterwards" + ); + assert!( + !fee_plan::delete(&db, plan.clone()).await.unwrap(), + "and it cannot be deleted either" + ); + } + } + // Every assertion above sits behind "the assign landed", so a run where + // it never did asserts nothing at all — the failure this counter turns + // into a loud one. + assert!(reached > 0, "no round ever placed the assignment"); + } + + /// The other half, and here "never both" *is* the invariant: a delete and + /// an assign racing must never leave a live assignment — with the charges + /// it billed — pointing at a plan that is gone. Stored state again, and a + /// real server again, for the same reasons. + /// + /// Both orderings are forced, because the interesting one does not happen on + /// its own: with both racers released together the assign wins ~24 rounds in + /// 25, so a run that only ever saw that ordering never tested a delete + /// landing first at all. Half the rounds therefore hold the assign back by a + /// beat, and the two counters below fail the test if either ordering went + /// unseen. Neither racer may answer 500 here either — this is the pair that + /// contends hardest, both writing the plan record itself. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_delete_racing_an_assign_never_orphans_an_assignment() { + let (db, _serialized) = crate::database::init_test_server("delete_race").await; + let (mut deleted_first, mut assigned_first) = (0, 0); + for round in 0..20 { + let hold_back_the_assign = round % 2 == 0; + let manager = UserId::from_key("mgr1"); + let student = UserId::from_key(&format!("stu{round}")); + let plan = a_plan( + &db, + vec![Installment::new( + LedgerAmount::try_new(100).unwrap(), + Timestamp::from_millis(1_000), + )], + ) + .await; + + let head_start = std::time::Duration::from_millis(5); + let drop_it = { + let (db, plan) = (db.clone(), plan.clone()); + tokio::spawn(async move { + if !hold_back_the_assign { + tokio::time::sleep(head_start).await; + } + fee_plan::delete(&db, plan).await + }) + }; + let assign = { + let (db, plan, manager, student) = + (db.clone(), plan.clone(), manager.clone(), student.clone()); + tokio::spawn(async move { + if hold_back_the_assign { + tokio::time::sleep(head_start).await; + } + assign(&db, &plan, &student, &manager).await + }) + }; + let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap()); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "a raced delete must retry, not 500: {drop_it:?}" + ); + assert!( + !matches!(assign, Err(AppError::Db(_))), + "a raced assign must retry, not 500: {assign:?}" + ); + + let gone = fee_plan::read(&db, plan.get_id()).await.unwrap().is_none(); + let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id()) + .await + .unwrap(); + deleted_first += usize::from(gone); + assigned_first += usize::from(assigned); + assert!( + !(gone && assigned), + "an assignment may not outlive the plan it names" + ); + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) + .await + .unwrap(); + assert!( + !(gone && !lines.is_empty()), + "and neither may the charges it raised" + ); + } + // The premise, not a nicety: "never both" is trivially true in a run + // where one of the two never landed, so a run that only saw one + // ordering has proven nothing and says so. + assert!(deleted_first > 0, "no round ever let the delete land first"); + assert!( + assigned_first > 0, + "no round ever let the assign land first" + ); + } +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 4d64c64..1e97bc3 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -2,6 +2,7 @@ //! SurrealQL text. pub mod appointment; pub mod appointment_slot; +pub mod attendance; pub mod badge; pub mod builder; pub mod chatbot_message; @@ -15,6 +16,8 @@ pub mod event; pub mod exam; pub mod exam_attempt; pub mod exam_question; +pub mod fee_plan; +pub mod fee_plan_assignment; pub mod meal_attendance; pub mod meal_booking; pub mod meal_ledger; @@ -28,6 +31,7 @@ pub mod profile; pub mod rag_output; pub mod registration; pub mod session; +pub mod session_attendance; pub mod settings; pub mod subject; pub mod term; diff --git a/src/service/payment_ledger.rs b/src/service/payment_ledger.rs index 9cecdeb..05a44fe 100644 --- a/src/service/payment_ledger.rs +++ b/src/service/payment_ledger.rs @@ -348,23 +348,23 @@ mod tests { /// Raise one charge of `amount` on a fresh student, and hand it back. async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { - use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; - use crate::domain::fee_plan_assignment::FeePlanAssignment; + use crate::db::fee_plan; + use crate::domain::fee_plan::{FeePlanName, Installment}; let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); - let plan = FeePlan::create( + let plan = fee_plan::create( + db, FeePlanName::try_new("Yearly").unwrap(), vec![Installment::new( LedgerAmount::try_new(amount).unwrap(), Timestamp::from_millis(1_000), )], &manager, - db, ) .await .unwrap(); - FeePlanAssignment::assign(&plan, &student, &manager, db) + crate::service::fee_plan_assignment::assign(db, &plan, &student, &manager) .await .unwrap(); let (lines, _) = payment_ledger::list_for_student(db, &student, None, 0) @@ -546,24 +546,24 @@ mod tests { /// reversal may point at a line of the wrong kind. #[tokio::test] async fn payments_are_capped_by_the_line_they_target() { - use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; - use crate::domain::fee_plan_assignment::FeePlanAssignment; + use crate::db::fee_plan; + use crate::domain::fee_plan::{FeePlanName, Installment}; let db = crate::database::init_mem().await.unwrap(); let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); - let plan = FeePlan::create( + let plan = fee_plan::create( + &db, FeePlanName::try_new("Yearly").unwrap(), vec![Installment::new( LedgerAmount::try_new(10_000).unwrap(), Timestamp::from_millis(1_000), )], &manager, - &db, ) .await .unwrap(); - FeePlanAssignment::assign(&plan, &student, &manager, &db) + crate::service::fee_plan_assignment::assign(&db, &plan, &student, &manager) .await .unwrap(); let (charges, _) = payment_ledger::list_for_student(&db, &student, None, 0) diff --git a/src/service/session_attendance.rs b/src/service/session_attendance.rs new file mode 100644 index 0000000..1db4c84 --- /dev/null +++ b/src/service/session_attendance.rs @@ -0,0 +1,137 @@ +//! The roll-call workflows: taking and clearing a lesson's roll call, with +//! the target-eligibility rules every roll-call path shares — a staff row is +//! management's to write (the session's own teacher is marked and cleared +//! only by manager+), only students attend lessons, and a non-teacher target +//! must be enrolled in the course. The queries and the badge-counter +//! transactions live in [`crate::db::session_attendance`]; who may take a +//! roll call at all (the session's teacher or a course manager) is the web +//! layer's authorization, judged against the session and course it loaded. + +use crate::database::Database; +use crate::db::session_attendance; +use crate::domain::attendance::AttendanceStatus; +use crate::domain::badge; +use crate::domain::course_session::CourseSession; +use crate::domain::role::Role; +use crate::domain::session_attendance::SessionAttendance; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Record `target`'s roll-call state for the session — the target-eligibility +/// gates plus the mark. Returns the written row and the target's user row as +/// the gates judged it (the response joins both people). +/// +/// - The session's own teacher is marked only by manager+: staff presence is +/// management's call, so a teacher can't mark themselves present. +/// - Everyone else on a lesson's roster is an enrolled student. Only students +/// attend classes; checking the live role keeps a stale enrollment (left by +/// a promotion) from putting staff on the roll. +/// +/// A badge is a decoration on top of the roll call: losing one to a +/// transient database error must never fail the mark, and the next counter +/// move re-runs this and heals it. Both people the mark can credit are +/// synced — the person marked (`lessons_attended`) and the lesson's teacher +/// (`lessons_held`, on the first roll call only). The teacher's runs on every +/// mark rather than only that first one: `sync` is add-only and idempotent, +/// so the extra calls cost one record read and are what heals a first sync +/// that failed, and knowing here whether the credit landed would mean +/// widening the write's return type for nothing. +pub async fn mark( + db: &Database, + session: &CourseSession, + marker: &User, + target: &UserId, + status: AttendanceStatus, +) -> Result<(SessionAttendance, User), AppError> { + // Target user must exist. + let target_user = crate::db::user::read(db, target) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + }))?; + + if session.is_teacher(target) { + // The session teacher's own presence is recorded by management. + if !marker.get_role().at_least(Role::Manager) { + return Err(AppError::Forbidden( + "marking the session's teacher requires manager role or higher", + )); + } + } else { + // Everyone else on a lesson's roster is an enrolled student. Only + // students attend classes; checking the live role keeps a stale + // enrollment (left by a promotion) from putting staff on the roll. + if target_user.get_role() != Role::Student { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "only students can be marked present in a lesson", + })); + } + if crate::db::enrollment::read_for_user(db, session.get_course(), target) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } + } + + let attendance = session_attendance::mark(db, session, target, status, marker.get_id()).await?; + for who in [target, session.get_teacher()] { + if let Err(err) = badge::sync(who, db).await { + tracing::warn!("failed to sync badges for {}: {err}", who.key()); + } + } + Ok((attendance, target_user)) +} + +/// List a session's roll call, paged. +pub async fn list_for_session( + db: &Database, + session: &crate::domain::course_session::CourseSessionId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + session_attendance::list_for_session(db, session, limit, offset).await +} + +/// Every roll-call row ever recorded for `user` — the session half of the +/// attendance report. +pub async fn list_for_user( + db: &Database, + user: &UserId, +) -> Result, AppError> { + session_attendance::list_for_user(db, user).await +} + +/// Clear `target`'s roll-call row from the session, with the one gate the +/// mark does not have: a staff row is management's to remove, keyed on the +/// *target's live role* rather than on `is_teacher` — reassigning a +/// session's teacher used to hand the incoming teacher, an ordinary one, the +/// outgoing teacher's staff row to delete without the manager+ this guard +/// exists to require. A target whose user row is gone can only be a +/// student's stale row (marking checks the role at write time), so it stays +/// the session teacher's to clear. +/// +/// `Err(NotFound)` when there was no row to remove. +pub async fn remove( + db: &Database, + session: &CourseSession, + remover: &User, + target: &UserId, +) -> Result { + let staff_row = crate::db::user::read(db, target) + .await? + .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher)); + if staff_row && !remover.get_role().at_least(Role::Manager) { + return Err(AppError::Forbidden( + "removing a staff roll-call row requires manager role or higher", + )); + } + session_attendance::remove(db, session.get_id(), target) + .await? + .ok_or(AppError::NotFound) +} diff --git a/src/web/attendance.rs b/src/web/attendance.rs index b11b9ab..8092d33 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::attendance::{Attendance, AttendanceStatus}; +use crate::domain::attendance::AttendanceStatus; use crate::domain::course::{Course, CourseId}; use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; @@ -104,8 +104,8 @@ async fn build_report( viewer: Option<&User>, db: &Database, ) -> Result { - let events = Attendance::list_for_user(user, db).await?; - let sessions = SessionAttendance::list_for_user(user, db).await?; + let events = crate::service::attendance::list_for_user(db, user).await?; + let sessions = crate::service::session_attendance::list_for_user(db, user).await?; // Group session rows by course, preserving first-seen (newest-first) order. let mut course_ids: Vec = Vec::new(); diff --git a/src/web/events.rs b/src/web/events.rs index 3e75b72..230473b 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -540,7 +540,8 @@ async fn mark( })); } - let attendance = Attendance::mark(&event_id, &target, status, user.get_id(), &st.db).await?; + let attendance = + crate::service::attendance::mark(&st.db, &event_id, &target, status, user.get_id()).await?; let people = PersonRef::map_of(&[&target_user, &user]); Ok(Json(AttendanceResponse::new(&attendance, &people))) } @@ -575,7 +576,8 @@ async fn list_attendance( service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; - let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?; + let (rows, total) = + crate::service::attendance::list_for_event(&st.db, &event_id, limit, offset).await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( rows.iter() @@ -612,8 +614,12 @@ async fn remove_attendance( _teacher: RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - let removed = - Attendance::remove(&EventId::from_key(&id), &UserId::from_key(&target), &st.db).await?; + let removed = crate::service::attendance::remove( + &st.db, + &EventId::from_key(&id), + &UserId::from_key(&target), + ) + .await?; if removed.is_none() { return Err(AppError::NotFound); } @@ -671,7 +677,7 @@ async fn roster( let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?; // ULID keys sort by creation instant — a stable order keeps pages coherent. members.sort_by(|a, b| a.key().cmp(b.key())); - let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?; + let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?; let by_user: HashMap<&str, &Attendance> = marks .iter() .map(|attendance| (attendance.get_user().key(), attendance)) diff --git a/src/web/payments.rs b/src/web/payments.rs index 4ae491d..d6b623e 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -23,10 +23,9 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES}; use crate::database::Database; use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment}; -use crate::domain::fee_plan_assignment::FeePlanAssignment; +use crate::domain::parent_link::ParentLink; use crate::domain::payment_ledger::{ LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, PaymentRequestKey, @@ -163,7 +162,7 @@ async fn plan_responses( } async fn require_plan(id: &str, db: &Database) -> Result { - FeePlan::read(&FeePlanId::from_key(id), db) + service::fee_plan::read(db, &FeePlanId::from_key(id)) .await? .ok_or(AppError::NotFound) } @@ -189,11 +188,11 @@ async fn create_plan( RequireManager(manager): RequireManager, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { - let plan = FeePlan::create( + let plan = service::fee_plan::create( + &st.db, FeePlanName::try_new(&req.name)?, InstallmentBody::list(req.installments)?, manager.get_id(), - &st.db, ) .await?; let people = PersonRef::map_of(&[&manager]); @@ -224,7 +223,7 @@ async fn list_plans( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (rows, total) = FeePlan::list_all(limit, offset, &st.db).await?; + let (rows, total) = service::fee_plan::list_all(&st.db, limit, offset).await?; let items = plan_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } @@ -291,7 +290,7 @@ async fn update_plan( let plan = require_plan(&id, &st.db).await?; let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?; let installments = req.installments.map(InstallmentBody::list).transpose()?; - let plan = plan.update(name, installments, &st.db).await?; + let plan = service::fee_plan::update(&st.db, plan, name, installments).await?; let items = plan_responses(std::slice::from_ref(&plan), &st.db).await?; Ok(Json( items.into_iter().next().expect("one plan in, one out"), @@ -323,7 +322,7 @@ async fn delete_plan( Path(id): Path, ) -> Result { let plan = require_plan(&id, &st.db).await?; - if !plan.delete(&st.db).await? { + if !service::fee_plan::delete(&st.db, plan).await? { return Err(AppError::Conflict("an assigned plan cannot be deleted")); } Ok(StatusCode::NO_CONTENT) @@ -405,59 +404,30 @@ async fn assign_plan( Path(id): Path, Json(req): Json, ) -> Result>, AppError> { - if req.student_ids.len() > MAX_FEE_PLAN_ASSIGN_STUDENTS { - return Err(AppError::Validation(ValidationError::Invalid { - field: "student_ids", - reason: "may name at most 200 students", - })); - } - let plan = require_plan(&id, &st.db).await?; - // The student cap alone cannot see the schedule: every student named - // appends *every* installment, so what really bounds this request is the - // product. Refused whole and before anything is written — a batch this API - // billed only part of would leave a bursar guessing which families were - // charged. - if req - .student_ids - .len() - .saturating_mul(plan.get_installments().len()) - > MAX_FEE_PLAN_ASSIGN_WRITES - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "student_ids", - reason: "too many charges for one request: students × installments \ - may not exceed 3000, so split the batch", - })); - } - let mut outcomes = Vec::with_capacity(req.student_ids.len()); - for student_id in req.student_ids { - let student = UserId::from_key(&student_id); - // A fee record belongs to a student; billing anyone else is a typo, and - // a typo here is money against the wrong person. - let is_student = crate::service::user::read(&st.db, &student) - .await? - .is_some_and(|user| user.get_role() == Role::Student); - let (status, reason) = if is_student { - match FeePlanAssignment::assign(&plan, &student, manager.get_id(), &st.db).await { - Ok((_, true)) => ("already_assigned", None), - Ok((_, false)) => ("assigned", None), - // The plan was deleted mid-batch. That is a per-student outcome - // like any other, not a reason to throw away the report for the - // students this batch already billed — their charges are - // written and the caller has to be told about them. - Err(AppError::NotFound) => ("rejected", Some("no such plan")), - Err(err) => return Err(err), - } - } else { - ("rejected", Some("no such student")) - }; - outcomes.push(AssignmentOutcome { - student_id, - status, - reason, - }); - } - Ok(Json(outcomes)) + let outcomes = + service::fee_plan_assignment::assign_batch(&st.db, &id, manager.get_id(), req.student_ids) + .await?; + Ok(Json( + outcomes + .into_iter() + .map(|(student_id, outcome)| { + let (status, reason) = match outcome { + service::fee_plan_assignment::Outcome::Assigned => ("assigned", None), + service::fee_plan_assignment::Outcome::AlreadyAssigned => { + ("already_assigned", None) + } + service::fee_plan_assignment::Outcome::Rejected(reason) => { + ("rejected", Some(reason)) + } + }; + AssignmentOutcome { + student_id, + status, + reason, + } + }) + .collect(), + )) } /// Who is on this plan, newest first. Paged via `?limit=&offset=`; returns a @@ -485,7 +455,7 @@ async fn list_plan_assignments( let (limit, offset) = page.resolve()?; let plan = require_plan(&id, &st.db).await?; let (rows, total) = - FeePlanAssignment::list_for_plan(plan.get_id(), limit, offset, &st.db).await?; + service::fee_plan_assignment::list_for_plan(&st.db, plan.get_id(), limit, offset).await?; let people = person_map( rows.iter() .flat_map(|row| [row.get_student().clone(), row.get_assigned_by().clone()]), @@ -905,13 +875,14 @@ async fn statement_response( }; // A charge names its assignment, and the assignment names the plan. - let (assignments, _) = FeePlanAssignment::list_for_student(student, None, 0, db).await?; + let (assignments, _) = + service::fee_plan_assignment::list_for_student(db, student, None, 0).await?; let mut plan_names: HashMap> = HashMap::new(); let mut plan_of: HashMap<&str, &FeePlanId> = HashMap::new(); for assignment in &assignments { let plan = assignment.get_plan(); if !plan_names.contains_key(plan.key()) { - let name = FeePlan::read(plan, db) + let name = service::fee_plan::read(db, plan) .await? .map(|plan| plan.get_name().as_str().to_string()); plan_names.insert(plan.key().to_string(), name); @@ -1119,7 +1090,8 @@ mod tests { let manager = UserId::from_key("mgr1"); let student = UserId::from_key("stu1"); let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000; - let plan = FeePlan::create( + let plan = service::fee_plan::create( + &db, FeePlanName::try_new("Yearly").unwrap(), vec![ // Already due, and only part paid — the overdue row. @@ -1133,11 +1105,10 @@ mod tests { ), ], &manager, - &db, ) .await .unwrap(); - FeePlanAssignment::assign(&plan, &student, &manager, &db) + service::fee_plan_assignment::assign(&db, &plan, &student, &manager) .await .unwrap(); diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 64d0e5d..d846510 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -18,7 +18,7 @@ use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; -use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::error::{AppError, ErrorResponse}; use crate::service; use crate::state::AppState; @@ -295,58 +295,8 @@ async fn mark_roll_call( let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; let target = UserId::from_key(&req.user_id); - // Target user must exist. - let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user does not exist", - })); - }; - - if session.is_teacher(&target) { - // The session teacher's own presence is recorded by management. - if !user.get_role().at_least(Role::Manager) { - return Err(AppError::Forbidden( - "marking the session's teacher requires manager role or higher", - )); - } - } else { - // Everyone else on a lesson's roster is an enrolled student. Only - // students attend classes; checking the live role keeps a stale - // enrollment (left by a promotion) from putting staff on the roll. - if target_user.get_role() != Role::Student { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "only students can be marked present in a lesson", - })); - } - if service::enrollment::read_for_user(&st.db, session.get_course(), &target) - .await? - .is_none() - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "user_id", - reason: "target user is not enrolled in this course", - })); - } - } - - let attendance = - SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?; - // A badge is a decoration on top of the roll call: losing one to a - // transient database error must never fail the mark, and the next counter - // move re-runs this and heals it. Both people the mark can credit are - // synced — the person marked (`lessons_attended`) and the lesson's teacher - // (`lessons_held`, on the first roll call only). The teacher's runs on every - // mark rather than only that first one: `sync` is add-only and idempotent, - // so the extra calls cost one record read and are what heals a first sync - // that failed, and knowing here whether the credit landed would mean - // widening `mark`'s return type for nothing. - for who in [&target, session.get_teacher()] { - if let Err(err) = service::badge::sync(&st.db, who).await { - tracing::warn!("failed to sync badges for {}: {err}", who.key()); - } - } + let (attendance, target_user) = + service::session_attendance::mark(&st.db, &session, &user, &target, status).await?; let people = PersonRef::map_of(&[&target_user, &user]); Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) } @@ -383,7 +333,8 @@ async fn list_roll_call( )); } let (rows, total) = - SessionAttendance::list_for_session(session.get_id(), limit, offset, &st.db).await?; + service::session_attendance::list_for_session(&st.db, session.get_id(), limit, offset) + .await?; // Join people onto the page alone — the lookup shrinks with the window. let people = person_map( rows.iter() @@ -431,23 +382,6 @@ async fn remove_roll_call( } crate::service::course::require_open(&st.db, &course).await?; let target = UserId::from_key(&target); - // A staff row is management's to remove, keyed on the *target's live role* - // rather than on `is_teacher`: reassigning a session's teacher used to hand - // the incoming teacher — an ordinary one — the outgoing teacher's staff row - // to delete without the manager+ this guard exists to require. A target - // whose user row is gone can only be a student's stale row (marking checks - // the role at write time), so it stays the session teacher's to clear. - let staff_row = crate::service::user::read(&st.db, &target) - .await? - .is_some_and(|target_user| target_user.get_role().at_least(Role::Teacher)); - if staff_row && !user.get_role().at_least(Role::Manager) { - return Err(AppError::Forbidden( - "removing a staff roll-call row requires manager role or higher", - )); - } - let removed = SessionAttendance::remove(session.get_id(), &target, &st.db).await?; - if removed.is_none() { - return Err(AppError::NotFound); - } + service::session_attendance::remove(&st.db, &session, &user, &target).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index 6d203cc..2b4382f 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -13,12 +13,13 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; use hezarfen_backend::database::Database; +use hezarfen_backend::db::attendance; use hezarfen_backend::db::course_session; +use hezarfen_backend::db::session_attendance; use hezarfen_backend::db::settings; -use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; +use hezarfen_backend::domain::attendance::AttendanceStatus; use hezarfen_backend::domain::course_session::CourseSessionId; use hezarfen_backend::domain::event::EventId; -use hezarfen_backend::domain::session_attendance::SessionAttendance; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; @@ -130,7 +131,7 @@ async fn reassigning_the_teacher_does_not_unlock_the_old_teachers_staff_row() { assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); // The row is still there, and a manager still clears it. - let rows = SessionAttendance::list_for_user(&UserId::from_key(&t1_id), &db) + let rows = session_attendance::list_for_user(&db, &UserId::from_key(&t1_id)) .await .unwrap(); 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() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); assert!( - SessionAttendance::list_for_user(&ali_ref, &db) + session_attendance::list_for_user(&db, &ali_ref) .await .unwrap() .is_empty(), @@ -226,12 +227,12 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { // Then the mark arrives, still believing in its snapshot. let school = settings::load(&db).await.unwrap(); let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); - let marked = SessionAttendance::mark( + let marked = session_attendance::mark( + &db, &snapshot, &ali_ref, status, &UserId::from_key(&hoca_id), - &db, ) .await; assert!( @@ -240,7 +241,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { ); // The stored state is the assertion — the return value is not trusted. assert!( - SessionAttendance::list_for_user(&ali_ref, &db) + session_attendance::list_for_user(&db, &ali_ref) .await .unwrap() .is_empty(), @@ -385,7 +386,7 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { .await; assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); assert!( - Attendance::list_for_user(&ali_ref, &db) + attendance::list_for_user(&db, &ali_ref) .await .unwrap() .is_empty(), @@ -396,14 +397,14 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { let school = settings::load(&db).await.unwrap(); let status = AttendanceStatus::try_new("present", school.get_attendance_statuses()).unwrap(); let marked = - Attendance::mark(&EventId::from_key(&event), &ali_ref, status, &hoca_ref, &db).await; + attendance::mark(&db, &EventId::from_key(&event), &ali_ref, status, &hoca_ref).await; assert!( matches!(marked, Err(AppError::NotFound)), "a mark on a deleted event is a 404, got {marked:?}" ); // The stored state is the assertion — the return value is not trusted. assert!( - Attendance::list_for_user(&ali_ref, &db) + attendance::list_for_user(&db, &ali_ref) .await .unwrap() .is_empty(), diff --git a/tests/regress_payments.rs b/tests/regress_payments.rs index ab33f37..f0029ec 100644 --- a/tests/regress_payments.rs +++ b/tests/regress_payments.rs @@ -15,12 +15,13 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, id_of, login, login_as, me_id, send}; use hezarfen_backend::constant::{MAX_FEE_PLAN_ASSIGN_WRITES, MAX_LEDGER_APPLIED_LINES}; -use hezarfen_backend::domain::fee_plan::{FeePlan, FeePlanName, Installment}; -use hezarfen_backend::domain::fee_plan_assignment::FeePlanAssignment; +use hezarfen_backend::db::fee_plan; +use hezarfen_backend::domain::fee_plan::{FeePlanName, Installment}; use hezarfen_backend::domain::payment_ledger::LedgerAmount; use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; +use hezarfen_backend::service::fee_plan_assignment; use serde_json::{Value, json}; /// 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() { /// deleted, and only then does the guarded `UPDATE` run. It matched nothing — /// because the row is gone, not because anyone is on the plan — and the answer /// was `409 "an assigned plan cannot be edited"` about a plan that never was. -/// `FeePlan::delete` already pays for the read that tells the two apart on its +/// `db::fee_plan::delete` already pays for the read that tells the two apart on its /// refusal path; the edit now does too, and a genuinely assigned plan is still /// the `409` it always was. #[tokio::test] @@ -233,22 +234,29 @@ async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() { Timestamp::from_millis(1_000), )] }; - let plan = FeePlan::create( + let plan = fee_plan::create( + &db, FeePlanName::try_new("Yearly").unwrap(), one(), &manager, - &db, ) .await .unwrap(); // The handler's snapshot, taken before the delete lands. - let read = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); - assert!(plan.delete(&db).await.unwrap(), "nobody is on it"); - let refused = read - .update(Some(FeePlanName::try_new("Renamed").unwrap()), None, &db) - .await - .unwrap_err(); + let read = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap(); + assert!( + fee_plan::delete(&db, plan).await.unwrap(), + "nobody is on it" + ); + let refused = fee_plan::update( + &db, + read, + Some(FeePlanName::try_new("Renamed").unwrap()), + None, + ) + .await + .unwrap_err(); assert!( matches!(refused, AppError::NotFound), "a plan that is gone is a 404, not an assigned-plan 409: {refused}" @@ -256,27 +264,30 @@ async fn editing_a_plan_deleted_since_it_was_read_is_a_404_not_a_409() { // The genuine refusal is untouched: a plan somebody is actually on still // answers 409, and its schedule is not edited. - let plan = FeePlan::create( + let plan = fee_plan::create( + &db, FeePlanName::try_new("Yearly").unwrap(), one(), &manager, - &db, ) .await .unwrap(); - FeePlanAssignment::assign(&plan, &UserId::from_key("del_stu"), &manager, &db) + fee_plan_assignment::assign(&db, &plan, &UserId::from_key("del_stu"), &manager) .await .unwrap(); - let refused = plan - .clone() - .update(Some(FeePlanName::try_new("Renamed").unwrap()), None, &db) - .await - .unwrap_err(); + let refused = fee_plan::update( + &db, + plan.clone(), + Some(FeePlanName::try_new("Renamed").unwrap()), + None, + ) + .await + .unwrap_err(); assert!( matches!(refused, AppError::Conflict(_)), "an assigned plan is still refused as assigned: {refused}" ); - let stored = FeePlan::read(plan.get_id(), &db).await.unwrap().unwrap(); + let stored = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap(); assert_eq!(stored.get_name().as_str(), "Yearly", "nothing was written"); }