diff --git a/README.md b/README.md index cdb64af..cc10b8b 100644 --- a/README.md +++ b/README.md @@ -817,12 +817,12 @@ window filtering, before paging; negative values are a `400` naming the field. | DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it — its charges name it | | 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` | | GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first · paged | -| 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) | -| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?}` — hand money back against one named payment; partials allowed, capped by that credit | +| 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` | +| 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 | | 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 | | 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`**) | -| 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` | -| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger | +| 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 | +| GET | `/payments/statement/{user}` | student | One student's statement; same gate as the ledger, same row paging | | GET | `/payments/balance/me` | student | The caller's fee balance, minor units (negative = owes the school) | | GET | `/payments/balance/{user}` | student | One student's fee balance; same gate as the ledger | | 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. `{credit_id, …}`, partials allowed, capped by what that credit was worth. This is also the **only** way a mistaken credit is corrected: a credit is never reversed, so money leaving the school is always spelled the one way. +- **A retry is not a second payment — when the client says so.** Both routes + take an optional `request_key` (`[A-Za-z0-9-]`, 1 to 64 characters — `_` is + the separator inside a ledger id, so a key may not carry one). With + one, the line is keyed `_k_` (a refund: `_kr_`), so + a client retrying after a network timeout gets **the line the first attempt + wrote**, not a second charge on the family — idempotence by identity, the + same rule that keeps a replayed assignment from billing twice, never a "has + this been recorded yet?" scan two concurrent requests can both walk past. The + replay is answered **before** the over-payment cap is consulted, so a payment + that filled its charge to the penny still replays as itself instead of coming + back "already paid in full". Sending that key again with a **different** + `amount_minor` or a different target is a `409`, never the stored line: that + is a client bug, and a `201` would bury it. Omit the key and nothing changes + from before — two identical posts are two payments, which is exactly what a + desk taking the same amount twice means. - **A reversal only undoes a `charge` or a `refund`**, for its exact amount and nothing else (`400` on any other kind). It is keyed `_r`, so a line has at most one reversal however often the call is retried, and the reversed line @@ -1537,14 +1552,17 @@ account. `GET /payments/ledger/{user}` is the raw lines, newest first, paged. `GET /payments/statement/me` and `/payments/statement/{user}` are the -**per-charge rollup**: one row per charge with its plan, the installment's +**per-charge rollup** (its rows paged by the usual opt-in `?limit=&offset=`, +in an `entries: {items, total, limit, offset}` envelope): one row per charge with its plan, the installment's amount and due date, what it collected, what went back out, what is still outstanding, whether the charge itself was reversed (such a charge owes nothing), and whether it is **`overdue`** — still owed, and its `due_at` has passed. All of that is folded from the raw lines **on every request and stored -nowhere**, `overdue` included. There is no overdue flag, no sweep that sets +nowhere**, `overdue` included. Paging windows the *returned rows* only, after +that fold: `balance_minor` — and every row's own arithmetic — is identical on +every page, because it is read from all of the student's lines either way. There is no overdue flag, no sweep that sets one, and no stored rollup: a stored rollup is a second version of the truth, and the ledger is the first. `GET /payments/balance/me` and `/payments/balance/{user}` are the same fold reduced to one number. diff --git a/src/constant.rs b/src/constant.rs index e127848..07fdddf 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -266,6 +266,13 @@ pub const MAX_FEE_PLAN_INSTALLMENTS: usize = 60; /// request's writes. pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; +/// Ceiling on the client-chosen `request_key` that makes a credit or a refund +/// retry-safe: it becomes part of the ledger line's record id, so it is bounded +/// and drawn from `[A-Za-z0-9-]` — `_` joins the parts of a ledger id, so a key +/// carrying one could spell another line's id. Sixty-four characters take a +/// UUID or a receipt number comfortably. +pub const MAX_PAYMENT_REQUEST_KEY_LEN: usize = 64; + /// Inclusive bounds for an exam's per-attempt duration, milliseconds /// (1 minute to 24 hours). Required for `async`, optional for `open`. pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; diff --git a/src/domain/payment_ledger.rs b/src/domain/payment_ledger.rs index d29b1cc..c56bb5a 100644 --- a/src/domain/payment_ledger.rs +++ b/src/domain/payment_ledger.rs @@ -40,6 +40,18 @@ //! self-heals when it is repeated. Money must never depend on a "has this //! been billed yet?" scan: two concurrent requests can both read "not yet" //! and both append. +//! - **A payment or a refund is replayable when the client names it.** An +//! optional `request_key` keys the line `_k_` (or `_kr_` for a +//! refund), so a retry after a timeout derives the row the first attempt +//! wrote — same identity rule, no scan. The key is scoped by the line it +//! targets, so it never has to be globally unique. Without a key the id is a +//! fresh ulid and two identical calls are two payments, which is what a desk +//! taking the same amount twice really means. The **replay read happens +//! before the cap check** and inside [`PAYMENT_LOCK`]: the first attempt's +//! line is already inside what the cap folds, so checking the cap first would +//! refuse the very payment that landed. A key replayed with a *different* +//! amount or against a *different* line is a `409`, never the stored line — +//! returning it would hide a client bug behind a `201`. //! //! **The over-payment cap is ADVISORY (accepted race).** [`PaymentLedger::credit`] //! and [`PaymentLedger::refund`] refuse to take more than the line they target @@ -60,6 +72,13 @@ //! and both entries are true records of money that really arrived. A CAS //! counter row was rejected — refunding would have to decrement it, which is a //! stored derived balance by another name. +//! +//! The same replica boundary bounds the `request_key` mismatch `409`: it is a +//! read-then-compare, so if two *first-time* posts of one key with different +//! amounts land on two replicas at once, the loser is handed the winner's line +//! as a `201` instead of the conflict. One line, one amount, no double charge — +//! the guarantee that matters holds; only the "you reused a key" diagnostic is +//! best-effort, and every retry after either has landed reports it correctly. use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; use tokio::sync::Mutex; @@ -121,6 +140,30 @@ impl PaymentLedgerId { )) } + /// The one line a `(target, request_key)` pair may ever have: `_k_` + /// for a payment, `_kr_` for a refund. Scoping the key by the line + /// it targets is what keeps one office's "receipt-114" from colliding with + /// another charge's, and the two markers keep the kinds apart the same way + /// `_c` and `_r` do above. + /// + /// **The grammar parses uniquely because `_` joins the parts and cannot + /// appear inside one.** Every id here is `__c` optionally + /// followed by one `_k_`, `_kr_` or `_r` — plan and student keys + /// are ULIDs (`[0-9A-Z]` only) and a `request_key` is + /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, so no part + /// can spell a separator plus a marker. That is not decoration: a key of + /// `abc_r` on a refund would derive exactly the id that refund's *reversal* + /// must own, and the loser of that collision would be handed a line of the + /// wrong kind and the wrong amount, with the real reversal impossible + /// forever after. The ban on `_` in a key is what makes the collision + /// unconstructible; [`PaymentLedger::append`] re-checks the kind anyway. + pub fn for_request(target: &PaymentLedgerId, marker: &str, key: &PaymentRequestKey) -> Self { + Self(RecordId::new( + PAYMENT_LEDGER_TABLE, + format!("{}_{marker}_{}", target.key(), key.as_str()), + )) + } + pub fn record(&self) -> RecordId { self.0.clone() } @@ -130,6 +173,23 @@ impl PaymentLedgerId { } } +/// A client-chosen idempotence key for one payment or refund. Never stored as +/// a column — it lives inside the line's record id, which is what makes a retry +/// derive the row it already wrote instead of a second one. +#[derive(Debug, Clone)] +pub struct PaymentRequestKey(String); + +impl PaymentRequestKey { + pub fn try_new(value: &str) -> Result { + crate::validate::validate_request_key(value)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + /// Did this `CREATE` fail *only* because the row is already there? Matched on /// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text /// and never on "any database error", because swallowing a real fault in money @@ -260,9 +320,25 @@ impl PaymentLedger { /// "already exists". Both are read back the same way, and a conflict that /// turns out to have written nothing is simply tried again; no path here /// can write a second line, since the id is the key. + /// + /// Both read-backs check the stored line is the *kind* that was being + /// appended. Handing a caller someone else's row is only safe while every + /// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a + /// future marker or a widened key charset ever let two shapes meet, this is + /// the check that turns silently-wrong money into a 500 instead. It should + /// be unreachable, and it is cheap enough to keep it that way. async fn append(row: PaymentLedger, db: &Database) -> Result { + let same_kind = |existing: PaymentLedger| { + if existing.kind == row.kind { + Ok(existing) + } else { + Err(AppError::Internal( + "a ledger id resolved to a line of another kind".into(), + )) + } + }; if let Some(existing) = Self::read(&row.id, db).await? { - return Ok(existing); + return same_kind(existing); } let id = row.id.clone(); for _ in 0..CAS_UPDATE_RETRIES { @@ -271,7 +347,7 @@ impl PaymentLedger { Ok(None) => break, Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { if let Some(existing) = Self::read(&id, db).await? { - return Ok(existing); + return same_kind(existing); } } Err(e) => return Err(e.into()), @@ -322,11 +398,17 @@ impl PaymentLedger { /// Money in, against one named `charge`. Partial payments are the norm, so /// a charge may collect several credits; together they may not exceed it /// (advisory — see the module doc's accepted race). + /// + /// With a `request_key` the line is keyed by it (see + /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without + /// one the id is a fresh ulid and two identical calls are two payments, + /// which is what a cash desk taking the same amount twice really means. pub async fn credit( charge: &PaymentLedger, amount_minor: LedgerAmount, method: Option, note: Option, + request_key: Option<&PaymentRequestKey>, recorded_by: &UserId, db: &Database, ) -> Result { @@ -339,6 +421,7 @@ impl PaymentLedger { amount_minor, method, note, + request_key.map(|key| PaymentLedgerId::for_request(charge.get_id(), "k", key)), recorded_by, db, ) @@ -347,12 +430,14 @@ impl PaymentLedger { /// Money back out, against one named `credit` — how an over-payment or a /// payment recorded in error is returned. Partials allowed, and no more - /// than the credit was worth (advisory, same race). + /// than the credit was worth (advisory, same race). `request_key` makes it + /// retry-safe exactly as it does for [`PaymentLedger::credit`]. pub async fn refund( credit: &PaymentLedger, amount_minor: LedgerAmount, method: Option, note: Option, + request_key: Option<&PaymentRequestKey>, recorded_by: &UserId, db: &Database, ) -> Result { @@ -365,6 +450,7 @@ impl PaymentLedger { amount_minor, method, note, + request_key.map(|key| PaymentLedgerId::for_request(credit.get_id(), "kr", key)), recorded_by, db, ) @@ -374,6 +460,13 @@ impl PaymentLedger { /// The shared body of `credit` and `refund`: check the target is the kind /// this line may point at, then append under [`PAYMENT_LOCK`] while the /// target's existing children still sum below its amount. + /// + /// The replay read comes **before** the cap, and inside the lock: on a + /// retry the first attempt's line is already part of the subtree the cap + /// folds, so consulting the cap first would answer a payment that landed + /// with "already paid in full" — refusing precisely the request that + /// succeeded. Reading the id under the lock also keeps two simultaneous + /// retries from both walking into the cap check. #[allow(clippy::too_many_arguments)] async fn against( target: &PaymentLedger, @@ -384,6 +477,7 @@ impl PaymentLedger { amount_minor: LedgerAmount, method: Option, note: Option, + keyed: Option, recorded_by: &UserId, db: &Database, ) -> Result { @@ -395,13 +489,29 @@ impl PaymentLedger { .into()); } let _guard = PAYMENT_LOCK.lock().await; + if let Some(id) = &keyed + && let Some(existing) = Self::read(id, db).await? + { + // A replay is answered from the stored line — but only if it is the + // same money. The same key for a different amount or a different + // target is a client bug, and handing back the old line would hide + // it behind a `201`. + if existing.amount_minor.as_minor() != amount_minor.as_minor() + || existing.get_source_key() != Some(target.id.key()) + { + return Err(AppError::Conflict( + "this request_key was already used for a different amount or target", + )); + } + return Ok(existing); + } let taken = Self::applied_to(target, db).await?; if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { return Err(AppError::Conflict(over)); } Self::append( PaymentLedger { - id: PaymentLedgerId::generate(), + id: keyed.unwrap_or_else(PaymentLedgerId::generate), student: target.student.clone(), kind, amount_minor, @@ -633,6 +743,30 @@ mod tests { ); } + /// A `request_key` is only an idempotence key if it derives the same id + /// every time, and only *safe* if it is scoped by the line it targets and + /// tells a payment from a refund. + #[test] + fn a_request_key_is_scoped_by_its_target_and_its_kind() { + let charge = PaymentLedgerId::from_key("plan1_stu1_c1"); + let other = PaymentLedgerId::from_key("plan1_stu1_c2"); + let key = PaymentRequestKey::try_new("receipt-114").unwrap(); + let credit = PaymentLedgerId::for_request(&charge, "k", &key); + + assert_eq!(credit.key(), "plan1_stu1_c1_k_receipt-114"); + assert_eq!( + PaymentLedgerId::for_request(&charge, "k", &key), + credit, + "a retry must derive the same id, or it pays twice" + ); + assert_ne!(PaymentLedgerId::for_request(&other, "k", &key), credit); + assert_ne!(PaymentLedgerId::for_request(&charge, "kr", &key), credit); + assert_eq!( + PaymentLedgerId::for_request(&credit, "kr", &key).key(), + "plan1_stu1_c1_k_receipt-114_kr_receipt-114" + ); + } + /// Raise one charge of `amount` on a fresh student, and hand it back. #[cfg(test)] async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) { @@ -661,6 +795,74 @@ mod tests { (lines.into_iter().next().unwrap(), student, manager) } + /// The collision the id grammar must not admit: with `_` legal in a key, a + /// refund keyed `abc_r` derived exactly `_r` — the id that refund's + /// own reversal must own — and whichever came second was handed the other's + /// line, of the wrong kind and the wrong amount, with the real reversal + /// impossible ever after. `_` is now illegal in a key, so the collision + /// cannot be constructed; the nearest legal key still works, and the + /// reversal still gets its own line. + #[tokio::test] + async fn a_keyed_refund_cannot_take_the_id_of_its_own_reversal() { + assert!( + PaymentRequestKey::try_new("abc_r").is_err(), + "the key that spelled a reversal's id must not parse" + ); + let db = crate::database::init_mem().await.unwrap(); + let (charge, _, manager) = one_charge(100, &db).await; + let key = PaymentRequestKey::try_new("abc-r").unwrap(); + let credit = PaymentLedger::credit( + &charge, + LedgerAmount::try_new(100).unwrap(), + None, + None, + None, + &manager, + &db, + ) + .await + .unwrap(); + let refund = PaymentLedger::refund( + &credit, + LedgerAmount::try_new(100).unwrap(), + None, + None, + Some(&key), + &manager, + &db, + ) + .await + .unwrap(); + let reversal = PaymentLedger::reversal(&refund, None, &manager, &db) + .await + .unwrap(); + assert_ne!(reversal.get_id(), refund.get_id()); + assert_eq!(reversal.get_kind(), PaymentLedgerKind::Reversal); + assert_eq!(reversal.get_amount_minor().as_minor(), 100); + + // And the last-ditch guard bites: an id that resolves to another kind + // is a 500, never that other line handed back as this one. + let intruder = PaymentLedger { + id: charge.get_id().clone(), + student: charge.student.clone(), + kind: PaymentLedgerKind::Credit, + amount_minor: LedgerAmount::try_new(1).unwrap(), + source: Some(charge.id.record()), + due_at: None, + method: None, + note: None, + recorded_by: manager.clone(), + created_at: Timestamp::now(), + }; + assert!( + matches!( + PaymentLedger::append(intruder, &db).await, + Err(AppError::Internal(_)) + ), + "a read-back of another kind must not pass for the appended line" + ); + } + /// The defect this fold replaced a plain sum for: a payment that was handed /// back frees the room it took, so the charge it paid can be paid again. It /// is the same charge, still owed — refusing the second payment would leave @@ -675,6 +877,7 @@ mod tests { LedgerAmount::try_new(amount).unwrap(), None, None, + None, &manager, &db, ) @@ -692,6 +895,7 @@ mod tests { LedgerAmount::try_new(100).unwrap(), None, None, + None, &manager, &db, ) @@ -723,6 +927,7 @@ mod tests { LedgerAmount::try_new(100).unwrap(), None, None, + None, &manager, &db, ) @@ -733,6 +938,7 @@ mod tests { LedgerAmount::try_new(100).unwrap(), None, None, + None, &manager, &db, ) @@ -749,6 +955,7 @@ mod tests { LedgerAmount::try_new(100).unwrap(), None, None, + None, &manager, &db ) @@ -797,6 +1004,7 @@ mod tests { LedgerAmount::try_new(amount).unwrap(), None, None, + None, &manager, &db, ) @@ -816,6 +1024,7 @@ mod tests { LedgerAmount::try_new(amount).unwrap(), None, None, + None, &manager, &db, ) @@ -835,6 +1044,7 @@ mod tests { LedgerAmount::try_new(1).unwrap(), None, None, + None, &manager, &db ) diff --git a/src/lib.rs b/src/lib.rs index b2dc7ea..fce30df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,7 @@ use crate::state::AppState; (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"), (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"), (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"), - (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 `_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"), + (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 `_k_` (`_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 `_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"), (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"), (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+"), (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"), diff --git a/src/validate.rs b/src/validate.rs index ad4cb80..5a776fe 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -3,10 +3,10 @@ use crate::constant::{ COURSE_KINDS, EXAM_MODES, HOMEWORK_STATUSES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, - MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, - MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, - MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS, - USERNAME_SEPARATORS, + MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, MAX_PAYMENT_REQUEST_KEY_LEN, + MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, + MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, + UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -198,6 +198,32 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> { Ok(()) } +/// A client-chosen idempotence key. It is concatenated into a record id whose +/// parts are joined by `_`, so the charset is an allowlist that **excludes the +/// separator itself**: a key containing `_` could spell another id's grammar +/// (a refund keyed `abc_r` would derive the id a reversal of that refund must +/// own), and two different ids meeting is money landing on the wrong line. +pub fn validate_request_key(value: &str) -> Result<(), ValidationError> { + let len = value.chars().count(); + if len == 0 { + return Err(ValidationError::Empty("request_key")); + } + if len > MAX_PAYMENT_REQUEST_KEY_LEN { + return Err(ValidationError::TooLong { + field: "request_key", + max: MAX_PAYMENT_REQUEST_KEY_LEN, + got: len, + }); + } + if !value.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { + return Err(ValidationError::Invalid { + field: "request_key", + reason: "may contain only letters, digits and '-'", + }); + } + Ok(()) +} + pub fn validate_course_kind(value: &str) -> Result<(), ValidationError> { if COURSE_KINDS.contains(&value) { Ok(()) @@ -397,6 +423,25 @@ mod tests { assert!(validate_phone("55+5123456").is_err()); // + only allowed in front } + #[tokio::test] + async fn request_key_rules() { + assert!(validate_request_key("invoice-2026-114").is_ok()); + assert!(validate_request_key(&"x".repeat(MAX_PAYMENT_REQUEST_KEY_LEN)).is_ok()); + assert!(validate_request_key("").is_err()); + assert!(validate_request_key(&"x".repeat(MAX_PAYMENT_REQUEST_KEY_LEN + 1)).is_err()); + // `_` is the record-id separator, so a key carrying one could spell + // another line's id: `abc_r` under a refund is the id that refund's + // reversal must own, and `a_kr_b` under a charge is the id of a refund + // against that charge's `a`-keyed credit. + assert!(validate_request_key("abc_r").is_err()); + assert!(validate_request_key("a_kr_b").is_err()); + // Anything that could break — or alias — a record id. + assert!(validate_request_key("a b").is_err()); + assert!(validate_request_key("a:b").is_err()); + assert!(validate_request_key("a/b").is_err()); + assert!(validate_request_key("naïve").is_err()); + } + #[tokio::test] async fn course_kind_rules() { for kind in ["course", "study", "club"] { diff --git a/src/web/limits.rs b/src/web/limits.rs index 5272780..5d6b9aa 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -230,6 +230,9 @@ struct PaymentLimits { max_plan_installments: usize, /// How many students one bulk assignment may name. max_assign_students: usize, + /// Ceiling on the optional `request_key` that makes a credit or a refund + /// retry-safe; charset `[A-Za-z0-9-]` (no `_`), at least one character. + max_request_key_len: usize, /// The only accepted payment-ledger `kind` values. #[schema(example = json!(["charge", "credit", "reversal", "refund"]))] ledger_kinds: Vec<&'static str>, @@ -437,6 +440,7 @@ impl LimitsResponse { max_plan_name_len: MAX_FEE_PLAN_NAME_LEN, max_plan_installments: MAX_FEE_PLAN_INSTALLMENTS, max_assign_students: MAX_FEE_PLAN_ASSIGN_STUDENTS, + max_request_key_len: MAX_PAYMENT_REQUEST_KEY_LEN, ledger_kinds: PAYMENT_LEDGER_KINDS.to_vec(), }, chatbot: ChatbotLimits { diff --git a/src/web/payments.rs b/src/web/payments.rs index 8052119..7c4230c 100644 --- a/src/web/payments.rs +++ b/src/web/payments.rs @@ -28,6 +28,7 @@ use crate::domain::fee_plan_assignment::FeePlanAssignment; use crate::domain::parent_link::ParentLink; use crate::domain::payment_ledger::{ LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, + PaymentRequestKey, }; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; @@ -35,7 +36,7 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, person_map}; +use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -549,6 +550,13 @@ struct RecordPayment { method: Option, #[schema(max_length = 500, example = "receipt 2026-114")] note: Option, + /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the + /// separator inside a ledger line's id). Send one and a + /// retry after a timeout returns the **same** line instead of recording the + /// money twice; omit it and two identical calls are two payments. The same + /// key sent with a different `amount_minor` or `charge_id` is a `409`. + #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] + request_key: Option, } #[derive(Deserialize, ToSchema)] @@ -563,6 +571,11 @@ struct RecordRefund { method: Option, #[schema(max_length = 500)] note: Option, + /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` — the same + /// retry-safety a payment gets, keyed by the credit it returns. The same + /// key with a different `amount_minor` or `credit_id` is a `409`. + #[schema(min_length = 1, max_length = 64, example = "refund-2026-114")] + request_key: Option, } #[derive(Deserialize, ToSchema)] @@ -581,10 +594,21 @@ fn note_of(raw: Option<&str>) -> Result, AppError> { Ok(raw.map(LedgerNote::try_new).transpose()?.flatten()) } +fn request_key_of(raw: Option<&str>) -> Result, AppError> { + Ok(raw.map(PaymentRequestKey::try_new).transpose()?) +} + /// Record money received against one named charge. Allocation is recorded, not /// inferred: a payment always says which installment it settles. Partial /// payments accumulate; one that would take the charge past what it is worth is /// a `409`. +/// +/// **Retry-safe on request** — send a `request_key` and a repeat of the call +/// (a client retry after a network timeout) returns the line the first attempt +/// wrote rather than recording the money a second time, even when that payment +/// filled the charge exactly. The same key with a different `amount_minor` or +/// `charge_id` is a `409`: that is a client bug, not a replay. Without a key +/// two identical calls are two payments, as before. #[utoipa::path( post, path = "/credits", @@ -597,7 +621,7 @@ fn note_of(raw: Option<&str>) -> Result, AppError> { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such ledger line", body = ErrorResponse), - (status = 409, description = "The charge is already paid in full", body = ErrorResponse), + (status = 409, description = "The charge is already paid in full, or the request_key was used for a different amount or charge", body = ErrorResponse), ), )] async fn record_payment( @@ -611,6 +635,7 @@ async fn record_payment( LedgerAmount::try_new(req.amount_minor)?, method_of(req.method.as_deref())?, note_of(req.note.as_deref())?, + request_key_of(req.request_key.as_deref())?.as_ref(), manager.get_id(), &st.db, ) @@ -621,6 +646,10 @@ async fn record_payment( /// Hand money back, against one named payment — how an over-payment or a /// payment recorded in error is returned, and the only way a mistaken *credit* /// is corrected (a credit is never reversed). Capped by that credit's amount. +/// +/// **Retry-safe on request** the same way a payment is: a `request_key` makes a +/// repeat return the existing refund, and the same key with a different +/// `amount_minor` or `credit_id` is a `409`. #[utoipa::path( post, path = "/refunds", @@ -633,7 +662,7 @@ async fn record_payment( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such ledger line", body = ErrorResponse), - (status = 409, description = "The payment is already refunded in full", body = ErrorResponse), + (status = 409, description = "The payment is already refunded in full, or the request_key was used for a different amount or payment", body = ErrorResponse), ), )] async fn record_refund( @@ -647,6 +676,7 @@ async fn record_refund( LedgerAmount::try_new(req.amount_minor)?, method_of(req.method.as_deref())?, note_of(req.note.as_deref())?, + request_key_of(req.request_key.as_deref())?.as_ref(), manager.get_id(), &st.db, ) @@ -782,8 +812,10 @@ struct StatementEntry { #[derive(Serialize, ToSchema)] struct StatementResponse { student: PersonRef, - /// One row per charge, newest first. - entries: Vec, + /// One row per charge, newest first, in the standard + /// `{items, total, limit, offset}` envelope. Paging windows these rows + /// only — `balance_minor` is folded from every line either way. + entries: Page, /// `credits + reversals - charges - refunds`, minor units. Negative means /// the family owes the school. #[schema(example = -100000)] @@ -796,8 +828,14 @@ struct StatementResponse { /// what is still owed, and whether it is late — is computed from the raw lines /// at request time and stored nowhere: a stored rollup is a second version of /// the truth, and the ledger is the first. +/// +/// `limit`/`offset` window the returned rows **after** the whole fold, never +/// the lines it folds: a page of a statement must still report the same +/// `balance_minor` (and the same overdue arithmetic) as every other page. async fn statement_response( student: &UserId, + limit: Option, + offset: i64, db: &Database, ) -> Result, AppError> { let (lines, _) = PaymentLedger::list_for_student(student, None, 0, db).await?; @@ -832,9 +870,16 @@ async fn statement_response( } let now = Timestamp::now().as_millis(); - let entries = lines + // The window is taken over the charges, not over the lines: the rollup + // above (and the balance below) still reads every line, so a page reports + // exactly the arithmetic the unpaged document does. + let charges: Vec<&PaymentLedger> = lines .iter() .filter(|line| line.get_kind() == PaymentLedgerKind::Charge) + .collect(); + let total = charges.len() as i64; + let entries: Vec = paginate(&charges, limit, offset) + .iter() .map(|charge| { let paid: Vec<&&PaymentLedger> = children .get(charge.get_id().key()) @@ -885,40 +930,48 @@ async fn statement_response( let people = person_map(std::iter::once(student.clone()), db).await?; Ok(Json(StatementResponse { student: PersonRef::resolve(&people, student), - entries, + entries: Page::new(entries, total, limit, offset), balance_minor: PaymentLedger::balance_of(student, db).await?, })) } -/// The caller's own statement. +/// The caller's own statement. The per-charge rows are paged via +/// `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the +/// same on every page, because the fold behind it reads every line. #[utoipa::path( get, path = "/statement/me", tag = "payments", security(("session_cookie" = [])), + params(PageParams), responses( (status = 200, description = "The caller's statement", body = StatementResponse), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn my_statement( State(st): State, CurrentUser(user): CurrentUser, + Query(page): Query, ) -> Result, AppError> { - statement_response(user.get_id(), &st.db).await + let (limit, offset) = page.resolve()?; + statement_response(user.get_id(), limit, offset, &st.db).await } /// One student's statement: a row per charge with what it collected, what went /// back out, what is still owed, and whether it is overdue. Own record always; -/// otherwise manager+ or a parent link (a teacher gets a `403`). +/// otherwise manager+ or a parent link (a teacher gets a `403`). The rows are +/// paged via `?limit=&offset=`; `balance_minor` is the same on every page. #[utoipa::path( get, path = "/statement/{user}", tag = "payments", security(("session_cookie" = [])), - params(("user" = String, Path, description = "Student id")), + params(("user" = String, Path, description = "Student id"), PageParams), responses( (status = 200, description = "The student's statement", body = StatementResponse), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), ), @@ -927,10 +980,12 @@ async fn user_statement( State(st): State, CurrentUser(caller): CurrentUser, Path(user): Path, + Query(page): Query, ) -> Result, AppError> { + let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); ensure_can_read_payments(&caller, &target, &st.db).await?; - statement_response(&target, &st.db).await + statement_response(&target, limit, offset, &st.db).await } #[derive(Serialize, ToSchema)] @@ -1048,6 +1103,7 @@ mod tests { LedgerAmount::try_new(6_000).unwrap(), None, None, + None, &manager, &db, ) @@ -1058,6 +1114,7 @@ mod tests { LedgerAmount::try_new(1_000).unwrap(), None, None, + None, &manager, &db, ) @@ -1067,10 +1124,11 @@ mod tests { .await .unwrap(); - let statement = statement_response(&student, &db).await.unwrap().0; + let statement = statement_response(&student, None, 0, &db).await.unwrap().0; let entry = |n: &str| { statement .entries + .items .iter() .find(|entry| entry.charge_id.ends_with(n)) .expect("a row per charge") diff --git a/tests/integration.rs b/tests/integration.rs index 604dd49..2dcb0c9 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -23145,6 +23145,42 @@ async fn refund(app: &axum::Router, cookie: &str, credit: &str, amount: i64) -> .await } +/// Record money in against `charge`, carrying a client idempotence key. +async fn pay_keyed( + app: &axum::Router, + cookie: &str, + charge: &str, + amount: i64, + key: &str, +) -> common::Res { + send( + app, + "POST", + "/payments/credits", + Some(cookie), + Some(json!({ "charge_id": charge, "amount_minor": amount, "request_key": key })), + ) + .await +} + +/// Hand money back against `credit`, carrying a client idempotence key. +async fn refund_keyed( + app: &axum::Router, + cookie: &str, + credit: &str, + amount: i64, + key: &str, +) -> common::Res { + send( + app, + "POST", + "/payments/refunds", + Some(cookie), + Some(json!({ "credit_id": credit, "amount_minor": amount, "request_key": key })), + ) + .await +} + /// Undo `line` (no assertion). async fn reverse(app: &axum::Router, cookie: &str, line: &str) -> common::Res { send( @@ -23450,7 +23486,7 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { let body = statement(mgr.clone(), student_id.clone()).await; let row = |body: &serde_json::Value, amount: i64| { - body["entries"] + body["entries"]["items"] .as_array() .unwrap() .iter() @@ -23505,7 +23541,7 @@ async fn the_statement_reports_overdue_and_its_rollup_matches_the_balance() { let own = send(&app, "GET", "/payments/statement/me", Some(&student), None).await; assert_eq!(own.status, StatusCode::OK); assert_eq!(own.body["balance_minor"], -225); - assert_eq!(own.body["entries"].as_array().unwrap().len(), 2); + assert_eq!(own.body["entries"]["items"].as_array().unwrap().len(), 2); let own = send(&app, "GET", "/payments/balance/me", Some(&student), None).await; assert_eq!(own.body["balance_minor"], -225); } @@ -23632,6 +23668,170 @@ async fn payment_reads_are_self_parent_or_manager_and_writes_are_manager_only() assert_eq!(pay_row_count(&db, "payment_ledger").await, 2); } +/// A client retry after a network timeout must not charge a family twice. The +/// key is what makes the retry the *same* line, so the interesting case is a +/// payment that filled its charge exactly: the cap, consulted first, would +/// refuse precisely the payment that landed. +#[tokio::test] +async fn a_replayed_request_key_returns_the_same_payment_instead_of_a_second_one() { + let (app, db) = app_and_db().await; + let (mgr, student_id, _) = + billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; + let charge = |amount| { + let app = app.clone(); + let mgr = mgr.clone(); + let student_id = student_id.clone(); + async move { charge_worth(&app, &mgr, &student_id, amount).await } + }; + let full = charge(100).await; + + // This payment fills the charge to the penny. + let first = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; + assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); + + let replay = pay_keyed(&app, &mgr, &full, 100, "receipt-114").await; + assert_eq!( + replay.status, + StatusCode::CREATED, + "a replay of a cap-filling payment must return the line, not a 409: {}", + replay.body + ); + assert_eq!(id_of(&replay.body), id_of(&first.body)); + assert_eq!( + pay_row_count(&db, "payment_ledger").await, + 4, + "the replay must not append a second credit" + ); + + // The same key for different money is a client bug, not a replay. + let mismatch = pay_keyed(&app, &mgr, &full, 50, "receipt-114").await; + assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 4); + + // Two different keys are two payments, and the cap still applies to them. + let sixty = charge(60).await; + let a = pay_keyed(&app, &mgr, &sixty, 30, "a").await; + let b = pay_keyed(&app, &mgr, &sixty, 30, "b").await; + assert_eq!(a.status, StatusCode::CREATED); + assert_eq!(b.status, StatusCode::CREATED, "{}", b.body); + assert_ne!(id_of(&a.body), id_of(&b.body)); + assert_eq!( + pay_keyed(&app, &mgr, &sixty, 1, "c").await.status, + StatusCode::CONFLICT, + "a fresh key does not buy room the charge does not have" + ); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 6); + + // No key: the old semantics stay exactly as they were — two identical + // posts are two payments, because a desk taking the same amount twice is. + let thirty = charge(30).await; + let one = pay(&app, &mgr, &thirty, 10).await; + let two = pay(&app, &mgr, &thirty, 10).await; + assert_eq!(one.status, StatusCode::CREATED); + assert_eq!(two.status, StatusCode::CREATED); + assert_ne!(id_of(&one.body), id_of(&two.body)); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 8); +} + +#[tokio::test] +async fn a_replayed_request_key_returns_the_same_refund_instead_of_a_second_one() { + let (app, db) = app_and_db().await; + let (mgr, student_id, _) = billed_student(&app, &db, &[(100, 1_000)]).await; + let charge = charge_worth(&app, &mgr, &student_id, 100).await; + let credit = pay(&app, &mgr, &charge, 100).await; + let credit_id = id_of(&credit.body); + + let first = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; + assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); + + // The refund used the credit up, so the cap would refuse a second one — + // the replay must still answer with the line that exists. + let replay = refund_keyed(&app, &mgr, &credit_id, 100, "back-1").await; + assert_eq!(replay.status, StatusCode::CREATED, "{}", replay.body); + assert_eq!(id_of(&replay.body), id_of(&first.body)); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); + + let mismatch = refund_keyed(&app, &mgr, &credit_id, 25, "back-1").await; + assert_eq!(mismatch.status, StatusCode::CONFLICT, "{}", mismatch.body); + assert_eq!(pay_row_count(&db, "payment_ledger").await, 3); + + // The balance is what it was after the single refund: money out once. + let res = send( + &app, + "GET", + &format!("/payments/balance/{student_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], -100); +} + +/// The statement pages its per-charge rows — but the money it reports is folded +/// from every line, so `balance_minor` must not move between pages. +#[tokio::test] +async fn the_statement_pages_its_rows_without_moving_the_balance() { + let (app, db) = app_and_db().await; + let (mgr, student_id, _) = + billed_student(&app, &db, &[(100, 1_000), (60, 2_000), (30, 3_000)]).await; + let statement = |query: &str| { + let app = app.clone(); + let uri = format!("/payments/statement/{student_id}{query}"); + let mgr = mgr.clone(); + async move { + let res = send(&app, "GET", &uri, Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body + } + }; + + let all = statement("").await; + assert_eq!(all["entries"]["items"].as_array().unwrap().len(), 3); + assert_eq!(all["entries"]["total"], 3); + assert_eq!(all["balance_minor"], -190); + + let head = statement("?limit=2&offset=0").await; + assert_eq!(head["entries"]["items"].as_array().unwrap().len(), 2); + assert_eq!(head["entries"]["total"], 3); + assert_eq!(head["entries"]["limit"], 2); + assert_eq!(head["entries"]["offset"], 0); + assert_eq!(head["balance_minor"], -190); + + let tail = statement("?limit=2&offset=2").await; + assert_eq!( + tail["entries"]["items"].as_array().unwrap().len(), + 1, + "the tail returns the remainder" + ); + assert_eq!(tail["balance_minor"], -190, "every page folds every line"); + // The window is a slice of one order, so the pages do not overlap. + let page_ids = |body: &serde_json::Value| { + body["entries"]["items"] + .as_array() + .unwrap() + .iter() + .map(|entry| entry["charge_id"].as_str().unwrap().to_string()) + .collect::>() + }; + let mut seen = page_ids(&head); + seen.extend(page_ids(&tail)); + seen.sort(); + seen.dedup(); + assert_eq!(seen.len(), 3, "two pages, three distinct charges"); + + let res = send( + &app, + "GET", + &format!("/payments/statement/{student_id}?limit=0"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); +} + #[tokio::test] async fn payment_lists_page_through_the_envelope() { let (app, db) = app_and_db().await; diff --git a/tests/persistence.rs b/tests/persistence.rs index be00f21..b7b9c53 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -1689,7 +1689,7 @@ async fn fee_plans_and_their_charges_survive_remigration() { ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); - assert_eq!(res.body["entries"].as_array().unwrap().len(), 2); + assert_eq!(res.body["entries"]["items"].as_array().unwrap().len(), 2); assert_eq!( res.body["balance_minor"], -400_000, "the charges the placement raised are still owed" diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 23e53f0..3c25acd 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -724,6 +724,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_LEDGER_NOTE_LEN as i64, ), + ("RecordPayment", "request_key", "minLength", 1), + ( + "RecordPayment", + "request_key", + "maxLength", + MAX_PAYMENT_REQUEST_KEY_LEN as i64, + ), ("RecordRefund", "amount_minor", "minimum", 1), ( "RecordRefund", @@ -743,6 +750,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_LEDGER_NOTE_LEN as i64, ), + ("RecordRefund", "request_key", "minLength", 1), + ( + "RecordRefund", + "request_key", + "maxLength", + MAX_PAYMENT_REQUEST_KEY_LEN as i64, + ), ( "RecordReversal", "note",