forge
Explore
Log in

Don't you dare go Hollow

Close the canteen's existence oracle and its cutoff trap

Browse files at this commit

4586d9a9588b93b9cef7de3f46adcb2691d38fb1Ahmet Kaan GümüşParent: 39821ef
  • fix
    • close the canteen's existence oracle and its cutoff trap
Show full message
🍽️ fix: close the canteen's existence oracle and its cutoff trap

cancel_booking read the booking before authorising, and booking ids are
derivable from the menu date, slot and user key. Any teacher could
enumerate exactly which student booked which meal by reading the status
code — 403 meant booked, 404 meant not — bypassing the deliberate
manager+ gate on the bookings list. It now authorises off the path id
first, so an unauthorised caller cannot tell the two apart. It was the
only read-then-authorise ordering in the file.

served_at fell back to midnight UTC when a slot carried no
serving_minute, and all three shipped slots carry none. Setting
meal_cancel_cutoff_minutes without serving hours therefore made every
same-day menu unbookable and uncancellable by students. A slot with no
serving hour now has no cutoff; the impossible-day refusal still runs
first, so the fail-closed rule survives.

claim_and_place and release_seat were the only conflict-retry loops in
the crate with no backoff and three tries, while every sibling uses eight
with exponential backoff — and these are precisely the "one HTTP burst
on a single parent" case that sizing exists for.

DietaryProfile::save did read-then-create, so two concurrent first
writes made the loser a 500.

book's held-seat path answered from a row read a round trip earlier, so
a cancel in the gap produced a 201 claiming a seat the store had already
cancelled and refunded.

Book/cancel cycles are now capped, and balance_of aggregates per kind
instead of folding the student's entire ledger in process.
src/domain/dietary_profile.rsmodified+18 -4
@@ -156,13 +156,27 @@ impl DietaryProfile {
156 let profile = Self {156 let profile = Self {
157 id: DietaryProfileId::of(student),157 id: DietaryProfileId::of(student),
158 student: student.clone(),158 student: student.clone(),
159- tags: tags.unwrap_or(DietaryTags(Vec::new())),159+ tags: tags.clone().unwrap_or(DietaryTags(Vec::new())),
160- note: note.flatten(),160+ note: note.clone().flatten(),
161 updated_by: by.clone(),161 updated_by: by.clone(),
162 updated_at: Timestamp::now(),162 updated_at: Timestamp::now(),
163 };163 };
164- let created: Option<Self> = db.create(profile.id.record()).content(profile).await?;164+ match db.create(profile.id.record()).content(profile).await {
165- return created.ok_or_else(|| AppError::Internal("failed to save the profile".into()));165+ Ok(Some(created)) => return Ok(created),
166+ Ok(None) => {
167+ return Err(AppError::Internal("failed to save the profile".into()));
168+ }
169+ // A rival first `PATCH` created the row in the round trip since
170+ // the read above (the `dietary_profile_student` UNIQUE index
171+ // catches the same collision), and `CREATE` leaves that row
172+ // untouched — so this call is a plain field write after all,
173+ // exactly as it would have been a moment later. Propagated, it
174+ // was a 500 on a legitimate request. Same shape as
175+ // [`MealLedger::append`](crate::domain::meal_ledger), which
176+ // reads the winner back rather than failing.
177+ Err(err) if err.is_already_exists() => {}
178+ Err(err) => return Err(err.into()),
179+ }
166 }180 }
167 FieldUpdate::new(DietaryProfileId::of(student).record())181 FieldUpdate::new(DietaryProfileId::of(student).record())
168 .set("tags", tags)182 .set("tags", tags)
src/domain/meal_booking.rsmodified+114 -19
@@ -31,9 +31,10 @@
31 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};31 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
32 32
33 use crate::constant::{33 use crate::constant::{
34- CAS_UPDATE_RETRIES, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD,34+ CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD,
35+ MENU_VERSION_FIELD,
35 };36 };
36-use crate::database::{Database, lost_the_race};37+use crate::database::{Database, backoff, lost_the_race};
37 use crate::domain::cap::{self, Claimed};38 use crate::domain::cap::{self, Claimed};
38 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};39 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
39 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot};40 use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot};
@@ -61,6 +62,21 @@ impl MealBookingId {
61 Self(RecordId::new(MEAL_BOOKING_TABLE, key))62 Self(RecordId::new(MEAL_BOOKING_TABLE, key))
62 }63 }
63 64
65+ /// Who the seat is for, read straight back off the key: [`Self::composite`]
66+ /// joins with `_` and a ULID user key carries none, so the last segment is
67+ /// always the student (a slot name may well hold one, and the menu half is
68+ /// in front). `None` for a key no `composite` ever minted.
69+ ///
70+ /// This is what lets a cancel decide *whose* seat it is asked to free
71+ /// before reading the row — the id is fully derivable from a menu and a
72+ /// user id, both readable by a teacher, so a 403-or-404 answered off the
73+ /// row is an existence oracle for the manager-only booking list.
74+ pub fn student(&self) -> Option<UserId> {
75+ self.key()
76+ .rsplit_once('_')
77+ .map(|(_, student)| UserId::from_key(student))
78+ }
79+
64 pub fn record(&self) -> RecordId {80 pub fn record(&self) -> RecordId {
65 self.0.clone()81 self.0.clone()
66 }82 }
@@ -181,7 +197,8 @@ impl MealBooking {
181 ) -> Result<MealBooking, AppError> {197 ) -> Result<MealBooking, AppError> {
182 let id = MealBookingId::composite(menu, student);198 let id = MealBookingId::composite(menu, student);
183 let seats = menu.record();199 let seats = menu.record();
184- for _ in 0..CAS_UPDATE_RETRIES {200+ for attempt in 0..CAP_WRITE_TRIES {
201+ backoff(attempt).await;
185 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;202 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
186 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;203 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
187 let existing: Option<MealBooking> = db.select(id.record()).await?;204 let existing: Option<MealBooking> = db.select(id.record()).await?;
@@ -200,23 +217,50 @@ impl MealBooking {
200 .filter(|row| row.status == MealBookingStatus::Booked)217 .filter(|row| row.status == MealBookingStatus::Booked)
201 {218 {
202 MealLedger::charge_booking(&held, booked_by, db).await?;219 MealLedger::charge_booking(&held, booked_by, db).await?;
203- return Ok(held);220+ // Answered off a re-read, never off the row read a round trip
221+ // ago: a cancel committing in that gap has freed the seat,
222+ // given the money back and left the row `cancelled`, and
223+ // returning `held` then reports a seat — `"status": "booked"`,
224+ // `cancelled_at: null` — the store does not hold. The stored
225+ // state was right all along; only the answer lied. Gone or
226+ // cancelled, the decision is simply made again, exactly as
227+ // `Claimed::Duplicate` below does, so the caller ends up with
228+ // the seat they asked for rather than a `201` about a seat
229+ // somebody already released.
230+ match Self::read(&id, db).await? {
231+ Some(live) if live.status == MealBookingStatus::Booked => return Ok(live),
232+ _ => continue,
233+ }
204 }234 }
205- // Before the seat: an unchargeable menu (dishes summing past the
206- // cap) must refuse the booking outright, never leave a
207- // booked-but-unbilled row behind.
208- let price = MealLedger::price_snapshot(menu, db).await?;
209 // The attempt is settled *here*, not by the revival's `attempt + 1`,235 // The attempt is settled *here*, not by the revival's `attempt + 1`,
210 // because the charge id is (seat, attempt) and the charge has to be236 // because the charge id is (seat, attempt) and the charge has to be
211 // built before the transaction that writes it. `existing` is either237 // built before the transaction that writes it. `existing` is either
212 // absent or cancelled — a booked row returned above.238 // absent or cancelled — a booked row returned above.
239+ let attempt = existing.as_ref().map_or(1, |prior| prior.attempt + 1);
240+ // A seat retaken without end is a ledger without end: each cycle
241+ // appends a charge and its reversal, both permanent, and every
242+ // later balance read is answered over the lot. Refused *before* the
243+ // menu is priced, so the answer is the ceiling rather than whatever
244+ // the pricing happens to say. A row already past the ceiling — an
245+ // upgrade's leftovers — is untouched by this: cancelling consults
246+ // no cap, so its seat and its money stay reachable, and only one
247+ // more revival is refused.
248+ if attempt > MAX_MEAL_BOOKING_ATTEMPTS {
249+ return Err(AppError::Conflict(
250+ "this seat has been booked and cancelled its maximum number of times",
251+ ));
252+ }
253+ // Before the seat: an unchargeable menu (dishes summing past the
254+ // cap) must refuse the booking outright, never leave a
255+ // booked-but-unbilled row behind.
256+ let price = MealLedger::price_snapshot(menu, db).await?;
213 let fresh_row = MealBooking {257 let fresh_row = MealBooking {
214 id: id.clone(),258 id: id.clone(),
215 menu: menu.clone(),259 menu: menu.clone(),
216 student: student.clone(),260 student: student.clone(),
217 booked_by: booked_by.clone(),261 booked_by: booked_by.clone(),
218 status: MealBookingStatus::Booked,262 status: MealBookingStatus::Booked,
219- attempt: existing.map_or(1, |prior| prior.attempt + 1),263+ attempt,
220 price_minor: price,264 price_minor: price,
221 cancelled_at: None,265 cancelled_at: None,
222 created_at: Timestamp::now(),266 created_at: Timestamp::now(),
@@ -329,7 +373,16 @@ impl MealBooking {
329 RETURN SELECT * FROM ONLY $id;373 RETURN SELECT * FROM ONLY $id;
330 COMMIT TRANSACTION;"374 COMMIT TRANSACTION;"
331 );375 );
332- for _ in 0..CAS_UPDATE_RETRIES {376+ // Every booking on one menu contends on that menu's single counter row,
377+ // which is one HTTP burst of racers on a single parent — the case
378+ // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no
379+ // backoff just re-synchronized them and 409'd the fourth student.
380+ // Admissible: a lost round aborts the whole transaction (nothing
381+ // written, no seat, no charge), and the two `CREATE`s that could
382+ // legitimately answer "already exists" are read as `Claimed::Duplicate`
383+ // below *before* the conflict check, so no decision is ever re-asked.
384+ for attempt in 0..CAP_WRITE_TRIES {
385+ backoff(attempt).await;
333 let query = db386 let query = db
334 .query(sql.as_str())387 .query(sql.as_str())
335 .bind(("menu", seats.clone()))388 .bind(("menu", seats.clone()))
@@ -522,7 +575,14 @@ impl MealBooking {
522 // Slots count BEGIN, the LET, the seat UPDATE and — when there is money575 // Slots count BEGIN, the LET, the seat UPDATE and — when there is money
523 // to give back — the IF.576 // to give back — the IF.
524 let returned = if refund.is_some() { 4 } else { 3 };577 let returned = if refund.is_some() { 4 } else { 3 };
525- for _ in 0..CAS_UPDATE_RETRIES {578+ // Same burst on the same counter as the book side, so the same patience
579+ // (see [`Self::claim_and_place`]) — a cancel that gave up left the seat
580+ // held with the charge standing. Admissible: the round aborts having
581+ // written nothing, and a re-send finds the row already `cancelled`, so
582+ // the flip matches nothing, the counter moves nothing and the guarded
583+ // reversal — keyed to (seat, attempt) — is not written twice.
584+ for attempt in 0..CAP_WRITE_TRIES {
585+ backoff(attempt).await;
526 let attempted = async {586 let attempted = async {
527 let query = db587 let query = db
528 .query(format!(588 .query(format!(
@@ -650,10 +710,11 @@ impl MealCutoff {
650 /// The instant the meal is served: midnight UTC of `date` plus the slot's710 /// The instant the meal is served: midnight UTC of `date` plus the slot's
651 /// `serving_minute`. `date` is text with no timezone (see [`MenuDate`]) and the711 /// `serving_minute`. `date` is text with no timezone (see [`MenuDate`]) and the
652 /// backend deliberately stores no school timezone, so the serving time is UTC712 /// backend deliberately stores no school timezone, so the serving time is UTC
653-/// too — a UTC+3 school enters 09:00 for a noon lunch. A slot with no serving713+/// too — a UTC+3 school enters 09:00 for a noon lunch.
654-/// time falls back to midnight UTC, exactly what every booking used before the714+///
655-/// field existed; refusing the booking instead would take the canteen offline715+/// `None` for a date no day can be parsed out of, which is the only thing
656-/// on an upgrade.716+/// [`check_cutoff`] uses the midnight case for: a slot with no serving minute
717+/// gets **no deadline at all** there, never a deadline counted from midnight.
657 fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp> {718 fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp> {
658 let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?;719 let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?;
659 Some(Timestamp::from_millis(720 Some(Timestamp::from_millis(
@@ -665,6 +726,18 @@ fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp>
665 /// Booking and cancelling both close `cutoff.minutes` before the meal is726 /// Booking and cancelling both close `cutoff.minutes` before the meal is
666 /// served. `None` = the school set no cutoff, so neither ever closes.727 /// served. `None` = the school set no cutoff, so neither ever closes.
667 ///728 ///
729+/// **A slot with no `serving_minute` closes nothing either.** There is no
730+/// instant to count the deadline back from, and counting from midnight UTC —
731+/// as this did — put the deadline of every same-day menu in the past the
732+/// moment a school set `meal_cancel_cutoff_minutes`: today's lunch could not be
733+/// booked (`409`), and the seats already held could not be cancelled by the
734+/// students and parents holding them, only by a manager. All three shipped
735+/// slots carry no serving minute, so setting the one cutoff knob took the
736+/// canteen offline — which is precisely what the midnight fallback was chosen
737+/// to avoid. An unset serving hour is now an unenforced cutoff: the school sets
738+/// the hour and the deadline starts binding, on menus already published too
739+/// (the slot list is read live).
740+///
668 /// A date no serving instant can be computed from **fails closed**. A menu on741 /// A date no serving instant can be computed from **fails closed**. A menu on
669 /// an impossible day (a 31st of February — refused by [`MenuDate`] now, but742 /// an impossible day (a 31st of February — refused by [`MenuDate`] now, but
670 /// rows written before that rule are still on the volume) otherwise skipped the743 /// rows written before that rule are still on the volume) otherwise skipped the
@@ -679,11 +752,19 @@ fn check_cutoff(date: &MenuDate, slot: &MenuSlot, cutoff: &MealCutoff) -> Result
679 let Some(minutes) = cutoff.minutes else {752 let Some(minutes) = cutoff.minutes else {
680 return Ok(());753 return Ok(());
681 };754 };
682- let Some(serving) = served_at(date, cutoff.serving_minute(slot)) else {755+ let serving_minute = cutoff.serving_minute(slot);
756+ // The impossible day is refused first, serving hour or not: it is a data
757+ // defect, and "the deadline binds every menu" has to stay true for the one
758+ // menu nobody meant to publish.
759+ let Some(serving) = served_at(date, serving_minute) else {
683 return Err(AppError::Conflict(760 return Err(AppError::Conflict(
684 "the menu's date is not a real calendar day, so its cutoff cannot be worked out",761 "the menu's date is not a real calendar day, so its cutoff cannot be worked out",
685 ));762 ));
686 };763 };
764+ // No serving hour, no instant to count back from, so nothing closes.
765+ if serving_minute.is_none() {
766+ return Ok(());
767+ }
687 let deadline = serving768 let deadline = serving
688 .as_millis()769 .as_millis()
689 .saturating_sub(minutes.saturating_mul(60_000));770 .saturating_sub(minutes.saturating_mul(60_000));
@@ -1210,8 +1291,22 @@ mod tests {
1210 assert!(check_cutoff(&impossible, &lunch(), &cutoff(None, Some(720))).is_ok());1291 assert!(check_cutoff(&impossible, &lunch(), &cutoff(None, Some(720))).is_ok());
1211 }1292 }
1212 1293
1294+ /// A slot with no serving hour has no instant to count a deadline back
1295+ /// from, so nothing on it ever closes. It used to count from midnight UTC
1296+ /// of the menu's day, which shut every same-day menu the moment a school
1297+ /// set the cutoff knob — and all three shipped slots carry no hour.
1298+ #[test]
1299+ fn a_slot_without_a_serving_hour_has_no_deadline() {
1300+ let past = MenuDate::try_new("2000-01-01").unwrap();
1301+ assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), None)).is_ok());
1302+ // The same menu, once the school sets the hour.
1303+ assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err());
1304+ }
1305+
1213 /// The instant the deadline counts back from: midnight UTC of the day plus1306 /// The instant the deadline counts back from: midnight UTC of the day plus
1214- /// the slot's serving minute, and midnight itself when the slot has none.1307+ /// the slot's serving minute. The `None` case still resolves to midnight,
1308+ /// but only as the date's validity probe — `check_cutoff` never counts a
1309+ /// deadline from it, which the case below pins.
1215 #[test]1310 #[test]
1216 fn serving_instant_offsets_midnight_utc() {1311 fn serving_instant_offsets_midnight_utc() {
1217 let day = MenuDate::try_new("1970-01-02").unwrap();1312 let day = MenuDate::try_new("1970-01-02").unwrap();
@@ -1221,8 +1316,8 @@ mod tests {
1221 86_400_000 + 12 * 60 * 60_0001316 86_400_000 + 12 * 60 * 60_000
1222 );1317 );
1223 // A slot the school no longer lists (renamed or retired after the1318 // A slot the school no longer lists (renamed or retired after the
1224- // menu snapshotted its name) resolves to no serving time, i.e. the1319+ // menu snapshotted its name) resolves to no serving time, which
1225- // midnight fallback rather than a refusal.1320+ // `check_cutoff` reads as no deadline at all.
1226 assert_eq!(1321 assert_eq!(
1227 cutoff(Some(60), Some(720)).serving_minute(&lunch()),1322 cutoff(Some(60), Some(720)).serving_minute(&lunch()),
1228 Some(720)1323 Some(720)
src/domain/meal_ledger.rsmodified+78 -7
@@ -547,19 +547,49 @@ impl MealLedger {
547 547
548 /// The derived balance: `credits + reversals - charges`, in minor units.548 /// The derived balance: `credits + reversals - charges`, in minor units.
549 /// Negative means the student owes the school. Never stored anywhere.549 /// Negative means the student owes the school. Never stored anywhere.
550- // ponytail: folds the student's lines in-process (a few hundred a year);550+ ///
551- // push it into a `math::sum` aggregate if a statement ever gets long.551+ /// **The sum is taken per kind by the database** and only the three totals
552+ /// come back, so a balance read costs the same whether the statement holds
553+ /// four lines or forty thousand. It used to decode and fold every line, and
554+ /// nothing bounds a statement's length but the cycle ceiling
555+ /// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS))
556+ /// added alongside this: every book/cancel
557+ /// pair appends two permanent rows, and each one was paid for again by
558+ /// every later `GET /meals/balance/*`.
559+ ///
560+ /// **The signs stay here**, applied by the very [`MealLedgerKind::sign`]
561+ /// the documented formula is spelled in. Summing `IF kind = 'charge' THEN
562+ /// -amount …` in SQL would have folded the whole balance in one statement
563+ /// and forked the one rule that decides what money means into a second
564+ /// language, where nothing would fail the day the two disagreed. Grouping
565+ /// instead keeps the aggregate ignorant of signs: it counts kinds, and
566+ /// Rust still says what a kind does. A stored running total was the third
567+ /// option and is a counter that can drift — a bug class this repo closes,
568+ /// not one it opens.
552 pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> {569 pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> {
553- Ok(Self::list_for_student(student, None, 0, db)570+ let totals: Vec<KindTotal> = db
571+ .query(format!(
572+ "SELECT kind, math::sum(amount_minor) AS total \
573+ FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind"
574+ ))
575+ .bind(("student", student.record()))
554 .await?576 .await?
555- .0577+ .check()?
578+ .take(0)?;
579+ Ok(totals
556 .iter()580 .iter()
557- .fold(0i64, |sum, line| {581+ .fold(0i64, |sum, row| sum + row.kind.sign() * row.total))
558- sum + line.kind.sign() * line.amount_minor.as_minor()
559- }))
560 }582 }
561 }583 }
562 584
585+/// One kind's whole sum, as the `GROUP BY` in [`MealLedger::balance_of`] hands
586+/// it back — at most three rows, never the lines behind them.
587+#[derive(Debug, SurrealValue)]
588+struct KindTotal {
589+ kind: MealLedgerKind,
590+ total: i64,
591+}
592+
563 #[cfg(test)]593 #[cfg(test)]
564 mod tests {594 mod tests {
565 use surrealdb::types::SurrealValue as _;595 use surrealdb::types::SurrealValue as _;
@@ -602,6 +632,47 @@ mod tests {
602 assert_eq!(balance, 10_000);632 assert_eq!(balance, 10_000);
603 }633 }
604 634
635+ /// The balance aggregate **against a real server**, and `#[ignore]`d for
636+ /// it: `init_mem`'s embedded engine is not the store this runs on, and an
637+ /// aggregate is exactly where the two are known to differ — a `count()`
638+ /// over an indexed field comes back `{count: N}` from the server and a
639+ /// bare int from memory, and `student` here *is* indexed. This asserts the
640+ /// `GROUP BY` really decodes into [`KindTotal`] and folds to the
641+ /// documented figure, per kind, scoped to one student.
642+ #[tokio::test]
643+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
644+ async fn the_balance_aggregate_decodes_on_a_real_server() {
645+ let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await;
646+ db.query(
647+ "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \
648+ amount_minor = 10000, recorded_by = user:adm, created_at = 1;
649+ CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \
650+ amount_minor = 4500, recorded_by = user:adm, created_at = 2;
651+ CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \
652+ amount_minor = 1500, recorded_by = user:adm, created_at = 3;
653+ CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \
654+ amount_minor = 4500, recorded_by = user:adm, created_at = 4;
655+ CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \
656+ amount_minor = 777, recorded_by = user:adm, created_at = 5;",
657+ )
658+ .await
659+ .unwrap()
660+ .check()
661+ .unwrap();
662+ let ali = UserId::from_key("ali");
663+ assert_eq!(
664+ MealLedger::balance_of(&ali, &db).await.unwrap(),
665+ 10_000 - 4_500 - 1_500 + 4_500
666+ );
667+ // Somebody with no lines at all: no groups come back, not an error.
668+ assert_eq!(
669+ MealLedger::balance_of(&UserId::from_key("nobody"), &db)
670+ .await
671+ .unwrap(),
672+ 0
673+ );
674+ }
675+
605 #[test]676 #[test]
606 fn an_amount_is_positive_and_capped() {677 fn an_amount_is_positive_and_capped() {
607 assert!(LedgerAmount::try_new(0).is_err());678 assert!(LedgerAmount::try_new(0).is_err());
src/domain/settings.rsmodified+5 -2
@@ -494,8 +494,11 @@ impl Settings {
494 DEFAULT_MEAL_SLOTS494 DEFAULT_MEAL_SLOTS
495 .map(|name| MealSlotDef {495 .map(|name| MealSlotDef {
496 name: name.to_string(),496 name: name.to_string(),
497- // No built-in serving time: the shipped defaults keep the497+ // No built-in serving time, and the backend will not guess
498- // midnight-UTC cutoff until a school sets real hours.498+ // one: a slot with no hour has no instant for the cutoff to
499+ // count back from, so the school's `meal_cancel_cutoff_
500+ // minutes` binds none of these slots until it sets real
501+ // hours (see `check_cutoff`).
499 serving_minute: None,502 serving_minute: None,
500 })503 })
501 .to_vec()504 .to_vec()
src/web/meals.rsmodified+32 -8
@@ -803,6 +803,12 @@ async fn booking_target(
803 /// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and803 /// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and
804 /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat804 /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat
805 /// is never handed out unbilled.805 /// is never handed out unbilled.
806+///
807+/// One seat may be taken at most `meal.max_booking_attempts` times (`GET
808+/// /limits`) — the first booking plus the re-bookings after a cancel. Past that
809+/// it is a `409`: every cycle appends a charge and its reversal, permanently, so
810+/// the ceiling bounds the student's statement rather than their mind changing.
811+/// A seat that really must move again is the canteen's to cancel.
806 #[utoipa::path(812 #[utoipa::path(
807 post,813 post,
808 path = "/menus/{id}/bookings",814 path = "/menus/{id}/bookings",
@@ -816,7 +822,7 @@ async fn booking_target(
816 (status = 401, description = "Not authenticated", body = ErrorResponse),822 (status = 401, description = "Not authenticated", body = ErrorResponse),
817 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),823 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
818 (status = 404, description = "No such menu", body = ErrorResponse),824 (status = 404, description = "No such menu", body = ErrorResponse),
819- (status = 409, description = "The menu is full, its cutoff has passed, its date is not a real calendar day so no cutoff can be worked out, or the menu kept being edited while the seat was being taken", body = ErrorResponse),825+ (status = 409, description = "The menu is full, its cutoff has passed, its date is not a real calendar day so no cutoff can be worked out, the seat has been booked and cancelled its maximum number of times, or the menu kept being edited while the seat was being taken", body = ErrorResponse),
820 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),826 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
821 ),827 ),
822 )]828 )]
@@ -933,6 +939,12 @@ async fn list_menu_bookings(
933 /// ever releases the attempt this call read, so the newer seat — one this API939 /// ever releases the attempt this call read, so the newer seat — one this API
934 /// answered `201` for and nobody here asked to free — is left alone. Send the940 /// answered `201` for and nobody here asked to free — is left alone. Send the
935 /// call again to cancel the seat as it now stands.941 /// call again to cancel the seat as it now stands.
942+///
943+/// **Who is asking is decided before the seat is looked up**, so an unauthorised
944+/// caller gets the same `403` whether or not the booking exists. Booking ids are
945+/// derivable (`{date}_{slot}_{student}`), and a `404` here would otherwise
946+/// answer "did this student book this meal?" — the manager-only list at
947+/// `GET /meals/menus/{id}/bookings`, one student at a time.
936 #[utoipa::path(948 #[utoipa::path(
937 delete,949 delete,
938 path = "/bookings/{bid}",950 path = "/bookings/{bid}",
@@ -942,8 +954,8 @@ async fn list_menu_bookings(
942 responses(954 responses(
943 (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse),955 (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse),
944 (status = 401, description = "Not authenticated", body = ErrorResponse),956 (status = 401, description = "Not authenticated", body = ErrorResponse),
945- (status = 403, description = "Not the booking's student, their parent, nor a manager", body = ErrorResponse),957+ (status = 403, description = "Not the booking's student, their parent, nor a manager — answered before the booking is read, so it is also what an unauthorised caller gets for a booking that does not exist", body = ErrorResponse),
946- (status = 404, description = "Not found", body = ErrorResponse),958+ (status = 404, description = "Not found (only for a caller who may cancel it)", body = ErrorResponse),
947 (status = 409, description = "The cutoff has passed (students and parents only), the menu's date is not a real calendar day so no cutoff can be worked out, the seat was booked again while this call ran, or the menu was too contended to free the seat", body = ErrorResponse),959 (status = 409, description = "The cutoff has passed (students and parents only), the menu's date is not a real calendar day so no cutoff can be worked out, the seat was booked again while this call ran, or the menu was too contended to free the seat", body = ErrorResponse),
948 ),960 ),
949 )]961 )]
@@ -952,9 +964,7 @@ async fn cancel_booking(
952 CurrentUser(user): CurrentUser,964 CurrentUser(user): CurrentUser,
953 Path(bid): Path<String>,965 Path(bid): Path<String>,
954 ) -> Result<Json<BookingResponse>, AppError> {966 ) -> Result<Json<BookingResponse>, AppError> {
955- let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db)967+ let id = MealBookingId::from_key(&bid);
956- .await?
957- .ok_or(AppError::NotFound)?;
958 // Manager+ may give back *any* seat. Not a convenience: `booking_target`968 // Manager+ may give back *any* seat. Not a convenience: `booking_target`
959 // grants only students and parents, so a student promoted to staff (or a969 // grants only students and parents, so a student promoted to staff (or a
960 // parent unlinked) left a live seat nobody on the API could cancel — the970 // parent unlinked) left a live seat nobody on the API could cancel — the
@@ -964,9 +974,20 @@ async fn cancel_booking(
964 // effect of a role change.974 // effect of a role change.
965 let staff = user.get_role().at_least(Role::Manager);975 let staff = user.get_role().at_least(Role::Manager);
966 if !staff {976 if !staff {
977+ // Decided off the *id*, before the row is read: the id is
978+ // `{date}_{slot}_{student}`, and a teacher may list both the menus and
979+ // the users, so authorising after the read answered 403 for a seat that
980+ // exists and 404 for one that does not — an existence oracle around the
981+ // deliberate manager+ gate on `GET /menus/{id}/bookings`, and one any
982+ // peer holding a user id could work too. An unauthorised caller now
983+ // gets the same 403 either way, and learns nothing.
984+ //
967 // Same door as booking: whoever may take the seat may give it back.985 // Same door as booking: whoever may take the seat may give it back.
968- let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?;986+ let student = id
969- if &target != booking.get_student() {987+ .student()
988+ .ok_or(AppError::Forbidden("not your booking"))?;
989+ let target = booking_target(&user, Some(student.key()), &st.db).await?;
990+ if target != student {
970 return Err(AppError::Forbidden("not your booking"));991 return Err(AppError::Forbidden("not your booking"));
971 }992 }
972 }993 }
@@ -983,6 +1004,9 @@ async fn cancel_booking(
983 };1004 };
984 // Flips the row and appends the reversal for that attempt's charge in one1005 // Flips the row and appends the reversal for that attempt's charge in one
985 // transaction; the charge itself stays.1006 // transaction; the charge itself stays.
1007+ let booking = MealBooking::read(&id, &st.db)
1008+ .await?
1009+ .ok_or(AppError::NotFound)?;
986 let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;1010 let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;
987 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;1011 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
988 Ok(Json(1012 Ok(Json(
src/web/settings.rsmodified+4 -2
@@ -200,8 +200,10 @@ struct UpdateSettings {
200 #[schema(max_items = 20)]200 #[schema(max_items = 20)]
201 dietary_tags: Option<Vec<String>>,201 dietary_tags: Option<Vec<String>>,
202 /// Minutes before a slot's `serving_minute` at which booking *and*202 /// Minutes before a slot's `serving_minute` at which booking *and*
203- /// cancelling close, `0`–`10080` (one week). A slot with no serving time203+ /// cancelling close, `0`–`10080` (one week). It binds only the slots that
204- /// is measured from midnight UTC of the menu's date instead. Omit to keep the current value; send `null` for204+ /// carry a `serving_minute`: with no serving hour there is no instant to
205+ /// count back from, so that slot's menus close at no deadline until the
206+ /// hour is set. Omit to keep the current value; send `null` for
205 /// no cutoff at all.207 /// no cutoff at all.
206 #[serde(default, deserialize_with = "set_or_clear")]208 #[serde(default, deserialize_with = "set_or_clear")]
207 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]209 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
tests/integration.rsmodified+28 -16
@@ -21769,12 +21769,18 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
21769 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);21769 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21770 let booking = id_of(&res.body);21770 let booking = id_of(&res.body);
21771 21771
21772+ // The serving hour goes with the knob: a slot without one has no instant
21773+ // for the deadline to count back from, so the cutoff binds none of its
21774+ // menus (see `meal_cutoff_counts_back_from_the_slots_serving_time`).
21772 let res = send(21775 let res = send(
21773 &app,21776 &app,
21774 "PATCH",21777 "PATCH",
21775 "/settings",21778 "/settings",
21776 Some(&mgr),21779 Some(&mgr),
21777- Some(json!({ "meal_cancel_cutoff_minutes": 60 })),21780+ Some(json!({
21781+ "meal_cancel_cutoff_minutes": 60,
21782+ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }],
21783+ })),
21778 )21784 )
21779 .await;21785 .await;
21780 assert_eq!(res.status, StatusCode::OK, "{}", res.body);21786 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -21826,8 +21832,10 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
21826 /// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already21832 /// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already
21827 /// inside it. Under the old midnight rule the seat is shut; measured from the21833 /// inside it. Under the old midnight rule the seat is shut; measured from the
21828 /// serving time it is open for another ~24 hours. Then, with no serving time on21834 /// serving time it is open for another ~24 hours. Then, with no serving time on
21829-/// the slot, the very same menu falls back to midnight and shuts — the upgrade21835+/// the slot, the very same menu closes at **nothing at all**: there is no
21830-/// path for every slot written before the field existed.21836+/// instant left to count the deadline back from, and counting from midnight —
21837+/// as this did — shut every same-day menu of a school that had set the cutoff
21838+/// knob without serving hours, which is how all three slots ship.
21831 #[tokio::test]21839 #[tokio::test]
21832 async fn meal_cutoff_counts_back_from_the_slots_serving_time() {21840 async fn meal_cutoff_counts_back_from_the_slots_serving_time() {
21833 let (app, db) = app_and_db().await;21841 let (app, db) = app_and_db().await;
@@ -21886,9 +21894,11 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() {
21886 );21894 );
21887 let booking = id_of(&res.body);21895 let booking = id_of(&res.body);
21888 21896
21889- // Drop the serving time from the same slot: the deadline snaps back to21897+ // Drop the serving time from the same slot: there is now no instant to
21890- // midnight of the menu's date, which the cutoff already covers. The slot21898+ // count the deadline back from, so this menu closes at nothing — it does
21891- // list is read live, so the menu published under it moves with it.21899+ // *not* snap back to midnight, which used to shut the canteen of every
21900+ // school that set the cutoff without setting hours. The slot list is read
21901+ // live, so the menu published under it moves with the edit.
21892 let res = send(21902 let res = send(
21893 &app,21903 &app,
21894 "PATCH",21904 "PATCH",
@@ -21916,11 +21926,12 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() {
21916 .await;21926 .await;
21917 assert_eq!(21927 assert_eq!(
21918 res.status,21928 res.status,
21919- StatusCode::CONFLICT,21929+ StatusCode::CREATED,
21920- "with no serving time the cutoff falls back to midnight UTC: {}",21930+ "an unset serving hour is an unenforced cutoff: {}",
21921 res.body21931 res.body
21922 );21932 );
21923- // Cancelling is closed by the same fallback deadline...21933+ // …and the student holding a seat can still give it back themselves,
21934+ // which the midnight fallback took away from them.
21924 let res = send(21935 let res = send(
21925 &app,21936 &app,
21926 "DELETE",21937 "DELETE",
@@ -21929,27 +21940,28 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() {
21929 None,21940 None,
21930 )21941 )
21931 .await;21942 .await;
21932- assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);21943+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21933 21944
21934- // ...and re-serving lunch at 23:59 opens both ends again.21945+ // Serving lunch at midnight instead makes the same cutoff bite: the
21946+ // deadline is that instant minus the cutoff, which is already past.
21935 let res = send(21947 let res = send(
21936 &app,21948 &app,
21937 "PATCH",21949 "PATCH",
21938 "/settings",21950 "/settings",
21939 Some(&mgr),21951 Some(&mgr),
21940- Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }] })),21952+ Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 0 }] })),
21941 )21953 )
21942 .await;21954 .await;
21943 assert_eq!(res.status, StatusCode::OK, "{}", res.body);21955 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21944 let res = send(21956 let res = send(
21945 &app,21957 &app,
21946- "DELETE",21958+ "POST",
21947- &format!("/meals/bookings/{booking}"),21959+ &format!("/meals/menus/{menu}/bookings"),
21948 Some(&ali),21960 Some(&ali),
21949- None,21961+ Some(json!({})),
21950 )21962 )
21951 .await;21963 .await;
21952- assert_eq!(res.status, StatusCode::OK, "{}", res.body);21964+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
21953 }21965 }
21954 21966
21955 /// Who may take a seat: the student it is for, or a parent holding a link to21967 /// Who may take a seat: the student it is for, or a parent holding a link to
tests/regress_meals.rsmodified+540 -2
@@ -44,6 +44,20 @@ async fn add_dish(app: &axum::Router, mgr: &str, menu: &str, price: i64) -> Stri
44 id_of(&res.body)44 id_of(&res.body)
45 }45 }
46 46
47+/// One student's balance as the API answers it.
48+async fn balance_of(app: &axum::Router, cookie: &str, student: &str) -> i64 {
49+ let res = send(
50+ app,
51+ "GET",
52+ &format!("/meals/balance/{student}"),
53+ Some(cookie),
54+ None,
55+ )
56+ .await;
57+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
58+ res.body["balance_minor"].as_i64().expect("a balance")
59+}
60+
47 /// A repeat `POST` of a seat the student already holds must replay that seat,61 /// A repeat `POST` of a seat the student already holds must replay that seat,
48 /// whatever the menu costs *now*. Pricing the menu before the already-booked62 /// whatever the menu costs *now*. Pricing the menu before the already-booked
49 /// short circuit made it a `400` ("amount_minor must be between…") the moment63 /// short circuit made it a `400` ("amount_minor must be between…") the moment
@@ -642,13 +656,18 @@ async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() {
642 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);656 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
643 let booking = id_of(&res.body);657 let booking = id_of(&res.body);
644 658
645- // The school sets a deadline, and it closed on this menu long ago.659+ // The school sets a deadline, and it closed on this menu long ago. The
660+ // serving hour goes with it: a slot without one has no instant for the
661+ // deadline to count back from, so the cutoff would bind nobody.
646 let res = send(662 let res = send(
647 &app,663 &app,
648 "PATCH",664 "PATCH",
649 "/settings",665 "/settings",
650 Some(&admin),666 Some(&admin),
651- Some(json!({ "meal_cancel_cutoff_minutes": 60 })),667+ Some(json!({
668+ "meal_cancel_cutoff_minutes": 60,
669+ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }],
670+ })),
652 )671 )
653 .await;672 .await;
654 assert_eq!(res.status, StatusCode::OK, "{}", res.body);673 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -759,3 +778,522 @@ async fn only_manager_reads_another_students_meal_money() {
759 );778 );
760 }779 }
761 }780 }
781+
782+/// A booking id is fully derivable — `{date}_{slot}_{student}` — and both
783+/// halves are readable by any teacher (`GET /users`, `GET /meals/menus`). The
784+/// cancel read the row before it checked who was asking, so the status code
785+/// answered a question the route never meant to: `403` for a seat that exists,
786+/// `404` for one that does not. That is the whole-school booking list, whose
787+/// own route is deliberately manager+, handed out one student at a time — and
788+/// any peer holding a user id (every `PersonRef` carries one) could ask it too.
789+#[tokio::test]
790+async fn an_unauthorised_cancel_tells_nobody_whether_the_seat_exists() {
791+ let (app, db) = app_and_db().await;
792+ let mgr = login_as(&app, &db, "oracle_mgr", "manager").await;
793+ let teacher = login_as(&app, &db, "oracle_teacher", "teacher").await;
794+ let ali = login(&app, "oracle_ali").await;
795+ let veli = login(&app, "oracle_veli").await;
796+ let veli_id = me_id(&app, &veli).await;
797+ let can_id = me_id(&app, &login(&app, "oracle_can").await).await;
798+ let menu = publish(&app, &mgr, "2026-09-19").await;
799+
800+ let res = send(
801+ &app,
802+ "POST",
803+ &format!("/meals/menus/{menu}/bookings"),
804+ Some(&ali),
805+ Some(json!({})),
806+ )
807+ .await;
808+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
809+ let booked = id_of(&res.body);
810+ // Never booked, and derived exactly as the seat that was: the menu key
811+ // joined to a student key anyone can read off a response.
812+ let never = format!("{menu}_{can_id}");
813+
814+ for (who, cookie) in [("a teacher", &teacher), ("a peer student", &veli)] {
815+ let held = send(
816+ &app,
817+ "DELETE",
818+ &format!("/meals/bookings/{booked}"),
819+ Some(cookie),
820+ None,
821+ )
822+ .await;
823+ let absent = send(
824+ &app,
825+ "DELETE",
826+ &format!("/meals/bookings/{never}"),
827+ Some(cookie),
828+ None,
829+ )
830+ .await;
831+ assert_eq!(
832+ held.status, absent.status,
833+ "{who} can tell a held seat from an unbooked one: {} vs {}",
834+ held.body, absent.body
835+ );
836+ assert_eq!(held.status, StatusCode::FORBIDDEN, "{}", held.body);
837+ }
838+
839+ // The gate did not turn into a blanket 403: the student it is for still
840+ // learns their own seat is gone, and still cancels the one they hold.
841+ let res = send(
842+ &app,
843+ "DELETE",
844+ &format!("/meals/bookings/{menu}_{veli_id}"),
845+ Some(&veli),
846+ None,
847+ )
848+ .await;
849+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
850+ let res = send(
851+ &app,
852+ "DELETE",
853+ &format!("/meals/bookings/{booked}"),
854+ Some(&ali),
855+ None,
856+ )
857+ .await;
858+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
859+ assert_eq!(res.body["status"], "cancelled", "{}", res.body);
860+ // …and manager+, who may read the whole list anyway, still sees existence.
861+ let res = send(
862+ &app,
863+ "DELETE",
864+ &format!("/meals/bookings/{never}"),
865+ Some(&mgr),
866+ None,
867+ )
868+ .await;
869+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
870+}
871+
872+/// Two first `PATCH`es of a profile nobody ever recorded both read "no row" and
873+/// both tried to `CREATE` it. The loser's create collided (on the id, and on
874+/// the `dietary_profile_student` UNIQUE index behind it) and propagated as a
875+/// `500` on a perfectly legitimate request. The winner's row is now written
876+/// over instead, which is what the second `PATCH` was asking for anyway.
877+#[tokio::test]
878+async fn two_first_profile_writes_land_without_a_500() {
879+ let (app, db) = app_and_db().await;
880+ let mgr = login_as(&app, &db, "first_mgr", "manager").await;
881+ let ali = login(&app, "first_ali").await;
882+ let ali_id = me_id(&app, &ali).await;
883+
884+ let route = format!("/meals/profiles/{ali_id}");
885+ let (one, two) = tokio::join!(
886+ send(
887+ &app,
888+ "PATCH",
889+ &route,
890+ Some(&mgr),
891+ Some(json!({ "tags": ["vegan"] })),
892+ ),
893+ send(
894+ &app,
895+ "PATCH",
896+ &route,
897+ Some(&mgr),
898+ Some(json!({ "note": "fındık" })),
899+ ),
900+ );
901+ for res in [&one, &two] {
902+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
903+ }
904+
905+ // Stored state, never a reported win: whichever landed second, the row
906+ // carries both writes — neither was dropped and neither 500'd.
907+ let res = send(&app, "GET", &route, Some(&mgr), None).await;
908+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
909+ assert_eq!(res.body["tags"], json!(["vegan"]), "{}", res.body);
910+ assert_eq!(res.body["note"], "fındık", "{}", res.body);
911+}
912+
913+/// A repeat `POST` of a held seat answered off the row it read a round trip
914+/// earlier. A cancel committing in that gap frees the seat, refunds it and
915+/// leaves the row `cancelled` — and the `201` still said `"status": "booked"`,
916+/// `cancelled_at: null`, so a client trusting the answer thought it held a seat
917+/// the store had given away. The stored state was right throughout; only the
918+/// answer lied.
919+///
920+/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT`
921+/// fires inside the very write the replay makes — here the charge it replays,
922+/// which is why the ledger is stripped first (a charge already there is a
923+/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not
924+/// trip it a second time.
925+#[tokio::test]
926+async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
927+ let (app, db) = app_and_db().await;
928+ let mgr = login_as(&app, &db, "stale_mgr", "manager").await;
929+ let ali = login(&app, "stale_ali").await;
930+ let menu = publish(&app, &mgr, "2026-09-20").await;
931+ add_dish(&app, &mgr, &menu, 1_000).await;
932+
933+ let res = send(
934+ &app,
935+ "POST",
936+ &format!("/meals/menus/{menu}/bookings"),
937+ Some(&ali),
938+ Some(json!({})),
939+ )
940+ .await;
941+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
942+ let booking = id_of(&res.body);
943+
944+ db.query(format!(
945+ "DELETE meal_ledger;
946+ DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{
947+ UPDATE type::record('meal_booking', '{booking}') \
948+ SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1;
949+ }};"
950+ ))
951+ .await
952+ .unwrap()
953+ .check()
954+ .unwrap();
955+
956+ let res = send(
957+ &app,
958+ "POST",
959+ &format!("/meals/menus/{menu}/bookings"),
960+ Some(&ali),
961+ Some(json!({})),
962+ )
963+ .await;
964+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
965+
966+ // The answer against the store, field by field — that is the whole claim.
967+ let stored = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await;
968+ let row = &stored.body["items"][0];
969+ assert_eq!(row["id"], json!(booking), "{}", stored.body);
970+ assert_eq!(
971+ res.body["status"], row["status"],
972+ "the answer disagrees with the row: {} vs {}",
973+ res.body, stored.body
974+ );
975+ assert_eq!(
976+ res.body["cancelled_at"], row["cancelled_at"],
977+ "the answer disagrees with the row: {} vs {}",
978+ res.body, stored.body
979+ );
980+ assert_eq!(res.body["status"], "booked", "{}", res.body);
981+}
982+
983+/// A slot with **no serving hour** has no instant for a deadline to count back
984+/// from, and the code counted from midnight UTC instead. All three shipped
985+/// slots carry no serving minute, so the day a school set
986+/// `meal_cancel_cutoff_minutes` — the one knob — every same-day menu was
987+/// already past its deadline: today's lunch could not be booked, and the seats
988+/// already held could not be given back by the students and parents holding
989+/// them, only by a manager. The fallback was chosen to keep the canteen up on
990+/// an upgrade and did the opposite. An unset hour is now an unenforced cutoff.
991+///
992+/// The existing unit test never caught it because it only ever passed a slot
993+/// *with* an hour, and the `None` case was exercised against an impossible
994+/// date, where the refusal comes from the date instead.
995+#[tokio::test]
996+async fn a_slot_with_no_serving_hour_closes_nothing() {
997+ let (app, db) = app_and_db().await;
998+ let admin = login_as(&app, &db, "hour_adm", "admin").await;
999+ let mgr = login_as(&app, &db, "hour_mgr", "manager").await;
1000+ let ali = login(&app, "hour_ali").await;
1001+
1002+ // The school sets its one cutoff knob and nothing else — the shipped
1003+ // slots still carry no `serving_minute`, which is the whole case.
1004+ let res = send(
1005+ &app,
1006+ "PATCH",
1007+ "/settings",
1008+ Some(&admin),
1009+ Some(json!({ "meal_cancel_cutoff_minutes": 120 })),
1010+ )
1011+ .await;
1012+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1013+ assert!(
1014+ res.body["meal_slots"]
1015+ .as_array()
1016+ .unwrap()
1017+ .iter()
1018+ .all(|slot| slot["serving_minute"].is_null()),
1019+ "the case only exists while no slot has an hour: {}",
1020+ res.body
1021+ );
1022+
1023+ // Today's menu: midnight UTC is behind us for all but the first two hours
1024+ // of the day, so the fallback deadline had already passed.
1025+ let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc()
1026+ .format("%Y-%m-%d")
1027+ .to_string();
1028+ let menu = publish(&app, &mgr, &today).await;
1029+ add_dish(&app, &mgr, &menu, 1_000).await;
1030+
1031+ let res = send(
1032+ &app,
1033+ "POST",
1034+ &format!("/meals/menus/{menu}/bookings"),
1035+ Some(&ali),
1036+ Some(json!({})),
1037+ )
1038+ .await;
1039+ assert_eq!(
1040+ res.status,
1041+ StatusCode::CREATED,
1042+ "today's menu must still be bookable: {}",
1043+ res.body
1044+ );
1045+ let booking = id_of(&res.body);
1046+
1047+ // …and the student can still free the seat themselves. This half is worse
1048+ // than the refusal: the seat was already held and only a manager could
1049+ // give it back.
1050+ let res = send(
1051+ &app,
1052+ "DELETE",
1053+ &format!("/meals/bookings/{booking}"),
1054+ Some(&ali),
1055+ None,
1056+ )
1057+ .await;
1058+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1059+ assert_eq!(res.body["status"], "cancelled", "{}", res.body);
1060+
1061+ // The deadline starts binding the moment the school sets the hour — on
1062+ // menus already published, since the slot list is read live. Midnight UTC
1063+ // plus two hours, minus a two-hour cutoff, is midnight: long past.
1064+ let res = send(
1065+ &app,
1066+ "PATCH",
1067+ "/settings",
1068+ Some(&admin),
1069+ Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 120 }] })),
1070+ )
1071+ .await;
1072+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1073+ let res = send(
1074+ &app,
1075+ "POST",
1076+ &format!("/meals/menus/{menu}/bookings"),
1077+ Some(&ali),
1078+ Some(json!({})),
1079+ )
1080+ .await;
1081+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1082+}
1083+
1084+/// Nothing bounded how often one seat could be retaken, and every cycle
1085+/// appends two permanent, undeletable ledger lines (the charge and its
1086+/// reversal). At the API's own request ceiling that is hundreds of thousands
1087+/// of rows a day against one account — and every later balance read used to
1088+/// fold the lot. The cycle ceiling is the growth half of that fix.
1089+#[tokio::test]
1090+async fn a_seat_cannot_be_retaken_without_end() {
1091+ let (app, db) = app_and_db().await;
1092+ let mgr = login_as(&app, &db, "cycle_mgr", "manager").await;
1093+ let ali = login(&app, "cycle_ali").await;
1094+ let ali_id = me_id(&app, &ali).await;
1095+ let menu = publish(&app, &mgr, "2026-09-21").await;
1096+ add_dish(&app, &mgr, &menu, 1_000).await;
1097+
1098+ // `max_booking_attempts` is published, so a client can say why before it
1099+ // sends the call that fails.
1100+ let limits = send(&app, "GET", "/limits", Some(&ali), None).await;
1101+ let ceiling = limits.body["meal"]["max_booking_attempts"]
1102+ .as_i64()
1103+ .unwrap_or_else(|| panic!("the ceiling is not published: {}", limits.body));
1104+
1105+ let seats = format!("/meals/menus/{menu}/bookings");
1106+ for round in 1..=ceiling {
1107+ let res = send(&app, "POST", &seats, Some(&ali), Some(json!({}))).await;
1108+ assert_eq!(
1109+ res.status,
1110+ StatusCode::CREATED,
1111+ "round {round}: {}",
1112+ res.body
1113+ );
1114+ let res = send(
1115+ &app,
1116+ "DELETE",
1117+ &format!("/meals/bookings/{}", id_of(&res.body)),
1118+ Some(&ali),
1119+ None,
1120+ )
1121+ .await;
1122+ assert_eq!(res.status, StatusCode::OK, "round {round}: {}", res.body);
1123+ }
1124+ let res = send(&app, "POST", &seats, Some(&ali), Some(json!({}))).await;
1125+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
1126+ assert!(
1127+ res.body["error"].as_str().unwrap().contains("maximum"),
1128+ "the refusal must say what happened: {}",
1129+ res.body
1130+ );
1131+
1132+ // Stored state: the seat stayed cancelled, and the refusal wrote no line —
1133+ // ten cycles, twenty lines, and the balance nets to zero.
1134+ let res = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await;
1135+ assert_eq!(res.body["items"][0]["status"], "cancelled", "{}", res.body);
1136+ let res = send(
1137+ &app,
1138+ "GET",
1139+ &format!("/meals/ledger/{ali_id}"),
1140+ Some(&mgr),
1141+ None,
1142+ )
1143+ .await;
1144+ assert_eq!(res.body["total"], ceiling * 2, "{}", res.body);
1145+ let res = send(
1146+ &app,
1147+ "GET",
1148+ &format!("/meals/balance/{ali_id}"),
1149+ Some(&mgr),
1150+ None,
1151+ )
1152+ .await;
1153+ assert_eq!(res.body["balance_minor"], 0, "{}", res.body);
1154+}
1155+
1156+/// The balance is summed **per kind by the database** now, not folded line by
1157+/// line in this process — the reason the ledger's length stopped being a cost
1158+/// on every read. What must not change with it is the answer: `credits +
1159+/// reversals - charges`, with the signs still applied by `MealLedgerKind::sign`
1160+/// rather than respelled in SQL.
1161+#[tokio::test]
1162+async fn the_balance_sums_every_kind_the_same_way_it_always_did() {
1163+ let (app, db) = app_and_db().await;
1164+ let admin = login_as(&app, &db, "sum_adm", "admin").await;
1165+ let mgr = login_as(&app, &db, "sum_mgr", "manager").await;
1166+ let ali = login(&app, "sum_ali").await;
1167+ let ali_id = me_id(&app, &ali).await;
1168+
1169+ // Nothing at all: no rows, so the aggregate returns no groups.
1170+ assert_eq!(balance_of(&app, &mgr, &ali_id).await, 0);
1171+
1172+ // A credit, then two charges on different menus, then one reversal — every
1173+ // kind, and more than one line in two of the three groups.
1174+ let res = send(
1175+ &app,
1176+ "POST",
1177+ "/meals/credits",
1178+ Some(&admin),
1179+ Some(json!({ "student_id": ali_id, "amount_minor": 10_000 })),
1180+ )
1181+ .await;
1182+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1183+ assert_eq!(balance_of(&app, &mgr, &ali_id).await, 10_000);
1184+
1185+ let mut bookings = Vec::new();
1186+ for (day, price) in [("2026-09-23", 4_500), ("2026-09-24", 1_500)] {
1187+ let menu = publish(&app, &mgr, day).await;
1188+ add_dish(&app, &mgr, &menu, price).await;
1189+ let res = send(
1190+ &app,
1191+ "POST",
1192+ &format!("/meals/menus/{menu}/bookings"),
1193+ Some(&ali),
1194+ Some(json!({})),
1195+ )
1196+ .await;
1197+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1198+ bookings.push(id_of(&res.body));
1199+ }
1200+ assert_eq!(
1201+ balance_of(&app, &mgr, &ali_id).await,
1202+ 10_000 - 4_500 - 1_500
1203+ );
1204+
1205+ let res = send(
1206+ &app,
1207+ "DELETE",
1208+ &format!("/meals/bookings/{}", bookings[0]),
1209+ Some(&ali),
1210+ None,
1211+ )
1212+ .await;
1213+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1214+ assert_eq!(
1215+ balance_of(&app, &mgr, &ali_id).await,
1216+ 10_000 - 1_500,
1217+ "credit + reversal - charges"
1218+ );
1219+ // A second student's lines are somebody else's: the aggregate is scoped by
1220+ // `WHERE student = …` exactly as the fold was.
1221+ let veli = login(&app, "sum_veli").await;
1222+ let res = send(
1223+ &app,
1224+ "POST",
1225+ "/meals/credits",
1226+ Some(&admin),
1227+ Some(json!({ "student_id": me_id(&app, &veli).await, "amount_minor": 777 })),
1228+ )
1229+ .await;
1230+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1231+ assert_eq!(
1232+ balance_of(&app, &mgr, &ali_id).await,
1233+ 10_000 - 1_500,
1234+ "another student's credit leaked into this balance"
1235+ );
1236+}
1237+
1238+/// The stale-data half of the cycle ceiling: a live volume may already hold a
1239+/// seat retaken more times than the new ceiling allows. Such a row must stay
1240+/// **cancellable** — the ceiling binds the write that would add another cycle,
1241+/// nothing else. A ceiling consulted on the cancel path instead would strand
1242+/// exactly the seats it was meant to stop growing: the menu refuses its own
1243+/// delete while a seat is held, and cancelling is the only route that reverses
1244+/// a charge.
1245+#[tokio::test]
1246+async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() {
1247+ let (app, db) = app_and_db().await;
1248+ let mgr = login_as(&app, &db, "old_mgr", "manager").await;
1249+ let ali = login(&app, "old_ali").await;
1250+ // A free menu: the row is aged by hand below, and a charge keyed to an
1251+ // attempt this test never really made would only muddy what is asserted.
1252+ let menu = publish(&app, &mgr, "2026-09-25").await;
1253+ let res = send(
1254+ &app,
1255+ "POST",
1256+ &format!("/meals/menus/{menu}/bookings"),
1257+ Some(&ali),
1258+ Some(json!({})),
1259+ )
1260+ .await;
1261+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1262+ let booking = id_of(&res.body);
1263+
1264+ // Aged past the ceiling, the way an older binary would have left it.
1265+ db.query(format!(
1266+ "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25"
1267+ ))
1268+ .await
1269+ .unwrap()
1270+ .check()
1271+ .unwrap();
1272+
1273+ let res = send(
1274+ &app,
1275+ "DELETE",
1276+ &format!("/meals/bookings/{booking}"),
1277+ Some(&ali),
1278+ None,
1279+ )
1280+ .await;
1281+ assert_eq!(
1282+ res.status,
1283+ StatusCode::OK,
1284+ "an over-ceiling seat must stay freeable: {}",
1285+ res.body
1286+ );
1287+ assert_eq!(res.body["status"], "cancelled", "{}", res.body);
1288+ // …and with the seat back the menu is deletable again, which is the whole
1289+ // point of not letting the ceiling reach the cancel.
1290+ let res = send(
1291+ &app,
1292+ "DELETE",
1293+ &format!("/meals/menus/{menu}"),
1294+ Some(&mgr),
1295+ None,
1296+ )
1297+ .await;
1298+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
1299+}