diff --git a/README.md b/README.md index 9721f78..cca3d11 100644 --- a/README.md +++ b/README.md @@ -991,7 +991,7 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` — take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full, its cutoff has passed, or the menu was edited so often mid-booking that the price could not be pinned | | GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first · paged | | GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged | -| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat | +| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays) — its student or their parent, **or any manager+**, whose seat and money must stay reachable after a role change; idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff, which binds **students and parents only** — a manager+ frees a closed meal's seat, and `409` when the seat was booked again while the call ran, since only the attempt it read is ever released | | POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` — mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; `404` if the menu is unpublished mid-request; **moves no money** | | GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu · paged | | GET | `/meals/attendance/{user}` | student | One student's meal-attendance history · `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day · paged · own id always, otherwise teacher+ or a parent link | @@ -1804,7 +1804,13 @@ teacher or manager ordering a child's lunch is a `403`. cancel cut short between the flip and the reversal (the tab closed, a proxy timed out) is recovered by sending it again. Refusing it as a `409` — as it once did — made that state permanent: no route could append the missing - reversal, and the student stayed billed for a seat they no longer held. + reversal, and the student stayed billed for a seat they no longer held. The + flip **only ever releases the attempt the call read** (`WHERE status = + 'booked' AND attempt = …`, the same fence the re-booking side carries): a + seat taken again while the cancel was in flight is a `409`, never a silent + cancellation of somebody else's brand-new seat. Unfenced it freed that seat, + refunded nothing (the money is keyed to the *older* attempt, already + reversed) and burnt the new attempt's reversal id for good. - **A manager+ may cancel anybody's seat.** Booking is student-and-parent only, and cancelling used to be the same door — which left a seat nobody on the API could give back the moment its student was promoted to staff or its diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index 24c3299..54bc305 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -417,14 +417,16 @@ impl MealBooking { .await? .ok_or(AppError::NotFound)?; check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; - // Lost the flip: another cancel took the seat back first. Its row is - // the truth — but only the attempt *this* call was cancelling may be - // refunded off it (see [`Self::refundable_after_lost_flip`]). + // Lost the flip: the row is no longer the `booked` attempt this call + // read — another cancel took the seat back first, or a booking took it + // again. Its row is the truth, but only the attempt *this* call was + // cancelling may be refunded off it (see + // [`Self::refundable_after_lost_flip`]). let saved = match Self::release_seat(&fresh, recorded_by, db).await? { Some(cancelled) => cancelled, None => { let live = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?; - if !Self::refundable_after_lost_flip(&fresh, &live) { + if !Self::refundable_after_lost_flip(&fresh, &live)? { return Ok(live); } live @@ -445,8 +447,25 @@ impl MealBooking { /// could never be refunded afterwards. A row at another attempt is the same /// story one step further on: whoever cancelled attempt N appended its /// reversal, and this call has nothing left to heal. - fn refundable_after_lost_flip(seen: &MealBooking, live: &MealBooking) -> bool { - live.status == MealBookingStatus::Cancelled && live.attempt == seen.attempt + /// + /// A seat that is `booked` again is a **409**, not a `200`: the flip was + /// fenced on the attempt this call read, so the row can only be held by a + /// booking that landed inside this very cancel — one the API answered `201` + /// for and which no caller here has seen, let alone decided to free. `200` + /// with a `booked` row would report a cancellation that did not happen; the + /// client is told to look again instead, and a fresh `DELETE` then cancels + /// the attempt it really read. (A repeat cancel of an *unchanged* seat never + /// reaches here: `cancel` answers an already-cancelled row above.) + fn refundable_after_lost_flip( + seen: &MealBooking, + live: &MealBooking, + ) -> Result { + if live.status == MealBookingStatus::Booked { + return Err(AppError::Conflict( + "the seat was booked again while this cancellation ran", + )); + } + Ok(live.attempt == seen.attempt) } /// Flip the seat to `cancelled` and give it back to the menu's counter **in @@ -470,9 +489,18 @@ impl MealBooking { /// there is no half-second anywhere in which a seat is held with no charge /// against it, or a charge stands with no seat behind it. /// - /// `None` = the row was not `booked` any more. Retried while the store - /// reports a write conflict: the menu row is contended by every booking on - /// it, and that contention is the cap working, not an error. + /// **The flip is fenced on the attempt it read**, exactly as the revival on + /// the book side is. `status = 'booked'` alone matches a seat somebody else + /// took in the round trip [`Self::cancel`] spends re-reading the menu: the + /// flip then cancels attempt N+1, hands its seat back, and refunds nothing + /// at all — the ids bound here are attempt N's, and N's reversal is already + /// written — so a `POST` answered `201` a moment ago loses its seat with its + /// charge standing, and the `(booking, N+1)` reversal id is burnt for good. + /// + /// `None` = the row was not this call's own `booked` attempt any more. + /// Retried while the store reports a write conflict: the menu row is + /// contended by every booking on it, and that contention is the cap + /// working, not an error. async fn release_seat( booked: &MealBooking, recorded_by: &UserId, @@ -500,7 +528,8 @@ impl MealBooking { .query(format!( "BEGIN TRANSACTION; LET $flipped = (UPDATE $id SET status = 'cancelled', \ - cancelled_at = $now WHERE status = 'booked' RETURN AFTER); + cancelled_at = $now \ + WHERE status = 'booked' AND attempt = $attempt RETURN AFTER); UPDATE $menu SET {MENU_SEAT_COUNT_FIELD} = math::max([\ ({MENU_SEAT_COUNT_FIELD} ?? 0) - array::len($flipped), 0]); {reverse} @@ -509,6 +538,7 @@ impl MealBooking { )) .bind(("id", booked.id.record())) .bind(("menu", booked.menu.record())) + .bind(("attempt", booked.attempt)) .bind(("now", Timestamp::now())); let query = match &refund { Some((charge, line)) => query @@ -933,21 +963,25 @@ mod tests { .unwrap(); let cancelled = seen.clone().cancel(&open, &ali, &db).await.unwrap(); // The seat this cancel released: its own attempt, still cancelled. - assert!(MealBooking::refundable_after_lost_flip(&seen, &cancelled)); + assert!(MealBooking::refundable_after_lost_flip(&seen, &cancelled).unwrap()); // A re-book landed in the window. The row is `booked` again with a live // charge against it — refunding that frees money for a seat that is - // still held, and burns the ledger id its own cancel will need. + // still held, and burns the ledger id its own cancel will need. The + // caller is refused rather than told it cancelled something. let rebooked = MealBooking::book(&menu, &ali, &ali, &open, &db) .await .unwrap(); assert_eq!(rebooked.get_attempt(), seen.get_attempt() + 1); - assert!(!MealBooking::refundable_after_lost_flip(&seen, &rebooked)); + assert!(matches!( + MealBooking::refundable_after_lost_flip(&seen, &rebooked), + Err(AppError::Conflict(_)) + )); // Re-booked *and* cancelled again: that cancel appended the reversal // for its own attempt, and this call has nothing left to heal. let later = rebooked.cancel(&open, &ali, &db).await.unwrap(); - assert!(!MealBooking::refundable_after_lost_flip(&seen, &later)); + assert!(!MealBooking::refundable_after_lost_flip(&seen, &later).unwrap()); // And the ordinary lost race — another cancel of the same attempt got // there first — still replays the refund, which is what heals a cancel @@ -956,7 +990,54 @@ mod tests { .await .unwrap(); let freed = other.clone().cancel(&open, &veli, &db).await.unwrap(); - assert!(MealBooking::refundable_after_lost_flip(&other, &freed)); + assert!(MealBooking::refundable_after_lost_flip(&other, &freed).unwrap()); + } + + /// A cancel may only ever release the attempt it read. The stale handle + /// here is what a cancel holds across its own `Menu::read` round trip: by + /// the time the flip runs, that seat has been cancelled and taken again, so + /// the flip must refuse — unfenced it cancelled the *new* attempt, freeing a + /// seat the API had just answered `201` for, without refunding it (the + /// reversal is keyed to the stale attempt, which is already refunded) and + /// burning the new attempt's own reversal id for good. + #[tokio::test] + async fn a_cancel_cannot_release_an_attempt_it_never_read() { + let (db, menu) = menu(Some(1)).await; + let (ali, veli) = (UserId::generate(), UserId::generate()); + let open = MealCutoff::default(); + add_dish(&menu, 1_000, &db).await; + + let stale = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + stale.clone().cancel(&open, &ali, &db).await.unwrap(); + let live = MealBooking::book(&menu, &ali, &ali, &open, &db) + .await + .unwrap(); + assert_eq!(live.get_attempt(), stale.get_attempt() + 1); + + assert!( + MealBooking::release_seat(&stale, &ali, &db) + .await + .unwrap() + .is_none(), + "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(); + 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"); + assert_eq!( + MealLedger::balance_of(&ali, &db).await.unwrap(), + -1_000, + "the live attempt's charge stands: it was never cancelled" + ); + // The seat is still really held — the cap says so too. + assert!(matches!( + MealBooking::book(&menu, &veli, &veli, &open, &db).await, + Err(AppError::Conflict(_)) + )); } /// The seat may not come back without the money. Driven against diff --git a/src/lib.rs b/src/lib.rs index 1691db7..a7c503d 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 `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 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 `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 = "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 2d1a33e..1ead42e 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -925,6 +925,11 @@ async fn list_menu_bookings( /// cancel that was cut short mid-flight (the tab closed, a proxy timed out) is /// recovered by simply sending it again — the reversal is keyed to the seat's /// attempt, so the money comes back exactly once however often it is retried. +/// +/// A seat **re-booked while this call was running** is a `409`: the flip only +/// ever releases the attempt this call read, so the newer seat — one this API +/// answered `201` for and nobody here asked to free — is left alone. Send the +/// call again to cancel the seat as it now stands. #[utoipa::path( delete, path = "/bookings/{bid}", @@ -936,7 +941,7 @@ async fn list_menu_bookings( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the booking's student, their parent, nor a manager", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The cutoff has passed (students and parents only), or the menu was too contended to free the seat", body = ErrorResponse), + (status = 409, description = "The cutoff has passed (students and parents only), the seat was booked again while this call ran, or the menu was too contended to free the seat", body = ErrorResponse), ), )] async fn cancel_booking(