From 4fe44879ff999b0bf1d8598f2c0be7a87e8088d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 03:28:35 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=8D=BD=EF=B8=8F=20make=20a=20meal?= =?UTF-8?q?=20credit=20retry-safe=20on=20request?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `POST /meals/credits` minted a fresh ulid per call, so the ledger's identity-based idempotence — the rule that keeps a double-clicked booking from billing twice — could never bite here. A response lost after the commit (proxy timeout, closed tab) left the client resending the identical body, and the money was taken a second time with no route able to edit or delete either line. It now takes the optional `request_key` its twin `POST /payments/credits` already takes, same validator and same grammar, folded into the line's id as `_k_`. The student is part of the id, so a key cannot reach another account; the same key for a different amount is a 409, checked on what the append gave back rather than on a read before it, so two retries racing get the same answer. Omitting the key keeps the old behaviour: two identical posts are two credits. Also carries the rustfmt reflow of the cancel-fence test added earlier. --- README.md | 16 +++++++- src/domain/meal_booking.rs | 5 ++- src/domain/meal_ledger.rs | 60 ++++++++++++++++++++++++++++-- src/lib.rs | 2 +- src/web/meals.rs | 25 ++++++++++++- tests/regress_meals.rs | 76 ++++++++++++++++++++++++++++++++++++++ tests/spec_bounds.rs | 7 ++++ 7 files changed, 183 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 351dc53..0e2903b 100644 --- a/README.md +++ b/README.md @@ -408,7 +408,7 @@ drift from it**, which is enforced rather than asked for: and fails unless each one is either referenced by `src/web/limits.rs` or listed as a deliberate exclusion *with a reason*. A new constant breaks the suite until someone decides, consciously, whether clients need it. -- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 168 published +- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 170 published bounds back out of the emitted JSON, and asserts each equals its constant. This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal only** — a `const` there does not compile — so the annotations are @@ -998,7 +998,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) | | GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise **manager+** or a parent link — a teacher gets a `403`, canteen debt is family debt | | GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate (manager+, parent link, or own) | -| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change) | +| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?, request_key?}` — record money received; **admin only**, appends a `credit` line; the target must be a student, or anyone already carrying ledger lines (a debt outlives a role change); a `request_key` makes the call retry-safe by identity (`409` on the same key for a different amount) | | POST | `/payments/plans` | manager | `{name, installments}` — write a fee plan (1–60 installments, each `{amount_minor, due_at}`; `due_at` may be in the past); bills nobody | | GET | `/payments/plans` | manager | List fee plans, newest first · paged | | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule | @@ -1998,6 +1998,18 @@ money on account. Amounts are stored positive; the sign lives in the `kind`. ("cash", "havale", …) and `note`, and records the admin as `recorded_by`. There is no payment gateway and no card data, ever. An over-credit is corrected with a compensating line, never a fix-up. +- **A credit is retry-safe on request**, exactly like `POST /payments/credits`: + send an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, + the separator inside a ledger line's id) and the line is keyed + `_k_`, so a client retry after a network timeout returns the + line the first attempt wrote instead of crediting the money twice. Without + one the id is a fresh ulid and a resent request is a second credit, as a desk + taking the same amount twice really is — and since nothing here edits or + deletes a line, that doubled credit can only be corrected by a compensating + one. The same key with a different `amount_minor` is a `409`, never the + stored line: that is a client bug, and answering `201` would hide it. The + student is part of the id, so one office's "receipt-114" can never land on + another student's account. `GET /meals/balance/me` is the caller's own balance. `GET /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index 686619b..2399273 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -1039,7 +1039,10 @@ mod tests { "the attempt this call read is gone, so it releases nothing" ); // Stored state, not the returned value: the mem engine forges wins. - let stored = MealBooking::read(live.get_id(), &db).await.unwrap().unwrap(); + let stored = MealBooking::read(live.get_id(), &db) + .await + .unwrap() + .unwrap(); assert_eq!(stored.get_status(), MealBookingStatus::Booked); assert_eq!(stored.get_attempt(), live.get_attempt()); assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back"); diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index 1f6e75d..bfc7090 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -38,6 +38,12 @@ //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of //! one seat can both read "no charge yet" and both append, which is how a //! double-click used to bill a seat twice. +//! - **A credit may be keyed too.** `POST /meals/credits` takes an optional +//! client-chosen `request_key`, which lands in the line's id +//! ([`MealLedgerId::for_request`]) and makes the call retry-safe by the same +//! identity rule: a retry after a timeout resolves the line it already wrote. +//! Without one, a fresh ulid is minted and a resent request is a second +//! credit — which nothing here can edit or delete afterwards. //! - **A no-show still pays.** Meal attendance has zero billing effect — //! nothing in this file reads or writes it. Do not add a no-show penalty //! here: the seat was reserved and the food was cooked. @@ -58,6 +64,9 @@ use crate::domain::meal_booking::{MealBooking, MealBookingId}; use crate::domain::menu::MenuId; use crate::domain::menu_dish::MenuDish; use crate::domain::page::PagedList; +// The client-chosen idempotence key both ledgers take — one grammar, one +// validator, one type, rather than a second newtype that could drift from it. +use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -105,6 +114,26 @@ impl MealLedgerId { )) } + /// The one credit a `(student, request_key)` pair may ever have. Same trick + /// as [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request), + /// scoped by the student because a credit points at no line of its own: one + /// office's "receipt-114" cannot land on another student's account, and a + /// key replayed for the wrong student cannot resolve to this line at all. + /// + /// The grammar parses uniquely because `_` joins the parts. A booking line + /// is `___c`, whose first part carries the `-` of a + /// `YYYY-MM-DD` day, and an unkeyed line is a bare ULID; a credit's first + /// part is a student ULID (`[0-9A-Z]`) and a `request_key` is + /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, which cannot + /// spell a separator plus a marker. No key can therefore derive an id some + /// other line owns — a collision would hand money to the wrong row. + pub fn for_request(student: &UserId, key: &PaymentRequestKey) -> Self { + Self(RecordId::new( + MEAL_LEDGER_TABLE, + format!("{}_k_{}", student.key(), key.as_str()), + )) + } + pub fn record(&self) -> RecordId { self.0.clone() } @@ -450,17 +479,29 @@ impl MealLedger { } /// Money in: a payment received, or an opening balance. + /// + /// With a `request_key` the line is keyed by it (see + /// [`MealLedgerId::for_request`]) and the call is **retry-safe**: a client + /// resending the identical body after a timeout gets back the line the + /// first attempt wrote, not a second credit — nothing on this API can edit + /// or delete one, so a doubled credit is corrected only by a compensating + /// line. Without one the id is a fresh ulid and two identical calls are two + /// credits, which is what a desk taking the same amount twice really means. pub async fn credit( student: &UserId, amount_minor: LedgerAmount, method: Option, note: Option, + request_key: Option<&PaymentRequestKey>, recorded_by: &UserId, db: &Database, ) -> Result { - Self::append( + let line = Self::append( MealLedger { - id: MealLedgerId::generate(), + id: match request_key { + Some(key) => MealLedgerId::for_request(student, key), + None => MealLedgerId::generate(), + }, student: student.clone(), kind: MealLedgerKind::Credit, amount_minor, @@ -472,7 +513,20 @@ impl MealLedger { }, db, ) - .await + .await?; + // A replay is answered from the stored line — but only if it is the + // same money. The same key for a different amount is a client bug, and + // handing back the old line would hide it behind a `201`. Checked on + // what `append` gave back rather than on a read before it: two retries + // arriving together both find no row, and only the id decides which + // one's amount is stored, so a check *before* the write would tell the + // loser its own amount landed. + if request_key.is_some() && line.amount_minor != amount_minor { + return Err(AppError::Conflict( + "this request_key was already used for a different amount", + )); + } + Ok(line) } /// A student's whole statement, newest first. diff --git a/src/lib.rs b/src/lib.rs index b01a569..9007cc8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,7 @@ use crate::state::AppState; (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (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). Those reads are refused (`409`) while the caller's own latest sitting on that exam is in progress, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. 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 must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /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}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), 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 **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. 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) except the two money reads below; 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 a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) 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 flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is 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; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), 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 the seat and its flip move in one transaction, 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, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. 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; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), 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?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) 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 **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), + (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 must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /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}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), 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 **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. 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) except the two money reads below; 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 a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) 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 flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is 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; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), 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 the seat and its flip move in one transaction, 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, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. 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; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), 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?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) 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. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `_k_`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), (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. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. 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. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay 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. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), diff --git a/src/web/meals.rs b/src/web/meals.rs index 1ead42e..bfabacb 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -28,6 +28,8 @@ use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, }; use crate::domain::parent_link::ParentLink; +// The same idempotence key `/payments/credits` takes — one grammar, one type. +use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::user::{User, UserId}; @@ -1389,6 +1391,13 @@ struct RecordCredit { 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 credits. The same key sent with a + /// different `amount_minor` is a `409`. + #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] + request_key: Option, } /// Record money received from a student. **Admin only** — not manager: writing @@ -1397,6 +1406,13 @@ struct RecordCredit { /// its debtor's role change, and it has to stay settleable. Appends a `credit` line; /// nothing in the ledger is ever edited or removed, so an over-credit is /// corrected by a compensating line, not by a fix-up. +/// +/// **Retry-safe on request** — send a `request_key` and a repeat of the call (a +/// client retry after a network timeout, which used to record the money a second +/// time the moment the response was lost) returns the line the first attempt +/// wrote. The same key with a different `amount_minor` is a `409`: that is a +/// client bug, not a replay. Without a key two identical calls are two credits, +/// as a desk taking the same amount twice really is. #[utoipa::path( post, path = "/credits", @@ -1405,10 +1421,11 @@ struct RecordCredit { request_body = RecordCredit, responses( (status = 201, description = "Credit recorded", body = LedgerResponse), - (status = 400, description = "Invalid amount, method, note, or a non-student target", body = ErrorResponse), + (status = 400, description = "Invalid amount, method, note, request_key, or a non-student target", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires the admin role", body = ErrorResponse), (status = 404, description = "No such user", body = ErrorResponse), + (status = 409, description = "The request_key was already used for a different amount", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -1439,6 +1456,11 @@ async fn record_credit( reason: "only a student carries a meal balance", })); } + let request_key = req + .request_key + .as_deref() + .map(PaymentRequestKey::try_new) + .transpose()?; let line = MealLedger::credit( &student, LedgerAmount::try_new(req.amount_minor)?, @@ -1452,6 +1474,7 @@ async fn record_credit( .map(LedgerNote::try_new) .transpose()? .flatten(), + request_key.as_ref(), admin.get_id(), &st.db, ) diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs index 82eba91..308519c 100644 --- a/tests/regress_meals.rs +++ b/tests/regress_meals.rs @@ -265,6 +265,82 @@ async fn a_credit_settles_a_debt_that_outlived_the_students_role() { assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); } +/// A credit resent after a lost response must not take the money twice. The id +/// was a fresh ulid, so the ledger's identity-based idempotence could never +/// bite: a proxy timing out anywhere after the commit left the client with a +/// second credit and no route to undo it, since nothing here edits or deletes a +/// line. A `request_key` folds into the id, exactly as it does on +/// `POST /payments/credits`, and the same key for a different amount is a `409` +/// rather than a `201` that hides a client bug behind a stored line. +#[tokio::test] +async fn a_credit_replayed_with_its_request_key_records_the_money_once() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "key_admin", "admin").await; + let ali = login(&app, "key_ali").await; + let ali_id = me_id(&app, &ali).await; + let credit = |body: serde_json::Value| { + let (app, admin) = (app.clone(), admin.clone()); + async move { send(&app, "POST", "/meals/credits", Some(&admin), Some(body)).await } + }; + let body = + json!({ "student_id": ali_id, "amount_minor": 25_000, "request_key": "receipt-114" }); + + let first = credit(body.clone()).await; + assert_eq!(first.status, StatusCode::CREATED, "{}", first.body); + // The retry: same body, same line back, and no second one behind it. + let again = credit(body.clone()).await; + assert_eq!(again.status, StatusCode::CREATED, "{}", again.body); + assert_eq!(again.body["id"], first.body["id"]); + + // The stored ledger, not the two responses: only one line ever landed. + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(res.body["total"], 1, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 25_000, "credited once"); + + // The same key for other money is a client bug, and is refused as one. + let res = credit(json!({ + "student_id": ali_id, "amount_minor": 30_000, "request_key": "receipt-114" + })) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + // A key with the id separator in it cannot be spelled at all: it would let + // one line's key derive another's id. + let res = credit(json!({ + "student_id": ali_id, "amount_minor": 30_000, "request_key": "receipt_114" + })) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // …and without a key a resent request is a second credit, as before. + let plain = json!({ "student_id": ali_id, "amount_minor": 1_000 }); + assert_eq!(credit(plain.clone()).await.status, StatusCode::CREATED); + assert_eq!(credit(plain).await.status, StatusCode::CREATED); + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&admin), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 27_000, "{}", res.body); +} + /// A mark must not create a row for a menu that is gone. The handler reads the /// menu first, so this is driven below it — exactly the interleaving a mark in /// flight while `DELETE /meals/menus/{id}` commits produces. The stake is not diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 1f3aba1..0e7a90f 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -702,6 +702,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_LEDGER_NOTE_LEN as i64, ), + ("RecordCredit", "request_key", "minLength", 1), + ( + "RecordCredit", + "request_key", + "maxLength", + MAX_PAYMENT_REQUEST_KEY_LEN as i64, + ), // --- school payments: fee plans and the payment ledger --- ("InstallmentBody", "amount_minor", "minimum", 1), (