forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

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

payment_ledger.rs304 lines, 13.3 KiBHistoryRawDownload
1//! The `payment_ledger` table: the append-only `INSERT`s and the reads the
2//! balance and the over-payment cap fold. Nothing here ever `UPDATE`s or
3//! `DELETE`s a row — a mistake is corrected by appending the opposing line.
4//! The row locks that serialize the money arithmetic around these calls are
5//! taken by the workflows in [`crate::service::payment_ledger`]
6//! ([`lock_for_cap`]).
7//!
8//! The ledger row's `id` is a derived TEXT primary key, so Postgres itself is
9//! the uniqueness check: a duplicate insert of the same key is the
10//! "already billed" answer, surfaced here as
11//! `INSERT … ON CONFLICT (id) DO NOTHING` plus a read-back of the row that
12//! won. That is what makes every deterministic id (see
13//! [`PaymentLedgerId::for_installment`] and friends) an idempotence key —
14//! replaying the same append is a no-op, never a second line and never an
15//! edit of the first, however the concurrent writers interleave.
16
17use sqlx::PgExecutor;
18
19use crate::constant::MAX_LEDGER_APPLIED_LINES;
20use crate::database::Database;
21use crate::db::page::PagedList;
22use crate::domain::fee_plan::Installment;
23use crate::domain::fee_plan_assignment::FeePlanAssignment;
24use crate::domain::payment_ledger::{
25 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
26};
27use crate::domain::timestamp::Timestamp;
28use crate::domain::user::UserId;
29use crate::error::AppError;
30
31/// The only writer: one `INSERT`, no update path anywhere in this module.
32///
33/// A line whose id already exists is left exactly as it is — the row wins,
34/// the write is dropped, and the winner's line is read back in the *same
35/// statement* (`ON CONFLICT (id) DO NOTHING`, and the `UNION ALL` arm answers
36/// with the stored row when the insert was skipped). Unlike a scan, the point
37/// read on the id cannot miss a row a concurrent writer just committed: an
38/// insert that races an identical id waits on the unique index until the
39/// other transaction settles, then takes the read-back arm.
40///
41/// The read-back also checks the stored line is the *kind* that was being
42/// appended. Handing a caller someone else's row is only safe while every id
43/// shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a future
44/// marker or a widened key charset ever let two shapes meet, this is the
45/// check that turns silently-wrong money into a 500 instead. It should be
46/// unreachable, and it is cheap enough to keep it that way.
47pub(crate) async fn append(
48 exe: impl PgExecutor<'_>,
49 row: PaymentLedger,
50) -> Result<PaymentLedger, AppError> {
51 let created = sqlx::query_as!(
52 PaymentLedger,
53 r#"WITH ins AS (
54 INSERT INTO payment_ledger
55 (id, student, kind, amount_minor, source, due_at, method, note,
56 recorded_by, created_at)
57 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
58 ON CONFLICT (id) DO NOTHING
59 RETURNING id, student, kind, amount_minor, source, due_at, method, note,
60 recorded_by, created_at)
61 SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId",
62 kind AS "kind!: PaymentLedgerKind",
63 amount_minor AS "amount_minor!: LedgerAmount", source,
64 due_at AS "due_at: Timestamp", method AS "method: LedgerMethod",
65 note AS "note: LedgerNote",
66 recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp"
67 FROM ins
68 UNION ALL
69 SELECT id AS "id!: PaymentLedgerId", student AS "student!: UserId",
70 kind AS "kind!: PaymentLedgerKind",
71 amount_minor AS "amount_minor!: LedgerAmount", source,
72 due_at AS "due_at: Timestamp", method AS "method: LedgerMethod",
73 note AS "note: LedgerNote",
74 recorded_by AS "recorded_by!: UserId", created_at AS "created_at!: Timestamp"
75 FROM payment_ledger
76 WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#,
77 row.id.key(),
78 row.student.uuid(),
79 row.kind.as_str(),
80 row.amount_minor.as_minor(),
81 row.source,
82 row.due_at.map(|t| t.as_millis()),
83 row.method.as_ref().map(|m| m.as_str()),
84 row.note.as_ref().map(|n| n.as_str()),
85 row.recorded_by.uuid(),
86 row.created_at.as_millis(),
87 )
88 .fetch_optional(exe)
89 .await?;
90 match created {
91 Some(line) if line.kind == row.kind => Ok(line),
92 Some(_) => Err(AppError::Internal(
93 "a ledger id resolved to a line of another kind".into(),
94 )),
95 // Unreachable: the statement either inserts or reads back the row
96 // with that very id.
97 None => Err(AppError::Internal("failed to write the ledger line".into())),
98 }
99}
100
101pub async fn read(
102 exe: impl PgExecutor<'_>,
103 id: &PaymentLedgerId,
104) -> Result<Option<PaymentLedger>, AppError> {
105 sqlx::query_as!(
106 PaymentLedger,
107 "SELECT id AS \"id: PaymentLedgerId\", student AS \"student: UserId\",
108 kind AS \"kind: PaymentLedgerKind\", amount_minor AS \"amount_minor: LedgerAmount\",
109 source, due_at AS \"due_at: Timestamp\", method AS \"method: LedgerMethod\",
110 note AS \"note: LedgerNote\", recorded_by AS \"recorded_by: UserId\",
111 created_at AS \"created_at: Timestamp\"
112 FROM payment_ledger WHERE id = $1",
113 id.key(),
114 )
115 .fetch_optional(exe)
116 .await
117 .map_err(Into::into)
118}
119
120/// Bill installment `n` (1-based) of `assignment`, at the amount and due
121/// date the plan carried when it was assigned — the charge is a frozen
122/// copy, so editing the plan afterwards moves no existing line.
123///
124/// Replaying it is free: the id is `(plan, student, n)`, so a duplicate
125/// assign writes nothing and an assignment whose charges landed only in
126/// part self-heals on the next assign of the same pair.
127pub async fn charge_for_installment(
128 exe: impl PgExecutor<'_>,
129 assignment: &FeePlanAssignment,
130 n: usize,
131 installment: &Installment,
132 recorded_by: &UserId,
133) -> Result<PaymentLedger, AppError> {
134 append(
135 exe,
136 PaymentLedger {
137 id: PaymentLedgerId::for_installment(&assignment.get_id(), n),
138 student: *assignment.get_student(),
139 kind: PaymentLedgerKind::Charge,
140 amount_minor: installment.get_amount_minor(),
141 source: Some(assignment.get_id().key()),
142 due_at: Some(installment.get_due_at()),
143 method: None,
144 note: None,
145 recorded_by: *recorded_by,
146 created_at: Timestamp::now(),
147 },
148 )
149 .await
150}
151
152/// A student's whole statement, newest first.
153pub async fn list_for_student(
154 db: &Database,
155 student: &UserId,
156 limit: Option<i64>,
157 offset: i64,
158) -> Result<(Vec<PaymentLedger>, i64), AppError> {
159 PagedList::new(
160 "payment_ledger WHERE student = $1",
161 "ORDER BY created_at DESC, id DESC",
162 )
163 .bind(student.uuid())
164 .run(limit, offset, db)
165 .await
166}
167
168/// One kind's fold, as [`balance_of`] and [`applied_to`] read it off the
169/// `GROUP BY` — at most four rows, never the lines behind them.
170struct KindFold {
171 kind: PaymentLedgerKind,
172 total: i64,
173 /// Lines behind the fold. [`balance_of`] never looks at it; [`applied_to`]
174 /// enforces the applied-lines ceiling with it.
175 lines: i64,
176}
177
178/// The derived balance: `credits + reversals - charges - refunds`, in minor
179/// units. Negative means the family owes the school. Never stored anywhere.
180///
181/// **The sum is taken per kind by the database** and only the four totals
182/// come back, so a balance read costs the same whether the ledger holds
183/// four lines or forty thousand.
184///
185/// **The signs stay here**, applied by the same
186/// `PaymentLedgerKind::sign` the documented formula is spelled in —
187/// [`PaymentLedger::fold_balance`](crate::domain::payment_ledger::PaymentLedger::fold_balance)
188/// folds the grouped totals and the raw lines alike. Summing
189/// `IF kind = 'charge' THEN -amount …` in SQL would have folded the whole
190/// balance in one statement and forked the one rule that decides what money
191/// means into a second language, where nothing fails the day the two
192/// disagree. Grouping keeps the aggregate ignorant of signs. A stored
193/// running total was the third option and is a counter that can drift — a
194/// bug class this repo closes, not one it opens.
195pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
196 let totals = sqlx::query_as!(
197 KindFold,
198 "SELECT kind AS \"kind!: PaymentLedgerKind\", \
199 COALESCE(sum(amount_minor), 0)::bigint AS \"total!: i64\", \
200 count(*)::bigint AS \"lines!: i64\" \
201 FROM payment_ledger WHERE student = $1 GROUP BY kind",
202 student.uuid(),
203 )
204 .fetch_all(db)
205 .await?;
206 Ok(PaymentLedger::fold_balance(
207 totals.into_iter().map(|row| (row.kind, row.total)),
208 ))
209}
210
211/// Lock the **ancestor chain** of `id` (`FOR UPDATE`, the line first, then
212/// its target, and so on up to a charge). Every write that moves the money
213/// arithmetic of a subtree takes this walk in its transaction, so writers to
214/// one subtree all contend on its **root's** row lock: a payment folding a
215/// charge's subtree cannot land between a refund's fold and its append
216/// deeper down. That is the whole guarantee the over-payment cap rests on —
217/// it replaces a process-wide mutex with the rows the money lives on.
218///
219/// Lock order is *deepest first*: a writer always wants the next ancestor,
220/// never the reverse, and an ancestor is never a descendant, so no two
221/// walks can cycle — no deadlock, nothing for the retry loop to unwind.
222/// The chain is at most three rows (charge ← credit ← refund; a reversal
223/// points at a charge or a refund), and a charge's `source` names a
224/// fee-plan assignment rather than a ledger row, which is where the walk
225/// stops.
226pub(crate) async fn lock_for_cap(
227 exe: &mut sqlx::PgConnection,
228 id: &PaymentLedgerId,
229) -> Result<(), AppError> {
230 let mut next = Some(id.clone());
231 while let Some(key) = next {
232 let row = sqlx::query!(
233 r#"SELECT kind AS "kind: PaymentLedgerKind", source
234 FROM payment_ledger WHERE id = $1 FOR UPDATE"#,
235 key.key(),
236 )
237 .fetch_optional(&mut *exe)
238 .await?;
239 next = match row {
240 // Keep walking while the row points at another *ledger* row.
241 Some(row) if row.kind != PaymentLedgerKind::Charge => {
242 row.source.map(|s| PaymentLedgerId::from_key(&s))
243 }
244 // A charge's source is an assignment key, not a ledger row —
245 // and by then the root lock is held, which is the point.
246 _ => None,
247 };
248 }
249 Ok(())
250}
251
252/// How much of `target` is already taken up — the balance fold restricted
253/// to everything that points at it, however deep, and read the way `target`
254/// is measured. Caller holds [`lock_for_cap`] on `target`'s chain in the
255/// same transaction, so the fold and the append it authorizes cannot be
256/// separated by a competing write.
257///
258/// The whole subtree, not just the direct children, because money given
259/// back frees the room it took: a charge paid in full and then *refunded*
260/// is owed again, so it must be payable again (the fold nets to zero). The
261/// same walk answers both sides, because the signs already say what each
262/// line does — a credit adds under a charge, its refund takes that back,
263/// and a reversal of that refund puts it back once more. `-target.sign()`
264/// is what flips the reading for a credit, whose room is measured in the
265/// refunds against it. The recursive CTE replaces the old
266/// one-query-per-child walk; the signs still fold in Rust, by
267/// [`PaymentLedger::fold_balance`](crate::domain::payment_ledger::PaymentLedger::fold_balance).
268///
269/// **The ceiling stays.** Past [`MAX_LEDGER_APPLIED_LINES`] lines the fold
270/// refuses — the count is what is refused, never the money already
271/// recorded, so a line that is *already* over the ceiling still reads,
272/// still refunds through its own children, and is still reversible. Only a
273/// fresh line applied to *it* is turned away.
274pub(crate) async fn applied_to(
275 exe: &mut sqlx::PgConnection,
276 target_key: &str,
277 target_kind: PaymentLedgerKind,
278) -> Result<i64, AppError> {
279 let folds = sqlx::query_as!(
280 KindFold,
281 r#"WITH RECURSIVE applied(id, kind, amount_minor) AS (
282 SELECT id, kind, amount_minor FROM payment_ledger WHERE source = $1
283 UNION ALL
284 SELECT l.id, l.kind, l.amount_minor
285 FROM payment_ledger l JOIN applied a ON l.source = a.id
286 )
287 SELECT kind AS "kind!: PaymentLedgerKind",
288 COALESCE(sum(amount_minor), 0)::bigint AS "total!: i64",
289 count(*)::bigint AS "lines!: i64"
290 FROM applied GROUP BY kind"#,
291 target_key,
292 )
293 .fetch_all(exe)
294 .await?;
295 let lines: i64 = folds.iter().map(|fold| fold.lines).sum();
296 if lines as usize >= MAX_LEDGER_APPLIED_LINES {
297 return Err(AppError::Conflict(
298 "this line already carries the most lines that may be applied to it; \
299 record the rest against another",
300 ));
301 }
302 let total = PaymentLedger::fold_balance(folds.into_iter().map(|fold| (fold.kind, fold.total)));
303 Ok(total * -target_kind.sign())
304}