Split payment_ledger into domain/db/service layers
Browse files at this commit73f9fa6c2c9a25897c30d5e68410186bdb42c4c0Parent: efea304- chore
- split payment_ledger into domain/db/service layers
7 changed files +936 -879
- src/db/mod.rs +1 -0
- src/db/payment_ledger.rs +241 -0
- src/domain/fee_plan_assignment.rs +9 -9
- src/domain/payment_ledger.rs +25 -854
- src/service/mod.rs +1 -0
- src/service/payment_ledger.rs +641 -0
- src/web/payments.rs +18 -16
src/db/mod.rsmodified+1 -0
| @@ -4,5 +4,6 @@ pub mod cap; | |||
| 4 | pub mod field_update; | 4 | pub mod field_update; |
| 5 | pub mod note; | 5 | pub mod note; |
| 6 | pub mod page; | 6 | pub mod page; |
| 7 | +pub mod payment_ledger; | ||
| 7 | pub mod session; | 8 | pub mod session; |
| 8 | pub mod settings; | 9 | pub mod settings; |
src/db/payment_ledger.rsadded+241 -0
| @@ -0,0 +1,241 @@ | |||
| 1 | +//! The `payment_ledger` table: the append-only `CREATE`s and the reads the | ||
| 2 | +//! balance and the statement fold. Nothing here ever `UPDATE`s or `DELETE`s a | ||
| 3 | +//! row — a mistake is corrected by appending the opposing line. The lock that | ||
| 4 | +//! serializes the money arithmetic around these calls lives in | ||
| 5 | +//! [`crate::service::payment_ledger`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::{AlreadyExistsError, SurrealValue}; | ||
| 8 | + | ||
| 9 | +use crate::constant::{CAS_UPDATE_RETRIES, PAYMENT_LEDGER_TABLE}; | ||
| 10 | +use crate::database::{Database, lost_the_race}; | ||
| 11 | +use crate::db::page::PagedList; | ||
| 12 | +use crate::domain::fee_plan::Installment; | ||
| 13 | +use crate::domain::fee_plan_assignment::FeePlanAssignment; | ||
| 14 | +use crate::domain::payment_ledger::{PaymentLedger, PaymentLedgerId, PaymentLedgerKind}; | ||
| 15 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | +use crate::domain::user::UserId; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | + | ||
| 19 | +/// Did this `CREATE` fail *only* because the row is already there? Matched on | ||
| 20 | +/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text | ||
| 21 | +/// and never on "any database error", because swallowing a real fault in money | ||
| 22 | +/// code would be far worse than the 500 it saves. | ||
| 23 | +fn is_duplicate_record(error: &surrealdb::Error) -> bool { | ||
| 24 | + matches!( | ||
| 25 | + error.already_exists_details(), | ||
| 26 | + Some(AlreadyExistsError::Record { .. }) | ||
| 27 | + ) | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// The only writer: one `CREATE`, no update path anywhere in this module. | ||
| 31 | +/// | ||
| 32 | +/// A line whose id already exists is left exactly as it is — the row wins, | ||
| 33 | +/// the write is dropped. That is what makes a deterministic id (see | ||
| 34 | +/// [`PaymentLedgerId::for_installment`]) an idempotence key: replaying the | ||
| 35 | +/// same append is a no-op, never a second line and never an edit of the | ||
| 36 | +/// first. The point read is on the id itself, so unlike a scan it cannot | ||
| 37 | +/// miss a row a concurrent writer just made — but it is only a fast path. | ||
| 38 | +/// The guarantee is `CREATE`'s own: on an existing id it *errors* and | ||
| 39 | +/// leaves the row untouched, so the writer that lost the race reads back | ||
| 40 | +/// the winner's line instead of failing the request with a 500. | ||
| 41 | +/// | ||
| 42 | +/// A *write conflict* is the same race decided one layer down — two appends | ||
| 43 | +/// of one id arriving together are no longer serialized by a process-wide | ||
| 44 | +/// lock, so the store aborts one as retryable instead of answering it | ||
| 45 | +/// "already exists". Both are read back the same way, and a conflict that | ||
| 46 | +/// turns out to have written nothing is simply tried again; no path here | ||
| 47 | +/// can write a second line, since the id is the key. | ||
| 48 | +/// | ||
| 49 | +/// Both read-backs check the stored line is the *kind* that was being | ||
| 50 | +/// appended. Handing a caller someone else's row is only safe while every | ||
| 51 | +/// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a | ||
| 52 | +/// future marker or a widened key charset ever let two shapes meet, this is | ||
| 53 | +/// the check that turns silently-wrong money into a 500 instead. It should | ||
| 54 | +/// be unreachable, and it is cheap enough to keep it that way. | ||
| 55 | +pub(crate) async fn append(db: &Database, row: PaymentLedger) -> Result<PaymentLedger, AppError> { | ||
| 56 | + let same_kind = |existing: PaymentLedger| { | ||
| 57 | + if existing.kind == row.kind { | ||
| 58 | + Ok(existing) | ||
| 59 | + } else { | ||
| 60 | + Err(AppError::Internal( | ||
| 61 | + "a ledger id resolved to a line of another kind".into(), | ||
| 62 | + )) | ||
| 63 | + } | ||
| 64 | + }; | ||
| 65 | + if let Some(existing) = read(db, &row.id).await? { | ||
| 66 | + return same_kind(existing); | ||
| 67 | + } | ||
| 68 | + let id = row.id.clone(); | ||
| 69 | + for _ in 0..CAS_UPDATE_RETRIES { | ||
| 70 | + match db.create(id.record()).content(row.clone()).await { | ||
| 71 | + Ok(Some(created)) => return Ok(created), | ||
| 72 | + Ok(None) => break, | ||
| 73 | + Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | ||
| 74 | + if let Some(existing) = read(db, &id).await? { | ||
| 75 | + return same_kind(existing); | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | + Err(e) => return Err(e.into()), | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | + Err(AppError::Internal("failed to write the ledger line".into())) | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result<Option<PaymentLedger>, AppError> { | ||
| 85 | + Ok(db.select(id.record()).await?) | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// Bill installment `n` (1-based) of `assignment`, at the amount and due | ||
| 89 | +/// date the plan carried when it was assigned — the charge is a frozen | ||
| 90 | +/// copy, so editing the plan afterwards moves no existing line. | ||
| 91 | +/// | ||
| 92 | +/// Replaying it is free: the id is `(plan, student, n)`, so a duplicate | ||
| 93 | +/// assign writes nothing and an assignment whose charges landed only in | ||
| 94 | +/// part self-heals on the next assign of the same pair. | ||
| 95 | +pub async fn charge_for_installment( | ||
| 96 | + db: &Database, | ||
| 97 | + assignment: &FeePlanAssignment, | ||
| 98 | + n: usize, | ||
| 99 | + installment: &Installment, | ||
| 100 | + recorded_by: &UserId, | ||
| 101 | +) -> Result<PaymentLedger, AppError> { | ||
| 102 | + append( | ||
| 103 | + db, | ||
| 104 | + PaymentLedger { | ||
| 105 | + id: PaymentLedgerId::for_installment(assignment.get_id(), n), | ||
| 106 | + student: assignment.get_student().clone(), | ||
| 107 | + kind: PaymentLedgerKind::Charge, | ||
| 108 | + amount_minor: installment.get_amount_minor(), | ||
| 109 | + source: Some(assignment.get_id().record()), | ||
| 110 | + due_at: Some(installment.get_due_at()), | ||
| 111 | + method: None, | ||
| 112 | + note: None, | ||
| 113 | + recorded_by: recorded_by.clone(), | ||
| 114 | + created_at: Timestamp::now(), | ||
| 115 | + }, | ||
| 116 | + ) | ||
| 117 | + .await | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// A student's whole statement, newest first. | ||
| 121 | +pub async fn list_for_student( | ||
| 122 | + db: &Database, | ||
| 123 | + student: &UserId, | ||
| 124 | + limit: Option<i64>, | ||
| 125 | + offset: i64, | ||
| 126 | +) -> Result<(Vec<PaymentLedger>, i64), AppError> { | ||
| 127 | + PagedList::new( | ||
| 128 | + "payment_ledger WHERE student = $student", | ||
| 129 | + "ORDER BY created_at DESC, id DESC", | ||
| 130 | + ) | ||
| 131 | + .bind("student", student.record()) | ||
| 132 | + .run(limit, offset, db) | ||
| 133 | + .await | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// Every line pointing at `source`: a charge's payments (and its reversal), | ||
| 137 | +/// a credit's refunds. Feeds the over-payment cap and, later, the statement | ||
| 138 | +/// rollup. Oldest first — this is a history, not a page. | ||
| 139 | +pub async fn list_for_source( | ||
| 140 | + db: &Database, | ||
| 141 | + source: &PaymentLedgerId, | ||
| 142 | +) -> Result<Vec<PaymentLedger>, AppError> { | ||
| 143 | + let mut result = db | ||
| 144 | + .query("SELECT * FROM payment_ledger WHERE source = $source ORDER BY created_at, id") | ||
| 145 | + .bind(("source", source.record())) | ||
| 146 | + .await? | ||
| 147 | + .check()?; | ||
| 148 | + Ok(result.take::<Vec<PaymentLedger>>(0)?) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] | ||
| 152 | +/// hands it back — at most four rows, never the lines behind them. | ||
| 153 | +#[derive(Debug, SurrealValue)] | ||
| 154 | +struct KindTotal { | ||
| 155 | + kind: PaymentLedgerKind, | ||
| 156 | + total: i64, | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +/// The derived balance: `credits + reversals - charges - refunds`, in minor | ||
| 160 | +/// units. Negative means the family owes the school. Never stored anywhere. | ||
| 161 | +/// | ||
| 162 | +/// **The sum is taken per kind by the database** and only the four totals | ||
| 163 | +/// come back, so a balance read costs the same whether the ledger holds | ||
| 164 | +/// four lines or forty thousand. It used to decode and fold every row, and | ||
| 165 | +/// a fee ledger grows by design rather than only under abuse: one | ||
| 166 | +/// assignment appends a charge *per installment* per student (up to | ||
| 167 | +/// [`MAX_FEE_PLAN_ASSIGN_WRITES`](crate::constant::MAX_FEE_PLAN_ASSIGN_WRITES) | ||
| 168 | +/// in a single request), and every one of those rows was decoded again by | ||
| 169 | +/// every later `GET /payments/balance/*`. | ||
| 170 | +/// | ||
| 171 | +/// **The signs stay here**, applied by the same | ||
| 172 | +/// `PaymentLedgerKind::sign` the documented formula is spelled in — | ||
| 173 | +/// [`PaymentLedger::fold_balance`](crate::domain::payment_ledger::PaymentLedger::fold_balance) | ||
| 174 | +/// folds the grouped totals and the raw lines alike. Summing | ||
| 175 | +/// `IF kind = 'charge' THEN -amount …` in SQL would have folded the whole | ||
| 176 | +/// balance in one statement and forked the one rule that decides what money | ||
| 177 | +/// means into a second language, where nothing fails the day the two | ||
| 178 | +/// disagree. Grouping keeps the aggregate ignorant of signs. A stored | ||
| 179 | +/// running total was the third option and is a counter that can drift — a | ||
| 180 | +/// bug class this repo closes, not one it opens. | ||
| 181 | +pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { | ||
| 182 | + let totals: Vec<KindTotal> = db | ||
| 183 | + .query(format!( | ||
| 184 | + "SELECT kind, math::sum(amount_minor) AS total \ | ||
| 185 | + FROM {PAYMENT_LEDGER_TABLE} WHERE student = $student GROUP BY kind" | ||
| 186 | + )) | ||
| 187 | + .bind(("student", student.record())) | ||
| 188 | + .await? | ||
| 189 | + .check()? | ||
| 190 | + .take(0)?; | ||
| 191 | + Ok(PaymentLedger::fold_balance( | ||
| 192 | + totals.into_iter().map(|row| (row.kind, row.total)), | ||
| 193 | + )) | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +#[cfg(test)] | ||
| 197 | +mod tests { | ||
| 198 | + use super::*; | ||
| 199 | + use crate::domain::user::UserId; | ||
| 200 | + | ||
| 201 | + /// The mem engine is not the store this runs against, and an aggregate is | ||
| 202 | + /// exactly where the two have diverged before: `count()` over an *indexed* | ||
| 203 | + /// field compared to a plan-time value comes back `{count: N}` rather than | ||
| 204 | + /// a plain int, and `student` is indexed on this table | ||
| 205 | + /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real | ||
| 206 | + /// server: that it decodes into [`KindTotal`], that it folds to the | ||
| 207 | + /// documented figure per kind, that it is scoped to one student, and that | ||
| 208 | + /// someone with no lines at all comes back `0` rather than an error. | ||
| 209 | + #[tokio::test] | ||
| 210 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 211 | + async fn the_balance_aggregate_decodes_on_a_real_server() { | ||
| 212 | + let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await; | ||
| 213 | + db.query( | ||
| 214 | + "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \ | ||
| 215 | + amount_minor = 10000, recorded_by = user:adm, created_at = 1; | ||
| 216 | + CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \ | ||
| 217 | + amount_minor = 6000, recorded_by = user:adm, created_at = 2; | ||
| 218 | + CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \ | ||
| 219 | + amount_minor = 1000, recorded_by = user:adm, created_at = 3; | ||
| 220 | + CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \ | ||
| 221 | + amount_minor = 4500, recorded_by = user:adm, created_at = 4; | ||
| 222 | + CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \ | ||
| 223 | + amount_minor = 777, recorded_by = user:adm, created_at = 5;", | ||
| 224 | + ) | ||
| 225 | + .await | ||
| 226 | + .unwrap() | ||
| 227 | + .check() | ||
| 228 | + .unwrap(); | ||
| 229 | + let ali = UserId::from_key("ali"); | ||
| 230 | + assert_eq!( | ||
| 231 | + balance_of(&db, &ali).await.unwrap(), | ||
| 232 | + 6_000 + 4_500 - 10_000 - 1_000, | ||
| 233 | + "credits + reversals - charges - refunds, and veli's line is not ali's" | ||
| 234 | + ); | ||
| 235 | + // Somebody with no lines at all: no groups come back, not an error. | ||
| 236 | + assert_eq!( | ||
| 237 | + balance_of(&db, &UserId::from_key("nobody")).await.unwrap(), | ||
| 238 | + 0 | ||
| 239 | + ); | ||
| 240 | + } | ||
| 241 | +} | ||
src/domain/fee_plan_assignment.rsmodified+9 -9
| @@ -20,9 +20,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |||
| 20 | use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE}; | 20 | use crate::constant::{FEE_PLAN_ASSIGNMENT_COUNT_FIELD, FEE_PLAN_ASSIGNMENT_TABLE}; |
| 21 | use crate::database::Database; | 21 | use crate::database::Database; |
| 22 | use crate::db::cap::{self, Claimed}; | 22 | use crate::db::cap::{self, Claimed}; |
| 23 | -use crate::domain::fee_plan::{FeePlan, FeePlanId}; | ||
| 24 | use crate::db::page::PagedList; | 23 | use crate::db::page::PagedList; |
| 25 | -use crate::domain::payment_ledger::PaymentLedger; | 24 | +use crate::db::payment_ledger; |
| 25 | +use crate::domain::fee_plan::{FeePlan, FeePlanId}; | ||
| 26 | use crate::domain::timestamp::Timestamp; | 26 | use crate::domain::timestamp::Timestamp; |
| 27 | use crate::domain::user::UserId; | 27 | use crate::domain::user::UserId; |
| 28 | use crate::error::AppError; | 28 | use crate::error::AppError; |
| @@ -147,12 +147,12 @@ impl FeePlanAssignment { | |||
| 147 | .await? | 147 | .await? |
| 148 | .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; | 148 | .ok_or_else(|| AppError::Internal("the assigned fee plan vanished".into()))?; |
| 149 | for (index, installment) in plan.get_installments().iter().enumerate() { | 149 | for (index, installment) in plan.get_installments().iter().enumerate() { |
| 150 | - PaymentLedger::charge_for_installment( | 150 | + payment_ledger::charge_for_installment( |
| 151 | + db, | ||
| 151 | &assignment, | 152 | &assignment, |
| 152 | index + 1, | 153 | index + 1, |
| 153 | installment, | 154 | installment, |
| 154 | assigned_by, | 155 | assigned_by, |
| 155 | - db, | ||
| 156 | ) | 156 | ) |
| 157 | .await?; | 157 | .await?; |
| 158 | } | 158 | } |
| @@ -258,7 +258,7 @@ mod tests { | |||
| 258 | .unwrap(); | 258 | .unwrap(); |
| 259 | assert!(!existed); | 259 | assert!(!existed); |
| 260 | assert_eq!( | 260 | assert_eq!( |
| 261 | - PaymentLedger::balance_of(&student, &db).await.unwrap(), | 261 | + payment_ledger::balance_of(&db, &student).await.unwrap(), |
| 262 | -400_000, | 262 | -400_000, |
| 263 | "both installments must be owed" | 263 | "both installments must be owed" |
| 264 | ); | 264 | ); |
| @@ -270,7 +270,7 @@ mod tests { | |||
| 270 | existed, | 270 | existed, |
| 271 | "the second assign is a replay, not a new placement" | 271 | "the second assign is a replay, not a new placement" |
| 272 | ); | 272 | ); |
| 273 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | 273 | + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) |
| 274 | .await | 274 | .await |
| 275 | .unwrap(); | 275 | .unwrap(); |
| 276 | assert_eq!(lines.len(), 2, "a replay may not append a single line"); | 276 | assert_eq!(lines.len(), 2, "a replay may not append a single line"); |
| @@ -280,7 +280,7 @@ mod tests { | |||
| 280 | .all(|l| l.get_kind() == PaymentLedgerKind::Charge) | 280 | .all(|l| l.get_kind() == PaymentLedgerKind::Charge) |
| 281 | ); | 281 | ); |
| 282 | assert_eq!( | 282 | assert_eq!( |
| 283 | - PaymentLedger::balance_of(&student, &db).await.unwrap(), | 283 | + payment_ledger::balance_of(&db, &student).await.unwrap(), |
| 284 | -400_000 | 284 | -400_000 |
| 285 | ); | 285 | ); |
| 286 | assert!( | 286 | assert!( |
| @@ -375,7 +375,7 @@ mod tests { | |||
| 375 | reached += 1; | 375 | reached += 1; |
| 376 | // The counter is what refuses every later edit, so it has to | 376 | // The counter is what refuses every later edit, so it has to |
| 377 | // agree with the rows it stands for. | 377 | // agree with the rows it stands for. |
| 378 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | 378 | + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) |
| 379 | .await | 379 | .await |
| 380 | .unwrap(); | 380 | .unwrap(); |
| 381 | assert_eq!(lines.len(), 1, "one installment, one charge"); | 381 | assert_eq!(lines.len(), 1, "one installment, one charge"); |
| @@ -482,7 +482,7 @@ mod tests { | |||
| 482 | !(gone && assigned), | 482 | !(gone && assigned), |
| 483 | "an assignment may not outlive the plan it names" | 483 | "an assignment may not outlive the plan it names" |
| 484 | ); | 484 | ); |
| 485 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | 485 | + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) |
| 486 | .await | 486 | .await |
| 487 | .unwrap(); | 487 | .unwrap(); |
| 488 | assert!( | 488 | assert!( |
src/domain/payment_ledger.rsmodified+25 -854
| @@ -20,7 +20,8 @@ | |||
| 20 | //! | 20 | //! |
| 21 | //! The rules the rest of the code depends on: | 21 | //! The rules the rest of the code depends on: |
| 22 | //! | 22 | //! |
| 23 | -//! - **Assignment is the charge trigger.** Assigning a [`FeePlan`] appends | 23 | +//! - **Assignment is the charge trigger.** Assigning a |
| 24 | +//! [`FeePlan`](crate::domain::fee_plan::FeePlan) appends | ||
| 24 | //! *every* installment as a charge at once, each carrying its own `due_at`. | 25 | //! *every* installment as a charge at once, each carrying its own `due_at`. |
| 25 | //! There is no scheduler and no sweep: "overdue" is a derived reading of an | 26 | //! There is no scheduler and no sweep: "overdue" is a derived reading of an |
| 26 | //! unpaid line whose `due_at` has passed. The amount is a frozen copy — later | 27 | //! unpaid line whose `due_at` has passed. The amount is a frozen copy — later |
| @@ -40,76 +41,19 @@ | |||
| 40 | //! self-heals when it is repeated. Money must never depend on a "has this | 41 | //! self-heals when it is repeated. Money must never depend on a "has this |
| 41 | //! been billed yet?" scan: two concurrent requests can both read "not yet" | 42 | //! been billed yet?" scan: two concurrent requests can both read "not yet" |
| 42 | //! and both append. | 43 | //! and both append. |
| 43 | -//! - **A payment or a refund is replayable when the client names it.** An | ||
| 44 | -//! optional `request_key` keys the line `<target>_k_<key>` (or `_kr_` for a | ||
| 45 | -//! refund), so a retry after a timeout derives the row the first attempt | ||
| 46 | -//! wrote — same identity rule, no scan. The key is scoped by the line it | ||
| 47 | -//! targets, so it never has to be globally unique. Without a key the id is a | ||
| 48 | -//! fresh ulid and two identical calls are two payments, which is what a desk | ||
| 49 | -//! taking the same amount twice really means. The **replay read happens | ||
| 50 | -//! before the cap check** and inside [`PAYMENT_LOCK`]: the first attempt's | ||
| 51 | -//! line is already inside what the cap folds, so checking the cap first would | ||
| 52 | -//! refuse the very payment that landed. A key replayed with a *different* | ||
| 53 | -//! amount or against a *different* line is a `409`, never the stored line — | ||
| 54 | -//! returning it would hide a client bug behind a `201`. | ||
| 55 | -//! | ||
| 56 | -//! **The over-payment cap is the lock's, not the database's.** [`PaymentLedger::credit`] | ||
| 57 | -//! and [`PaymentLedger::refund`] refuse to take more than the line they target | ||
| 58 | -//! is worth, by folding that line's whole subtree under [`PAYMENT_LOCK`]. The | ||
| 59 | -//! fold, rather than a sum of the direct children, because money handed back | ||
| 60 | -//! frees the room it took: a charge paid in full and then refunded is owed | ||
| 61 | -//! again, and must be payable again. Every write that *moves* that arithmetic | ||
| 62 | -//! takes the same lock — [`PaymentLedger::reversal`] included, since a reversal | ||
| 63 | -//! landing between a payment's fold and its append would admit the payment | ||
| 64 | -//! against room it no longer has. | ||
| 65 | -//! | ||
| 66 | -//! The lock is what makes that check mean anything, and it is load-bearing: | ||
| 67 | -//! the fold is a count-then-write across rows, and SurrealDB does not | ||
| 68 | -//! conflict-check a cross-record read against a concurrent insert (the | ||
| 69 | -//! write-skew this repo has hit before), so a fold left unserialized would let | ||
| 70 | -//! two payments both see room and both take it. Running as one process buys | ||
| 71 | -//! nothing on its own — two request tasks interleave across the fold's `await` | ||
| 72 | -//! exactly as two machines would. The cap therefore holds only for as long as | ||
| 73 | -//! *every* write that moves this arithmetic is taken under [`PAYMENT_LOCK`]; | ||
| 74 | -//! a future append that skips it re-opens the hole silently, which is why the | ||
| 75 | -//! rule is stated here rather than left to be noticed. If an over-payment ever | ||
| 76 | -//! does land it is not a crisis — an over-paid charge is plainly visible in the | ||
| 77 | -//! statement and undone by appending a refund, and both entries are true | ||
| 78 | -//! records of money that really arrived. A CAS counter row was rejected — | ||
| 79 | -//! refunding would have to decrement it, which is a stored derived balance by | ||
| 80 | -//! another name. What the fold costs is also what bounds it: at most | ||
| 81 | -//! [`MAX_LEDGER_APPLIED_LINES`] lines may be applied to any one line, since | ||
| 82 | -//! every one of them is another query taken with the lock held. | ||
| 83 | -//! | ||
| 84 | -//! The `request_key` mismatch `409` rides on the same lock: it is a | ||
| 85 | -//! read-then-compare, and it is read *inside* the lock, so two first-time posts | ||
| 86 | -//! of one key with different amounts cannot both walk past it. One line, one | ||
| 87 | -//! amount, no double charge, and the "you reused a key" diagnostic is exact. | ||
| 88 | 44 | ||
| 89 | -use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; | 45 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 90 | -use tokio::sync::Mutex; | ||
| 91 | 46 | ||
| 92 | -use crate::constant::{CAS_UPDATE_RETRIES, MAX_LEDGER_APPLIED_LINES, PAYMENT_LEDGER_TABLE}; | 47 | +use crate::constant::PAYMENT_LEDGER_TABLE; |
| 93 | -use crate::database::{Database, lost_the_race}; | 48 | +use crate::domain::fee_plan_assignment::FeePlanAssignmentId; |
| 94 | -use crate::domain::fee_plan::Installment; | ||
| 95 | -use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId}; | ||
| 96 | // The three value types are the *same* money vocabulary the canteen ledger | 49 | // The three value types are the *same* money vocabulary the canteen ledger |
| 97 | // speaks, so they are imported rather than copied: one cap, one trim rule, one | 50 | // speaks, so they are imported rather than copied: one cap, one trim rule, one |
| 98 | // error message for both ledgers. | 51 | // error message for both ledgers. |
| 99 | pub use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote}; | 52 | pub use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote}; |
| 100 | use crate::domain::monotonic_id::next_ulid; | 53 | use crate::domain::monotonic_id::next_ulid; |
| 101 | -use crate::db::page::PagedList; | ||
| 102 | use crate::domain::timestamp::Timestamp; | 54 | use crate::domain::timestamp::Timestamp; |
| 103 | use crate::domain::user::UserId; | 55 | use crate::domain::user::UserId; |
| 104 | -use crate::error::{AppError, ValidationError}; | 56 | +use crate::error::ValidationError; |
| 105 | - | ||
| 106 | -/// Serializes the over-payment check, the append it authorizes, and every | ||
| 107 | -/// other append that changes the arithmetic that check does — nothing else. | ||
| 108 | -/// It is the whole guarantee behind that cap, not a convenience: the fold it | ||
| 109 | -/// protects is a cross-record read the database will not conflict-check | ||
| 110 | -/// against a concurrent insert. Held across no other lock, and no other lock is | ||
| 111 | -/// taken while it is held. | ||
| 112 | -pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 113 | 57 | ||
| 114 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 58 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 115 | pub struct PaymentLedgerId(RecordId); | 59 | pub struct PaymentLedgerId(RecordId); |
| @@ -163,7 +107,8 @@ impl PaymentLedgerId { | |||
| 163 | /// must own, and the loser of that collision would be handed a line of the | 107 | /// must own, and the loser of that collision would be handed a line of the |
| 164 | /// wrong kind and the wrong amount, with the real reversal impossible | 108 | /// wrong kind and the wrong amount, with the real reversal impossible |
| 165 | /// forever after. The ban on `_` in a key is what makes the collision | 109 | /// forever after. The ban on `_` in a key is what makes the collision |
| 166 | - /// unconstructible; [`PaymentLedger::append`] re-checks the kind anyway. | 110 | + /// unconstructible; `crate::db::payment_ledger::append` re-checks the |
| 111 | + /// kind anyway. | ||
| 167 | pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { | 112 | pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { |
| 168 | Self(RecordId::new( | 113 | Self(RecordId::new( |
| 169 | PAYMENT_LEDGER_TABLE, | 114 | PAYMENT_LEDGER_TABLE, |
| @@ -197,17 +142,6 @@ impl PaymentRequestKey { | |||
| 197 | } | 142 | } |
| 198 | } | 143 | } |
| 199 | 144 | ||
| 200 | -/// Did this `CREATE` fail *only* because the row is already there? Matched on | ||
| 201 | -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text | ||
| 202 | -/// and never on "any database error", because swallowing a real fault in money | ||
| 203 | -/// code would be far worse than the 500 it saves. | ||
| 204 | -fn is_duplicate_record(error: &surrealdb::Error) -> bool { | ||
| 205 | - matches!( | ||
| 206 | - error.already_exists_details(), | ||
| 207 | - Some(AlreadyExistsError::Record { .. }) | ||
| 208 | - ) | ||
| 209 | -} | ||
| 210 | - | ||
| 211 | /// The bare key of a record id — how every id leaves this API. | 145 | /// The bare key of a record id — how every id leaves this API. |
| 212 | fn key_of(record: &RecordId) -> &str { | 146 | fn key_of(record: &RecordId) -> &str { |
| 213 | match &record.key { | 147 | match &record.key { |
| @@ -241,7 +175,7 @@ impl PaymentLedgerKind { | |||
| 241 | /// How the line folds into the balance: a charge bills the family and a | 175 | /// How the line folds into the balance: a charge bills the family and a |
| 242 | /// refund hands money back, so both take away. This is the *single* place | 176 | /// refund hands money back, so both take away. This is the *single* place |
| 243 | /// the sign convention lives. | 177 | /// the sign convention lives. |
| 244 | - fn sign(self) -> i64 { | 178 | + pub(crate) fn sign(self) -> i64 { |
| 245 | match self { | 179 | match self { |
| 246 | PaymentLedgerKind::Charge | PaymentLedgerKind::Refund => -1, | 180 | PaymentLedgerKind::Charge | PaymentLedgerKind::Refund => -1, |
| 247 | PaymentLedgerKind::Credit | PaymentLedgerKind::Reversal => 1, | 181 | PaymentLedgerKind::Credit | PaymentLedgerKind::Reversal => 1, |
| @@ -249,22 +183,25 @@ impl PaymentLedgerKind { | |||
| 249 | } | 183 | } |
| 250 | } | 184 | } |
| 251 | 185 | ||
| 186 | +/// Fields are crate-visible: [`crate::db::payment_ledger`] mints the charge | ||
| 187 | +/// rows, and [`crate::service::payment_ledger`] appends the credits, refunds, | ||
| 188 | +/// and reversals the cap lock authorizes. | ||
| 252 | #[derive(Debug, Clone, SurrealValue)] | 189 | #[derive(Debug, Clone, SurrealValue)] |
| 253 | pub struct PaymentLedger { | 190 | pub struct PaymentLedger { |
| 254 | - id: PaymentLedgerId, | 191 | + pub(crate) id: PaymentLedgerId, |
| 255 | - student: UserId, | 192 | + pub(crate) student: UserId, |
| 256 | - kind: PaymentLedgerKind, | 193 | + pub(crate) kind: PaymentLedgerKind, |
| 257 | - amount_minor: LedgerAmount, | 194 | + pub(crate) amount_minor: LedgerAmount, |
| 258 | /// What caused the line: a charge points at its `fee_plan_assignment`, a | 195 | /// What caused the line: a charge points at its `fee_plan_assignment`, a |
| 259 | /// credit at the charge it pays, a refund at the credit it returns, a | 196 | /// credit at the charge it pays, a refund at the credit it returns, a |
| 260 | /// reversal at the line it undoes. Untyped, hence a bare `RecordId`. | 197 | /// reversal at the line it undoes. Untyped, hence a bare `RecordId`. |
| 261 | - source: Option<RecordId>, | 198 | + pub(crate) source: Option<RecordId>, |
| 262 | /// When this installment falls due. Charges only — nothing else has one. | 199 | /// When this installment falls due. Charges only — nothing else has one. |
| 263 | - due_at: Option<Timestamp>, | 200 | + pub(crate) due_at: Option<Timestamp>, |
| 264 | - method: Option<LedgerMethod>, | 201 | + pub(crate) method: Option<LedgerMethod>, |
| 265 | - note: Option<LedgerNote>, | 202 | + pub(crate) note: Option<LedgerNote>, |
| 266 | - recorded_by: UserId, | 203 | + pub(crate) recorded_by: UserId, |
| 267 | - created_at: Timestamp, | 204 | + pub(crate) created_at: Timestamp, |
| 268 | } | 205 | } |
| 269 | 206 | ||
| 270 | impl PaymentLedger { | 207 | impl PaymentLedger { |
| @@ -309,422 +246,10 @@ impl PaymentLedger { | |||
| 309 | self.created_at | 246 | self.created_at |
| 310 | } | 247 | } |
| 311 | 248 | ||
| 312 | - /// The only writer: one `CREATE`, no update path anywhere in this module. | ||
| 313 | - /// | ||
| 314 | - /// A line whose id already exists is left exactly as it is — the row wins, | ||
| 315 | - /// the write is dropped. That is what makes a deterministic id (see | ||
| 316 | - /// [`PaymentLedgerId::for_installment`]) an idempotence key: replaying the | ||
| 317 | - /// same append is a no-op, never a second line and never an edit of the | ||
| 318 | - /// first. The point read is on the id itself, so unlike a scan it cannot | ||
| 319 | - /// miss a row a concurrent writer just made — but it is only a fast path. | ||
| 320 | - /// The guarantee is `CREATE`'s own: on an existing id it *errors* and | ||
| 321 | - /// leaves the row untouched, so the writer that lost the race reads back | ||
| 322 | - /// the winner's line instead of failing the request with a 500. | ||
| 323 | - /// | ||
| 324 | - /// A *write conflict* is the same race decided one layer down — two appends | ||
| 325 | - /// of one id arriving together are no longer serialized by a process-wide | ||
| 326 | - /// lock, so the store aborts one as retryable instead of answering it | ||
| 327 | - /// "already exists". Both are read back the same way, and a conflict that | ||
| 328 | - /// turns out to have written nothing is simply tried again; no path here | ||
| 329 | - /// can write a second line, since the id is the key. | ||
| 330 | - /// | ||
| 331 | - /// Both read-backs check the stored line is the *kind* that was being | ||
| 332 | - /// appended. Handing a caller someone else's row is only safe while every | ||
| 333 | - /// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a | ||
| 334 | - /// future marker or a widened key charset ever let two shapes meet, this is | ||
| 335 | - /// the check that turns silently-wrong money into a 500 instead. It should | ||
| 336 | - /// be unreachable, and it is cheap enough to keep it that way. | ||
| 337 | - async fn append(row: PaymentLedger, db: &Database) -> Result<PaymentLedger, AppError> { | ||
| 338 | - let same_kind = |existing: PaymentLedger| { | ||
| 339 | - if existing.kind == row.kind { | ||
| 340 | - Ok(existing) | ||
| 341 | - } else { | ||
| 342 | - Err(AppError::Internal( | ||
| 343 | - "a ledger id resolved to a line of another kind".into(), | ||
| 344 | - )) | ||
| 345 | - } | ||
| 346 | - }; | ||
| 347 | - if let Some(existing) = Self::read(&row.id, db).await? { | ||
| 348 | - return same_kind(existing); | ||
| 349 | - } | ||
| 350 | - let id = row.id.clone(); | ||
| 351 | - for _ in 0..CAS_UPDATE_RETRIES { | ||
| 352 | - match db.create(id.record()).content(row.clone()).await { | ||
| 353 | - Ok(Some(created)) => return Ok(created), | ||
| 354 | - Ok(None) => break, | ||
| 355 | - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | ||
| 356 | - if let Some(existing) = Self::read(&id, db).await? { | ||
| 357 | - return same_kind(existing); | ||
| 358 | - } | ||
| 359 | - } | ||
| 360 | - Err(e) => return Err(e.into()), | ||
| 361 | - } | ||
| 362 | - } | ||
| 363 | - Err(AppError::Internal("failed to write the ledger line".into())) | ||
| 364 | - } | ||
| 365 | - | ||
| 366 | - pub async fn read( | ||
| 367 | - id: &PaymentLedgerId, | ||
| 368 | - db: &Database, | ||
| 369 | - ) -> Result<Option<PaymentLedger>, AppError> { | ||
| 370 | - Ok(db.select(id.record()).await?) | ||
| 371 | - } | ||
| 372 | - | ||
| 373 | - /// Bill installment `n` (1-based) of `assignment`, at the amount and due | ||
| 374 | - /// date the plan carried when it was assigned — the charge is a frozen | ||
| 375 | - /// copy, so editing the plan afterwards moves no existing line. | ||
| 376 | - /// | ||
| 377 | - /// Replaying it is free: the id is `(plan, student, n)`, so a duplicate | ||
| 378 | - /// assign writes nothing and an assignment whose charges landed only in | ||
| 379 | - /// part self-heals on the next assign of the same pair. | ||
| 380 | - pub async fn charge_for_installment( | ||
| 381 | - assignment: &FeePlanAssignment, | ||
| 382 | - n: usize, | ||
| 383 | - installment: &Installment, | ||
| 384 | - recorded_by: &UserId, | ||
| 385 | - db: &Database, | ||
| 386 | - ) -> Result<PaymentLedger, AppError> { | ||
| 387 | - Self::append( | ||
| 388 | - PaymentLedger { | ||
| 389 | - id: PaymentLedgerId::for_installment(assignment.get_id(), n), | ||
| 390 | - student: assignment.get_student().clone(), | ||
| 391 | - kind: PaymentLedgerKind::Charge, | ||
| 392 | - amount_minor: installment.get_amount_minor(), | ||
| 393 | - source: Some(assignment.get_id().record()), | ||
| 394 | - due_at: Some(installment.get_due_at()), | ||
| 395 | - method: None, | ||
| 396 | - note: None, | ||
| 397 | - recorded_by: recorded_by.clone(), | ||
| 398 | - created_at: Timestamp::now(), | ||
| 399 | - }, | ||
| 400 | - db, | ||
| 401 | - ) | ||
| 402 | - .await | ||
| 403 | - } | ||
| 404 | - | ||
| 405 | - /// Money in, against one named `charge`. Partial payments are the norm, so | ||
| 406 | - /// a charge may collect several credits; together they may not exceed it | ||
| 407 | - /// (advisory — see the module doc's accepted race). A *reversed* charge | ||
| 408 | - /// takes no payment either, and is refused saying so rather than claiming | ||
| 409 | - /// it was paid. | ||
| 410 | - /// | ||
| 411 | - /// With a `request_key` the line is keyed by it (see | ||
| 412 | - /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without | ||
| 413 | - /// one the id is a fresh ulid and two identical calls are two payments, | ||
| 414 | - /// which is what a cash desk taking the same amount twice really means. | ||
| 415 | - pub async fn credit( | ||
| 416 | - charge: &PaymentLedger, | ||
| 417 | - amount_minor: LedgerAmount, | ||
| 418 | - method: Option<LedgerMethod>, | ||
| 419 | - note: Option<LedgerNote>, | ||
| 420 | - request_key: Option<&PaymentRequestKey>, | ||
| 421 | - recorded_by: &UserId, | ||
| 422 | - db: &Database, | ||
| 423 | - ) -> Result<PaymentLedger, AppError> { | ||
| 424 | - Self::against( | ||
| 425 | - charge, | ||
| 426 | - PaymentLedgerKind::Charge, | ||
| 427 | - PaymentLedgerKind::Credit, | ||
| 428 | - "a payment must be recorded against a charge", | ||
| 429 | - "the charge is already paid in full", | ||
| 430 | - // A charge *is* reversible, and its reversal fills the same room a | ||
| 431 | - // payment would, so the fold refuses the two cases identically. | ||
| 432 | - Some("the charge was reversed, so it is no longer owed"), | ||
| 433 | - amount_minor, | ||
| 434 | - method, | ||
| 435 | - note, | ||
| 436 | - request_key.map(|key| PaymentLedgerId::for_request(charge.get_id(), "k", key)), | ||
| 437 | - recorded_by, | ||
| 438 | - db, | ||
| 439 | - ) | ||
| 440 | - .await | ||
| 441 | - } | ||
| 442 | - | ||
| 443 | - /// Money back out, against one named `credit` — how an over-payment or a | ||
| 444 | - /// payment recorded in error is returned. Partials allowed, and no more | ||
| 445 | - /// than the credit was worth (advisory, same race). `request_key` makes it | ||
| 446 | - /// retry-safe exactly as it does for [`PaymentLedger::credit`]. | ||
| 447 | - pub async fn refund( | ||
| 448 | - credit: &PaymentLedger, | ||
| 449 | - amount_minor: LedgerAmount, | ||
| 450 | - method: Option<LedgerMethod>, | ||
| 451 | - note: Option<LedgerNote>, | ||
| 452 | - request_key: Option<&PaymentRequestKey>, | ||
| 453 | - recorded_by: &UserId, | ||
| 454 | - db: &Database, | ||
| 455 | - ) -> Result<PaymentLedger, AppError> { | ||
| 456 | - Self::against( | ||
| 457 | - credit, | ||
| 458 | - PaymentLedgerKind::Credit, | ||
| 459 | - PaymentLedgerKind::Refund, | ||
| 460 | - "a refund must be recorded against a payment", | ||
| 461 | - "the payment is already refunded in full", | ||
| 462 | - // A credit is never reversed ([`PaymentLedger::reversal`] refuses | ||
| 463 | - // it), so a full fold here can only mean the refunds, and there is | ||
| 464 | - // no second reason to tell apart — nor a read to spend looking. | ||
| 465 | - None, | ||
| 466 | - amount_minor, | ||
| 467 | - method, | ||
| 468 | - note, | ||
| 469 | - request_key.map(|key| PaymentLedgerId::for_request(credit.get_id(), "kr", key)), | ||
| 470 | - recorded_by, | ||
| 471 | - db, | ||
| 472 | - ) | ||
| 473 | - .await | ||
| 474 | - } | ||
| 475 | - | ||
| 476 | - /// The shared body of `credit` and `refund`: check the target is the kind | ||
| 477 | - /// this line may point at, then append under [`PAYMENT_LOCK`] while the | ||
| 478 | - /// target's existing children still sum below its amount. | ||
| 479 | - /// | ||
| 480 | - /// The replay read comes **before** the cap, and inside the lock: on a | ||
| 481 | - /// retry the first attempt's line is already part of the subtree the cap | ||
| 482 | - /// folds, so consulting the cap first would answer a payment that landed | ||
| 483 | - /// with "already paid in full" — refusing precisely the request that | ||
| 484 | - /// succeeded. Reading the id under the lock also keeps two simultaneous | ||
| 485 | - /// retries from both walking into the cap check. | ||
| 486 | - #[allow(clippy::too_many_arguments)] | ||
| 487 | - async fn against( | ||
| 488 | - target: &PaymentLedger, | ||
| 489 | - expected: PaymentLedgerKind, | ||
| 490 | - kind: PaymentLedgerKind, | ||
| 491 | - wrong_target: &'static str, | ||
| 492 | - over: &'static str, | ||
| 493 | - reversed: Option<&'static str>, | ||
| 494 | - amount_minor: LedgerAmount, | ||
| 495 | - method: Option<LedgerMethod>, | ||
| 496 | - note: Option<LedgerNote>, | ||
| 497 | - keyed: Option<PaymentLedgerId>, | ||
| 498 | - recorded_by: &UserId, | ||
| 499 | - db: &Database, | ||
| 500 | - ) -> Result<PaymentLedger, AppError> { | ||
| 501 | - if target.kind != expected { | ||
| 502 | - return Err(ValidationError::Invalid { | ||
| 503 | - field: "source", | ||
| 504 | - reason: wrong_target, | ||
| 505 | - } | ||
| 506 | - .into()); | ||
| 507 | - } | ||
| 508 | - let _guard = PAYMENT_LOCK.lock().await; | ||
| 509 | - if let Some(id) = &keyed | ||
| 510 | - && let Some(existing) = Self::read(id, db).await? | ||
| 511 | - { | ||
| 512 | - // A replay is answered from the stored line — but only if it is the | ||
| 513 | - // same money. The same key for a different amount or a different | ||
| 514 | - // target is a client bug, and handing back the old line would hide | ||
| 515 | - // it behind a `201`. | ||
| 516 | - if existing.amount_minor.as_minor() != amount_minor.as_minor() | ||
| 517 | - || existing.get_source_key() != Some(target.id.key()) | ||
| 518 | - { | ||
| 519 | - return Err(AppError::Conflict( | ||
| 520 | - "this request_key was already used for a different amount or target", | ||
| 521 | - )); | ||
| 522 | - } | ||
| 523 | - return Ok(existing); | ||
| 524 | - } | ||
| 525 | - let taken = Self::applied_to(target, db).await?; | ||
| 526 | - if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { | ||
| 527 | - // The fold cannot say *why* the room is gone: a reversal is a child | ||
| 528 | - // of the line it undoes and folds in at `+amount` exactly as a | ||
| 529 | - // payment does, so a reversed charge reads as full to the kuruş. | ||
| 530 | - // The stored answer is the same either way — nothing may be | ||
| 531 | - // recorded against it — but "already paid in full" told a bursar | ||
| 532 | - // money had arrived when none ever did. The reversal's id is | ||
| 533 | - // derived from its target's, so telling the two apart is one read, | ||
| 534 | - // taken only on the refusal path. | ||
| 535 | - if let Some(reversed) = reversed | ||
| 536 | - && Self::read(&PaymentLedgerId::for_reversal(&target.id), db) | ||
| 537 | - .await? | ||
| 538 | - .is_some() | ||
| 539 | - { | ||
| 540 | - return Err(AppError::Conflict(reversed)); | ||
| 541 | - } | ||
| 542 | - return Err(AppError::Conflict(over)); | ||
| 543 | - } | ||
| 544 | - Self::append( | ||
| 545 | - PaymentLedger { | ||
| 546 | - id: keyed.unwrap_or_else(PaymentLedgerId::generate), | ||
| 547 | - student: target.student.clone(), | ||
| 548 | - kind, | ||
| 549 | - amount_minor, | ||
| 550 | - source: Some(target.id.record()), | ||
| 551 | - due_at: None, | ||
| 552 | - method, | ||
| 553 | - note, | ||
| 554 | - recorded_by: recorded_by.clone(), | ||
| 555 | - created_at: Timestamp::now(), | ||
| 556 | - }, | ||
| 557 | - db, | ||
| 558 | - ) | ||
| 559 | - .await | ||
| 560 | - } | ||
| 561 | - | ||
| 562 | - /// How much of `target` is already taken up — the balance fold restricted | ||
| 563 | - /// to everything that points at it, however deep, and read the way `target` | ||
| 564 | - /// is measured. | ||
| 565 | - /// | ||
| 566 | - /// The whole subtree, not just the direct children, because money given | ||
| 567 | - /// back frees the room it took: a charge paid in full and then *refunded* | ||
| 568 | - /// is owed again, so it must be payable again (the fold nets to zero). The | ||
| 569 | - /// same walk answers both sides, because the signs already say what each | ||
| 570 | - /// line does — a credit adds under a charge, its refund takes that back, | ||
| 571 | - /// and a reversal of that refund puts it back once more. `-target.sign()` | ||
| 572 | - /// is what flips the reading for a credit, whose room is measured in the | ||
| 573 | - /// refunds against it. | ||
| 574 | - /// | ||
| 575 | - /// **The subtree is bounded, and that is what makes the walk affordable.** | ||
| 576 | - /// One query per line, all of them while [`PAYMENT_LOCK`] is held, so an | ||
| 577 | - /// unbounded subtree stalls every other payment in the school: a charge | ||
| 578 | - /// settled 2 000 kuruş at a time would make the next payment issue 2 001 | ||
| 579 | - /// sequential queries under the lock. Past | ||
| 580 | - /// [`MAX_LEDGER_APPLIED_LINES`] the walk stops where it is and the write is | ||
| 581 | - /// refused — the count is what is refused, never the money already | ||
| 582 | - /// recorded, so a line that is *already* over the ceiling (written before | ||
| 583 | - /// it existed) still reads, still refunds through its own children, and is | ||
| 584 | - /// still reversible. Only a fresh line applied to *it* is turned away. | ||
| 585 | - // corner-cut: one query per line, ceiling MAX_LEDGER_APPLIED_LINES; fold the | ||
| 586 | - // walk into one recursive statement if that ceiling ever has to rise. | ||
| 587 | - async fn applied_to(target: &PaymentLedger, db: &Database) -> Result<i64, AppError> { | ||
| 588 | - let mut total = 0i64; | ||
| 589 | - let mut seen = 0usize; | ||
| 590 | - // The graph is a DAG by construction — a line can only point at one | ||
| 591 | - // that already existed — so the walk terminates. | ||
| 592 | - let mut pending = vec![target.id.clone()]; | ||
| 593 | - while let Some(id) = pending.pop() { | ||
| 594 | - for child in Self::list_for_source(&id, db).await? { | ||
| 595 | - seen += 1; | ||
| 596 | - if seen >= MAX_LEDGER_APPLIED_LINES { | ||
| 597 | - return Err(AppError::Conflict( | ||
| 598 | - "this line already carries the most lines that may be applied to it; \ | ||
| 599 | - record the rest against another", | ||
| 600 | - )); | ||
| 601 | - } | ||
| 602 | - total = total.saturating_add(child.kind.sign() * child.amount_minor.as_minor()); | ||
| 603 | - pending.push(child.id); | ||
| 604 | - } | ||
| 605 | - } | ||
| 606 | - Ok(total * -target.kind.sign()) | ||
| 607 | - } | ||
| 608 | - | ||
| 609 | - /// Undo a line entered by mistake, for its exact amount, with `source` | ||
| 610 | - /// pointing at it. The line itself is never touched. | ||
| 611 | - /// | ||
| 612 | - /// Only a *negative-fold* line may be reversed: a charge that should never | ||
| 613 | - /// have been raised, or a refund that should never have been paid out. A | ||
| 614 | - /// mistaken credit is corrected by a [`PaymentLedger::refund`] against it, | ||
| 615 | - /// which is the same money leaving the school and is spelled that one way. | ||
| 616 | - /// Keyed `<line>_r`, so a retried undo reverses once. | ||
| 617 | - /// | ||
| 618 | - /// Appends under [`PAYMENT_LOCK`] — not for its own sake (the id makes it | ||
| 619 | - /// idempotent by itself) but for the cap's: a reversal *changes* the | ||
| 620 | - /// subtree [`PaymentLedger::applied_to`] folds, so one landing between a | ||
| 621 | - /// concurrent payment's fold and its append would let that payment be | ||
| 622 | - /// admitted against room it no longer has. The lock is what makes the cap | ||
| 623 | - /// exact, which is the promise this module's doc makes. | ||
| 624 | - pub async fn reversal( | ||
| 625 | - line: &PaymentLedger, | ||
| 626 | - note: Option<LedgerNote>, | ||
| 627 | - recorded_by: &UserId, | ||
| 628 | - db: &Database, | ||
| 629 | - ) -> Result<PaymentLedger, AppError> { | ||
| 630 | - if !matches!( | ||
| 631 | - line.kind, | ||
| 632 | - PaymentLedgerKind::Charge | PaymentLedgerKind::Refund | ||
| 633 | - ) { | ||
| 634 | - return Err(ValidationError::Invalid { | ||
| 635 | - field: "source", | ||
| 636 | - reason: "only a charge or a refund can be reversed; refund a payment instead", | ||
| 637 | - } | ||
| 638 | - .into()); | ||
| 639 | - } | ||
| 640 | - let _guard = PAYMENT_LOCK.lock().await; | ||
| 641 | - Self::append( | ||
| 642 | - PaymentLedger { | ||
| 643 | - id: PaymentLedgerId::for_reversal(line.get_id()), | ||
| 644 | - student: line.student.clone(), | ||
| 645 | - kind: PaymentLedgerKind::Reversal, | ||
| 646 | - amount_minor: line.amount_minor, | ||
| 647 | - source: Some(line.id.record()), | ||
| 648 | - due_at: None, | ||
| 649 | - method: None, | ||
| 650 | - note, | ||
| 651 | - recorded_by: recorded_by.clone(), | ||
| 652 | - created_at: Timestamp::now(), | ||
| 653 | - }, | ||
| 654 | - db, | ||
| 655 | - ) | ||
| 656 | - .await | ||
| 657 | - } | ||
| 658 | - | ||
| 659 | - /// A student's whole statement, newest first. | ||
| 660 | - pub async fn list_for_student( | ||
| 661 | - student: &UserId, | ||
| 662 | - limit: Option<i64>, | ||
| 663 | - offset: i64, | ||
| 664 | - db: &Database, | ||
| 665 | - ) -> Result<(Vec<PaymentLedger>, i64), AppError> { | ||
| 666 | - PagedList::new( | ||
| 667 | - "payment_ledger WHERE student = $student", | ||
| 668 | - "ORDER BY created_at DESC, id DESC", | ||
| 669 | - ) | ||
| 670 | - .bind("student", student.record()) | ||
| 671 | - .run(limit, offset, db) | ||
| 672 | - .await | ||
| 673 | - } | ||
| 674 | - | ||
| 675 | - /// Every line pointing at `source`: a charge's payments (and its reversal), | ||
| 676 | - /// a credit's refunds. Feeds the over-payment cap and, later, the statement | ||
| 677 | - /// rollup. Oldest first — this is a history, not a page. | ||
| 678 | - pub async fn list_for_source( | ||
| 679 | - source: &PaymentLedgerId, | ||
| 680 | - db: &Database, | ||
| 681 | - ) -> Result<Vec<PaymentLedger>, AppError> { | ||
| 682 | - let mut result = db | ||
| 683 | - .query("SELECT * FROM payment_ledger WHERE source = $source ORDER BY created_at, id") | ||
| 684 | - .bind(("source", source.record())) | ||
| 685 | - .await? | ||
| 686 | - .check()?; | ||
| 687 | - Ok(result.take::<Vec<PaymentLedger>>(0)?) | ||
| 688 | - } | ||
| 689 | - | ||
| 690 | - /// The derived balance: `credits + reversals - charges - refunds`, in minor | ||
| 691 | - /// units. Negative means the family owes the school. Never stored anywhere. | ||
| 692 | - /// | ||
| 693 | - /// **The sum is taken per kind by the database** and only the four totals | ||
| 694 | - /// come back, so a balance read costs the same whether the ledger holds | ||
| 695 | - /// four lines or forty thousand. It used to decode and fold every row, and | ||
| 696 | - /// a fee ledger grows by design rather than only under abuse: one | ||
| 697 | - /// assignment appends a charge *per installment* per student (up to | ||
| 698 | - /// [`MAX_FEE_PLAN_ASSIGN_WRITES`](crate::constant::MAX_FEE_PLAN_ASSIGN_WRITES) | ||
| 699 | - /// in a single request), and every one of those rows was decoded again by | ||
| 700 | - /// every later `GET /payments/balance/*`. | ||
| 701 | - /// | ||
| 702 | - /// **The signs stay here**, applied by the same [`PaymentLedgerKind::sign`] | ||
| 703 | - /// the documented formula is spelled in — [`PaymentLedger::fold_balance`] | ||
| 704 | - /// folds the grouped totals and the raw lines alike. Summing | ||
| 705 | - /// `IF kind = 'charge' THEN -amount …` in SQL would have folded the whole | ||
| 706 | - /// balance in one statement and forked the one rule that decides what money | ||
| 707 | - /// means into a second language, where nothing fails the day the two | ||
| 708 | - /// disagree. Grouping keeps the aggregate ignorant of signs. A stored | ||
| 709 | - /// running total was the third option and is a counter that can drift — a | ||
| 710 | - /// bug class this repo closes, not one it opens. | ||
| 711 | - pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> { | ||
| 712 | - let totals: Vec<KindTotal> = db | ||
| 713 | - .query(format!( | ||
| 714 | - "SELECT kind, math::sum(amount_minor) AS total \ | ||
| 715 | - FROM {PAYMENT_LEDGER_TABLE} WHERE student = $student GROUP BY kind" | ||
| 716 | - )) | ||
| 717 | - .bind(("student", student.record())) | ||
| 718 | - .await? | ||
| 719 | - .check()? | ||
| 720 | - .take(0)?; | ||
| 721 | - Ok(Self::fold_balance( | ||
| 722 | - totals.into_iter().map(|row| (row.kind, row.total)), | ||
| 723 | - )) | ||
| 724 | - } | ||
| 725 | - | ||
| 726 | /// The one fold, over whatever already carries a kind and an amount: the | 249 | /// The one fold, over whatever already carries a kind and an amount: the |
| 727 | - /// four grouped totals above, or the raw lines a caller has in hand. A | 250 | + /// four grouped totals |
| 251 | + /// [`crate::db::payment_ledger::balance_of`] hands back, or the raw lines | ||
| 252 | + /// a caller has in hand. A | ||
| 728 | /// document that reports both a per-charge rollup and a balance must fold | 253 | /// document that reports both a per-charge rollup and a balance must fold |
| 729 | /// both from one read — two reads straddle a payment landing between them, | 254 | /// both from one read — two reads straddle a payment landing between them, |
| 730 | /// and the halves then disagree about the same money in the same response. | 255 | /// and the halves then disagree about the same money in the same response. |
| @@ -741,14 +266,6 @@ impl PaymentLedger { | |||
| 741 | } | 266 | } |
| 742 | } | 267 | } |
| 743 | 268 | ||
| 744 | -/// One kind's whole sum, as the `GROUP BY` in [`PaymentLedger::balance_of`] | ||
| 745 | -/// hands it back — at most four rows, never the lines behind them. | ||
| 746 | -#[derive(Debug, SurrealValue)] | ||
| 747 | -struct KindTotal { | ||
| 748 | - kind: PaymentLedgerKind, | ||
| 749 | - total: i64, | ||
| 750 | -} | ||
| 751 | - | ||
| 752 | #[cfg(test)] | 269 | #[cfg(test)] |
| 753 | mod tests { | 270 | mod tests { |
| 754 | use surrealdb::types::Value; | 271 | use surrealdb::types::Value; |
| @@ -817,49 +334,6 @@ mod tests { | |||
| 817 | ); | 334 | ); |
| 818 | } | 335 | } |
| 819 | 336 | ||
| 820 | - /// The mem engine is not the store this runs against, and an aggregate is | ||
| 821 | - /// exactly where the two have diverged before: `count()` over an *indexed* | ||
| 822 | - /// field compared to a plan-time value comes back `{count: N}` rather than | ||
| 823 | - /// a plain int, and `student` is indexed on this table | ||
| 824 | - /// (`payment_ledger_student`). So the `GROUP BY` is proved on a real | ||
| 825 | - /// server: that it decodes into [`KindTotal`], that it folds to the | ||
| 826 | - /// documented figure per kind, that it is scoped to one student, and that | ||
| 827 | - /// someone with no lines at all comes back `0` rather than an error. | ||
| 828 | - #[tokio::test] | ||
| 829 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 830 | - async fn the_balance_aggregate_decodes_on_a_real_server() { | ||
| 831 | - let (db, _serialized) = crate::database::init_test_server("payment_balance_sum").await; | ||
| 832 | - db.query( | ||
| 833 | - "CREATE payment_ledger:a SET student = user:ali, kind = 'charge', \ | ||
| 834 | - amount_minor = 10000, recorded_by = user:adm, created_at = 1; | ||
| 835 | - CREATE payment_ledger:b SET student = user:ali, kind = 'credit', \ | ||
| 836 | - amount_minor = 6000, recorded_by = user:adm, created_at = 2; | ||
| 837 | - CREATE payment_ledger:c SET student = user:ali, kind = 'refund', \ | ||
| 838 | - amount_minor = 1000, recorded_by = user:adm, created_at = 3; | ||
| 839 | - CREATE payment_ledger:d SET student = user:ali, kind = 'reversal', \ | ||
| 840 | - amount_minor = 4500, recorded_by = user:adm, created_at = 4; | ||
| 841 | - CREATE payment_ledger:e SET student = user:veli, kind = 'credit', \ | ||
| 842 | - amount_minor = 777, recorded_by = user:adm, created_at = 5;", | ||
| 843 | - ) | ||
| 844 | - .await | ||
| 845 | - .unwrap() | ||
| 846 | - .check() | ||
| 847 | - .unwrap(); | ||
| 848 | - let ali = UserId::from_key("ali"); | ||
| 849 | - assert_eq!( | ||
| 850 | - PaymentLedger::balance_of(&ali, &db).await.unwrap(), | ||
| 851 | - 6_000 + 4_500 - 10_000 - 1_000, | ||
| 852 | - "credits + reversals - charges - refunds, and veli's line is not ali's" | ||
| 853 | - ); | ||
| 854 | - // Somebody with no lines at all: no groups come back, not an error. | ||
| 855 | - assert_eq!( | ||
| 856 | - PaymentLedger::balance_of(&UserId::from_key("nobody"), &db) | ||
| 857 | - .await | ||
| 858 | - .unwrap(), | ||
| 859 | - 0 | ||
| 860 | - ); | ||
| 861 | - } | ||
| 862 | - | ||
| 863 | /// Idempotence rests on identity: the same (plan, student, installment) | 337 | /// Idempotence rests on identity: the same (plan, student, installment) |
| 864 | /// must always derive the same charge id, and a reversal must be the one | 338 | /// must always derive the same charge id, and a reversal must be the one |
| 865 | /// line its target can ever have. | 339 | /// line its target can ever have. |
| @@ -906,307 +380,4 @@ mod tests { | |||
| 906 | "plan1_stu1_c1_k_receipt-114_kr_receipt-114" | 380 | "plan1_stu1_c1_k_receipt-114_kr_receipt-114" |
| 907 | ); | 381 | ); |
| 908 | } | 382 | } |
| 909 | - | ||
| 910 | - /// Raise one charge of `amount` on a fresh student, and hand it back. | ||
| 911 | - #[cfg(test)] | ||
| 912 | - async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { | ||
| 913 | - use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; | ||
| 914 | - use crate::domain::fee_plan_assignment::FeePlanAssignment; | ||
| 915 | - | ||
| 916 | - let manager = UserId::from_key("mgr1"); | ||
| 917 | - let student = UserId::from_key("stu1"); | ||
| 918 | - let plan = FeePlan::create( | ||
| 919 | - FeePlanName::try_new("Yearly").unwrap(), | ||
| 920 | - vec![Installment::new( | ||
| 921 | - LedgerAmount::try_new(amount).unwrap(), | ||
| 922 | - Timestamp::from_millis(1_000), | ||
| 923 | - )], | ||
| 924 | - &manager, | ||
| 925 | - db, | ||
| 926 | - ) | ||
| 927 | - .await | ||
| 928 | - .unwrap(); | ||
| 929 | - FeePlanAssignment::assign(&plan, &student, &manager, db) | ||
| 930 | - .await | ||
| 931 | - .unwrap(); | ||
| 932 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, db) | ||
| 933 | - .await | ||
| 934 | - .unwrap(); | ||
| 935 | - (lines.into_iter().next().unwrap(), student, manager) | ||
| 936 | - } | ||
| 937 | - | ||
| 938 | - /// The collision the id grammar must not admit: with `_` legal in a key, a | ||
| 939 | - /// refund keyed `abc_r` derived exactly `<refund>_r` — the id that refund's | ||
| 940 | - /// own reversal must own — and whichever came second was handed the other's | ||
| 941 | - /// line, of the wrong kind and the wrong amount, with the real reversal | ||
| 942 | - /// impossible ever after. `_` is now illegal in a key, so the collision | ||
| 943 | - /// cannot be constructed; the nearest legal key still works, and the | ||
| 944 | - /// reversal still gets its own line. | ||
| 945 | - #[tokio::test] | ||
| 946 | - async fn a_keyed_refund_cannot_take_the_id_of_its_own_reversal() { | ||
| 947 | - assert!( | ||
| 948 | - PaymentRequestKey::try_new("abc_r").is_err(), | ||
| 949 | - "the key that spelled a reversal's id must not parse" | ||
| 950 | - ); | ||
| 951 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 952 | - let (charge, _, manager) = one_charge(100, &db).await; | ||
| 953 | - let key = PaymentRequestKey::try_new("abc-r").unwrap(); | ||
| 954 | - let credit = PaymentLedger::credit( | ||
| 955 | - &charge, | ||
| 956 | - LedgerAmount::try_new(100).unwrap(), | ||
| 957 | - None, | ||
| 958 | - None, | ||
| 959 | - None, | ||
| 960 | - &manager, | ||
| 961 | - &db, | ||
| 962 | - ) | ||
| 963 | - .await | ||
| 964 | - .unwrap(); | ||
| 965 | - let refund = PaymentLedger::refund( | ||
| 966 | - &credit, | ||
| 967 | - LedgerAmount::try_new(100).unwrap(), | ||
| 968 | - None, | ||
| 969 | - None, | ||
| 970 | - Some(&key), | ||
| 971 | - &manager, | ||
| 972 | - &db, | ||
| 973 | - ) | ||
| 974 | - .await | ||
| 975 | - .unwrap(); | ||
| 976 | - let reversal = PaymentLedger::reversal(&refund, None, &manager, &db) | ||
| 977 | - .await | ||
| 978 | - .unwrap(); | ||
| 979 | - assert_ne!(reversal.get_id(), refund.get_id()); | ||
| 980 | - assert_eq!(reversal.get_kind(), PaymentLedgerKind::Reversal); | ||
| 981 | - assert_eq!(reversal.get_amount_minor().as_minor(), 100); | ||
| 982 | - | ||
| 983 | - // And the last-ditch guard bites: an id that resolves to another kind | ||
| 984 | - // is a 500, never that other line handed back as this one. | ||
| 985 | - let intruder = PaymentLedger { | ||
| 986 | - id: charge.get_id().clone(), | ||
| 987 | - student: charge.student.clone(), | ||
| 988 | - kind: PaymentLedgerKind::Credit, | ||
| 989 | - amount_minor: LedgerAmount::try_new(1).unwrap(), | ||
| 990 | - source: Some(charge.id.record()), | ||
| 991 | - due_at: None, | ||
| 992 | - method: None, | ||
| 993 | - note: None, | ||
| 994 | - recorded_by: manager.clone(), | ||
| 995 | - created_at: Timestamp::now(), | ||
| 996 | - }; | ||
| 997 | - assert!( | ||
| 998 | - matches!( | ||
| 999 | - PaymentLedger::append(intruder, &db).await, | ||
| 1000 | - Err(AppError::Internal(_)) | ||
| 1001 | - ), | ||
| 1002 | - "a read-back of another kind must not pass for the appended line" | ||
| 1003 | - ); | ||
| 1004 | - } | ||
| 1005 | - | ||
| 1006 | - /// The defect this fold replaced a plain sum for: a payment that was handed | ||
| 1007 | - /// back frees the room it took, so the charge it paid can be paid again. It | ||
| 1008 | - /// is the same charge, still owed — refusing the second payment would leave | ||
| 1009 | - /// a family unable to settle a bill the school itself refunded. | ||
| 1010 | - #[tokio::test] | ||
| 1011 | - async fn a_refund_frees_the_room_it_took_under_the_charge() { | ||
| 1012 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1013 | - let (charge, student, manager) = one_charge(100, &db).await; | ||
| 1014 | - let pay = |amount| { | ||
| 1015 | - PaymentLedger::credit( | ||
| 1016 | - &charge, | ||
| 1017 | - LedgerAmount::try_new(amount).unwrap(), | ||
| 1018 | - None, | ||
| 1019 | - None, | ||
| 1020 | - None, | ||
| 1021 | - &manager, | ||
| 1022 | - &db, | ||
| 1023 | - ) | ||
| 1024 | - }; | ||
| 1025 | - | ||
| 1026 | - let credit = pay(100).await.unwrap(); | ||
| 1027 | - // Still fully paid: a second payment has no room. | ||
| 1028 | - assert!( | ||
| 1029 | - matches!(pay(100).await, Err(AppError::Conflict(_))), | ||
| 1030 | - "a charge paid in full may not be paid twice" | ||
| 1031 | - ); | ||
| 1032 | - | ||
| 1033 | - PaymentLedger::refund( | ||
| 1034 | - &credit, | ||
| 1035 | - LedgerAmount::try_new(100).unwrap(), | ||
| 1036 | - None, | ||
| 1037 | - None, | ||
| 1038 | - None, | ||
| 1039 | - &manager, | ||
| 1040 | - &db, | ||
| 1041 | - ) | ||
| 1042 | - .await | ||
| 1043 | - .unwrap(); | ||
| 1044 | - assert_eq!( | ||
| 1045 | - PaymentLedger::balance_of(&student, &db).await.unwrap(), | ||
| 1046 | - -100, | ||
| 1047 | - "the refund puts the charge back on the family" | ||
| 1048 | - ); | ||
| 1049 | - let repaid = pay(100) | ||
| 1050 | - .await | ||
| 1051 | - .expect("the refunded charge is payable again"); | ||
| 1052 | - assert_eq!(repaid.get_amount_minor().as_minor(), 100); | ||
| 1053 | - assert_eq!(PaymentLedger::balance_of(&student, &db).await.unwrap(), 0); | ||
| 1054 | - | ||
| 1055 | - // And the room is gone again, so the cap still bites after all that. | ||
| 1056 | - assert!(matches!(pay(1).await, Err(AppError::Conflict(_)))); | ||
| 1057 | - } | ||
| 1058 | - | ||
| 1059 | - /// The other half of the fold: reversing a refund un-does the money going | ||
| 1060 | - /// out, so the room that refund freed is taken back. | ||
| 1061 | - #[tokio::test] | ||
| 1062 | - async fn a_reversed_refund_takes_its_room_back() { | ||
| 1063 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1064 | - let (charge, _, manager) = one_charge(100, &db).await; | ||
| 1065 | - let credit = PaymentLedger::credit( | ||
| 1066 | - &charge, | ||
| 1067 | - LedgerAmount::try_new(100).unwrap(), | ||
| 1068 | - None, | ||
| 1069 | - None, | ||
| 1070 | - None, | ||
| 1071 | - &manager, | ||
| 1072 | - &db, | ||
| 1073 | - ) | ||
| 1074 | - .await | ||
| 1075 | - .unwrap(); | ||
| 1076 | - let refund = PaymentLedger::refund( | ||
| 1077 | - &credit, | ||
| 1078 | - LedgerAmount::try_new(100).unwrap(), | ||
| 1079 | - None, | ||
| 1080 | - None, | ||
| 1081 | - None, | ||
| 1082 | - &manager, | ||
| 1083 | - &db, | ||
| 1084 | - ) | ||
| 1085 | - .await | ||
| 1086 | - .unwrap(); | ||
| 1087 | - PaymentLedger::reversal(&refund, None, &manager, &db) | ||
| 1088 | - .await | ||
| 1089 | - .unwrap(); | ||
| 1090 | - | ||
| 1091 | - assert!( | ||
| 1092 | - matches!( | ||
| 1093 | - PaymentLedger::credit( | ||
| 1094 | - &charge, | ||
| 1095 | - LedgerAmount::try_new(100).unwrap(), | ||
| 1096 | - None, | ||
| 1097 | - None, | ||
| 1098 | - None, | ||
| 1099 | - &manager, | ||
| 1100 | - &db | ||
| 1101 | - ) | ||
| 1102 | - .await, | ||
| 1103 | - Err(AppError::Conflict(_)) | ||
| 1104 | - ), | ||
| 1105 | - "the refund was undone, so the charge is paid in full again" | ||
| 1106 | - ); | ||
| 1107 | - } | ||
| 1108 | - | ||
| 1109 | - /// The money branches, end to end against the engine: partial payments | ||
| 1110 | - /// accumulate, the advisory cap refuses the one that would overshoot the | ||
| 1111 | - /// charge, a refund is capped by *its* credit, and neither a credit nor a | ||
| 1112 | - /// reversal may point at a line of the wrong kind. | ||
| 1113 | - #[tokio::test] | ||
| 1114 | - async fn payments_are_capped_by_the_line_they_target() { | ||
| 1115 | - use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; | ||
| 1116 | - use crate::domain::fee_plan_assignment::FeePlanAssignment; | ||
| 1117 | - | ||
| 1118 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1119 | - let manager = UserId::from_key("mgr1"); | ||
| 1120 | - let student = UserId::from_key("stu1"); | ||
| 1121 | - let plan = FeePlan::create( | ||
| 1122 | - FeePlanName::try_new("Yearly").unwrap(), | ||
| 1123 | - vec![Installment::new( | ||
| 1124 | - LedgerAmount::try_new(10_000).unwrap(), | ||
| 1125 | - Timestamp::from_millis(1_000), | ||
| 1126 | - )], | ||
| 1127 | - &manager, | ||
| 1128 | - &db, | ||
| 1129 | - ) | ||
| 1130 | - .await | ||
| 1131 | - .unwrap(); | ||
| 1132 | - FeePlanAssignment::assign(&plan, &student, &manager, &db) | ||
| 1133 | - .await | ||
| 1134 | - .unwrap(); | ||
| 1135 | - let (charge, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | ||
| 1136 | - .await | ||
| 1137 | - .unwrap(); | ||
| 1138 | - let charge = charge.into_iter().next().unwrap(); | ||
| 1139 | - assert_eq!(charge.get_due_at(), Some(Timestamp::from_millis(1_000))); | ||
| 1140 | - | ||
| 1141 | - let paid = |amount| { | ||
| 1142 | - PaymentLedger::credit( | ||
| 1143 | - &charge, | ||
| 1144 | - LedgerAmount::try_new(amount).unwrap(), | ||
| 1145 | - None, | ||
| 1146 | - None, | ||
| 1147 | - None, | ||
| 1148 | - &manager, | ||
| 1149 | - &db, | ||
| 1150 | - ) | ||
| 1151 | - }; | ||
| 1152 | - let first = paid(6_000).await.unwrap(); | ||
| 1153 | - assert!( | ||
| 1154 | - matches!(paid(5_000).await, Err(AppError::Conflict(_))), | ||
| 1155 | - "6 000 + 5 000 overshoots a 10 000 charge" | ||
| 1156 | - ); | ||
| 1157 | - paid(4_000).await.expect("the exact remainder is allowed"); | ||
| 1158 | - assert_eq!(PaymentLedger::balance_of(&student, &db).await.unwrap(), 0); | ||
| 1159 | - | ||
| 1160 | - // A refund is bounded by the credit it returns, not by the charge. | ||
| 1161 | - let refund = |amount| { | ||
| 1162 | - PaymentLedger::refund( | ||
| 1163 | - &first, | ||
| 1164 | - LedgerAmount::try_new(amount).unwrap(), | ||
| 1165 | - None, | ||
| 1166 | - None, | ||
| 1167 | - None, | ||
| 1168 | - &manager, | ||
| 1169 | - &db, | ||
| 1170 | - ) | ||
| 1171 | - }; | ||
| 1172 | - assert!(matches!(refund(6_001).await, Err(AppError::Conflict(_)))); | ||
| 1173 | - refund(6_000).await.unwrap(); | ||
| 1174 | - assert_eq!( | ||
| 1175 | - PaymentLedger::balance_of(&student, &db).await.unwrap(), | ||
| 1176 | - -6_000, | ||
| 1177 | - "money handed back puts the debt back on the family" | ||
| 1178 | - ); | ||
| 1179 | - | ||
| 1180 | - // Wrong-kind targets are refused, and a credit is never reversed. | ||
| 1181 | - assert!( | ||
| 1182 | - PaymentLedger::credit( | ||
| 1183 | - &first, | ||
| 1184 | - LedgerAmount::try_new(1).unwrap(), | ||
| 1185 | - None, | ||
| 1186 | - None, | ||
| 1187 | - None, | ||
| 1188 | - &manager, | ||
| 1189 | - &db | ||
| 1190 | - ) | ||
| 1191 | - .await | ||
| 1192 | - .is_err() | ||
| 1193 | - ); | ||
| 1194 | - assert!( | ||
| 1195 | - PaymentLedger::reversal(&first, None, &manager, &db) | ||
| 1196 | - .await | ||
| 1197 | - .is_err() | ||
| 1198 | - ); | ||
| 1199 | - // A charge, though, reverses — once, however often it is retried. | ||
| 1200 | - let reversed = PaymentLedger::reversal(&charge, None, &manager, &db) | ||
| 1201 | - .await | ||
| 1202 | - .unwrap(); | ||
| 1203 | - let again = PaymentLedger::reversal(&charge, None, &manager, &db) | ||
| 1204 | - .await | ||
| 1205 | - .unwrap(); | ||
| 1206 | - assert_eq!(reversed.get_id(), again.get_id()); | ||
| 1207 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | ||
| 1208 | - .await | ||
| 1209 | - .unwrap(); | ||
| 1210 | - assert_eq!(lines.len(), 5, "charge, two credits, refund, one reversal"); | ||
| 1211 | - } | ||
| 1212 | } | 383 | } |
src/service/mod.rsmodified+1 -0
| @@ -2,5 +2,6 @@ | |||
| 2 | //! SurrealQL text. | 2 | //! SurrealQL text. |
| 3 | 3 | ||
| 4 | pub mod note; | 4 | pub mod note; |
| 5 | +pub mod payment_ledger; | ||
| 5 | pub mod session; | 6 | pub mod session; |
| 6 | pub mod settings; | 7 | pub mod settings; |
src/service/payment_ledger.rsadded+641 -0
| @@ -0,0 +1,641 @@ | |||
| 1 | +//! The money workflows: recording a payment, handing one back, and undoing a | ||
| 2 | +//! mistaken line, each under the lock the over-payment cap is built on. | ||
| 3 | +//! | ||
| 4 | +//! **A payment or a refund is replayable when the client names it.** An | ||
| 5 | +//! optional `request_key` keys the line `<target>_k_<key>` (or `_kr_` for a | ||
| 6 | +//! refund), so a retry after a timeout derives the row the first attempt | ||
| 7 | +//! wrote — same identity rule, no scan. The key is scoped by the line it | ||
| 8 | +//! targets, so it never has to be globally unique. Without a key the id is a | ||
| 9 | +//! fresh ulid and two identical calls are two payments, which is what a desk | ||
| 10 | +//! taking the same amount twice really means. The **replay read happens | ||
| 11 | +//! before the cap check** and inside `PAYMENT_LOCK`: the first attempt's | ||
| 12 | +//! line is already inside what the cap folds, so checking the cap first would | ||
| 13 | +//! refuse the very payment that landed. A key replayed with a *different* | ||
| 14 | +//! amount or against a *different* line is a `409`, never the stored line — | ||
| 15 | +//! returning it would hide a client bug behind a `201`. | ||
| 16 | +//! | ||
| 17 | +//! **The over-payment cap is the lock's, not the database's.** [`credit`] | ||
| 18 | +//! and [`refund`] refuse to take more than the line they target | ||
| 19 | +//! is worth, by folding that line's whole subtree under `PAYMENT_LOCK`. The | ||
| 20 | +//! fold, rather than a sum of the direct children, because money handed back | ||
| 21 | +//! frees the room it took: a charge paid in full and then refunded is owed | ||
| 22 | +//! again, and must be payable again. Every write that *moves* that arithmetic | ||
| 23 | +//! takes the same lock — [`reversal`] included, since a reversal | ||
| 24 | +//! landing between a payment's fold and its append would admit the payment | ||
| 25 | +//! against room it no longer has. | ||
| 26 | +//! | ||
| 27 | +//! The lock is what makes that check mean anything, and it is load-bearing: | ||
| 28 | +//! the fold is a count-then-write across rows, and SurrealDB does not | ||
| 29 | +//! conflict-check a cross-record read against a concurrent insert (the | ||
| 30 | +//! write-skew this repo has hit before), so a fold left unserialized would let | ||
| 31 | +//! two payments both see room and both take it. Running as one process buys | ||
| 32 | +//! nothing on its own — two request tasks interleave across the fold's `await` | ||
| 33 | +//! exactly as two machines would. The cap therefore holds only for as long as | ||
| 34 | +//! *every* write that moves this arithmetic is taken under `PAYMENT_LOCK`; | ||
| 35 | +//! a future append that skips it re-opens the hole silently, which is why the | ||
| 36 | +//! rule is stated here rather than left to be noticed. If an over-payment ever | ||
| 37 | +//! does land it is not a crisis — an over-paid charge is plainly visible in the | ||
| 38 | +//! statement and undone by appending a refund, and both entries are true | ||
| 39 | +//! records of money that really arrived. A CAS counter row was rejected — | ||
| 40 | +//! refunding would have to decrement it, which is a stored derived balance by | ||
| 41 | +//! another name. What the fold costs is also what bounds it: at most | ||
| 42 | +//! [`MAX_LEDGER_APPLIED_LINES`] lines may be applied to any one line, since | ||
| 43 | +//! every one of them is another query taken with the lock held. | ||
| 44 | +//! | ||
| 45 | +//! The `request_key` mismatch `409` rides on the same lock: it is a | ||
| 46 | +//! read-then-compare, and it is read *inside* the lock, so two first-time posts | ||
| 47 | +//! of one key with different amounts cannot both walk past it. One line, one | ||
| 48 | +//! amount, no double charge, and the "you reused a key" diagnostic is exact. | ||
| 49 | + | ||
| 50 | +use tokio::sync::Mutex; | ||
| 51 | + | ||
| 52 | +use crate::constant::MAX_LEDGER_APPLIED_LINES; | ||
| 53 | +use crate::database::Database; | ||
| 54 | +use crate::db::payment_ledger; | ||
| 55 | +use crate::domain::payment_ledger::{ | ||
| 56 | + LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, | ||
| 57 | + PaymentRequestKey, | ||
| 58 | +}; | ||
| 59 | +use crate::domain::timestamp::Timestamp; | ||
| 60 | +use crate::domain::user::UserId; | ||
| 61 | +use crate::error::{AppError, ValidationError}; | ||
| 62 | + | ||
| 63 | +/// Serializes the over-payment check, the append it authorizes, and every | ||
| 64 | +/// other append that changes the arithmetic that check does — nothing else. | ||
| 65 | +/// It is the whole guarantee behind that cap, not a convenience: the fold it | ||
| 66 | +/// protects is a cross-record read the database will not conflict-check | ||
| 67 | +/// against a concurrent insert. Held across no other lock, and no other lock is | ||
| 68 | +/// taken while it is held. | ||
| 69 | +pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(()); | ||
| 70 | + | ||
| 71 | +/// Money in, against one named `charge`. Partial payments are the norm, so | ||
| 72 | +/// a charge may collect several credits; together they may not exceed it | ||
| 73 | +/// (advisory — see the module doc's accepted race). A *reversed* charge | ||
| 74 | +/// takes no payment either, and is refused saying so rather than claiming | ||
| 75 | +/// it was paid. | ||
| 76 | +/// | ||
| 77 | +/// With a `request_key` the line is keyed by it (see | ||
| 78 | +/// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without | ||
| 79 | +/// one the id is a fresh ulid and two identical calls are two payments, | ||
| 80 | +/// which is what a cash desk taking the same amount twice really means. | ||
| 81 | +pub async fn credit( | ||
| 82 | + db: &Database, | ||
| 83 | + charge: &PaymentLedger, | ||
| 84 | + amount_minor: LedgerAmount, | ||
| 85 | + method: Option<LedgerMethod>, | ||
| 86 | + note: Option<LedgerNote>, | ||
| 87 | + request_key: Option<&PaymentRequestKey>, | ||
| 88 | + recorded_by: &UserId, | ||
| 89 | +) -> Result<PaymentLedger, AppError> { | ||
| 90 | + against( | ||
| 91 | + db, | ||
| 92 | + charge, | ||
| 93 | + PaymentLedgerKind::Charge, | ||
| 94 | + PaymentLedgerKind::Credit, | ||
| 95 | + "a payment must be recorded against a charge", | ||
| 96 | + "the charge is already paid in full", | ||
| 97 | + // A charge *is* reversible, and its reversal fills the same room a | ||
| 98 | + // payment would, so the fold refuses the two cases identically. | ||
| 99 | + Some("the charge was reversed, so it is no longer owed"), | ||
| 100 | + amount_minor, | ||
| 101 | + method, | ||
| 102 | + note, | ||
| 103 | + request_key.map(|key| PaymentLedgerId::for_request(charge.get_id(), "k", key)), | ||
| 104 | + recorded_by, | ||
| 105 | + ) | ||
| 106 | + .await | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// Money back out, against one named `credit` — how an over-payment or a | ||
| 110 | +/// payment recorded in error is returned. Partials allowed, and no more | ||
| 111 | +/// than the credit was worth (advisory, same race). `request_key` makes it | ||
| 112 | +/// retry-safe exactly as it does for [`credit`]. | ||
| 113 | +pub async fn refund( | ||
| 114 | + db: &Database, | ||
| 115 | + credit: &PaymentLedger, | ||
| 116 | + amount_minor: LedgerAmount, | ||
| 117 | + method: Option<LedgerMethod>, | ||
| 118 | + note: Option<LedgerNote>, | ||
| 119 | + request_key: Option<&PaymentRequestKey>, | ||
| 120 | + recorded_by: &UserId, | ||
| 121 | +) -> Result<PaymentLedger, AppError> { | ||
| 122 | + against( | ||
| 123 | + db, | ||
| 124 | + credit, | ||
| 125 | + PaymentLedgerKind::Credit, | ||
| 126 | + PaymentLedgerKind::Refund, | ||
| 127 | + "a refund must be recorded against a payment", | ||
| 128 | + "the payment is already refunded in full", | ||
| 129 | + // A credit is never reversed ([`reversal`] refuses | ||
| 130 | + // it), so a full fold here can only mean the refunds, and there is | ||
| 131 | + // no second reason to tell apart — nor a read to spend looking. | ||
| 132 | + None, | ||
| 133 | + amount_minor, | ||
| 134 | + method, | ||
| 135 | + note, | ||
| 136 | + request_key.map(|key| PaymentLedgerId::for_request(credit.get_id(), "kr", key)), | ||
| 137 | + recorded_by, | ||
| 138 | + ) | ||
| 139 | + .await | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// The shared body of `credit` and `refund`: check the target is the kind | ||
| 143 | +/// this line may point at, then append under [`PAYMENT_LOCK`] while the | ||
| 144 | +/// target's existing children still sum below its amount. | ||
| 145 | +/// | ||
| 146 | +/// The replay read comes **before** the cap, and inside the lock: on a | ||
| 147 | +/// retry the first attempt's line is already part of the subtree the cap | ||
| 148 | +/// folds, so consulting the cap first would answer a payment that landed | ||
| 149 | +/// with "already paid in full" — refusing precisely the request that | ||
| 150 | +/// succeeded. Reading the id under the lock also keeps two simultaneous | ||
| 151 | +/// retries from both walking into the cap check. | ||
| 152 | +#[allow(clippy::too_many_arguments)] | ||
| 153 | +async fn against( | ||
| 154 | + db: &Database, | ||
| 155 | + target: &PaymentLedger, | ||
| 156 | + expected: PaymentLedgerKind, | ||
| 157 | + kind: PaymentLedgerKind, | ||
| 158 | + wrong_target: &'static str, | ||
| 159 | + over: &'static str, | ||
| 160 | + reversed: Option<&'static str>, | ||
| 161 | + amount_minor: LedgerAmount, | ||
| 162 | + method: Option<LedgerMethod>, | ||
| 163 | + note: Option<LedgerNote>, | ||
| 164 | + keyed: Option<PaymentLedgerId>, | ||
| 165 | + recorded_by: &UserId, | ||
| 166 | +) -> Result<PaymentLedger, AppError> { | ||
| 167 | + if target.kind != expected { | ||
| 168 | + return Err(ValidationError::Invalid { | ||
| 169 | + field: "source", | ||
| 170 | + reason: wrong_target, | ||
| 171 | + } | ||
| 172 | + .into()); | ||
| 173 | + } | ||
| 174 | + let _guard = PAYMENT_LOCK.lock().await; | ||
| 175 | + if let Some(id) = &keyed | ||
| 176 | + && let Some(existing) = payment_ledger::read(db, id).await? | ||
| 177 | + { | ||
| 178 | + // A replay is answered from the stored line — but only if it is the | ||
| 179 | + // same money. The same key for a different amount or a different | ||
| 180 | + // target is a client bug, and handing back the old line would hide | ||
| 181 | + // it behind a `201`. | ||
| 182 | + if existing.amount_minor.as_minor() != amount_minor.as_minor() | ||
| 183 | + || existing.get_source_key() != Some(target.id.key()) | ||
| 184 | + { | ||
| 185 | + return Err(AppError::Conflict( | ||
| 186 | + "this request_key was already used for a different amount or target", | ||
| 187 | + )); | ||
| 188 | + } | ||
| 189 | + return Ok(existing); | ||
| 190 | + } | ||
| 191 | + let taken = applied_to(db, target).await?; | ||
| 192 | + if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { | ||
| 193 | + // The fold cannot say *why* the room is gone: a reversal is a child | ||
| 194 | + // of the line it undoes and folds in at `+amount` exactly as a | ||
| 195 | + // payment does, so a reversed charge reads as full to the kuruş. | ||
| 196 | + // The stored answer is the same either way — nothing may be | ||
| 197 | + // recorded against it — but "already paid in full" told a bursar | ||
| 198 | + // money had arrived when none ever did. The reversal's id is | ||
| 199 | + // derived from its target's, so telling the two apart is one read, | ||
| 200 | + // taken only on the refusal path. | ||
| 201 | + if let Some(reversed) = reversed | ||
| 202 | + && payment_ledger::read(db, &PaymentLedgerId::for_reversal(&target.id)) | ||
| 203 | + .await? | ||
| 204 | + .is_some() | ||
| 205 | + { | ||
| 206 | + return Err(AppError::Conflict(reversed)); | ||
| 207 | + } | ||
| 208 | + return Err(AppError::Conflict(over)); | ||
| 209 | + } | ||
| 210 | + payment_ledger::append( | ||
| 211 | + db, | ||
| 212 | + PaymentLedger { | ||
| 213 | + id: keyed.unwrap_or_else(PaymentLedgerId::generate), | ||
| 214 | + student: target.student.clone(), | ||
| 215 | + kind, | ||
| 216 | + amount_minor, | ||
| 217 | + source: Some(target.id.record()), | ||
| 218 | + due_at: None, | ||
| 219 | + method, | ||
| 220 | + note, | ||
| 221 | + recorded_by: recorded_by.clone(), | ||
| 222 | + created_at: Timestamp::now(), | ||
| 223 | + }, | ||
| 224 | + ) | ||
| 225 | + .await | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +/// How much of `target` is already taken up — the balance fold restricted | ||
| 229 | +/// to everything that points at it, however deep, and read the way `target` | ||
| 230 | +/// is measured. | ||
| 231 | +/// | ||
| 232 | +/// The whole subtree, not just the direct children, because money given | ||
| 233 | +/// back frees the room it took: a charge paid in full and then *refunded* | ||
| 234 | +/// is owed again, so it must be payable again (the fold nets to zero). The | ||
| 235 | +/// same walk answers both sides, because the signs already say what each | ||
| 236 | +/// line does — a credit adds under a charge, its refund takes that back, | ||
| 237 | +/// and a reversal of that refund puts it back once more. `-target.sign()` | ||
| 238 | +/// is what flips the reading for a credit, whose room is measured in the | ||
| 239 | +/// refunds against it. | ||
| 240 | +/// | ||
| 241 | +/// **The subtree is bounded, and that is what makes the walk affordable.** | ||
| 242 | +/// One query per line, all of them while [`PAYMENT_LOCK`] is held, so an | ||
| 243 | +/// unbounded subtree stalls every other payment in the school: a charge | ||
| 244 | +/// settled 2 000 kuruş at a time would make the next payment issue 2 001 | ||
| 245 | +/// sequential queries under the lock. Past | ||
| 246 | +/// [`MAX_LEDGER_APPLIED_LINES`] the walk stops where it is and the write is | ||
| 247 | +/// refused — the count is what is refused, never the money already | ||
| 248 | +/// recorded, so a line that is *already* over the ceiling (written before | ||
| 249 | +/// it existed) still reads, still refunds through its own children, and is | ||
| 250 | +/// still reversible. Only a fresh line applied to *it* is turned away. | ||
| 251 | +// corner-cut: one query per line, ceiling MAX_LEDGER_APPLIED_LINES; fold the | ||
| 252 | +// walk into one recursive statement if that ceiling ever has to rise. | ||
| 253 | +async fn applied_to(db: &Database, target: &PaymentLedger) -> Result<i64, AppError> { | ||
| 254 | + let mut total = 0i64; | ||
| 255 | + let mut seen = 0usize; | ||
| 256 | + // The graph is a DAG by construction — a line can only point at one | ||
| 257 | + // that already existed — so the walk terminates. | ||
| 258 | + let mut pending = vec![target.id.clone()]; | ||
| 259 | + while let Some(id) = pending.pop() { | ||
| 260 | + for child in payment_ledger::list_for_source(db, &id).await? { | ||
| 261 | + seen += 1; | ||
| 262 | + if seen >= MAX_LEDGER_APPLIED_LINES { | ||
| 263 | + return Err(AppError::Conflict( | ||
| 264 | + "this line already carries the most lines that may be applied to it; \ | ||
| 265 | + record the rest against another", | ||
| 266 | + )); | ||
| 267 | + } | ||
| 268 | + total = total.saturating_add(child.kind.sign() * child.amount_minor.as_minor()); | ||
| 269 | + pending.push(child.id); | ||
| 270 | + } | ||
| 271 | + } | ||
| 272 | + Ok(total * -target.kind.sign()) | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +/// Undo a line entered by mistake, for its exact amount, with `source` | ||
| 276 | +/// pointing at it. The line itself is never touched. | ||
| 277 | +/// | ||
| 278 | +/// Only a *negative-fold* line may be reversed: a charge that should never | ||
| 279 | +/// have been raised, or a refund that should never have been paid out. A | ||
| 280 | +/// mistaken credit is corrected by a [`refund`] against it, | ||
| 281 | +/// which is the same money leaving the school and is spelled that one way. | ||
| 282 | +/// Keyed `<line>_r`, so a retried undo reverses once. | ||
| 283 | +/// | ||
| 284 | +/// Appends under `PAYMENT_LOCK` — not for its own sake (the id makes it | ||
| 285 | +/// idempotent by itself) but for the cap's: a reversal *changes* the | ||
| 286 | +/// subtree `applied_to` folds, so one landing between a | ||
| 287 | +/// concurrent payment's fold and its append would let that payment be | ||
| 288 | +/// admitted against room it no longer has. The lock is what makes the cap | ||
| 289 | +/// exact, which is the promise this module's doc makes. | ||
| 290 | +pub async fn reversal( | ||
| 291 | + db: &Database, | ||
| 292 | + line: &PaymentLedger, | ||
| 293 | + note: Option<LedgerNote>, | ||
| 294 | + recorded_by: &UserId, | ||
| 295 | +) -> Result<PaymentLedger, AppError> { | ||
| 296 | + if !matches!( | ||
| 297 | + line.kind, | ||
| 298 | + PaymentLedgerKind::Charge | PaymentLedgerKind::Refund | ||
| 299 | + ) { | ||
| 300 | + return Err(ValidationError::Invalid { | ||
| 301 | + field: "source", | ||
| 302 | + reason: "only a charge or a refund can be reversed; refund a payment instead", | ||
| 303 | + } | ||
| 304 | + .into()); | ||
| 305 | + } | ||
| 306 | + let _guard = PAYMENT_LOCK.lock().await; | ||
| 307 | + payment_ledger::append( | ||
| 308 | + db, | ||
| 309 | + PaymentLedger { | ||
| 310 | + id: PaymentLedgerId::for_reversal(line.get_id()), | ||
| 311 | + student: line.student.clone(), | ||
| 312 | + kind: PaymentLedgerKind::Reversal, | ||
| 313 | + amount_minor: line.amount_minor, | ||
| 314 | + source: Some(line.id.record()), | ||
| 315 | + due_at: None, | ||
| 316 | + method: None, | ||
| 317 | + note, | ||
| 318 | + recorded_by: recorded_by.clone(), | ||
| 319 | + created_at: Timestamp::now(), | ||
| 320 | + }, | ||
| 321 | + ) | ||
| 322 | + .await | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result<Option<PaymentLedger>, AppError> { | ||
| 326 | + payment_ledger::read(db, id).await | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +/// A student's whole statement, newest first. | ||
| 330 | +pub async fn list_for_student( | ||
| 331 | + db: &Database, | ||
| 332 | + student: &UserId, | ||
| 333 | + limit: Option<i64>, | ||
| 334 | + offset: i64, | ||
| 335 | +) -> Result<(Vec<PaymentLedger>, i64), AppError> { | ||
| 336 | + payment_ledger::list_for_student(db, student, limit, offset).await | ||
| 337 | +} | ||
| 338 | + | ||
| 339 | +/// The derived balance: `credits + reversals - charges - refunds`, in minor | ||
| 340 | +/// units. Negative means the family owes the school. | ||
| 341 | +pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> { | ||
| 342 | + payment_ledger::balance_of(db, student).await | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +#[cfg(test)] | ||
| 346 | +mod tests { | ||
| 347 | + use super::*; | ||
| 348 | + | ||
| 349 | + /// Raise one charge of `amount` on a fresh student, and hand it back. | ||
| 350 | + async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { | ||
| 351 | + use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; | ||
| 352 | + use crate::domain::fee_plan_assignment::FeePlanAssignment; | ||
| 353 | + | ||
| 354 | + let manager = UserId::from_key("mgr1"); | ||
| 355 | + let student = UserId::from_key("stu1"); | ||
| 356 | + let plan = FeePlan::create( | ||
| 357 | + FeePlanName::try_new("Yearly").unwrap(), | ||
| 358 | + vec![Installment::new( | ||
| 359 | + LedgerAmount::try_new(amount).unwrap(), | ||
| 360 | + Timestamp::from_millis(1_000), | ||
| 361 | + )], | ||
| 362 | + &manager, | ||
| 363 | + db, | ||
| 364 | + ) | ||
| 365 | + .await | ||
| 366 | + .unwrap(); | ||
| 367 | + FeePlanAssignment::assign(&plan, &student, &manager, db) | ||
| 368 | + .await | ||
| 369 | + .unwrap(); | ||
| 370 | + let (lines, _) = payment_ledger::list_for_student(db, &student, None, 0) | ||
| 371 | + .await | ||
| 372 | + .unwrap(); | ||
| 373 | + (lines.into_iter().next().unwrap(), student, manager) | ||
| 374 | + } | ||
| 375 | + | ||
| 376 | + /// The collision the id grammar must not admit: with `_` legal in a key, a | ||
| 377 | + /// refund keyed `abc_r` derived exactly `<refund>_r` — the id that refund's | ||
| 378 | + /// own reversal must own — and whichever came second was handed the other's | ||
| 379 | + /// line, of the wrong kind and the wrong amount, with the real reversal | ||
| 380 | + /// impossible ever after. `_` is now illegal in a key, so the collision | ||
| 381 | + /// cannot be constructed; the nearest legal key still works, and the | ||
| 382 | + /// reversal still gets its own line. | ||
| 383 | + #[tokio::test] | ||
| 384 | + async fn a_keyed_refund_cannot_take_the_id_of_its_own_reversal() { | ||
| 385 | + assert!( | ||
| 386 | + PaymentRequestKey::try_new("abc_r").is_err(), | ||
| 387 | + "the key that spelled a reversal's id must not parse" | ||
| 388 | + ); | ||
| 389 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 390 | + let (charge, _, manager) = one_charge(100, &db).await; | ||
| 391 | + let key = PaymentRequestKey::try_new("abc-r").unwrap(); | ||
| 392 | + let credit_line = credit( | ||
| 393 | + &db, | ||
| 394 | + &charge, | ||
| 395 | + LedgerAmount::try_new(100).unwrap(), | ||
| 396 | + None, | ||
| 397 | + None, | ||
| 398 | + None, | ||
| 399 | + &manager, | ||
| 400 | + ) | ||
| 401 | + .await | ||
| 402 | + .unwrap(); | ||
| 403 | + let refund_line = refund( | ||
| 404 | + &db, | ||
| 405 | + &credit_line, | ||
| 406 | + LedgerAmount::try_new(100).unwrap(), | ||
| 407 | + None, | ||
| 408 | + None, | ||
| 409 | + Some(&key), | ||
| 410 | + &manager, | ||
| 411 | + ) | ||
| 412 | + .await | ||
| 413 | + .unwrap(); | ||
| 414 | + let reversal_line = reversal(&db, &refund_line, None, &manager).await.unwrap(); | ||
| 415 | + assert_ne!(reversal_line.get_id(), refund_line.get_id()); | ||
| 416 | + assert_eq!(reversal_line.get_kind(), PaymentLedgerKind::Reversal); | ||
| 417 | + assert_eq!(reversal_line.get_amount_minor().as_minor(), 100); | ||
| 418 | + | ||
| 419 | + // And the last-ditch guard bites: an id that resolves to another kind | ||
| 420 | + // is a 500, never that other line handed back as this one. | ||
| 421 | + let intruder = PaymentLedger { | ||
| 422 | + id: charge.get_id().clone(), | ||
| 423 | + student: charge.student.clone(), | ||
| 424 | + kind: PaymentLedgerKind::Credit, | ||
| 425 | + amount_minor: LedgerAmount::try_new(1).unwrap(), | ||
| 426 | + source: Some(charge.id.record()), | ||
| 427 | + due_at: None, | ||
| 428 | + method: None, | ||
| 429 | + note: None, | ||
| 430 | + recorded_by: manager.clone(), | ||
| 431 | + created_at: Timestamp::now(), | ||
| 432 | + }; | ||
| 433 | + assert!( | ||
| 434 | + matches!( | ||
| 435 | + payment_ledger::append(&db, intruder).await, | ||
| 436 | + Err(AppError::Internal(_)) | ||
| 437 | + ), | ||
| 438 | + "a read-back of another kind must not pass for the appended line" | ||
| 439 | + ); | ||
| 440 | + } | ||
| 441 | + | ||
| 442 | + /// The defect this fold replaced a plain sum for: a payment that was handed | ||
| 443 | + /// back frees the room it took, so the charge it paid can be paid again. It | ||
| 444 | + /// is the same charge, still owed — refusing the second payment would leave | ||
| 445 | + /// a family unable to settle a bill the school itself refunded. | ||
| 446 | + #[tokio::test] | ||
| 447 | + async fn a_refund_frees_the_room_it_took_under_the_charge() { | ||
| 448 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 449 | + let (charge, student, manager) = one_charge(100, &db).await; | ||
| 450 | + let pay = |amount| { | ||
| 451 | + credit( | ||
| 452 | + &db, | ||
| 453 | + &charge, | ||
| 454 | + LedgerAmount::try_new(amount).unwrap(), | ||
| 455 | + None, | ||
| 456 | + None, | ||
| 457 | + None, | ||
| 458 | + &manager, | ||
| 459 | + ) | ||
| 460 | + }; | ||
| 461 | + | ||
| 462 | + let credit_line = pay(100).await.unwrap(); | ||
| 463 | + // Still fully paid: a second payment has no room. | ||
| 464 | + assert!( | ||
| 465 | + matches!(pay(100).await, Err(AppError::Conflict(_))), | ||
| 466 | + "a charge paid in full may not be paid twice" | ||
| 467 | + ); | ||
| 468 | + | ||
| 469 | + refund( | ||
| 470 | + &db, | ||
| 471 | + &credit_line, | ||
| 472 | + LedgerAmount::try_new(100).unwrap(), | ||
| 473 | + None, | ||
| 474 | + None, | ||
| 475 | + None, | ||
| 476 | + &manager, | ||
| 477 | + ) | ||
| 478 | + .await | ||
| 479 | + .unwrap(); | ||
| 480 | + assert_eq!( | ||
| 481 | + balance_of(&db, &student).await.unwrap(), | ||
| 482 | + -100, | ||
| 483 | + "the refund puts the charge back on the family" | ||
| 484 | + ); | ||
| 485 | + let repaid = pay(100) | ||
| 486 | + .await | ||
| 487 | + .expect("the refunded charge is payable again"); | ||
| 488 | + assert_eq!(repaid.get_amount_minor().as_minor(), 100); | ||
| 489 | + assert_eq!(balance_of(&db, &student).await.unwrap(), 0); | ||
| 490 | + | ||
| 491 | + // And the room is gone again, so the cap still bites after all that. | ||
| 492 | + assert!(matches!(pay(1).await, Err(AppError::Conflict(_)))); | ||
| 493 | + } | ||
| 494 | + | ||
| 495 | + /// The other half of the fold: reversing a refund un-does the money going | ||
| 496 | + /// out, so the room that refund freed is taken back. | ||
| 497 | + #[tokio::test] | ||
| 498 | + async fn a_reversed_refund_takes_its_room_back() { | ||
| 499 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 500 | + let (charge, _, manager) = one_charge(100, &db).await; | ||
| 501 | + let credit_line = credit( | ||
| 502 | + &db, | ||
| 503 | + &charge, | ||
| 504 | + LedgerAmount::try_new(100).unwrap(), | ||
| 505 | + None, | ||
| 506 | + None, | ||
| 507 | + None, | ||
| 508 | + &manager, | ||
| 509 | + ) | ||
| 510 | + .await | ||
| 511 | + .unwrap(); | ||
| 512 | + let refund_line = refund( | ||
| 513 | + &db, | ||
| 514 | + &credit_line, | ||
| 515 | + LedgerAmount::try_new(100).unwrap(), | ||
| 516 | + None, | ||
| 517 | + None, | ||
| 518 | + None, | ||
| 519 | + &manager, | ||
| 520 | + ) | ||
| 521 | + .await | ||
| 522 | + .unwrap(); | ||
| 523 | + reversal(&db, &refund_line, None, &manager).await.unwrap(); | ||
| 524 | + | ||
| 525 | + assert!( | ||
| 526 | + matches!( | ||
| 527 | + credit( | ||
| 528 | + &db, | ||
| 529 | + &charge, | ||
| 530 | + LedgerAmount::try_new(100).unwrap(), | ||
| 531 | + None, | ||
| 532 | + None, | ||
| 533 | + None, | ||
| 534 | + &manager | ||
| 535 | + ) | ||
| 536 | + .await, | ||
| 537 | + Err(AppError::Conflict(_)) | ||
| 538 | + ), | ||
| 539 | + "the refund was undone, so the charge is paid in full again" | ||
| 540 | + ); | ||
| 541 | + } | ||
| 542 | + | ||
| 543 | + /// The money branches, end to end against the engine: partial payments | ||
| 544 | + /// accumulate, the advisory cap refuses the one that would overshoot the | ||
| 545 | + /// charge, a refund is capped by *its* credit, and neither a credit nor a | ||
| 546 | + /// reversal may point at a line of the wrong kind. | ||
| 547 | + #[tokio::test] | ||
| 548 | + async fn payments_are_capped_by_the_line_they_target() { | ||
| 549 | + use crate::domain::fee_plan::{FeePlan, FeePlanName, Installment}; | ||
| 550 | + use crate::domain::fee_plan_assignment::FeePlanAssignment; | ||
| 551 | + | ||
| 552 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 553 | + let manager = UserId::from_key("mgr1"); | ||
| 554 | + let student = UserId::from_key("stu1"); | ||
| 555 | + let plan = FeePlan::create( | ||
| 556 | + FeePlanName::try_new("Yearly").unwrap(), | ||
| 557 | + vec![Installment::new( | ||
| 558 | + LedgerAmount::try_new(10_000).unwrap(), | ||
| 559 | + Timestamp::from_millis(1_000), | ||
| 560 | + )], | ||
| 561 | + &manager, | ||
| 562 | + &db, | ||
| 563 | + ) | ||
| 564 | + .await | ||
| 565 | + .unwrap(); | ||
| 566 | + FeePlanAssignment::assign(&plan, &student, &manager, &db) | ||
| 567 | + .await | ||
| 568 | + .unwrap(); | ||
| 569 | + let (charges, _) = payment_ledger::list_for_student(&db, &student, None, 0) | ||
| 570 | + .await | ||
| 571 | + .unwrap(); | ||
| 572 | + let charge = charges.into_iter().next().unwrap(); | ||
| 573 | + assert_eq!(charge.get_due_at(), Some(Timestamp::from_millis(1_000))); | ||
| 574 | + | ||
| 575 | + let paid = |amount| { | ||
| 576 | + credit( | ||
| 577 | + &db, | ||
| 578 | + &charge, | ||
| 579 | + LedgerAmount::try_new(amount).unwrap(), | ||
| 580 | + None, | ||
| 581 | + None, | ||
| 582 | + None, | ||
| 583 | + &manager, | ||
| 584 | + ) | ||
| 585 | + }; | ||
| 586 | + let first = paid(6_000).await.unwrap(); | ||
| 587 | + assert!( | ||
| 588 | + matches!(paid(5_000).await, Err(AppError::Conflict(_))), | ||
| 589 | + "6 000 + 5 000 overshoots a 10 000 charge" | ||
| 590 | + ); | ||
| 591 | + paid(4_000).await.expect("the exact remainder is allowed"); | ||
| 592 | + assert_eq!(balance_of(&db, &student).await.unwrap(), 0); | ||
| 593 | + | ||
| 594 | + // A refund is bounded by the credit it returns, not by the charge. | ||
| 595 | + let refund_amount = |amount| { | ||
| 596 | + refund( | ||
| 597 | + &db, | ||
| 598 | + &first, | ||
| 599 | + LedgerAmount::try_new(amount).unwrap(), | ||
| 600 | + None, | ||
| 601 | + None, | ||
| 602 | + None, | ||
| 603 | + &manager, | ||
| 604 | + ) | ||
| 605 | + }; | ||
| 606 | + assert!(matches!( | ||
| 607 | + refund_amount(6_001).await, | ||
| 608 | + Err(AppError::Conflict(_)) | ||
| 609 | + )); | ||
| 610 | + refund_amount(6_000).await.unwrap(); | ||
| 611 | + assert_eq!( | ||
| 612 | + balance_of(&db, &student).await.unwrap(), | ||
| 613 | + -6_000, | ||
| 614 | + "money handed back puts the debt back on the family" | ||
| 615 | + ); | ||
| 616 | + | ||
| 617 | + // Wrong-kind targets are refused, and a credit is never reversed. | ||
| 618 | + assert!( | ||
| 619 | + credit( | ||
| 620 | + &db, | ||
| 621 | + &first, | ||
| 622 | + LedgerAmount::try_new(1).unwrap(), | ||
| 623 | + None, | ||
| 624 | + None, | ||
| 625 | + None, | ||
| 626 | + &manager, | ||
| 627 | + ) | ||
| 628 | + .await | ||
| 629 | + .is_err() | ||
| 630 | + ); | ||
| 631 | + assert!(reversal(&db, &first, None, &manager).await.is_err()); | ||
| 632 | + // A charge, though, reverses — once, however often it is retried. | ||
| 633 | + let reversed = reversal(&db, &charge, None, &manager).await.unwrap(); | ||
| 634 | + let again = reversal(&db, &charge, None, &manager).await.unwrap(); | ||
| 635 | + assert_eq!(reversed.get_id(), again.get_id()); | ||
| 636 | + let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0) | ||
| 637 | + .await | ||
| 638 | + .unwrap(); | ||
| 639 | + assert_eq!(lines.len(), 5, "charge, two credits, refund, one reversal"); | ||
| 640 | + } | ||
| 641 | +} | ||
src/web/payments.rsmodified+18 -16
| @@ -35,6 +35,7 @@ use crate::domain::role::Role; | |||
| 35 | use crate::domain::timestamp::Timestamp; | 35 | use crate::domain::timestamp::Timestamp; |
| 36 | use crate::domain::user::{User, UserId}; | 36 | use crate::domain::user::{User, UserId}; |
| 37 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 37 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 38 | +use crate::service; | ||
| 38 | use crate::state::AppState; | 39 | use crate::state::AppState; |
| 39 | 40 | ||
| 40 | use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map}; | 41 | use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map}; |
| @@ -576,7 +577,7 @@ async fn appended( | |||
| 576 | } | 577 | } |
| 577 | 578 | ||
| 578 | async fn require_line(id: &str, db: &Database) -> Result<PaymentLedger, AppError> { | 579 | async fn require_line(id: &str, db: &Database) -> Result<PaymentLedger, AppError> { |
| 579 | - PaymentLedger::read(&PaymentLedgerId::from_key(id), db) | 580 | + service::payment_ledger::read(db, &PaymentLedgerId::from_key(id)) |
| 580 | .await? | 581 | .await? |
| 581 | .ok_or(AppError::NotFound) | 582 | .ok_or(AppError::NotFound) |
| 582 | } | 583 | } |
| @@ -678,14 +679,14 @@ async fn record_payment( | |||
| 678 | Json(req): Json<RecordPayment>, | 679 | Json(req): Json<RecordPayment>, |
| 679 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { | 680 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { |
| 680 | let charge = require_line(&req.charge_id, &st.db).await?; | 681 | let charge = require_line(&req.charge_id, &st.db).await?; |
| 681 | - let line = PaymentLedger::credit( | 682 | + let line = service::payment_ledger::credit( |
| 683 | + &st.db, | ||
| 682 | &charge, | 684 | &charge, |
| 683 | LedgerAmount::try_new(req.amount_minor)?, | 685 | LedgerAmount::try_new(req.amount_minor)?, |
| 684 | method_of(req.method.as_deref())?, | 686 | method_of(req.method.as_deref())?, |
| 685 | note_of(req.note.as_deref())?, | 687 | note_of(req.note.as_deref())?, |
| 686 | request_key_of(req.request_key.as_deref())?.as_ref(), | 688 | request_key_of(req.request_key.as_deref())?.as_ref(), |
| 687 | manager.get_id(), | 689 | manager.get_id(), |
| 688 | - &st.db, | ||
| 689 | ) | 690 | ) |
| 690 | .await?; | 691 | .await?; |
| 691 | appended(line, &st.db).await | 692 | appended(line, &st.db).await |
| @@ -720,14 +721,14 @@ async fn record_refund( | |||
| 720 | Json(req): Json<RecordRefund>, | 721 | Json(req): Json<RecordRefund>, |
| 721 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { | 722 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { |
| 722 | let credit = require_line(&req.credit_id, &st.db).await?; | 723 | let credit = require_line(&req.credit_id, &st.db).await?; |
| 723 | - let line = PaymentLedger::refund( | 724 | + let line = service::payment_ledger::refund( |
| 725 | + &st.db, | ||
| 724 | &credit, | 726 | &credit, |
| 725 | LedgerAmount::try_new(req.amount_minor)?, | 727 | LedgerAmount::try_new(req.amount_minor)?, |
| 726 | method_of(req.method.as_deref())?, | 728 | method_of(req.method.as_deref())?, |
| 727 | note_of(req.note.as_deref())?, | 729 | note_of(req.note.as_deref())?, |
| 728 | request_key_of(req.request_key.as_deref())?.as_ref(), | 730 | request_key_of(req.request_key.as_deref())?.as_ref(), |
| 729 | manager.get_id(), | 731 | manager.get_id(), |
| 730 | - &st.db, | ||
| 731 | ) | 732 | ) |
| 732 | .await?; | 733 | .await?; |
| 733 | appended(line, &st.db).await | 734 | appended(line, &st.db).await |
| @@ -759,11 +760,11 @@ async fn record_reversal( | |||
| 759 | Json(req): Json<RecordReversal>, | 760 | Json(req): Json<RecordReversal>, |
| 760 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { | 761 | ) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> { |
| 761 | let target = require_line(&req.line_id, &st.db).await?; | 762 | let target = require_line(&req.line_id, &st.db).await?; |
| 762 | - let line = PaymentLedger::reversal( | 763 | + let line = service::payment_ledger::reversal( |
| 764 | + &st.db, | ||
| 763 | &target, | 765 | &target, |
| 764 | note_of(req.note.as_deref())?, | 766 | note_of(req.note.as_deref())?, |
| 765 | manager.get_id(), | 767 | manager.get_id(), |
| 766 | - &st.db, | ||
| 767 | ) | 768 | ) |
| 768 | .await?; | 769 | .await?; |
| 769 | appended(line, &st.db).await | 770 | appended(line, &st.db).await |
| @@ -827,7 +828,8 @@ async fn user_ledger( | |||
| 827 | let (limit, offset) = page.resolve()?; | 828 | let (limit, offset) = page.resolve()?; |
| 828 | let target = UserId::from_key(&user); | 829 | let target = UserId::from_key(&user); |
| 829 | ensure_can_read_payments(&caller, &target, &st.db).await?; | 830 | ensure_can_read_payments(&caller, &target, &st.db).await?; |
| 830 | - let (rows, total) = PaymentLedger::list_for_student(&target, limit, offset, &st.db).await?; | 831 | + let (rows, total) = |
| 832 | + service::payment_ledger::list_for_student(&st.db, &target, limit, offset).await?; | ||
| 831 | let items = line_responses(&rows, &st.db).await?; | 833 | let items = line_responses(&rows, &st.db).await?; |
| 832 | Ok(Json(Page::new(items, total, limit, offset))) | 834 | Ok(Json(Page::new(items, total, limit, offset))) |
| 833 | } | 835 | } |
| @@ -888,7 +890,7 @@ async fn statement_response( | |||
| 888 | offset: i64, | 890 | offset: i64, |
| 889 | db: &Database, | 891 | db: &Database, |
| 890 | ) -> Result<Json<StatementResponse>, AppError> { | 892 | ) -> Result<Json<StatementResponse>, AppError> { |
| 891 | - let (lines, _) = PaymentLedger::list_for_student(student, None, 0, db).await?; | 893 | + let (lines, _) = service::payment_ledger::list_for_student(db, student, None, 0).await?; |
| 892 | // Index every line by what it points at, so the rollup is one pass over the | 894 | // Index every line by what it points at, so the rollup is one pass over the |
| 893 | // student's history rather than a query per charge. | 895 | // student's history rather than a query per charge. |
| 894 | let mut children: HashMap<&str, Vec<&PaymentLedger>> = HashMap::new(); | 896 | let mut children: HashMap<&str, Vec<&PaymentLedger>> = HashMap::new(); |
| @@ -1058,7 +1060,7 @@ async fn balance_response( | |||
| 1058 | let people = person_map(std::iter::once(student.clone()), db).await?; | 1060 | let people = person_map(std::iter::once(student.clone()), db).await?; |
| 1059 | Ok(Json(PaymentBalanceResponse { | 1061 | Ok(Json(PaymentBalanceResponse { |
| 1060 | student: PersonRef::resolve(&people, student), | 1062 | student: PersonRef::resolve(&people, student), |
| 1061 | - balance_minor: PaymentLedger::balance_of(student, db).await?, | 1063 | + balance_minor: service::payment_ledger::balance_of(db, student).await?, |
| 1062 | })) | 1064 | })) |
| 1063 | } | 1065 | } |
| 1064 | 1066 | ||
| @@ -1141,7 +1143,7 @@ mod tests { | |||
| 1141 | .await | 1143 | .await |
| 1142 | .unwrap(); | 1144 | .unwrap(); |
| 1143 | 1145 | ||
| 1144 | - let (lines, _) = PaymentLedger::list_for_student(&student, None, 0, &db) | 1146 | + let (lines, _) = service::payment_ledger::list_for_student(&db, &student, None, 0) |
| 1145 | .await | 1147 | .await |
| 1146 | .unwrap(); | 1148 | .unwrap(); |
| 1147 | let charge = |amount: i64| { | 1149 | let charge = |amount: i64| { |
| @@ -1151,29 +1153,29 @@ mod tests { | |||
| 1151 | .expect("the installment was billed") | 1153 | .expect("the installment was billed") |
| 1152 | .clone() | 1154 | .clone() |
| 1153 | }; | 1155 | }; |
| 1154 | - let paid = PaymentLedger::credit( | 1156 | + let paid = service::payment_ledger::credit( |
| 1157 | + &db, | ||
| 1155 | &charge(10_000), | 1158 | &charge(10_000), |
| 1156 | LedgerAmount::try_new(6_000).unwrap(), | 1159 | LedgerAmount::try_new(6_000).unwrap(), |
| 1157 | None, | 1160 | None, |
| 1158 | None, | 1161 | None, |
| 1159 | None, | 1162 | None, |
| 1160 | &manager, | 1163 | &manager, |
| 1161 | - &db, | ||
| 1162 | ) | 1164 | ) |
| 1163 | .await | 1165 | .await |
| 1164 | .unwrap(); | 1166 | .unwrap(); |
| 1165 | - PaymentLedger::refund( | 1167 | + service::payment_ledger::refund( |
| 1168 | + &db, | ||
| 1166 | &paid, | 1169 | &paid, |
| 1167 | LedgerAmount::try_new(1_000).unwrap(), | 1170 | LedgerAmount::try_new(1_000).unwrap(), |
| 1168 | None, | 1171 | None, |
| 1169 | None, | 1172 | None, |
| 1170 | None, | 1173 | None, |
| 1171 | &manager, | 1174 | &manager, |
| 1172 | - &db, | ||
| 1173 | ) | 1175 | ) |
| 1174 | .await | 1176 | .await |
| 1175 | .unwrap(); | 1177 | .unwrap(); |
| 1176 | - PaymentLedger::reversal(&charge(20_000), None, &manager, &db) | 1178 | + service::payment_ledger::reversal(&db, &charge(20_000), None, &manager) |
| 1177 | .await | 1179 | .await |
| 1178 | .unwrap(); | 1180 | .unwrap(); |
| 1179 | 1181 | ||