π make a retried payment one payment, and page the statement
Browse files at this commit4fe02bc27db875a22e71996ff2a1647d3fd964c1Parent: 740e96a- fix
- π make a retried payment one payment, and page the statement
10 changed files +587 -31
- README.md +24 -6
- src/constant.rs +7 -0
- src/domain/payment_ledger.rs +214 -4
- src/lib.rs +1 -1
- src/validate.rs +49 -4
- src/web/limits.rs +4 -0
- src/web/payments.rs +71 -13
- tests/integration.rs +202 -2
- tests/persistence.rs +1 -1
- tests/spec_bounds.rs +14 -0
README.mdmodified+24 -6
| @@ -817,12 +817,12 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 817 | | DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β its charges name it | | 817 | | DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it β its charges name it | |
| 818 | | POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (β€ 200) β place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` | | 818 | | POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (β€ 200) β place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` | |
| 819 | | GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged | | 819 | | GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first Β· paged | |
| 820 | -| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?}` β record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory) | | 820 | +| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` β record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory). A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` | |
| 821 | -| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?}` β hand money back against one named payment; partials allowed, capped by that credit | | 821 | +| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` β hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety | |
| 822 | | POST | `/payments/reversals` | manager | `{line_id, note?}` β undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line | | 822 | | POST | `/payments/reversals` | manager | `{line_id, note?}` β undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line | |
| 823 | | GET | `/payments/ledger/{user}` | student | One student's raw lines β charges, payments, refunds, reversals β newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) | | 823 | | GET | `/payments/ledger/{user}` | student | One student's raw lines β charges, payments, refunds, reversals β newest first Β· paged Β· own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) | |
| 824 | -| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue` | | 824 | +| GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page | |
| 825 | -| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger | | 825 | +| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging | |
| 826 | | GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) | | 826 | | GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) | |
| 827 | | GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger | | 827 | | GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger | |
| 828 | | POST | `/chatbot/threads` | student | `{title?}` β start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` | | 828 | | POST | `/chatbot/threads` | student | `{title?}` β start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` | |
| @@ -1510,6 +1510,21 @@ account. | |||
| 1510 | `{credit_id, β¦}`, partials allowed, capped by what that credit was worth. | 1510 | `{credit_id, β¦}`, partials allowed, capped by what that credit was worth. |
| 1511 | This is also the **only** way a mistaken credit is corrected: a credit is | 1511 | This is also the **only** way a mistaken credit is corrected: a credit is |
| 1512 | never reversed, so money leaving the school is always spelled the one way. | 1512 | never reversed, so money leaving the school is always spelled the one way. |
| 1513 | +- **A retry is not a second payment β when the client says so.** Both routes | ||
| 1514 | + take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters β `_` is | ||
| 1515 | + the separator inside a ledger id, so a key may not carry one). With | ||
| 1516 | + one, the line is keyed `<charge>_k_<key>` (a refund: `<credit>_kr_<key>`), so | ||
| 1517 | + a client retrying after a network timeout gets **the line the first attempt | ||
| 1518 | + wrote**, not a second charge on the family β idempotence by identity, the | ||
| 1519 | + same rule that keeps a replayed assignment from billing twice, never a "has | ||
| 1520 | + this been recorded yet?" scan two concurrent requests can both walk past. The | ||
| 1521 | + replay is answered **before** the over-payment cap is consulted, so a payment | ||
| 1522 | + that filled its charge to the penny still replays as itself instead of coming | ||
| 1523 | + back "already paid in full". Sending that key again with a **different** | ||
| 1524 | + `amount_minor` or a different target is a `409`, never the stored line: that | ||
| 1525 | + is a client bug, and a `201` would bury it. Omit the key and nothing changes | ||
| 1526 | + from before β two identical posts are two payments, which is exactly what a | ||
| 1527 | + desk taking the same amount twice means. | ||
| 1513 | - **A reversal only undoes a `charge` or a `refund`**, for its exact amount and | 1528 | - **A reversal only undoes a `charge` or a `refund`**, for its exact amount and |
| 1514 | nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has | 1529 | nothing else (`400` on any other kind). It is keyed `<line>_r`, so a line has |
| 1515 | at most one reversal however often the call is retried, and the reversed line | 1530 | at most one reversal however often the call is retried, and the reversed line |
| @@ -1537,14 +1552,17 @@ account. | |||
| 1537 | 1552 | ||
| 1538 | `GET /payments/ledger/{user}` is the raw lines, newest first, paged. | 1553 | `GET /payments/ledger/{user}` is the raw lines, newest first, paged. |
| 1539 | `GET /payments/statement/me` and `/payments/statement/{user}` are the | 1554 | `GET /payments/statement/me` and `/payments/statement/{user}` are the |
| 1540 | -**per-charge rollup**: one row per charge with its plan, the installment's | 1555 | +**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`, |
| 1556 | +in an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's | ||
| 1541 | amount and due date, what it collected, what went back out, what is still | 1557 | amount and due date, what it collected, what went back out, what is still |
| 1542 | outstanding, whether the charge itself was reversed (such a charge owes | 1558 | outstanding, whether the charge itself was reversed (such a charge owes |
| 1543 | nothing), and whether it is **`overdue`** β still owed, and its `due_at` has | 1559 | nothing), and whether it is **`overdue`** β still owed, and its `due_at` has |
| 1544 | passed. | 1560 | passed. |
| 1545 | 1561 | ||
| 1546 | All of that is folded from the raw lines **on every request and stored | 1562 | All of that is folded from the raw lines **on every request and stored |
| 1547 | -nowhere**, `overdue` included. There is no overdue flag, no sweep that sets | 1563 | +nowhere**, `overdue` included. Paging windows the *returned rows* only, after |
| 1564 | +that fold: `balance_minor` β and every row's own arithmetic β is identical on | ||
| 1565 | +every page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets | ||
| 1548 | one, and no stored rollup: a stored rollup is a second version of the truth, | 1566 | one, and no stored rollup: a stored rollup is a second version of the truth, |
| 1549 | and the ledger is the first. `GET /payments/balance/me` and | 1567 | and the ledger is the first. `GET /payments/balance/me` and |
| 1550 | `/payments/balance/{user}` are the same fold reduced to one number. | 1568 | `/payments/balance/{user}` are the same fold reduced to one number. |
src/constant.rsmodified+7 -0
| @@ -266,6 +266,13 @@ pub const MAX_FEE_PLAN_INSTALLMENTS: usize = 60; | |||
| 266 | /// request's writes. | 266 | /// request's writes. |
| 267 | pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; | 267 | pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; |
| 268 | 268 | ||
| 269 | +/// Ceiling on the client-chosen `request_key` that makes a credit or a refund | ||
| 270 | +/// retry-safe: it becomes part of the ledger line's record id, so it is bounded | ||
| 271 | +/// and drawn from `[A-Za-z0-9-]` β `_` joins the parts of a ledger id, so a key | ||
| 272 | +/// carrying one could spell another line's id. Sixty-four characters take a | ||
| 273 | +/// UUID or a receipt number comfortably. | ||
| 274 | +pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64; | ||
| 275 | + | ||
| 269 | /// Inclusive bounds for an exam's per-attempt duration, milliseconds | 276 | /// Inclusive bounds for an exam's per-attempt duration, milliseconds |
| 270 | /// (1 minute to 24 hours). Required for `async`, optional for `open`. | 277 | /// (1 minute to 24 hours). Required for `async`, optional for `open`. |
| 271 | pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; | 278 | pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; |
src/domain/payment_ledger.rsmodified+214 -4
| @@ -40,6 +40,18 @@ | |||
| 40 | //! self-heals when it is repeated. Money must never depend on a "has this | 40 | //! 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" | 41 | //! been billed yet?" scan: two concurrent requests can both read "not yet" |
| 42 | //! and both append. | 42 | //! 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`. | ||
| 43 | //! | 55 | //! |
| 44 | //! **The over-payment cap is ADVISORY (accepted race).** [`PaymentLedger::credit`] | 56 | //! **The over-payment cap is ADVISORY (accepted race).** [`PaymentLedger::credit`] |
| 45 | //! and [`PaymentLedger::refund`] refuse to take more than the line they target | 57 | //! and [`PaymentLedger::refund`] refuse to take more than the line they target |
| @@ -60,6 +72,13 @@ | |||
| 60 | //! and both entries are true records of money that really arrived. A CAS | 72 | //! and both entries are true records of money that really arrived. A CAS |
| 61 | //! counter row was rejected β refunding would have to decrement it, which is a | 73 | //! counter row was rejected β refunding would have to decrement it, which is a |
| 62 | //! stored derived balance by another name. | 74 | //! stored derived balance by another name. |
| 75 | +//! | ||
| 76 | +//! The same replica boundary bounds the `request_key` mismatch `409`: it is a | ||
| 77 | +//! read-then-compare, so if two *first-time* posts of one key with different | ||
| 78 | +//! amounts land on two replicas at once, the loser is handed the winner's line | ||
| 79 | +//! as a `201` instead of the conflict. One line, one amount, no double charge β | ||
| 80 | +//! the guarantee that matters holds; only the "you reused a key" diagnostic is | ||
| 81 | +//! best-effort, and every retry after either has landed reports it correctly. | ||
| 63 | 82 | ||
| 64 | use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; | 83 | use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; |
| 65 | use tokio::sync::Mutex; | 84 | use tokio::sync::Mutex; |
| @@ -121,6 +140,30 @@ impl PaymentLedgerId { | |||
| 121 | )) | 140 | )) |
| 122 | } | 141 | } |
| 123 | 142 | ||
| 143 | + /// The one line a `(target, request_key)` pair may ever have: `<target>_k_` | ||
| 144 | + /// for a payment, `<target>_kr_` for a refund. Scoping the key by the line | ||
| 145 | + /// it targets is what keeps one office's "receipt-114" from colliding with | ||
| 146 | + /// another charge's, and the two markers keep the kinds apart the same way | ||
| 147 | + /// `_c<n>` and `_r` do above. | ||
| 148 | + /// | ||
| 149 | + /// **The grammar parses uniquely because `_` joins the parts and cannot | ||
| 150 | + /// appear inside one.** Every id here is `<ulid>_<ulid>_c<n>` optionally | ||
| 151 | + /// followed by one `_k_<key>`, `_kr_<key>` or `_r` β plan and student keys | ||
| 152 | + /// are ULIDs (`[0-9A-Z]` only) and a `request_key` is | ||
| 153 | + /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, so no part | ||
| 154 | + /// can spell a separator plus a marker. That is not decoration: a key of | ||
| 155 | + /// `abc_r` on a refund would derive exactly the id that refund's *reversal* | ||
| 156 | + /// must own, and the loser of that collision would be handed a line of the | ||
| 157 | + /// wrong kind and the wrong amount, with the real reversal impossible | ||
| 158 | + /// forever after. The ban on `_` in a key is what makes the collision | ||
| 159 | + /// unconstructible; [`PaymentLedger::append`] re-checks the kind anyway. | ||
| 160 | + pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { | ||
| 161 | + Self(RecordId::new( | ||
| 162 | + PAYMENT_LEDGER_TABLE, | ||
| 163 | + format!("{}_{marker}_{}", target.key(), key.as_str()), | ||
| 164 | + )) | ||
| 165 | + } | ||
| 166 | + | ||
| 124 | pub fn record(&self) -> RecordId { | 167 | pub fn record(&self) -> RecordId { |
| 125 | self.0.clone() | 168 | self.0.clone() |
| 126 | } | 169 | } |
| @@ -130,6 +173,23 @@ impl PaymentLedgerId { | |||
| 130 | } | 173 | } |
| 131 | } | 174 | } |
| 132 | 175 | ||
| 176 | +/// A client-chosen idempotence key for one payment or refund. Never stored as | ||
| 177 | +/// a column β it lives inside the line's record id, which is what makes a retry | ||
| 178 | +/// derive the row it already wrote instead of a second one. | ||
| 179 | +#[derive(Debug, Clone)] | ||
| 180 | +pub struct PaymentRequestKey(String); | ||
| 181 | + | ||
| 182 | +impl PaymentRequestKey { | ||
| 183 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 184 | + crate::validate::validate_request_key(value)?; | ||
| 185 | + Ok(Self(value.to_string())) | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + pub fn as_str(&self) -> &str { | ||
| 189 | + &self.0 | ||
| 190 | + } | ||
| 191 | +} | ||
| 192 | + | ||
| 133 | /// Did this `CREATE` fail *only* because the row is already there? Matched on | 193 | /// Did this `CREATE` fail *only* because the row is already there? Matched on |
| 134 | /// the SDK's typed `AlreadyExists`/`Record` detail β never on the message text | 194 | /// the SDK's typed `AlreadyExists`/`Record` detail β never on the message text |
| 135 | /// and never on "any database error", because swallowing a real fault in money | 195 | /// and never on "any database error", because swallowing a real fault in money |
| @@ -260,9 +320,25 @@ impl PaymentLedger { | |||
| 260 | /// "already exists". Both are read back the same way, and a conflict that | 320 | /// "already exists". Both are read back the same way, and a conflict that |
| 261 | /// turns out to have written nothing is simply tried again; no path here | 321 | /// turns out to have written nothing is simply tried again; no path here |
| 262 | /// can write a second line, since the id is the key. | 322 | /// can write a second line, since the id is the key. |
| 323 | + /// | ||
| 324 | + /// Both read-backs check the stored line is the *kind* that was being | ||
| 325 | + /// appended. Handing a caller someone else's row is only safe while every | ||
| 326 | + /// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a | ||
| 327 | + /// future marker or a widened key charset ever let two shapes meet, this is | ||
| 328 | + /// the check that turns silently-wrong money into a 500 instead. It should | ||
| 329 | + /// be unreachable, and it is cheap enough to keep it that way. | ||
| 263 | async fn append(row: PaymentLedger, db: &Database) -> Result<PaymentLedger, AppError> { | 330 | async fn append(row: PaymentLedger, db: &Database) -> Result<PaymentLedger, AppError> { |
| 331 | + let same_kind = |existing: PaymentLedger| { | ||
| 332 | + if existing.kind == row.kind { | ||
| 333 | + Ok(existing) | ||
| 334 | + } else { | ||
| 335 | + Err(AppError::Internal( | ||
| 336 | + "a ledger id resolved to a line of another kind".into(), | ||
| 337 | + )) | ||
| 338 | + } | ||
| 339 | + }; | ||
| 264 | if let Some(existing) = Self::read(&row.id, db).await? { | 340 | if let Some(existing) = Self::read(&row.id, db).await? { |
| 265 | - return Ok(existing); | 341 | + return same_kind(existing); |
| 266 | } | 342 | } |
| 267 | let id = row.id.clone(); | 343 | let id = row.id.clone(); |
| 268 | for _ in 0..CAS_UPDATE_RETRIES { | 344 | for _ in 0..CAS_UPDATE_RETRIES { |
| @@ -271,7 +347,7 @@ impl PaymentLedger { | |||
| 271 | Ok(None) => break, | 347 | Ok(None) => break, |
| 272 | Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { | 348 | Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { |
| 273 | if let Some(existing) = Self::read(&id, db).await? { | 349 | if let Some(existing) = Self::read(&id, db).await? { |
| 274 | - return Ok(existing); | 350 | + return same_kind(existing); |
| 275 | } | 351 | } |
| 276 | } | 352 | } |
| 277 | Err(e) => return Err(e.into()), | 353 | Err(e) => return Err(e.into()), |
| @@ -322,11 +398,17 @@ impl PaymentLedger { | |||
| 322 | /// Money in, against one named `charge`. Partial payments are the norm, so | 398 | /// Money in, against one named `charge`. Partial payments are the norm, so |
| 323 | /// a charge may collect several credits; together they may not exceed it | 399 | /// a charge may collect several credits; together they may not exceed it |
| 324 | /// (advisory β see the module doc's accepted race). | 400 | /// (advisory β see the module doc's accepted race). |
| 401 | + /// | ||
| 402 | + /// With a `request_key` the line is keyed by it (see | ||
| 403 | + /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without | ||
| 404 | + /// one the id is a fresh ulid and two identical calls are two payments, | ||
| 405 | + /// which is what a cash desk taking the same amount twice really means. | ||
| 325 | pub async fn credit( | 406 | pub async fn credit( |
| 326 | charge: &PaymentLedger, | 407 | charge: &PaymentLedger, |
| 327 | amount_minor: LedgerAmount, | 408 | amount_minor: LedgerAmount, |
| 328 | method: Option<LedgerMethod>, | 409 | method: Option<LedgerMethod>, |
| 329 | note: Option<LedgerNote>, | 410 | note: Option<LedgerNote>, |
| 411 | + request_key: Option<&PaymentRequestKey>, | ||
| 330 | recorded_by: &UserId, | 412 | recorded_by: &UserId, |
| 331 | db: &Database, | 413 | db: &Database, |
| 332 | ) -> Result<PaymentLedger, AppError> { | 414 | ) -> Result<PaymentLedger, AppError> { |
| @@ -339,6 +421,7 @@ impl PaymentLedger { | |||
| 339 | amount_minor, | 421 | amount_minor, |
| 340 | method, | 422 | method, |
| 341 | note, | 423 | note, |
| 424 | + request_key.map(|key| PaymentLedgerId::for_request(charge.get_id(), "k", key)), | ||
| 342 | recorded_by, | 425 | recorded_by, |
| 343 | db, | 426 | db, |
| 344 | ) | 427 | ) |
| @@ -347,12 +430,14 @@ impl PaymentLedger { | |||
| 347 | 430 | ||
| 348 | /// Money back out, against one named `credit` β how an over-payment or a | 431 | /// Money back out, against one named `credit` β how an over-payment or a |
| 349 | /// payment recorded in error is returned. Partials allowed, and no more | 432 | /// payment recorded in error is returned. Partials allowed, and no more |
| 350 | - /// than the credit was worth (advisory, same race). | 433 | + /// than the credit was worth (advisory, same race). `request_key` makes it |
| 434 | + /// retry-safe exactly as it does for [`PaymentLedger::credit`]. | ||
| 351 | pub async fn refund( | 435 | pub async fn refund( |
| 352 | credit: &PaymentLedger, | 436 | credit: &PaymentLedger, |
| 353 | amount_minor: LedgerAmount, | 437 | amount_minor: LedgerAmount, |
| 354 | method: Option<LedgerMethod>, | 438 | method: Option<LedgerMethod>, |
| 355 | note: Option<LedgerNote>, | 439 | note: Option<LedgerNote>, |
| 440 | + request_key: Option<&PaymentRequestKey>, | ||
| 356 | recorded_by: &UserId, | 441 | recorded_by: &UserId, |
| 357 | db: &Database, | 442 | db: &Database, |
| 358 | ) -> Result<PaymentLedger, AppError> { | 443 | ) -> Result<PaymentLedger, AppError> { |
| @@ -365,6 +450,7 @@ impl PaymentLedger { | |||
| 365 | amount_minor, | 450 | amount_minor, |
| 366 | method, | 451 | method, |
| 367 | note, | 452 | note, |
| 453 | + request_key.map(|key| PaymentLedgerId::for_request(credit.get_id(), "kr", key)), | ||
| 368 | recorded_by, | 454 | recorded_by, |
| 369 | db, | 455 | db, |
| 370 | ) | 456 | ) |
| @@ -374,6 +460,13 @@ impl PaymentLedger { | |||
| 374 | /// The shared body of `credit` and `refund`: check the target is the kind | 460 | /// The shared body of `credit` and `refund`: check the target is the kind |
| 375 | /// this line may point at, then append under [`PAYMENT_LOCK`] while the | 461 | /// this line may point at, then append under [`PAYMENT_LOCK`] while the |
| 376 | /// target's existing children still sum below its amount. | 462 | /// target's existing children still sum below its amount. |
| 463 | + /// | ||
| 464 | + /// The replay read comes **before** the cap, and inside the lock: on a | ||
| 465 | + /// retry the first attempt's line is already part of the subtree the cap | ||
| 466 | + /// folds, so consulting the cap first would answer a payment that landed | ||
| 467 | + /// with "already paid in full" β refusing precisely the request that | ||
| 468 | + /// succeeded. Reading the id under the lock also keeps two simultaneous | ||
| 469 | + /// retries from both walking into the cap check. | ||
| 377 | #[allow(clippy::too_many_arguments)] | 470 | #[allow(clippy::too_many_arguments)] |
| 378 | async fn against( | 471 | async fn against( |
| 379 | target: &PaymentLedger, | 472 | target: &PaymentLedger, |
| @@ -384,6 +477,7 @@ impl PaymentLedger { | |||
| 384 | amount_minor: LedgerAmount, | 477 | amount_minor: LedgerAmount, |
| 385 | method: Option<LedgerMethod>, | 478 | method: Option<LedgerMethod>, |
| 386 | note: Option<LedgerNote>, | 479 | note: Option<LedgerNote>, |
| 480 | + keyed: Option<PaymentLedgerId>, | ||
| 387 | recorded_by: &UserId, | 481 | recorded_by: &UserId, |
| 388 | db: &Database, | 482 | db: &Database, |
| 389 | ) -> Result<PaymentLedger, AppError> { | 483 | ) -> Result<PaymentLedger, AppError> { |
| @@ -395,13 +489,29 @@ impl PaymentLedger { | |||
| 395 | .into()); | 489 | .into()); |
| 396 | } | 490 | } |
| 397 | let _guard = PAYMENT_LOCK.lock().await; | 491 | let _guard = PAYMENT_LOCK.lock().await; |
| 492 | + if let Some(id) = &keyed | ||
| 493 | + && let Some(existing) = Self::read(id, db).await? | ||
| 494 | + { | ||
| 495 | + // A replay is answered from the stored line β but only if it is the | ||
| 496 | + // same money. The same key for a different amount or a different | ||
| 497 | + // target is a client bug, and handing back the old line would hide | ||
| 498 | + // it behind a `201`. | ||
| 499 | + if existing.amount_minor.as_minor() != amount_minor.as_minor() | ||
| 500 | + || existing.get_source_key() != Some(target.id.key()) | ||
| 501 | + { | ||
| 502 | + return Err(AppError::Conflict( | ||
| 503 | + "this request_key was already used for a different amount or target", | ||
| 504 | + )); | ||
| 505 | + } | ||
| 506 | + return Ok(existing); | ||
| 507 | + } | ||
| 398 | let taken = Self::applied_to(target, db).await?; | 508 | let taken = Self::applied_to(target, db).await?; |
| 399 | if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { | 509 | if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { |
| 400 | return Err(AppError::Conflict(over)); | 510 | return Err(AppError::Conflict(over)); |
| 401 | } | 511 | } |
| 402 | Self::append( | 512 | Self::append( |
| 403 | PaymentLedger { | 513 | PaymentLedger { |
| 404 | - id: PaymentLedgerId::generate(), | 514 | + id: keyed.unwrap_or_else(PaymentLedgerId::generate), |
| 405 | student: target.student.clone(), | 515 | student: target.student.clone(), |
| 406 | kind, | 516 | kind, |
| 407 | amount_minor, | 517 | amount_minor, |
| @@ -633,6 +743,30 @@ mod tests { | |||
| 633 | ); | 743 | ); |
| 634 | } | 744 | } |
| 635 | 745 | ||
| 746 | + /// A `request_key` is only an idempotence key if it derives the same id | ||
| 747 | + /// every time, and only *safe* if it is scoped by the line it targets and | ||
| 748 | + /// tells a payment from a refund. | ||
| 749 | + #[test] | ||
| 750 | + fn a_request_key_is_scoped_by_its_target_and_its_kind() { | ||
| 751 | + let charge = PaymentLedgerId::from_key("plan1_stu1_c1"); | ||
| 752 | + let other = PaymentLedgerId::from_key("plan1_stu1_c2"); | ||
| 753 | + let key = PaymentRequestKey::try_new("receipt-114").unwrap(); | ||
| 754 | + let credit = PaymentLedgerId::for_request(&charge, "k", &key); | ||
| 755 | + | ||
| 756 | + assert_eq!(credit.key(), "plan1_stu1_c1_k_receipt-114"); | ||
| 757 | + assert_eq!( | ||
| 758 | + PaymentLedgerId::for_request(&charge, "k", &key), | ||
| 759 | + credit, | ||
| 760 | + "a retry must derive the same id, or it pays twice" | ||
| 761 | + ); | ||
| 762 | + assert_ne!(PaymentLedgerId::for_request(&other, "k", &key), credit); | ||
| 763 | + assert_ne!(PaymentLedgerId::for_request(&charge, "kr", &key), credit); | ||
| 764 | + assert_eq!( | ||
| 765 | + PaymentLedgerId::for_request(&credit, "kr", &key).key(), | ||
| 766 | + "plan1_stu1_c1_k_receipt-114_kr_receipt-114" | ||
| 767 | + ); | ||
| 768 | + } | ||
| 769 | + | ||
| 636 | /// Raise one charge of `amount` on a fresh student, and hand it back. | 770 | /// Raise one charge of `amount` on a fresh student, and hand it back. |
| 637 | #[cfg(test)] | 771 | #[cfg(test)] |
| 638 | async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { | 772 | async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { |
| @@ -661,6 +795,74 @@ mod tests { | |||
| 661 | (lines.into_iter().next().unwrap(), student, manager) | 795 | (lines.into_iter().next().unwrap(), student, manager) |
| 662 | } | 796 | } |
| 663 | 797 | ||
| 798 | + /// The collision the id grammar must not admit: with `_` legal in a key, a | ||
| 799 | + /// refund keyed `abc_r` derived exactly `<refund>_r` β the id that refund's | ||
| 800 | + /// own reversal must own β and whichever came second was handed the other's | ||
| 801 | + /// line, of the wrong kind and the wrong amount, with the real reversal | ||
| 802 | + /// impossible ever after. `_` is now illegal in a key, so the collision | ||
| 803 | + /// cannot be constructed; the nearest legal key still works, and the | ||
| 804 | + /// reversal still gets its own line. | ||
| 805 | + #[tokio::test] | ||
| 806 | + async fn a_keyed_refund_cannot_take_the_id_of_its_own_reversal() { | ||
| 807 | + assert!( | ||
| 808 | + PaymentRequestKey::try_new("abc_r").is_err(), | ||
| 809 | + "the key that spelled a reversal's id must not parse" | ||
| 810 | + ); | ||
| 811 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 812 | + let (charge, _, manager) = one_charge(100, &db).await; | ||
| 813 | + let key = PaymentRequestKey::try_new("abc-r").unwrap(); | ||
| 814 | + let credit = PaymentLedger::credit( | ||
| 815 | + &charge, | ||
| 816 | + LedgerAmount::try_new(100).unwrap(), | ||
| 817 | + None, | ||
| 818 | + None, | ||
| 819 | + None, | ||
| 820 | + &manager, | ||
| 821 | + &db, | ||
| 822 | + ) | ||
| 823 | + .await | ||
| 824 | + .unwrap(); | ||
| 825 | + let refund = PaymentLedger::refund( | ||
| 826 | + &credit, | ||
| 827 | + LedgerAmount::try_new(100).unwrap(), | ||
| 828 | + None, | ||
| 829 | + None, | ||
| 830 | + Some(&key), | ||
| 831 | + &manager, | ||
| 832 | + &db, | ||
| 833 | + ) | ||
| 834 | + .await | ||
| 835 | + .unwrap(); | ||
| 836 | + let reversal = PaymentLedger::reversal(&refund, None, &manager, &db) | ||
| 837 | + .await | ||
| 838 | + .unwrap(); | ||
| 839 | + assert_ne!(reversal.get_id(), refund.get_id()); | ||
| 840 | + assert_eq!(reversal.get_kind(), PaymentLedgerKind::Reversal); | ||
| 841 | + assert_eq!(reversal.get_amount_minor().as_minor(), 100); | ||
| 842 | + | ||
| 843 | + // And the last-ditch guard bites: an id that resolves to another kind | ||
| 844 | + // is a 500, never that other line handed back as this one. | ||
| 845 | + let intruder = PaymentLedger { | ||
| 846 | + id: charge.get_id().clone(), | ||
| 847 | + student: charge.student.clone(), | ||
| 848 | + kind: PaymentLedgerKind::Credit, | ||
| 849 | + amount_minor: LedgerAmount::try_new(1).unwrap(), | ||
| 850 | + source: Some(charge.id.record()), | ||
| 851 | + due_at: None, | ||
| 852 | + method: None, | ||
| 853 | + note: None, | ||
| 854 | + recorded_by: manager.clone(), | ||
| 855 | + created_at: Timestamp::now(), | ||
| 856 | + }; | ||
| 857 | + assert!( | ||
| 858 | + matches!( | ||
| 859 | + PaymentLedger::append(intruder, &db).await, | ||
| 860 | + Err(AppError::Internal(_)) | ||
| 861 | + ), | ||
| 862 | + "a read-back of another kind must not pass for the appended line" | ||
| 863 | + ); | ||
| 864 | + } | ||
| 865 | + | ||
| 664 | /// The defect this fold replaced a plain sum for: a payment that was handed | 866 | /// The defect this fold replaced a plain sum for: a payment that was handed |
| 665 | /// back frees the room it took, so the charge it paid can be paid again. It | 867 | /// back frees the room it took, so the charge it paid can be paid again. It |
| 666 | /// is the same charge, still owed β refusing the second payment would leave | 868 | /// is the same charge, still owed β refusing the second payment would leave |
| @@ -675,6 +877,7 @@ mod tests { | |||
| 675 | LedgerAmount::try_new(amount).unwrap(), | 877 | LedgerAmount::try_new(amount).unwrap(), |
| 676 | None, | 878 | None, |
| 677 | None, | 879 | None, |
| 880 | + None, | ||
| 678 | &manager, | 881 | &manager, |
| 679 | &db, | 882 | &db, |
| 680 | ) | 883 | ) |
| @@ -692,6 +895,7 @@ mod tests { | |||
| 692 | LedgerAmount::try_new(100).unwrap(), | 895 | LedgerAmount::try_new(100).unwrap(), |
| 693 | None, | 896 | None, |
| 694 | None, | 897 | None, |
| 898 | + None, | ||
| 695 | &manager, | 899 | &manager, |
| 696 | &db, | 900 | &db, |
| 697 | ) | 901 | ) |
| @@ -723,6 +927,7 @@ mod tests { | |||
| 723 | LedgerAmount::try_new(100).unwrap(), | 927 | LedgerAmount::try_new(100).unwrap(), |
| 724 | None, | 928 | None, |
| 725 | None, | 929 | None, |
| 930 | + None, | ||
| 726 | &manager, | 931 | &manager, |
| 727 | &db, | 932 | &db, |
| 728 | ) | 933 | ) |
| @@ -733,6 +938,7 @@ mod tests { | |||
| 733 | LedgerAmount::try_new(100).unwrap(), | 938 | LedgerAmount::try_new(100).unwrap(), |
| 734 | None, | 939 | None, |
| 735 | None, | 940 | None, |
| 941 | + None, | ||
| 736 | &manager, | 942 | &manager, |
| 737 | &db, | 943 | &db, |
| 738 | ) | 944 | ) |
| @@ -749,6 +955,7 @@ mod tests { | |||
| 749 | LedgerAmount::try_new(100).unwrap(), | 955 | LedgerAmount::try_new(100).unwrap(), |
| 750 | None, | 956 | None, |
| 751 | None, | 957 | None, |
| 958 | + None, | ||
| 752 | &manager, | 959 | &manager, |
| 753 | &db | 960 | &db |
| 754 | ) | 961 | ) |
| @@ -797,6 +1004,7 @@ mod tests { | |||
| 797 | LedgerAmount::try_new(amount).unwrap(), | 1004 | LedgerAmount::try_new(amount).unwrap(), |
| 798 | None, | 1005 | None, |
| 799 | None, | 1006 | None, |
| 1007 | + None, | ||
| 800 | &manager, | 1008 | &manager, |
| 801 | &db, | 1009 | &db, |
| 802 | ) | 1010 | ) |
| @@ -816,6 +1024,7 @@ mod tests { | |||
| 816 | LedgerAmount::try_new(amount).unwrap(), | 1024 | LedgerAmount::try_new(amount).unwrap(), |
| 817 | None, | 1025 | None, |
| 818 | None, | 1026 | None, |
| 1027 | + None, | ||
| 819 | &manager, | 1028 | &manager, |
| 820 | &db, | 1029 | &db, |
| 821 | ) | 1030 | ) |
| @@ -835,6 +1044,7 @@ mod tests { | |||
| 835 | LedgerAmount::try_new(1).unwrap(), | 1044 | LedgerAmount::try_new(1).unwrap(), |
| 836 | None, | 1045 | None, |
| 837 | None, | 1046 | None, |
| 1047 | + None, | ||
| 838 | &manager, | 1048 | &manager, |
| 839 | &db | 1049 | &db |
| 840 | ) | 1050 | ) |
src/lib.rsmodified+1 -1
| @@ -58,7 +58,7 @@ use crate::state::AppState; | |||
| 58 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 58 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 59 | (name = "exams", description = "Exams (per course, weighted by their kind β see `settings`): results, sync/async/open scheduling, attempts (students only β staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, β€ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β no `mode`, or `open` β drop out); without it the list stays newest-first"), | 59 | (name = "exams", description = "Exams (per course, weighted by their kind β see `settings`): results, sync/async/open scheduling, attempts (students only β staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, β€ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β no `mode`, or `open` β drop out); without it the list stays newest-first"), |
| 60 | (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruΕ) as an integer β this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β own always, otherwise teacher+ or a parent link β and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β inside that window neither booking nor cancelling lands (`409`) β measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), | 60 | (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruΕ) as an integer β this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β own always, otherwise teacher+ or a parent link β and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β inside that window neither booking nor cancelling lands (`409`) β measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"), |
| 61 | - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruΕ) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, β¦}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β that cap is **advisory**: it is a cross-record sum taken under a process-local lock, and with two replicas serving, two payments recorded in the same instant can together overshoot a charge. Accepted deliberately: the outcome is an over-paid charge, visible in the statement and undone by a refund, and both lines are true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", β¦). Every write here is **manager+** β teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}`, `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β all folded from the raw lines on every request and stored nowhere"), | 61 | + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` β a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruΕ) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** β an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) β so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree β write a new plan instead. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** β it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) β allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, β¦}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1β64 characters β no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. Payments and refunds are capped by the line they target (`409` past it) β that cap is **advisory**: it is a cross-record sum taken under a process-local lock, and with two replicas serving, two payments recorded in the same instant can together overshoot a charge. Accepted deliberately: the outcome is an over-paid charge, visible in the statement and undone by a refund, and both lines are true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", β¦). Every write here is **manager+** β teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope β the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ β **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup β plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) β all folded from the raw lines on every request and stored nowhere"), |
| 62 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 62 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 63 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β those marks would silently re-weight. Also the food program: the meal slots menus are published for β each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), | 63 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β those marks would silently re-weight. Also the food program: the meal slots menus are published for β each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"), |
| 64 | (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), | 64 | (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), |
src/validate.rsmodified+49 -4
| @@ -3,10 +3,10 @@ | |||
| 3 | 3 | ||
| 4 | use crate::constant::{ | 4 | use crate::constant::{ |
| 5 | COURSE_KINDS, EXAM_MODES, HOMEWORK_STATUSES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, | 5 | COURSE_KINDS, EXAM_MODES, HOMEWORK_STATUSES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, |
| 6 | - MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, | 6 | + MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PAYMENT_REQUEST_KEY_LEN, |
| 7 | - MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, | 7 | + MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, |
| 8 | - MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, | 8 | + MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, |
| 9 | - USERNAME_SEPARATORS, | 9 | + UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, |
| 10 | }; | 10 | }; |
| 11 | use crate::error::ValidationError; | 11 | use crate::error::ValidationError; |
| 12 | 12 | ||
| @@ -198,6 +198,32 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> { | |||
| 198 | Ok(()) | 198 | Ok(()) |
| 199 | } | 199 | } |
| 200 | 200 | ||
| 201 | +/// A client-chosen idempotence key. It is concatenated into a record id whose | ||
| 202 | +/// parts are joined by `_`, so the charset is an allowlist that **excludes the | ||
| 203 | +/// separator itself**: a key containing `_` could spell another id's grammar | ||
| 204 | +/// (a refund keyed `abc_r` would derive the id a reversal of that refund must | ||
| 205 | +/// own), and two different ids meeting is money landing on the wrong line. | ||
| 206 | +pub fn validate_request_key(value: &str) -> Result<(), ValidationError> { | ||
| 207 | + let len = value.chars().count(); | ||
| 208 | + if len == 0 { | ||
| 209 | + return Err(ValidationError::Empty("request_key")); | ||
| 210 | + } | ||
| 211 | + if len > MAX_PAYMENT_REQUEST_KEY_LEN { | ||
| 212 | + return Err(ValidationError::TooLong { | ||
| 213 | + field: "request_key", | ||
| 214 | + max: MAX_PAYMENT_REQUEST_KEY_LEN, | ||
| 215 | + got: len, | ||
| 216 | + }); | ||
| 217 | + } | ||
| 218 | + if !value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { | ||
| 219 | + return Err(ValidationError::Invalid { | ||
| 220 | + field: "request_key", | ||
| 221 | + reason: "may contain only letters, digits and '-'", | ||
| 222 | + }); | ||
| 223 | + } | ||
| 224 | + Ok(()) | ||
| 225 | +} | ||
| 226 | + | ||
| 201 | pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { | 227 | pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { |
| 202 | if COURSE_KINDS.contains(&value) { | 228 | if COURSE_KINDS.contains(&value) { |
| 203 | Ok(()) | 229 | Ok(()) |
| @@ -397,6 +423,25 @@ mod tests { | |||
| 397 | assert!(validate_phone("55+5123456").is_err()); // + only allowed in front | 423 | assert!(validate_phone("55+5123456").is_err()); // + only allowed in front |
| 398 | } | 424 | } |
| 399 | 425 | ||
| 426 | + #[tokio::test] | ||
| 427 | + async fn request_key_rules() { | ||
| 428 | + assert!(validate_request_key("invoice-2026-114").is_ok()); | ||
| 429 | + assert!(validate_request_key(&"x".repeat(MAX_PAYMENT_REQUEST_KEY_LEN)).is_ok()); | ||
| 430 | + assert!(validate_request_key("").is_err()); | ||
| 431 | + assert!(validate_request_key(&"x".repeat(MAX_PAYMENT_REQUEST_KEY_LEN + 1)).is_err()); | ||
| 432 | + // `_` is the record-id separator, so a key carrying one could spell | ||
| 433 | + // another line's id: `abc_r` under a refund is the id that refund's | ||
| 434 | + // reversal must own, and `a_kr_b` under a charge is the id of a refund | ||
| 435 | + // against that charge's `a`-keyed credit. | ||
| 436 | + assert!(validate_request_key("abc_r").is_err()); | ||
| 437 | + assert!(validate_request_key("a_kr_b").is_err()); | ||
| 438 | + // Anything that could break β or alias β a record id. | ||
| 439 | + assert!(validate_request_key("a b").is_err()); | ||
| 440 | + assert!(validate_request_key("a:b").is_err()); | ||
| 441 | + assert!(validate_request_key("a/b").is_err()); | ||
| 442 | + assert!(validate_request_key("naΓ―ve").is_err()); | ||
| 443 | + } | ||
| 444 | + | ||
| 400 | #[tokio::test] | 445 | #[tokio::test] |
| 401 | async fn course_kind_rules() { | 446 | async fn course_kind_rules() { |
| 402 | for kind in ["course", "study", "club"] { | 447 | for kind in ["course", "study", "club"] { |
src/web/limits.rsmodified+4 -0
| @@ -230,6 +230,9 @@ struct PaymentLimits { | |||
| 230 | max_plan_installments: usize, | 230 | max_plan_installments: usize, |
| 231 | /// How many students one bulk assignment may name. | 231 | /// How many students one bulk assignment may name. |
| 232 | max_assign_students: usize, | 232 | max_assign_students: usize, |
| 233 | + /// Ceiling on the optional `request_key` that makes a credit or a refund | ||
| 234 | + /// retry-safe; charset `[A-Za-z0-9-]` (no `_`), at least one character. | ||
| 235 | + max_request_key_len: usize, | ||
| 233 | /// The only accepted payment-ledger `kind` values. | 236 | /// The only accepted payment-ledger `kind` values. |
| 234 | #[schema(example = json!(["charge", "credit", "reversal", "refund"]))] | 237 | #[schema(example = json!(["charge", "credit", "reversal", "refund"]))] |
| 235 | ledger_kinds: Vec<&'static str>, | 238 | ledger_kinds: Vec<&'static str>, |
| @@ -437,6 +440,7 @@ impl LimitsResponse { | |||
| 437 | max_plan_name_len: MAX_FEE_PLAN_NAME_LEN, | 440 | max_plan_name_len: MAX_FEE_PLAN_NAME_LEN, |
| 438 | max_plan_installments: MAX_FEE_PLAN_INSTALLMENTS, | 441 | max_plan_installments: MAX_FEE_PLAN_INSTALLMENTS, |
| 439 | max_assign_students: MAX_FEE_PLAN_ASSIGN_STUDENTS, | 442 | max_assign_students: MAX_FEE_PLAN_ASSIGN_STUDENTS, |
| 443 | + max_request_key_len: MAX_PAYMENT_REQUEST_KEY_LEN, | ||
| 440 | ledger_kinds: PAYMENT_LEDGER_KINDS.to_vec(), | 444 | ledger_kinds: PAYMENT_LEDGER_KINDS.to_vec(), |
| 441 | }, | 445 | }, |
| 442 | chatbot: ChatbotLimits { | 446 | chatbot: ChatbotLimits { |
src/web/payments.rsmodified+71 -13
| @@ -28,6 +28,7 @@ use crate::domain::fee_plan_assignment::FeePlanAssignment; | |||
| 28 | use crate::domain::parent_link::ParentLink; | 28 | use crate::domain::parent_link::ParentLink; |
| 29 | use crate::domain::payment_ledger::{ | 29 | use crate::domain::payment_ledger::{ |
| 30 | LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, | 30 | LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, |
| 31 | + PaymentRequestKey, | ||
| 31 | }; | 32 | }; |
| 32 | use crate::domain::role::Role; | 33 | use crate::domain::role::Role; |
| 33 | use crate::domain::timestamp::Timestamp; | 34 | use crate::domain::timestamp::Timestamp; |
| @@ -35,7 +36,7 @@ use crate::domain::user::{User, UserId}; | |||
| 35 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 36 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 36 | use crate::state::AppState; | 37 | use crate::state::AppState; |
| 37 | 38 | ||
| 38 | -use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map}; | 39 | +use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map}; |
| 39 | 40 | ||
| 40 | pub fn routes() -> OpenApiRouter<AppState> { | 41 | pub fn routes() -> OpenApiRouter<AppState> { |
| 41 | OpenApiRouter::new() | 42 | OpenApiRouter::new() |
| @@ -549,6 +550,13 @@ struct RecordPayment { | |||
| 549 | method: Option<String>, | 550 | method: Option<String>, |
| 550 | #[schema(max_length = 500, example = "receipt 2026-114")] | 551 | #[schema(max_length = 500, example = "receipt 2026-114")] |
| 551 | note: Option<String>, | 552 | note: Option<String>, |
| 553 | + /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the | ||
| 554 | + /// separator inside a ledger line's id). Send one and a | ||
| 555 | + /// retry after a timeout returns the **same** line instead of recording the | ||
| 556 | + /// money twice; omit it and two identical calls are two payments. The same | ||
| 557 | + /// key sent with a different `amount_minor` or `charge_id` is a `409`. | ||
| 558 | + #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] | ||
| 559 | + request_key: Option<String>, | ||
| 552 | } | 560 | } |
| 553 | 561 | ||
| 554 | #[derive(Deserialize, ToSchema)] | 562 | #[derive(Deserialize, ToSchema)] |
| @@ -563,6 +571,11 @@ struct RecordRefund { | |||
| 563 | method: Option<String>, | 571 | method: Option<String>, |
| 564 | #[schema(max_length = 500)] | 572 | #[schema(max_length = 500)] |
| 565 | note: Option<String>, | 573 | note: Option<String>, |
| 574 | + /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` β the same | ||
| 575 | + /// retry-safety a payment gets, keyed by the credit it returns. The same | ||
| 576 | + /// key with a different `amount_minor` or `credit_id` is a `409`. | ||
| 577 | + #[schema(min_length = 1, max_length = 64, example = "refund-2026-114")] | ||
| 578 | + request_key: Option<String>, | ||
| 566 | } | 579 | } |
| 567 | 580 | ||
| 568 | #[derive(Deserialize, ToSchema)] | 581 | #[derive(Deserialize, ToSchema)] |
| @@ -581,10 +594,21 @@ fn note_of(raw: Option<&str>) -> Result<Option<LedgerNote>, AppError> { | |||
| 581 | Ok(raw.map(LedgerNote::try_new).transpose()?.flatten()) | 594 | Ok(raw.map(LedgerNote::try_new).transpose()?.flatten()) |
| 582 | } | 595 | } |
| 583 | 596 | ||
| 597 | +fn request_key_of(raw: Option<&str>) -> Result<Option<PaymentRequestKey>, AppError> { | ||
| 598 | + Ok(raw.map(PaymentRequestKey::try_new).transpose()?) | ||
| 599 | +} | ||
| 600 | + | ||
| 584 | /// Record money received against one named charge. Allocation is recorded, not | 601 | /// Record money received against one named charge. Allocation is recorded, not |
| 585 | /// inferred: a payment always says which installment it settles. Partial | 602 | /// inferred: a payment always says which installment it settles. Partial |
| 586 | /// payments accumulate; one that would take the charge past what it is worth is | 603 | /// payments accumulate; one that would take the charge past what it is worth is |
| 587 | /// a `409`. | 604 | /// a `409`. |
| 605 | +/// | ||
| 606 | +/// **Retry-safe on request** β send a `request_key` and a repeat of the call | ||
| 607 | +/// (a client retry after a network timeout) returns the line the first attempt | ||
| 608 | +/// wrote rather than recording the money a second time, even when that payment | ||
| 609 | +/// filled the charge exactly. The same key with a different `amount_minor` or | ||
| 610 | +/// `charge_id` is a `409`: that is a client bug, not a replay. Without a key | ||
| 611 | +/// two identical calls are two payments, as before. | ||
| 588 | #[utoipa::path( | 612 | #[utoipa::path( |
| 589 | post, | 613 | post, |
| 590 | path = "/credits", | 614 | path = "/credits", |
| @@ -597,7 +621,7 @@ fn note_of(raw: Option<&str>) -> Result<Option<LedgerNote>, AppError> { | |||
| 597 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 621 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 598 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 622 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 599 | (status = 404, description = "No such ledger line", body = ErrorResponse), | 623 | (status = 404, description = "No such ledger line", body = ErrorResponse), |
| 600 | - (status = 409, description = "The charge is already paid in full", body = ErrorResponse), | 624 | + (status = 409, description = "The charge is already paid in full, or the request_key was used for a different amount or charge", body = ErrorResponse), |
| 601 | ), | 625 | ), |
| 602 | )] | 626 | )] |
| 603 | async fn record_payment( | 627 | async fn record_payment( |
| @@ -611,6 +635,7 @@ async fn record_payment( | |||
| 611 | LedgerAmount::try_new(req.amount_minor)?, | 635 | LedgerAmount::try_new(req.amount_minor)?, |
| 612 | method_of(req.method.as_deref())?, | 636 | method_of(req.method.as_deref())?, |
| 613 | note_of(req.note.as_deref())?, | 637 | note_of(req.note.as_deref())?, |
| 638 | + request_key_of(req.request_key.as_deref())?.as_ref(), | ||
| 614 | manager.get_id(), | 639 | manager.get_id(), |
| 615 | &st.db, | 640 | &st.db, |
| 616 | ) | 641 | ) |
| @@ -621,6 +646,10 @@ async fn record_payment( | |||
| 621 | /// Hand money back, against one named payment β how an over-payment or a | 646 | /// Hand money back, against one named payment β how an over-payment or a |
| 622 | /// payment recorded in error is returned, and the only way a mistaken *credit* | 647 | /// payment recorded in error is returned, and the only way a mistaken *credit* |
| 623 | /// is corrected (a credit is never reversed). Capped by that credit's amount. | 648 | /// is corrected (a credit is never reversed). Capped by that credit's amount. |
| 649 | +/// | ||
| 650 | +/// **Retry-safe on request** the same way a payment is: a `request_key` makes a | ||
| 651 | +/// repeat return the existing refund, and the same key with a different | ||
| 652 | +/// `amount_minor` or `credit_id` is a `409`. | ||
| 624 | #[utoipa::path( | 653 | #[utoipa::path( |
| 625 | post, | 654 | post, |
| 626 | path = "/refunds", | 655 | path = "/refunds", |
| @@ -633,7 +662,7 @@ async fn record_payment( | |||
| 633 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 662 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 634 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | 663 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 635 | (status = 404, description = "No such ledger line", body = ErrorResponse), | 664 | (status = 404, description = "No such ledger line", body = ErrorResponse), |
| 636 | - (status = 409, description = "The payment is already refunded in full", body = ErrorResponse), | 665 | + (status = 409, description = "The payment is already refunded in full, or the request_key was used for a different amount or payment", body = ErrorResponse), |
| 637 | ), | 666 | ), |
| 638 | )] | 667 | )] |
| 639 | async fn record_refund( | 668 | async fn record_refund( |
| @@ -647,6 +676,7 @@ async fn record_refund( | |||
| 647 | LedgerAmount::try_new(req.amount_minor)?, | 676 | LedgerAmount::try_new(req.amount_minor)?, |
| 648 | method_of(req.method.as_deref())?, | 677 | method_of(req.method.as_deref())?, |
| 649 | note_of(req.note.as_deref())?, | 678 | note_of(req.note.as_deref())?, |
| 679 | + request_key_of(req.request_key.as_deref())?.as_ref(), | ||
| 650 | manager.get_id(), | 680 | manager.get_id(), |
| 651 | &st.db, | 681 | &st.db, |
| 652 | ) | 682 | ) |
| @@ -782,8 +812,10 @@ struct StatementEntry { | |||
| 782 | #[derive(Serialize, ToSchema)] | 812 | #[derive(Serialize, ToSchema)] |
| 783 | struct StatementResponse { | 813 | struct StatementResponse { |
| 784 | student: PersonRef, | 814 | student: PersonRef, |
| 785 | - /// One row per charge, newest first. | 815 | + /// One row per charge, newest first, in the standard |
| 786 | - entries: Vec<StatementEntry>, | 816 | + /// `{items, total, limit, offset}` envelope. Paging windows these rows |
| 817 | + /// only β `balance_minor` is folded from every line either way. | ||
| 818 | + entries: Page<StatementEntry>, | ||
| 787 | /// `credits + reversals - charges - refunds`, minor units. Negative means | 819 | /// `credits + reversals - charges - refunds`, minor units. Negative means |
| 788 | /// the family owes the school. | 820 | /// the family owes the school. |
| 789 | #[schema(example = -100000)] | 821 | #[schema(example = -100000)] |
| @@ -796,8 +828,14 @@ struct StatementResponse { | |||
| 796 | /// what is still owed, and whether it is late β is computed from the raw lines | 828 | /// what is still owed, and whether it is late β is computed from the raw lines |
| 797 | /// at request time and stored nowhere: a stored rollup is a second version of | 829 | /// at request time and stored nowhere: a stored rollup is a second version of |
| 798 | /// the truth, and the ledger is the first. | 830 | /// the truth, and the ledger is the first. |
| 831 | +/// | ||
| 832 | +/// `limit`/`offset` window the returned rows **after** the whole fold, never | ||
| 833 | +/// the lines it folds: a page of a statement must still report the same | ||
| 834 | +/// `balance_minor` (and the same overdue arithmetic) as every other page. | ||
| 799 | async fn statement_response( | 835 | async fn statement_response( |
| 800 | student: &UserId, | 836 | student: &UserId, |
| 837 | + limit: Option<i64>, | ||
| 838 | + offset: i64, | ||
| 801 | db: &Database, | 839 | db: &Database, |
| 802 | ) -> Result<Json<StatementResponse>, AppError> { | 840 | ) -> Result<Json<StatementResponse>, AppError> { |
| 803 | let (lines, _) = PaymentLedger::list_for_student(student, None, 0, db).await?; | 841 | let (lines, _) = PaymentLedger::list_for_student(student, None, 0, db).await?; |
| @@ -832,9 +870,16 @@ async fn statement_response( | |||
| 832 | } | 870 | } |
| 833 | 871 | ||
| 834 | let now = Timestamp::now().as_millis(); | 872 | let now = Timestamp::now().as_millis(); |
| 835 | - let entries = lines | 873 | + // The window is taken over the charges, not over the lines: the rollup |
| 874 | + // above (and the balance below) still reads every line, so a page reports | ||
| 875 | + // exactly the arithmetic the unpaged document does. | ||
| 876 | + let charges: Vec<&PaymentLedger> = lines | ||
| 836 | .iter() | 877 | .iter() |
| 837 | .filter(|line| line.get_kind() == PaymentLedgerKind::Charge) | 878 | .filter(|line| line.get_kind() == PaymentLedgerKind::Charge) |
| 879 | + .collect(); | ||
| 880 | + let total = charges.len() as i64; | ||
| 881 | + let entries: Vec<StatementEntry> = paginate(&charges, limit, offset) | ||
| 882 | + .iter() | ||
| 838 | .map(|charge| { | 883 | .map(|charge| { |
| 839 | let paid: Vec<&&PaymentLedger> = children | 884 | let paid: Vec<&&PaymentLedger> = children |
| 840 | .get(charge.get_id().key()) | 885 | .get(charge.get_id().key()) |
| @@ -885,40 +930,48 @@ async fn statement_response( | |||
| 885 | let people = person_map(std::iter::once(student.clone()), db).await?; | 930 | let people = person_map(std::iter::once(student.clone()), db).await?; |
| 886 | Ok(Json(StatementResponse { | 931 | Ok(Json(StatementResponse { |
| 887 | student: PersonRef::resolve(&people, student), | 932 | student: PersonRef::resolve(&people, student), |
| 888 | - entries, | 933 | + entries: Page::new(entries, total, limit, offset), |
| 889 | balance_minor: PaymentLedger::balance_of(student, db).await?, | 934 | balance_minor: PaymentLedger::balance_of(student, db).await?, |
| 890 | })) | 935 | })) |
| 891 | } | 936 | } |
| 892 | 937 | ||
| 893 | -/// The caller's own statement. | 938 | +/// The caller's own statement. The per-charge rows are paged via |
| 939 | +/// `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the | ||
| 940 | +/// same on every page, because the fold behind it reads every line. | ||
| 894 | #[utoipa::path( | 941 | #[utoipa::path( |
| 895 | get, | 942 | get, |
| 896 | path = "/statement/me", | 943 | path = "/statement/me", |
| 897 | tag = "payments", | 944 | tag = "payments", |
| 898 | security(("session_cookie" = [])), | 945 | security(("session_cookie" = [])), |
| 946 | + params(PageParams), | ||
| 899 | responses( | 947 | responses( |
| 900 | (status = 200, description = "The caller's statement", body = StatementResponse), | 948 | (status = 200, description = "The caller's statement", body = StatementResponse), |
| 949 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 901 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 950 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 902 | ), | 951 | ), |
| 903 | )] | 952 | )] |
| 904 | async fn my_statement( | 953 | async fn my_statement( |
| 905 | State(st): State<AppState>, | 954 | State(st): State<AppState>, |
| 906 | CurrentUser(user): CurrentUser, | 955 | CurrentUser(user): CurrentUser, |
| 956 | + Query(page): Query<PageParams>, | ||
| 907 | ) -> Result<Json<StatementResponse>, AppError> { | 957 | ) -> Result<Json<StatementResponse>, AppError> { |
| 908 | - statement_response(user.get_id(), &st.db).await | 958 | + let (limit, offset) = page.resolve()?; |
| 959 | + statement_response(user.get_id(), limit, offset, &st.db).await | ||
| 909 | } | 960 | } |
| 910 | 961 | ||
| 911 | /// One student's statement: a row per charge with what it collected, what went | 962 | /// One student's statement: a row per charge with what it collected, what went |
| 912 | /// back out, what is still owed, and whether it is overdue. Own record always; | 963 | /// back out, what is still owed, and whether it is overdue. Own record always; |
| 913 | -/// otherwise manager+ or a parent link (a teacher gets a `403`). | 964 | +/// otherwise manager+ or a parent link (a teacher gets a `403`). The rows are |
| 965 | +/// paged via `?limit=&offset=`; `balance_minor` is the same on every page. | ||
| 914 | #[utoipa::path( | 966 | #[utoipa::path( |
| 915 | get, | 967 | get, |
| 916 | path = "/statement/{user}", | 968 | path = "/statement/{user}", |
| 917 | tag = "payments", | 969 | tag = "payments", |
| 918 | security(("session_cookie" = [])), | 970 | security(("session_cookie" = [])), |
| 919 | - params(("user" = String, Path, description = "Student id")), | 971 | + params(("user" = String, Path, description = "Student id"), PageParams), |
| 920 | responses( | 972 | responses( |
| 921 | (status = 200, description = "The student's statement", body = StatementResponse), | 973 | (status = 200, description = "The student's statement", body = StatementResponse), |
| 974 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | ||
| 922 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 975 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 923 | (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), | 976 | (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), |
| 924 | ), | 977 | ), |
| @@ -927,10 +980,12 @@ async fn user_statement( | |||
| 927 | State(st): State<AppState>, | 980 | State(st): State<AppState>, |
| 928 | CurrentUser(caller): CurrentUser, | 981 | CurrentUser(caller): CurrentUser, |
| 929 | Path(user): Path<String>, | 982 | Path(user): Path<String>, |
| 983 | + Query(page): Query<PageParams>, | ||
| 930 | ) -> Result<Json<StatementResponse>, AppError> { | 984 | ) -> Result<Json<StatementResponse>, AppError> { |
| 985 | + let (limit, offset) = page.resolve()?; | ||
| 931 | let target = UserId::from_key(&user); | 986 | let target = UserId::from_key(&user); |
| 932 | ensure_can_read_payments(&caller, &target, &st.db).await?; | 987 | ensure_can_read_payments(&caller, &target, &st.db).await?; |
| 933 | - statement_response(&target, &st.db).await | 988 | + statement_response(&target, limit, offset, &st.db).await |
| 934 | } | 989 | } |
| 935 | 990 | ||
| 936 | #[derive(Serialize, ToSchema)] | 991 | #[derive(Serialize, ToSchema)] |
| @@ -1048,6 +1103,7 @@ mod tests { | |||
| 1048 | LedgerAmount::try_new(6_000).unwrap(), | 1103 | LedgerAmount::try_new(6_000).unwrap(), |
| 1049 | None, | 1104 | None, |
| 1050 | None, | 1105 | None, |
| 1106 | + None, | ||
| 1051 | &manager, | 1107 | &manager, |
| 1052 | &db, | 1108 | &db, |
| 1053 | ) | 1109 | ) |
| @@ -1058,6 +1114,7 @@ mod tests { | |||
| 1058 | LedgerAmount::try_new(1_000).unwrap(), | 1114 | LedgerAmount::try_new(1_000).unwrap(), |
| 1059 | None, | 1115 | None, |
| 1060 | None, | 1116 | None, |
| 1117 | + None, | ||
| 1061 | &manager, | 1118 | &manager, |
| 1062 | &db, | 1119 | &db, |
| 1063 | ) | 1120 | ) |
| @@ -1067,10 +1124,11 @@ mod tests { | |||
| 1067 | .await | 1124 | .await |
| 1068 | .unwrap(); | 1125 | .unwrap(); |
| 1069 | 1126 | ||
| 1070 | - let statement = statement_response(&student, &db).await.unwrap().0; | 1127 | + let statement = statement_response(&student, None, 0, &db).await.unwrap().0; |
| 1071 | let entry = |n: &str| { | 1128 | let entry = |n: &str| { |
| 1072 | statement | 1129 | statement |
| 1073 | .entries | 1130 | .entries |
| 1131 | + .items | ||
| 1074 | .iter() | 1132 | .iter() |
| 1075 | .find(|entry| entry.charge_id.ends_with(n)) | 1133 | .find(|entry| entry.charge_id.ends_with(n)) |
| 1076 | .expect("a row per charge") | 1134 | .expect("a row per charge") |
tests/integration.rsmodified+202 -2
| @@ -23145,6 +23145,42 @@ async fn refund(app: &axum::Router, cookie: &str, credit: &str, amount: i64) -> | |||
| 23145 | .await | 23145 | .await |
| 23146 | } | 23146 | } |
| 23147 | 23147 | ||
| 23148 | +/// Record money in against `charge`, carrying a client idempotence key. | ||
| 23149 | +async fn pay_keyed( | ||
| 23150 | + app: &axum::Router, | ||
| 23151 | + cookie: &str, | ||
| 23152 | + charge: &str, | ||
| 23153 | + amount: i64, | ||
| 23154 | + key: &str, | ||
| 23155 | +) -> common::Res { | ||
| 23156 | + send( | ||
| 23157 | + app, | ||
| 23158 | + "POST", | ||
| 23159 | + "/payments/credits", | ||
| 23160 | + Some(cookie), | ||
| 23161 | + Some(json!({ "charge_id": charge, "amount_minor": amount, "request_key": key })), | ||
| 23162 | + ) | ||
| 23163 | + .await | ||
| 23164 | +} | ||
| 23165 | + | ||
| 23166 | +/// Hand money back against `credit`, carrying a client idempotence key. | ||
| 23167 | +async fn refund_keyed( | ||
| 23168 | + app: &axum::Router, | ||
| 23169 | + cookie: &str, | ||
| 23170 | + credit: &str, | ||
| 23171 | + amount: i64, | ||
| 23172 | + key: &str, | ||
| 23173 | +) -> common::Res { | ||
| 23174 | + send( | ||
| 23175 | + app, | ||
| 23176 | + "POST", | ||
| 23177 | + "/payments/refunds", | ||
| 23178 | + Some(cookie), | ||
| 23179 | + Some(json!({ "credit_id": credit, "amount_minor": amount, "request_key": key })), | ||
| 23180 | + ) | ||
| 23181 | + .await | ||
| 23182 | +} | ||
| 23183 | + | ||
| 23148 | /// Undo `line` (no assertion). | 23184 | /// Undo `line` (no assertion). |
| 23149 | async fn reverse(app: &axum::Router, cookie: &str, line: &str) -> common::Res { | 23185 | async fn reverse(app: &axum::Router, cookie: &str, line: &str) -> common::Res { |
| 23150 | send( | 23186 | send( |
| @@ -23450,7 +23486,7 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { | |||
| 23450 | 23486 | ||
| 23451 | let body = statement(mgr.clone(), student_id.clone()).await; | 23487 | let body = statement(mgr.clone(), student_id.clone()).await; |
| 23452 | let row = |body: &serde_json::Value, amount: i64| { | 23488 | let row = |body: &serde_json::Value, amount: i64| { |
| 23453 | - body["entries"] | 23489 | + body["entries"]["items"] |
| 23454 | .as_array() | 23490 | .as_array() |
| 23455 | .unwrap() | 23491 | .unwrap() |
| 23456 | .iter() | 23492 | .iter() |
| @@ -23505,7 +23541,7 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { | |||
| 23505 | let own = send(&app, "GET", "/payments/statement/me", Some(&student), None).await; | 23541 | let own = send(&app, "GET", "/payments/statement/me", Some(&student), None).await; |
| 23506 | assert_eq!(own.status, StatusCode::OK); | 23542 | assert_eq!(own.status, StatusCode::OK); |
| 23507 | assert_eq!(own.body["balance_minor"], -225); | 23543 | assert_eq!(own.body["balance_minor"], -225); |
| 23508 | - assert_eq!(own.body["entries"].as_array().unwrap().len(), 2); | 23544 | + assert_eq!(own.body["entries"]["items"].as_array().unwrap().len(), 2); |
| 23509 | let own = send(&app, "GET", "/payments/balance/me", Some(&student), None).await; | 23545 | let own = send(&app, "GET", "/payments/balance/me", Some(&student), None).await; |
| 23510 | assert_eq!(own.body["balance_minor"], -225); | 23546 | assert_eq!(own.body["balance_minor"], -225); |
| 23511 | } | 23547 | } |
| @@ -23632,6 +23668,170 @@ async fn payment_reads_are_self_parent_or_manager_and_writes_are_manager_only() | |||
| 23632 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 2); | 23668 | assert_eq!(pay_row_count(&db, "payment_ledger").await, 2); |
| 23633 | } | 23669 | } |
| 23634 | 23670 | ||
| 23671 | +/// A client retry after a network timeout must not charge a family twice. The | ||
| 23672 | +/// key is what makes the retry the *same* line, so the interesting case is a | ||
| 23673 | +/// payment that filled its charge exactly: the cap, consulted first, would | ||
| 23674 | +/// refuse precisely the payment that landed. | ||
| 23675 | +#[tokio::test] | ||
| 23676 | +async fn a_replayed_request_key_returns_the_same_payment_instead_of_a_second_one() { | ||
| 23677 | + let (app, db) = app_and_db().await; | ||
| 23678 | + let (mgr, student_id, _) = | ||
| 23679 | + billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; | ||
| 23680 | + let charge = |amount| { | ||
| 23681 | + let app = app.clone(); | ||
| 23682 | + let mgr = mgr.clone(); | ||
| 23683 | + let student_id = student_id.clone(); | ||
| 23684 | + async move { charge_worth(&app, &mgr, &student_id, amount).await } | ||
| 23685 | + }; | ||
| 23686 | + let full = charge(100).await; | ||
| 23687 | + | ||
| 23688 | + // This payment fills the charge to the penny. | ||
| 23689 | + let first = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; | ||
| 23690 | + assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); | ||
| 23691 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); | ||
| 23692 | + | ||
| 23693 | + let replay = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; | ||
| 23694 | + assert_eq!( | ||
| 23695 | + replay.status, | ||
| 23696 | + StatusCode::CREATED, | ||
| 23697 | + "a replay of a cap-filling payment must return the line, not a 409: {}", | ||
| 23698 | + replay.body | ||
| 23699 | + ); | ||
| 23700 | + assert_eq!(id_of(&replay.body), id_of(&first.body)); | ||
| 23701 | + assert_eq!( | ||
| 23702 | + pay_row_count(&db, "payment_ledger").await, | ||
| 23703 | + 4, | ||
| 23704 | + "the replay must not append a second credit" | ||
| 23705 | + ); | ||
| 23706 | + | ||
| 23707 | + // The same key for different money is a client bug, not a replay. | ||
| 23708 | + let mismatch = pay_keyed(&app, &mgr, &full, 50, "receipt-114").await; | ||
| 23709 | + assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); | ||
| 23710 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); | ||
| 23711 | + | ||
| 23712 | + // Two different keys are two payments, and the cap still applies to them. | ||
| 23713 | + let sixty = charge(60).await; | ||
| 23714 | + let a = pay_keyed(&app, &mgr, &sixty, 30, "a").await; | ||
| 23715 | + let b = pay_keyed(&app, &mgr, &sixty, 30, "b").await; | ||
| 23716 | + assert_eq!(a.status, StatusCode::CREATED); | ||
| 23717 | + assert_eq!(b.status, StatusCode::CREATED, "{}", b.body); | ||
| 23718 | + assert_ne!(id_of(&a.body), id_of(&b.body)); | ||
| 23719 | + assert_eq!( | ||
| 23720 | + pay_keyed(&app, &mgr, &sixty, 1, "c").await.status, | ||
| 23721 | + StatusCode::CONFLICT, | ||
| 23722 | + "a fresh key does not buy room the charge does not have" | ||
| 23723 | + ); | ||
| 23724 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 6); | ||
| 23725 | + | ||
| 23726 | + // No key: the old semantics stay exactly as they were β two identical | ||
| 23727 | + // posts are two payments, because a desk taking the same amount twice is. | ||
| 23728 | + let thirty = charge(30).await; | ||
| 23729 | + let one = pay(&app, &mgr, &thirty, 10).await; | ||
| 23730 | + let two = pay(&app, &mgr, &thirty, 10).await; | ||
| 23731 | + assert_eq!(one.status, StatusCode::CREATED); | ||
| 23732 | + assert_eq!(two.status, StatusCode::CREATED); | ||
| 23733 | + assert_ne!(id_of(&one.body), id_of(&two.body)); | ||
| 23734 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 8); | ||
| 23735 | +} | ||
| 23736 | + | ||
| 23737 | +#[tokio::test] | ||
| 23738 | +async fn a_replayed_request_key_returns_the_same_refund_instead_of_a_second_one() { | ||
| 23739 | + let (app, db) = app_and_db().await; | ||
| 23740 | + let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; | ||
| 23741 | + let charge = charge_worth(&app, &mgr, &student_id, 100).await; | ||
| 23742 | + let credit = pay(&app, &mgr, &charge, 100).await; | ||
| 23743 | + let credit_id = id_of(&credit.body); | ||
| 23744 | + | ||
| 23745 | + let first = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; | ||
| 23746 | + assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); | ||
| 23747 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); | ||
| 23748 | + | ||
| 23749 | + // The refund used the credit up, so the cap would refuse a second one β | ||
| 23750 | + // the replay must still answer with the line that exists. | ||
| 23751 | + let replay = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; | ||
| 23752 | + assert_eq!(replay.status, StatusCode::CREATED, "{}", replay.body); | ||
| 23753 | + assert_eq!(id_of(&replay.body), id_of(&first.body)); | ||
| 23754 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); | ||
| 23755 | + | ||
| 23756 | + let mismatch = refund_keyed(&app, &mgr, &credit_id, 25, "back-1").await; | ||
| 23757 | + assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); | ||
| 23758 | + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); | ||
| 23759 | + | ||
| 23760 | + // The balance is what it was after the single refund: money out once. | ||
| 23761 | + let res = send( | ||
| 23762 | + &app, | ||
| 23763 | + "GET", | ||
| 23764 | + &format!("/payments/balance/{student_id}"), | ||
| 23765 | + Some(&mgr), | ||
| 23766 | + None, | ||
| 23767 | + ) | ||
| 23768 | + .await; | ||
| 23769 | + assert_eq!(res.body["balance_minor"], -100); | ||
| 23770 | +} | ||
| 23771 | + | ||
| 23772 | +/// The statement pages its per-charge rows β but the money it reports is folded | ||
| 23773 | +/// from every line, so `balance_minor` must not move between pages. | ||
| 23774 | +#[tokio::test] | ||
| 23775 | +async fn the_statement_pages_its_rows_without_moving_the_balance() { | ||
| 23776 | + let (app, db) = app_and_db().await; | ||
| 23777 | + let (mgr, student_id, _) = | ||
| 23778 | + billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; | ||
| 23779 | + let statement = |query: &str| { | ||
| 23780 | + let app = app.clone(); | ||
| 23781 | + let uri = format!("/payments/statement/{student_id}{query}"); | ||
| 23782 | + let mgr = mgr.clone(); | ||
| 23783 | + async move { | ||
| 23784 | + let res = send(&app, "GET", &uri, Some(&mgr), None).await; | ||
| 23785 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 23786 | + res.body | ||
| 23787 | + } | ||
| 23788 | + }; | ||
| 23789 | + | ||
| 23790 | + let all = statement("").await; | ||
| 23791 | + assert_eq!(all["entries"]["items"].as_array().unwrap().len(), 3); | ||
| 23792 | + assert_eq!(all["entries"]["total"], 3); | ||
| 23793 | + assert_eq!(all["balance_minor"], -190); | ||
| 23794 | + | ||
| 23795 | + let head = statement("?limit=2&offset=0").await; | ||
| 23796 | + assert_eq!(head["entries"]["items"].as_array().unwrap().len(), 2); | ||
| 23797 | + assert_eq!(head["entries"]["total"], 3); | ||
| 23798 | + assert_eq!(head["entries"]["limit"], 2); | ||
| 23799 | + assert_eq!(head["entries"]["offset"], 0); | ||
| 23800 | + assert_eq!(head["balance_minor"], -190); | ||
| 23801 | + | ||
| 23802 | + let tail = statement("?limit=2&offset=2").await; | ||
| 23803 | + assert_eq!( | ||
| 23804 | + tail["entries"]["items"].as_array().unwrap().len(), | ||
| 23805 | + 1, | ||
| 23806 | + "the tail returns the remainder" | ||
| 23807 | + ); | ||
| 23808 | + assert_eq!(tail["balance_minor"], -190, "every page folds every line"); | ||
| 23809 | + // The window is a slice of one order, so the pages do not overlap. | ||
| 23810 | + let page_ids = |body: &serde_json::Value| { | ||
| 23811 | + body["entries"]["items"] | ||
| 23812 | + .as_array() | ||
| 23813 | + .unwrap() | ||
| 23814 | + .iter() | ||
| 23815 | + .map(|entry| entry["charge_id"].as_str().unwrap().to_string()) | ||
| 23816 | + .collect::<Vec<_>>() | ||
| 23817 | + }; | ||
| 23818 | + let mut seen = page_ids(&head); | ||
| 23819 | + seen.extend(page_ids(&tail)); | ||
| 23820 | + seen.sort(); | ||
| 23821 | + seen.dedup(); | ||
| 23822 | + assert_eq!(seen.len(), 3, "two pages, three distinct charges"); | ||
| 23823 | + | ||
| 23824 | + let res = send( | ||
| 23825 | + &app, | ||
| 23826 | + "GET", | ||
| 23827 | + &format!("/payments/statement/{student_id}?limit=0"), | ||
| 23828 | + Some(&mgr), | ||
| 23829 | + None, | ||
| 23830 | + ) | ||
| 23831 | + .await; | ||
| 23832 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 23833 | +} | ||
| 23834 | + | ||
| 23635 | #[tokio::test] | 23835 | #[tokio::test] |
| 23636 | async fn payment_lists_page_through_the_envelope() { | 23836 | async fn payment_lists_page_through_the_envelope() { |
| 23637 | let (app, db) = app_and_db().await; | 23837 | let (app, db) = app_and_db().await; |
tests/persistence.rsmodified+1 -1
| @@ -1689,7 +1689,7 @@ async fn fee_plans_and_their_charges_survive_remigration() { | |||
| 1689 | ) | 1689 | ) |
| 1690 | .await; | 1690 | .await; |
| 1691 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 1691 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 1692 | - assert_eq!(res.body["entries"].as_array().unwrap().len(), 2); | 1692 | + assert_eq!(res.body["entries"]["items"].as_array().unwrap().len(), 2); |
| 1693 | assert_eq!( | 1693 | assert_eq!( |
| 1694 | res.body["balance_minor"], -400_000, | 1694 | res.body["balance_minor"], -400_000, |
| 1695 | "the charges the placement raised are still owed" | 1695 | "the charges the placement raised are still owed" |
tests/spec_bounds.rsmodified+14 -0
| @@ -724,6 +724,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 724 | "maxLength", | 724 | "maxLength", |
| 725 | MAX_LEDGER_NOTE_LEN as i64, | 725 | MAX_LEDGER_NOTE_LEN as i64, |
| 726 | ), | 726 | ), |
| 727 | + ("RecordPayment", "request_key", "minLength", 1), | ||
| 728 | + ( | ||
| 729 | + "RecordPayment", | ||
| 730 | + "request_key", | ||
| 731 | + "maxLength", | ||
| 732 | + MAX_PAYMENT_REQUEST_KEY_LEN as i64, | ||
| 733 | + ), | ||
| 727 | ("RecordRefund", "amount_minor", "minimum", 1), | 734 | ("RecordRefund", "amount_minor", "minimum", 1), |
| 728 | ( | 735 | ( |
| 729 | "RecordRefund", | 736 | "RecordRefund", |
| @@ -743,6 +750,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | |||
| 743 | "maxLength", | 750 | "maxLength", |
| 744 | MAX_LEDGER_NOTE_LEN as i64, | 751 | MAX_LEDGER_NOTE_LEN as i64, |
| 745 | ), | 752 | ), |
| 753 | + ("RecordRefund", "request_key", "minLength", 1), | ||
| 754 | + ( | ||
| 755 | + "RecordRefund", | ||
| 756 | + "request_key", | ||
| 757 | + "maxLength", | ||
| 758 | + MAX_PAYMENT_REQUEST_KEY_LEN as i64, | ||
| 759 | + ), | ||
| 746 | ( | 760 | ( |
| 747 | "RecordReversal", | 761 | "RecordReversal", |
| 748 | "note", | 762 | "note", |