forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

fee_plan_assignment.rs508 lines, 21.5 KiBHistoryRawDownload
1//! The assign workflow: placing a plan on a student and billing it — the
2//! moment the plan becomes money owed — plus the batch loop and the bounds
3//! one assign request may carry. The queries live in
4//! [`crate::db::fee_plan_assignment`]; the ledger appends in
5//! [`crate::db::payment_ledger`].
6//!
7//! The row is keyed `<plan>_<student>`, and every charge it raises is keyed
8//! from that same key plus the installment number, so the whole operation is
9//! idempotent **by identity**: assigning twice writes nothing the second time,
10//! however the two requests interleave, and an assign cut short after three of
11//! twelve charges landed completes itself when it is repeated. No scan decides
12//! "has this been billed yet?" — a scan can be slipped past by a concurrent
13//! writer, and the cost of that mistake here is a double-billed family.
14
15use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES};
16use crate::database::Database;
17use crate::db::cap::Claimed;
18use crate::db::{fee_plan, fee_plan_assignment, payment_ledger};
19use crate::domain::fee_plan::FeePlan;
20use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
21use crate::domain::role::Role;
22use crate::domain::timestamp::Timestamp;
23use crate::domain::user::UserId;
24use crate::error::{AppError, ValidationError};
25
26/// Place `plan` on `student` and bill it. Returns the assignment and
27/// whether it was *already* there, so the web layer can answer a replay
28/// honestly instead of pretending it just happened.
29///
30/// The row and the plan's assignment refcount are written in **one
31/// statement** ([`fee_plan_assignment::create`]'s claim): that increment is
32/// what makes the
33/// plan un-editable and un-deletable, and it has to be indivisible from the
34/// row it counts, or an edit could slip between the two. A plan the counter
35/// cannot be claimed on is one a concurrent delete already removed, which is
36/// the same `404` the handler's own lookup would have given.
37///
38/// The installments are then re-read **from the stored plan**, not taken
39/// from the caller's snapshot: the claim is the moment the plan freezes, and
40/// an edit that landed between the handler's read and that claim is
41/// legitimate. Billing the snapshot would raise charges from a schedule the
42/// plan no longer shows — precisely the divergence the 409 exists to
43/// prevent.
44///
45/// The charges are appended after the row, never before: each one is keyed
46/// by (assignment, installment number), so this loop is safe to re-enter
47/// from the top — which is exactly what a repeated assign does, and the
48/// only way a half-written assignment ever gets its missing lines.
49pub async fn assign(
50 db: &Database,
51 plan: &FeePlan,
52 student: &UserId,
53 assigned_by: &UserId,
54) -> Result<(FeePlanAssignment, bool), AppError> {
55 let id = FeePlanAssignmentId::composite(plan.get_id(), student);
56 let claimed =
57 fee_plan_assignment::create(db, plan.get_id(), student, assigned_by, Timestamp::now())
58 .await?;
59 let (assignment, existed) = match claimed {
60 Claimed::Made(created) => (created, false),
61 // Someone assigned this pair first — their row is the answer, and
62 // the charges below are keyed the same, so continuing here can only
63 // *complete* the billing. Their claim already counts this row.
64 Claimed::Duplicate => (require(&id, db).await?, true),
65 // The counter is uncapped, so the only miss is a plan that is gone.
66 Claimed::Full => return Err(AppError::NotFound),
67 };
68 // Frozen as of the claim above: no edit can land past it any more.
69 let plan = fee_plan::read(db, plan.get_id())
70 .await?
71 .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?;
72 for (index, installment) in plan.get_installments().iter().enumerate() {
73 payment_ledger::charge_for_installment(
74 db,
75 &assignment,
76 index + 1,
77 installment,
78 assigned_by,
79 )
80 .await?;
81 }
82 Ok((assignment, existed))
83}
84
85async fn require(id: &FeePlanAssignmentId, db: &Database) -> Result<FeePlanAssignment, AppError> {
86 fee_plan_assignment::read(db, id)
87 .await?
88 .ok_or_else(|| AppError::Internal("failed to assign the fee plan".into()))
89}
90
91/// What one student in an assign batch came to. The web layer spells these
92/// as its response statuses.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Outcome {
95 /// Placed and billed now.
96 Assigned,
97 /// A replay: the student was already on this plan, nothing billed again.
98 AlreadyAssigned,
99 /// Refused for this student alone — the batch carries on.
100 Rejected(&'static str),
101}
102
103/// Place one plan on a batch of students, which is what turns it into money
104/// owed: every installment is appended as a charge line right away, each with
105/// its own due date. Returns one outcome per student, in the order sent.
106///
107/// Only students carry a fee record, so any other target is rejected. One bad
108/// id never loses the rest of the batch: the outcome reports each student
109/// separately.
110///
111/// Placing the first student **freezes** the plan: it can no longer be edited
112/// or deleted. The installments billed are read back from the stored plan at
113/// that instant, so an edit that landed a moment earlier is the one billed,
114/// never the version this request first looked at. A plan deleted while the
115/// batch is running is `Rejected` from that student on — a per-student
116/// outcome like any other, so the students it already billed stay in the
117/// report.
118///
119/// One request is bounded by the **charges it would raise**, not by the head
120/// count alone: `student_ids × installments` may not exceed 3 000 (200
121/// students up to a 15-installment plan; 50 at a time on a 60-installment
122/// one). Past that the whole call is a `400` telling the caller to split the
123/// batch — nothing is written, because a money route that billed half a batch
124/// and gave up would leave a bursar guessing which families were charged.
125pub async fn assign_batch(
126 db: &Database,
127 plan_key: &str,
128 assigner: &UserId,
129 student_ids: Vec<String>,
130) -> Result<Vec<(String, Outcome)>, AppError> {
131 if student_ids.len() > MAX_FEE_PLAN_ASSIGN_STUDENTS {
132 return Err(AppError::Validation(ValidationError::Invalid {
133 field: "student_ids",
134 reason: "may name at most 200 students",
135 }));
136 }
137 let plan = fee_plan::read(db, &crate::domain::fee_plan::FeePlanId::from_key(plan_key))
138 .await?
139 .ok_or(AppError::NotFound)?;
140 // The student cap alone cannot see the schedule: every student named
141 // appends *every* installment, so what really bounds this request is the
142 // product. Refused whole and before anything is written — a batch this API
143 // billed only part of would leave a bursar guessing which families were
144 // charged.
145 if student_ids
146 .len()
147 .saturating_mul(plan.get_installments().len())
148 > MAX_FEE_PLAN_ASSIGN_WRITES
149 {
150 return Err(AppError::Validation(ValidationError::Invalid {
151 field: "student_ids",
152 reason: "too many charges for one request: students × installments \
153 may not exceed 3000, so split the batch",
154 }));
155 }
156 let mut outcomes = Vec::with_capacity(student_ids.len());
157 for student_id in student_ids {
158 let student = UserId::from_key(&student_id);
159 // A fee record belongs to a student; billing anyone else is a typo, and
160 // a typo here is money against the wrong person.
161 let is_student = crate::db::user::read(db, &student)
162 .await?
163 .is_some_and(|user| user.get_role() == Role::Student);
164 let outcome = if is_student {
165 match assign(db, &plan, &student, assigner).await {
166 Ok((_, true)) => Outcome::AlreadyAssigned,
167 Ok((_, false)) => Outcome::Assigned,
168 // The plan was deleted mid-batch. That is a per-student outcome
169 // like any other, not a reason to throw away the report for the
170 // students this batch already billed — their charges are
171 // written and the caller has to be told about them.
172 Err(AppError::NotFound) => Outcome::Rejected("no such plan"),
173 Err(err) => return Err(err),
174 }
175 } else {
176 Outcome::Rejected("no such student")
177 };
178 outcomes.push((student_id, outcome));
179 }
180 Ok(outcomes)
181}
182
183/// The placement, for callers that only inspect it.
184pub async fn read(
185 db: &Database,
186 id: &FeePlanAssignmentId,
187) -> Result<Option<FeePlanAssignment>, AppError> {
188 fee_plan_assignment::read(db, id).await
189}
190
191/// Who is on this plan, newest first.
192pub async fn list_for_plan(
193 db: &Database,
194 plan: &crate::domain::fee_plan::FeePlanId,
195 limit: Option<i64>,
196 offset: i64,
197) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
198 fee_plan_assignment::list_for_plan(db, plan, limit, offset).await
199}
200
201/// Which plans a student is on.
202pub async fn list_for_student(
203 db: &Database,
204 student: &UserId,
205 limit: Option<i64>,
206 offset: i64,
207) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
208 fee_plan_assignment::list_for_student(db, student, limit, offset).await
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use crate::database::init_test_db;
215 use crate::domain::fee_plan::{FeePlanName, Installment};
216 use crate::domain::payment_ledger::LedgerAmount;
217
218 /// A real `app_user` row: managers and students are foreign keys now. The
219 /// label names the row's username; the id is minted, so repeated calls are
220 /// new people, not the same row.
221 async fn a_person(db: &Database, label: &str, role: &str) -> UserId {
222 let user = UserId::generate();
223 sqlx::query(
224 "INSERT INTO app_user (id, username, created_at, role) \
225 VALUES ($1, $2, 0, $3)",
226 )
227 .bind(user.uuid())
228 .bind(format!("{label}-{}", &user.key()[30..]))
229 .bind(role)
230 .execute(db)
231 .await
232 .unwrap();
233 user
234 }
235
236 async fn a_plan(db: &Database, installments: Vec<Installment>) -> FeePlan {
237 let manager = a_person(db, "mgr", "manager").await;
238 fee_plan::create(
239 db,
240 FeePlanName::try_new("Yearly").unwrap(),
241 installments,
242 &manager,
243 )
244 .await
245 .unwrap()
246 }
247
248 /// The invariant the whole module exists for: assigning bills every
249 /// installment once, and assigning *again* bills nothing — the second call
250 /// must not double a family's debt.
251 #[tokio::test]
252 async fn assigning_bills_every_installment_and_a_replay_bills_nothing() {
253 let (db, _leases) = init_test_db().await;
254 let manager = a_person(&db, "mgr", "manager").await;
255 let student = a_person(&db, "stu", "student").await;
256 let plan = a_plan(
257 &db,
258 vec![
259 Installment::new(
260 LedgerAmount::try_new(150_000).unwrap(),
261 Timestamp::from_millis(1_000),
262 ),
263 Installment::new(
264 LedgerAmount::try_new(250_000).unwrap(),
265 Timestamp::from_millis(2_000),
266 ),
267 ],
268 )
269 .await;
270
271 let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap();
272 assert!(!existed);
273 assert_eq!(
274 payment_ledger::balance_of(&db, &student).await.unwrap(),
275 -400_000,
276 "both installments must be owed"
277 );
278
279 let (_, existed) = assign(&db, &plan, &student, &manager).await.unwrap();
280 assert!(
281 existed,
282 "the second assign is a replay, not a new placement"
283 );
284 let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
285 .await
286 .unwrap();
287 assert_eq!(lines.len(), 2, "a replay may not append a single line");
288 assert!(
289 lines
290 .iter()
291 .all(|l| l.get_kind() == crate::domain::payment_ledger::PaymentLedgerKind::Charge)
292 );
293 assert_eq!(
294 payment_ledger::balance_of(&db, &student).await.unwrap(),
295 -400_000
296 );
297 assert!(
298 fee_plan_assignment::exists_for_plan(&db, plan.get_id())
299 .await
300 .unwrap()
301 );
302 }
303
304 /// The race the refcount exists for: an edit and an assign, both licensed
305 /// by the same instant.
306 ///
307 /// "Neither lands" is *not* the invariant — the two are legal in one order
308 /// (edit, then assign the edited plan) and illegal in the other. What may
309 /// never happen is the money and the plan disagreeing: the charges raised
310 /// must be copies of the schedule the plan actually ends up carrying, and
311 /// once anybody is on the plan no further edit or delete may land at all.
312 ///
313 /// Asserted against the **stored** state, never against which call returned
314 /// `Ok`: a winner's word is not evidence about what the store kept.
315 /// The one thing the *returned* values are good for is the second
316 /// invariant: neither racer may answer 500. Losing a single-record round to
317 /// a rival is the ordinary way this guard works, and the loser's recovery is
318 /// to re-send, not to fail the request.
319 ///
320 /// Multi-threaded on purpose: on the single-threaded runtime the two tasks
321 /// interleave only at await points and the store never reports a conflict at
322 /// all, which is how a version of this test watched a 45-in-50 500 rate and
323 /// passed.
324 ///
325 /// Real server, and `#[ignore]`d rather than falling back to `init_mem`:
326 /// the embedded engine drops one of two concurrent writes to a record and
327 /// answers `Ok` to both, which fails this very assertion out of nowhere
328 /// (measured 2026-07-30: 2 runs in 36 on `memory` under host load, 0 in
329 /// 10 000 rounds on the server). See [`crate::database::init_test_server`].
330 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
331 async fn an_edit_racing_an_assign_leaves_the_plan_and_the_money_agreeing() {
332 let (db, _leases) = crate::database::init_test_db().await;
333 let mut reached = 0;
334 for _round in 0..20 {
335 let manager = a_person(&db, "mgr", "manager").await;
336 let student = a_person(&db, "stu", "student").await;
337 let plan = a_plan(
338 &db,
339 vec![Installment::new(
340 LedgerAmount::try_new(100).unwrap(),
341 Timestamp::from_millis(1_000),
342 )],
343 )
344 .await;
345
346 let edit = {
347 let (plan, db) = (plan.clone(), db.clone());
348 tokio::spawn(async move {
349 fee_plan::update(
350 &db,
351 plan,
352 None,
353 Some(vec![Installment::new(
354 LedgerAmount::try_new(999).unwrap(),
355 Timestamp::from_millis(2_000),
356 )]),
357 )
358 .await
359 })
360 };
361 let assign = {
362 let (db, plan, manager, student) = (db.clone(), plan.clone(), manager, student);
363 tokio::spawn(async move { assign(&db, &plan, &student, &manager).await })
364 };
365 let (edit, assign) = (edit.await.unwrap(), assign.await.unwrap());
366 assert!(
367 !matches!(edit, Err(AppError::Db(_))),
368 "a raced edit must be refused, not 500: {edit:?}"
369 );
370 assert!(
371 !matches!(assign, Err(AppError::Db(_))),
372 "a raced assign must retry, not 500: {assign:?}"
373 );
374
375 let stored = fee_plan::read(&db, plan.get_id()).await.unwrap().unwrap();
376 let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id())
377 .await
378 .unwrap();
379 if assigned {
380 reached += 1;
381 // The counter is what refuses every later edit, so it has to
382 // agree with the rows it stands for.
383 let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
384 .await
385 .unwrap();
386 assert_eq!(lines.len(), 1, "one installment, one charge");
387 assert_eq!(
388 lines[0].get_amount_minor().as_minor(),
389 stored.get_installments()[0].get_amount_minor().as_minor(),
390 "the charge must be a copy of the plan as it now stands"
391 );
392 assert!(
393 fee_plan::update(&db, plan.clone(), None, None)
394 .await
395 .is_ok(),
396 "an empty PATCH writes nothing, so it is not refused"
397 );
398 assert!(
399 matches!(
400 fee_plan::update(
401 &db,
402 plan.clone(),
403 Some(FeePlanName::try_new("Nope").unwrap()),
404 None
405 )
406 .await,
407 Err(AppError::Conflict(_))
408 ),
409 "an assigned plan stays frozen afterwards"
410 );
411 assert!(
412 !fee_plan::delete(&db, plan.clone()).await.unwrap(),
413 "and it cannot be deleted either"
414 );
415 }
416 }
417 // Every assertion above sits behind "the assign landed", so a run where
418 // it never did asserts nothing at all — the failure this counter turns
419 // into a loud one.
420 assert!(reached > 0, "no round ever placed the assignment");
421 }
422
423 /// The other half, and here "never both" *is* the invariant: a delete and
424 /// an assign racing must never leave a live assignment — with the charges
425 /// it billed — pointing at a plan that is gone. Stored state again, and a
426 /// real server again, for the same reasons.
427 ///
428 /// Both orderings are forced, because the interesting one does not happen on
429 /// its own: with both racers released together the assign wins ~24 rounds in
430 /// 25, so a run that only ever saw that ordering never tested a delete
431 /// landing first at all. Half the rounds therefore hold the assign back by a
432 /// beat, and the two counters below fail the test if either ordering went
433 /// unseen. Neither racer may answer 500 here either — this is the pair that
434 /// contends hardest, both writing the plan record itself.
435 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
436 async fn a_delete_racing_an_assign_never_orphans_an_assignment() {
437 let (db, _leases) = crate::database::init_test_db().await;
438 let (mut deleted_first, mut assigned_first) = (0, 0);
439 for round in 0..20 {
440 let hold_back_the_assign = round % 2 == 0;
441 let manager = a_person(&db, "mgr", "manager").await;
442 let student = a_person(&db, "stu", "student").await;
443 let plan = a_plan(
444 &db,
445 vec![Installment::new(
446 LedgerAmount::try_new(100).unwrap(),
447 Timestamp::from_millis(1_000),
448 )],
449 )
450 .await;
451
452 let head_start = std::time::Duration::from_millis(5);
453 let drop_it = {
454 let (db, plan) = (db.clone(), plan.clone());
455 tokio::spawn(async move {
456 if !hold_back_the_assign {
457 tokio::time::sleep(head_start).await;
458 }
459 fee_plan::delete(&db, plan).await
460 })
461 };
462 let assign = {
463 let (db, plan, manager, student) = (db.clone(), plan.clone(), manager, student);
464 tokio::spawn(async move {
465 if hold_back_the_assign {
466 tokio::time::sleep(head_start).await;
467 }
468 assign(&db, &plan, &student, &manager).await
469 })
470 };
471 let (drop_it, assign) = (drop_it.await.unwrap(), assign.await.unwrap());
472 assert!(
473 !matches!(drop_it, Err(AppError::Db(_))),
474 "a raced delete must retry, not 500: {drop_it:?}"
475 );
476 assert!(
477 !matches!(assign, Err(AppError::Db(_))),
478 "a raced assign must retry, not 500: {assign:?}"
479 );
480
481 let gone = fee_plan::read(&db, plan.get_id()).await.unwrap().is_none();
482 let assigned = fee_plan_assignment::exists_for_plan(&db, plan.get_id())
483 .await
484 .unwrap();
485 deleted_first += usize::from(gone);
486 assigned_first += usize::from(assigned);
487 assert!(
488 !(gone && assigned),
489 "an assignment may not outlive the plan it names"
490 );
491 let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
492 .await
493 .unwrap();
494 assert!(
495 !(gone && !lines.is_empty()),
496 "and neither may the charges it raised"
497 );
498 }
499 // The premise, not a nicety: "never both" is trivially true in a run
500 // where one of the two never landed, so a run that only saw one
501 // ordering has proven nothing and says so.
502 assert!(deleted_first > 0, "no round ever let the delete land first");
503 assert!(
504 assigned_first > 0,
505 "no round ever let the assign land first"
506 );
507 }
508}