forge
Explore
Log in

Don't you dare go Hollow

🍽️ make a meal credit retry-safe on request

Browse files at this commit

4fe44879ff999b0bf1d8598f2c0be7a87e8088d9Ahmet Kaan GümüşParent: 5fdba75
  • fix
    • 🍽️ make a meal credit retry-safe on request
Show full message
fix: 🍽️ make a meal credit retry-safe on request

`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 `<student>_k_<key>`. 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.mdmodified+14 -2
@@ -408,7 +408,7 @@ drift from it**, which is enforced rather than asked for:
408 and fails unless each one is either referenced by `src/web/limits.rs` or408 and fails unless each one is either referenced by `src/web/limits.rs` or
409 listed as a deliberate exclusion *with a reason*. A new constant breaks the409 listed as a deliberate exclusion *with a reason*. A new constant breaks the
410 suite until someone decides, consciously, whether clients need it.410 suite until someone decides, consciously, whether clients need it.
411-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 168 published411+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 170 published
412 bounds back out of the emitted JSON, and asserts each equals its constant.412 bounds back out of the emitted JSON, and asserts each equals its constant.
413 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal413 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
414 only** β€” a `const` there does not compile β€” so the annotations are414 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.
998 | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |998 | GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |
999 | 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 |999 | 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 |
1000 | GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate (manager+, parent link, or own) |1000 | GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate (manager+, parent link, or own) |
1001-| 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) |1001+| 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) |
1002 | 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 |1002 | 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 |
1003 | GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |1003 | GET | `/payments/plans` | manager | List fee plans, newest first Β· paged |
1004 | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule |1004 | 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`.
1998 ("cash", "havale", …) and `note`, and records the admin as `recorded_by`.1998 ("cash", "havale", …) and `note`, and records the admin as `recorded_by`.
1999 There is no payment gateway and no card data, ever. An over-credit is1999 There is no payment gateway and no card data, ever. An over-credit is
2000 corrected with a compensating line, never a fix-up.2000 corrected with a compensating line, never a fix-up.
2001+- **A credit is retry-safe on request**, exactly like `POST /payments/credits`:
2002+ send an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters β€” no `_`,
2003+ the separator inside a ledger line's id) and the line is keyed
2004+ `<student>_k_<key>`, so a client retry after a network timeout returns the
2005+ line the first attempt wrote instead of crediting the money twice. Without
2006+ one the id is a fresh ulid and a resent request is a second credit, as a desk
2007+ taking the same amount twice really is β€” and since nothing here edits or
2008+ deletes a line, that doubled credit can only be corrected by a compensating
2009+ one. The same key with a different `amount_minor` is a `409`, never the
2010+ stored line: that is a client bug, and answering `201` would hide it. The
2011+ student is part of the id, so one office's "receipt-114" can never land on
2012+ another student's account.
2001 2013
2002 `GET /meals/balance/me` is the caller's own balance. `GET2014 `GET /meals/balance/me` is the caller's own balance. `GET
2003 /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line2015 /meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line
src/domain/meal_booking.rsmodified+4 -1
@@ -1039,7 +1039,10 @@ mod tests {
1039 "the attempt this call read is gone, so it releases nothing"1039 "the attempt this call read is gone, so it releases nothing"
1040 );1040 );
1041 // Stored state, not the returned value: the mem engine forges wins.1041 // Stored state, not the returned value: the mem engine forges wins.
1042- let stored = MealBooking::read(live.get_id(), &db).await.unwrap().unwrap();1042+ let stored = MealBooking::read(live.get_id(), &db)
1043+ .await
1044+ .unwrap()
1045+ .unwrap();
1043 assert_eq!(stored.get_status(), MealBookingStatus::Booked);1046 assert_eq!(stored.get_status(), MealBookingStatus::Booked);
1044 assert_eq!(stored.get_attempt(), live.get_attempt());1047 assert_eq!(stored.get_attempt(), live.get_attempt());
1045 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");1048 assert_eq!(seats(&menu, &db).await, 1, "and gives no seat back");
src/domain/meal_ledger.rsmodified+57 -3
@@ -38,6 +38,12 @@
38 //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of38 //! depend on a "has this been billed yet?" scan: two concurrent `POST`s of
39 //! one seat can both read "no charge yet" and both append, which is how a39 //! one seat can both read "no charge yet" and both append, which is how a
40 //! double-click used to bill a seat twice.40 //! double-click used to bill a seat twice.
41+//! - **A credit may be keyed too.** `POST /meals/credits` takes an optional
42+//! client-chosen `request_key`, which lands in the line's id
43+//! ([`MealLedgerId::for_request`]) and makes the call retry-safe by the same
44+//! identity rule: a retry after a timeout resolves the line it already wrote.
45+//! Without one, a fresh ulid is minted and a resent request is a second
46+//! credit β€” which nothing here can edit or delete afterwards.
41 //! - **A no-show still pays.** Meal attendance has zero billing effect β€”47 //! - **A no-show still pays.** Meal attendance has zero billing effect β€”
42 //! nothing in this file reads or writes it. Do not add a no-show penalty48 //! nothing in this file reads or writes it. Do not add a no-show penalty
43 //! here: the seat was reserved and the food was cooked.49 //! here: the seat was reserved and the food was cooked.
@@ -58,6 +64,9 @@ use crate::domain::meal_booking::{MealBooking, MealBookingId};
58 use crate::domain::menu::MenuId;64 use crate::domain::menu::MenuId;
59 use crate::domain::menu_dish::MenuDish;65 use crate::domain::menu_dish::MenuDish;
60 use crate::domain::page::PagedList;66 use crate::domain::page::PagedList;
67+// The client-chosen idempotence key both ledgers take β€” one grammar, one
68+// validator, one type, rather than a second newtype that could drift from it.
69+use crate::domain::payment_ledger::PaymentRequestKey;
61 use crate::domain::timestamp::Timestamp;70 use crate::domain::timestamp::Timestamp;
62 use crate::domain::user::UserId;71 use crate::domain::user::UserId;
63 use crate::error::{AppError, ValidationError};72 use crate::error::{AppError, ValidationError};
@@ -105,6 +114,26 @@ impl MealLedgerId {
105 ))114 ))
106 }115 }
107 116
117+ /// The one credit a `(student, request_key)` pair may ever have. Same trick
118+ /// as [`PaymentLedgerId::for_request`](crate::domain::payment_ledger::PaymentLedgerId::for_request),
119+ /// scoped by the student because a credit points at no line of its own: one
120+ /// office's "receipt-114" cannot land on another student's account, and a
121+ /// key replayed for the wrong student cannot resolve to this line at all.
122+ ///
123+ /// The grammar parses uniquely because `_` joins the parts. A booking line
124+ /// is `<date>_<slot>_<student>_c<n>`, whose first part carries the `-` of a
125+ /// `YYYY-MM-DD` day, and an unkeyed line is a bare ULID; a credit's first
126+ /// part is a student ULID (`[0-9A-Z]`) and a `request_key` is
127+ /// [`crate::validate::validate_request_key`]'s `[A-Za-z0-9-]`, which cannot
128+ /// spell a separator plus a marker. No key can therefore derive an id some
129+ /// other line owns β€” a collision would hand money to the wrong row.
130+ pub fn for_request(student: &UserId, key: &PaymentRequestKey) -> Self {
131+ Self(RecordId::new(
132+ MEAL_LEDGER_TABLE,
133+ format!("{}_k_{}", student.key(), key.as_str()),
134+ ))
135+ }
136+
108 pub fn record(&self) -> RecordId {137 pub fn record(&self) -> RecordId {
109 self.0.clone()138 self.0.clone()
110 }139 }
@@ -450,17 +479,29 @@ impl MealLedger {
450 }479 }
451 480
452 /// Money in: a payment received, or an opening balance.481 /// Money in: a payment received, or an opening balance.
482+ ///
483+ /// With a `request_key` the line is keyed by it (see
484+ /// [`MealLedgerId::for_request`]) and the call is **retry-safe**: a client
485+ /// resending the identical body after a timeout gets back the line the
486+ /// first attempt wrote, not a second credit β€” nothing on this API can edit
487+ /// or delete one, so a doubled credit is corrected only by a compensating
488+ /// line. Without one the id is a fresh ulid and two identical calls are two
489+ /// credits, which is what a desk taking the same amount twice really means.
453 pub async fn credit(490 pub async fn credit(
454 student: &UserId,491 student: &UserId,
455 amount_minor: LedgerAmount,492 amount_minor: LedgerAmount,
456 method: Option<LedgerMethod>,493 method: Option<LedgerMethod>,
457 note: Option<LedgerNote>,494 note: Option<LedgerNote>,
495+ request_key: Option<&PaymentRequestKey>,
458 recorded_by: &UserId,496 recorded_by: &UserId,
459 db: &Database,497 db: &Database,
460 ) -> Result<MealLedger, AppError> {498 ) -> Result<MealLedger, AppError> {
461- Self::append(499+ let line = Self::append(
462 MealLedger {500 MealLedger {
463- id: MealLedgerId::generate(),501+ id: match request_key {
502+ Some(key) => MealLedgerId::for_request(student, key),
503+ None => MealLedgerId::generate(),
504+ },
464 student: student.clone(),505 student: student.clone(),
465 kind: MealLedgerKind::Credit,506 kind: MealLedgerKind::Credit,
466 amount_minor,507 amount_minor,
@@ -472,7 +513,20 @@ impl MealLedger {
472 },513 },
473 db,514 db,
474 )515 )
475- .await516+ .await?;
517+ // A replay is answered from the stored line β€” but only if it is the
518+ // same money. The same key for a different amount is a client bug, and
519+ // handing back the old line would hide it behind a `201`. Checked on
520+ // what `append` gave back rather than on a read before it: two retries
521+ // arriving together both find no row, and only the id decides which
522+ // one's amount is stored, so a check *before* the write would tell the
523+ // loser its own amount landed.
524+ if request_key.is_some() && line.amount_minor != amount_minor {
525+ return Err(AppError::Conflict(
526+ "this request_key was already used for a different amount",
527+ ));
528+ }
529+ Ok(line)
476 }530 }
477 531
478 /// A student's whole statement, newest first.532 /// A student's whole statement, newest first.
src/lib.rsmodified+1 -1
@@ -58,7 +58,7 @@ use crate::state::AppState;
58 (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"),58 (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"),
59 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),59 (name = "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"),
60 (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"),60 (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"),
61- (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"),61+ (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 `<student>_k_<key>`, 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"),
62 (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 `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β€” even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. 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"),62 (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 `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice β€” even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. 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"),
63 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),63 (name = "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"),
64 (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+"),64 (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+"),
src/web/meals.rsmodified+24 -1
@@ -28,6 +28,8 @@ use crate::domain::menu_dish::{
28 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,28 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
29 };29 };
30 use crate::domain::parent_link::ParentLink;30 use crate::domain::parent_link::ParentLink;
31+// The same idempotence key `/payments/credits` takes β€” one grammar, one type.
32+use crate::domain::payment_ledger::PaymentRequestKey;
31 use crate::domain::role::Role;33 use crate::domain::role::Role;
32 use crate::domain::settings::Settings;34 use crate::domain::settings::Settings;
33 use crate::domain::user::{User, UserId};35 use crate::domain::user::{User, UserId};
@@ -1389,6 +1391,13 @@ struct RecordCredit {
1389 method: Option<String>,1391 method: Option<String>,
1390 #[schema(max_length = 500, example = "receipt 2026-114")]1392 #[schema(max_length = 500, example = "receipt 2026-114")]
1391 note: Option<String>,1393 note: Option<String>,
1394+ /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the
1395+ /// separator inside a ledger line's id). Send one and a retry after a
1396+ /// timeout returns the **same** line instead of recording the money twice;
1397+ /// omit it and two identical calls are two credits. The same key sent with a
1398+ /// different `amount_minor` is a `409`.
1399+ #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")]
1400+ request_key: Option<String>,
1392 }1401 }
1393 1402
1394 /// Record money received from a student. **Admin only** β€” not manager: writing1403 /// Record money received from a student. **Admin only** β€” not manager: writing
@@ -1397,6 +1406,13 @@ struct RecordCredit {
1397 /// its debtor's role change, and it has to stay settleable. Appends a `credit` line;1406 /// its debtor's role change, and it has to stay settleable. Appends a `credit` line;
1398 /// nothing in the ledger is ever edited or removed, so an over-credit is1407 /// nothing in the ledger is ever edited or removed, so an over-credit is
1399 /// corrected by a compensating line, not by a fix-up.1408 /// corrected by a compensating line, not by a fix-up.
1409+///
1410+/// **Retry-safe on request** β€” send a `request_key` and a repeat of the call (a
1411+/// client retry after a network timeout, which used to record the money a second
1412+/// time the moment the response was lost) returns the line the first attempt
1413+/// wrote. The same key with a different `amount_minor` is a `409`: that is a
1414+/// client bug, not a replay. Without a key two identical calls are two credits,
1415+/// as a desk taking the same amount twice really is.
1400 #[utoipa::path(1416 #[utoipa::path(
1401 post,1417 post,
1402 path = "/credits",1418 path = "/credits",
@@ -1405,10 +1421,11 @@ struct RecordCredit {
1405 request_body = RecordCredit,1421 request_body = RecordCredit,
1406 responses(1422 responses(
1407 (status = 201, description = "Credit recorded", body = LedgerResponse),1423 (status = 201, description = "Credit recorded", body = LedgerResponse),
1408- (status = 400, description = "Invalid amount, method, note, or a non-student target", body = ErrorResponse),1424+ (status = 400, description = "Invalid amount, method, note, request_key, or a non-student target", body = ErrorResponse),
1409 (status = 401, description = "Not authenticated", body = ErrorResponse),1425 (status = 401, description = "Not authenticated", body = ErrorResponse),
1410 (status = 403, description = "Requires the admin role", body = ErrorResponse),1426 (status = 403, description = "Requires the admin role", body = ErrorResponse),
1411 (status = 404, description = "No such user", body = ErrorResponse),1427 (status = 404, description = "No such user", body = ErrorResponse),
1428+ (status = 409, description = "The request_key was already used for a different amount", body = ErrorResponse),
1412 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),1429 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1413 ),1430 ),
1414 )]1431 )]
@@ -1439,6 +1456,11 @@ async fn record_credit(
1439 reason: "only a student carries a meal balance",1456 reason: "only a student carries a meal balance",
1440 }));1457 }));
1441 }1458 }
1459+ let request_key = req
1460+ .request_key
1461+ .as_deref()
1462+ .map(PaymentRequestKey::try_new)
1463+ .transpose()?;
1442 let line = MealLedger::credit(1464 let line = MealLedger::credit(
1443 &student,1465 &student,
1444 LedgerAmount::try_new(req.amount_minor)?,1466 LedgerAmount::try_new(req.amount_minor)?,
@@ -1452,6 +1474,7 @@ async fn record_credit(
1452 .map(LedgerNote::try_new)1474 .map(LedgerNote::try_new)
1453 .transpose()?1475 .transpose()?
1454 .flatten(),1476 .flatten(),
1477+ request_key.as_ref(),
1455 admin.get_id(),1478 admin.get_id(),
1456 &st.db,1479 &st.db,
1457 )1480 )
tests/regress_meals.rsmodified+76 -0
@@ -265,6 +265,82 @@ async fn a_credit_settles_a_debt_that_outlived_the_students_role() {
265 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);265 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
266 }266 }
267 267
268+/// A credit resent after a lost response must not take the money twice. The id
269+/// was a fresh ulid, so the ledger's identity-based idempotence could never
270+/// bite: a proxy timing out anywhere after the commit left the client with a
271+/// second credit and no route to undo it, since nothing here edits or deletes a
272+/// line. A `request_key` folds into the id, exactly as it does on
273+/// `POST /payments/credits`, and the same key for a different amount is a `409`
274+/// rather than a `201` that hides a client bug behind a stored line.
275+#[tokio::test]
276+async fn a_credit_replayed_with_its_request_key_records_the_money_once() {
277+ let (app, db) = app_and_db().await;
278+ let admin = login_as(&app, &db, "key_admin", "admin").await;
279+ let ali = login(&app, "key_ali").await;
280+ let ali_id = me_id(&app, &ali).await;
281+ let credit = |body: serde_json::Value| {
282+ let (app, admin) = (app.clone(), admin.clone());
283+ async move { send(&app, "POST", "/meals/credits", Some(&admin), Some(body)).await }
284+ };
285+ let body =
286+ json!({ "student_id": ali_id, "amount_minor": 25_000, "request_key": "receipt-114" });
287+
288+ let first = credit(body.clone()).await;
289+ assert_eq!(first.status, StatusCode::CREATED, "{}", first.body);
290+ // The retry: same body, same line back, and no second one behind it.
291+ let again = credit(body.clone()).await;
292+ assert_eq!(again.status, StatusCode::CREATED, "{}", again.body);
293+ assert_eq!(again.body["id"], first.body["id"]);
294+
295+ // The stored ledger, not the two responses: only one line ever landed.
296+ let res = send(
297+ &app,
298+ "GET",
299+ &format!("/meals/ledger/{ali_id}"),
300+ Some(&admin),
301+ None,
302+ )
303+ .await;
304+ assert_eq!(res.body["total"], 1, "{}", res.body);
305+ let res = send(
306+ &app,
307+ "GET",
308+ &format!("/meals/balance/{ali_id}"),
309+ Some(&admin),
310+ None,
311+ )
312+ .await;
313+ assert_eq!(res.body["balance_minor"], 25_000, "credited once");
314+
315+ // The same key for other money is a client bug, and is refused as one.
316+ let res = credit(json!({
317+ "student_id": ali_id, "amount_minor": 30_000, "request_key": "receipt-114"
318+ }))
319+ .await;
320+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
321+ // A key with the id separator in it cannot be spelled at all: it would let
322+ // one line's key derive another's id.
323+ let res = credit(json!({
324+ "student_id": ali_id, "amount_minor": 30_000, "request_key": "receipt_114"
325+ }))
326+ .await;
327+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
328+
329+ // …and without a key a resent request is a second credit, as before.
330+ let plain = json!({ "student_id": ali_id, "amount_minor": 1_000 });
331+ assert_eq!(credit(plain.clone()).await.status, StatusCode::CREATED);
332+ assert_eq!(credit(plain).await.status, StatusCode::CREATED);
333+ let res = send(
334+ &app,
335+ "GET",
336+ &format!("/meals/balance/{ali_id}"),
337+ Some(&admin),
338+ None,
339+ )
340+ .await;
341+ assert_eq!(res.body["balance_minor"], 27_000, "{}", res.body);
342+}
343+
268 /// A mark must not create a row for a menu that is gone. The handler reads the344 /// A mark must not create a row for a menu that is gone. The handler reads the
269 /// menu first, so this is driven below it β€” exactly the interleaving a mark in345 /// menu first, so this is driven below it β€” exactly the interleaving a mark in
270 /// flight while `DELETE /meals/menus/{id}` commits produces. The stake is not346 /// flight while `DELETE /meals/menus/{id}` commits produces. The stake is not
tests/spec_bounds.rsmodified+7 -0
@@ -702,6 +702,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
702 "maxLength",702 "maxLength",
703 MAX_LEDGER_NOTE_LEN as i64,703 MAX_LEDGER_NOTE_LEN as i64,
704 ),704 ),
705+ ("RecordCredit", "request_key", "minLength", 1),
706+ (
707+ "RecordCredit",
708+ "request_key",
709+ "maxLength",
710+ MAX_PAYMENT_REQUEST_KEY_LEN as i64,
711+ ),
705 // --- school payments: fee plans and the payment ledger ---712 // --- school payments: fee plans and the payment ledger ---
706 ("InstallmentBody", "amount_minor", "minimum", 1),713 ("InstallmentBody", "amount_minor", "minimum", 1),
707 (714 (