diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs index 8e72393..c5995e3 100644 --- a/src/domain/dietary_profile.rs +++ b/src/domain/dietary_profile.rs @@ -156,13 +156,27 @@ impl DietaryProfile { let profile = Self { id: DietaryProfileId::of(student), student: student.clone(), - tags: tags.unwrap_or(DietaryTags(Vec::new())), - note: note.flatten(), + tags: tags.clone().unwrap_or(DietaryTags(Vec::new())), + note: note.clone().flatten(), updated_by: by.clone(), updated_at: Timestamp::now(), }; - let created: Option = db.create(profile.id.record()).content(profile).await?; - return created.ok_or_else(|| AppError::Internal("failed to save the profile".into())); + match db.create(profile.id.record()).content(profile).await { + Ok(Some(created)) => return Ok(created), + Ok(None) => { + return Err(AppError::Internal("failed to save the profile".into())); + } + // A rival first `PATCH` created the row in the round trip since + // the read above (the `dietary_profile_student` UNIQUE index + // catches the same collision), and `CREATE` leaves that row + // untouched — so this call is a plain field write after all, + // exactly as it would have been a moment later. Propagated, it + // was a 500 on a legitimate request. Same shape as + // [`MealLedger::append`](crate::domain::meal_ledger), which + // reads the winner back rather than failing. + Err(err) if err.is_already_exists() => {} + Err(err) => return Err(err.into()), + } } FieldUpdate::new(DietaryProfileId::of(student).record()) .set("tags", tags) diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index 2399273..4c7f174 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -31,9 +31,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - CAS_UPDATE_RETRIES, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD, MENU_VERSION_FIELD, + CAP_WRITE_TRIES, MAX_MEAL_BOOKING_ATTEMPTS, MEAL_BOOKING_TABLE, MENU_SEAT_COUNT_FIELD, + MENU_VERSION_FIELD, }; -use crate::database::{Database, lost_the_race}; +use crate::database::{Database, backoff, lost_the_race}; use crate::domain::cap::{self, Claimed}; use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot}; @@ -61,6 +62,21 @@ impl MealBookingId { Self(RecordId::new(MEAL_BOOKING_TABLE, key)) } + /// Who the seat is for, read straight back off the key: [`Self::composite`] + /// joins with `_` and a ULID user key carries none, so the last segment is + /// always the student (a slot name may well hold one, and the menu half is + /// in front). `None` for a key no `composite` ever minted. + /// + /// This is what lets a cancel decide *whose* seat it is asked to free + /// before reading the row — the id is fully derivable from a menu and a + /// user id, both readable by a teacher, so a 403-or-404 answered off the + /// row is an existence oracle for the manager-only booking list. + pub fn student(&self) -> Option { + self.key() + .rsplit_once('_') + .map(|(_, student)| UserId::from_key(student)) + } + pub fn record(&self) -> RecordId { self.0.clone() } @@ -181,7 +197,8 @@ impl MealBooking { ) -> Result { let id = MealBookingId::composite(menu, student); let seats = menu.record(); - for _ in 0..CAS_UPDATE_RETRIES { + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; let existing: Option = db.select(id.record()).await?; @@ -200,23 +217,50 @@ impl MealBooking { .filter(|row| row.status == MealBookingStatus::Booked) { MealLedger::charge_booking(&held, booked_by, db).await?; - return Ok(held); + // Answered off a re-read, never off the row read a round trip + // ago: a cancel committing in that gap has freed the seat, + // given the money back and left the row `cancelled`, and + // returning `held` then reports a seat — `"status": "booked"`, + // `cancelled_at: null` — the store does not hold. The stored + // state was right all along; only the answer lied. Gone or + // cancelled, the decision is simply made again, exactly as + // `Claimed::Duplicate` below does, so the caller ends up with + // the seat they asked for rather than a `201` about a seat + // somebody already released. + match Self::read(&id, db).await? { + Some(live) if live.status == MealBookingStatus::Booked => return Ok(live), + _ => continue, + } } - // Before the seat: an unchargeable menu (dishes summing past the - // cap) must refuse the booking outright, never leave a - // booked-but-unbilled row behind. - let price = MealLedger::price_snapshot(menu, db).await?; // The attempt is settled *here*, not by the revival's `attempt + 1`, // because the charge id is (seat, attempt) and the charge has to be // built before the transaction that writes it. `existing` is either // absent or cancelled — a booked row returned above. + let attempt = existing.as_ref().map_or(1, |prior| prior.attempt + 1); + // A seat retaken without end is a ledger without end: each cycle + // appends a charge and its reversal, both permanent, and every + // later balance read is answered over the lot. Refused *before* the + // menu is priced, so the answer is the ceiling rather than whatever + // the pricing happens to say. A row already past the ceiling — an + // upgrade's leftovers — is untouched by this: cancelling consults + // no cap, so its seat and its money stay reachable, and only one + // more revival is refused. + if attempt > MAX_MEAL_BOOKING_ATTEMPTS { + return Err(AppError::Conflict( + "this seat has been booked and cancelled its maximum number of times", + )); + } + // Before the seat: an unchargeable menu (dishes summing past the + // cap) must refuse the booking outright, never leave a + // booked-but-unbilled row behind. + let price = MealLedger::price_snapshot(menu, db).await?; let fresh_row = MealBooking { id: id.clone(), menu: menu.clone(), student: student.clone(), booked_by: booked_by.clone(), status: MealBookingStatus::Booked, - attempt: existing.map_or(1, |prior| prior.attempt + 1), + attempt, price_minor: price, cancelled_at: None, created_at: Timestamp::now(), @@ -329,7 +373,16 @@ impl MealBooking { RETURN SELECT * FROM ONLY $id; COMMIT TRANSACTION;" ); - for _ in 0..CAS_UPDATE_RETRIES { + // Every booking on one menu contends on that menu's single counter row, + // which is one HTTP burst of racers on a single parent — the case + // `CAP_WRITE_TRIES` is sized for. Three immediate re-sends with no + // backoff just re-synchronized them and 409'd the fourth student. + // Admissible: a lost round aborts the whole transaction (nothing + // written, no seat, no charge), and the two `CREATE`s that could + // legitimately answer "already exists" are read as `Claimed::Duplicate` + // below *before* the conflict check, so no decision is ever re-asked. + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; let query = db .query(sql.as_str()) .bind(("menu", seats.clone())) @@ -522,7 +575,14 @@ impl MealBooking { // Slots count BEGIN, the LET, the seat UPDATE and — when there is money // to give back — the IF. let returned = if refund.is_some() { 4 } else { 3 }; - for _ in 0..CAS_UPDATE_RETRIES { + // Same burst on the same counter as the book side, so the same patience + // (see [`Self::claim_and_place`]) — a cancel that gave up left the seat + // held with the charge standing. Admissible: the round aborts having + // written nothing, and a re-send finds the row already `cancelled`, so + // the flip matches nothing, the counter moves nothing and the guarded + // reversal — keyed to (seat, attempt) — is not written twice. + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; let attempted = async { let query = db .query(format!( @@ -650,10 +710,11 @@ impl MealCutoff { /// The instant the meal is served: midnight UTC of `date` plus the slot's /// `serving_minute`. `date` is text with no timezone (see [`MenuDate`]) and the /// backend deliberately stores no school timezone, so the serving time is UTC -/// too — a UTC+3 school enters 09:00 for a noon lunch. A slot with no serving -/// time falls back to midnight UTC, exactly what every booking used before the -/// field existed; refusing the booking instead would take the canteen offline -/// on an upgrade. +/// too — a UTC+3 school enters 09:00 for a noon lunch. +/// +/// `None` for a date no day can be parsed out of, which is the only thing +/// [`check_cutoff`] uses the midnight case for: a slot with no serving minute +/// gets **no deadline at all** there, never a deadline counted from midnight. fn served_at(date: &MenuDate, serving_minute: Option) -> Option { let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?; Some(Timestamp::from_millis( @@ -665,6 +726,18 @@ fn served_at(date: &MenuDate, serving_minute: Option) -> Option /// Booking and cancelling both close `cutoff.minutes` before the meal is /// served. `None` = the school set no cutoff, so neither ever closes. /// +/// **A slot with no `serving_minute` closes nothing either.** There is no +/// instant to count the deadline back from, and counting from midnight UTC — +/// as this did — put the deadline of every same-day menu in the past the +/// moment a school set `meal_cancel_cutoff_minutes`: today's lunch could not be +/// booked (`409`), and the seats already held could not be cancelled by the +/// students and parents holding them, only by a manager. All three shipped +/// slots carry no serving minute, so setting the one cutoff knob took the +/// canteen offline — which is precisely what the midnight fallback was chosen +/// to avoid. An unset serving hour is now an unenforced cutoff: the school sets +/// the hour and the deadline starts binding, on menus already published too +/// (the slot list is read live). +/// /// A date no serving instant can be computed from **fails closed**. A menu on /// an impossible day (a 31st of February — refused by [`MenuDate`] now, but /// 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 let Some(minutes) = cutoff.minutes else { return Ok(()); }; - let Some(serving) = served_at(date, cutoff.serving_minute(slot)) else { + let serving_minute = cutoff.serving_minute(slot); + // The impossible day is refused first, serving hour or not: it is a data + // defect, and "the deadline binds every menu" has to stay true for the one + // menu nobody meant to publish. + let Some(serving) = served_at(date, serving_minute) else { return Err(AppError::Conflict( "the menu's date is not a real calendar day, so its cutoff cannot be worked out", )); }; + // No serving hour, no instant to count back from, so nothing closes. + if serving_minute.is_none() { + return Ok(()); + } let deadline = serving .as_millis() .saturating_sub(minutes.saturating_mul(60_000)); @@ -1210,8 +1291,22 @@ mod tests { assert!(check_cutoff(&impossible, &lunch(), &cutoff(None, Some(720))).is_ok()); } + /// A slot with no serving hour has no instant to count a deadline back + /// from, so nothing on it ever closes. It used to count from midnight UTC + /// of the menu's day, which shut every same-day menu the moment a school + /// set the cutoff knob — and all three shipped slots carry no hour. + #[test] + fn a_slot_without_a_serving_hour_has_no_deadline() { + let past = MenuDate::try_new("2000-01-01").unwrap(); + assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), None)).is_ok()); + // The same menu, once the school sets the hour. + assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); + } + /// The instant the deadline counts back from: midnight UTC of the day plus - /// the slot's serving minute, and midnight itself when the slot has none. + /// the slot's serving minute. The `None` case still resolves to midnight, + /// but only as the date's validity probe — `check_cutoff` never counts a + /// deadline from it, which the case below pins. #[test] fn serving_instant_offsets_midnight_utc() { let day = MenuDate::try_new("1970-01-02").unwrap(); @@ -1221,8 +1316,8 @@ mod tests { 86_400_000 + 12 * 60 * 60_000 ); // A slot the school no longer lists (renamed or retired after the - // menu snapshotted its name) resolves to no serving time, i.e. the - // midnight fallback rather than a refusal. + // menu snapshotted its name) resolves to no serving time, which + // `check_cutoff` reads as no deadline at all. assert_eq!( cutoff(Some(60), Some(720)).serving_minute(&lunch()), Some(720) diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index bfc7090..8158d93 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -547,19 +547,49 @@ impl MealLedger { /// The derived balance: `credits + reversals - charges`, in minor units. /// Negative means the student owes the school. Never stored anywhere. - // ponytail: folds the student's lines in-process (a few hundred a year); - // push it into a `math::sum` aggregate if a statement ever gets long. + /// + /// **The sum is taken per kind by the database** and only the three totals + /// come back, so a balance read costs the same whether the statement holds + /// four lines or forty thousand. It used to decode and fold every line, and + /// nothing bounds a statement's length but the cycle ceiling + /// ([`MAX_MEAL_BOOKING_ATTEMPTS`](crate::constant::MAX_MEAL_BOOKING_ATTEMPTS)) + /// added alongside this: every book/cancel + /// pair appends two permanent rows, and each one was paid for again by + /// every later `GET /meals/balance/*`. + /// + /// **The signs stay here**, applied by the very [`MealLedgerKind::sign`] + /// the documented formula is spelled in. Summing `IF kind = 'charge' THEN + /// -amount …` in SQL would have folded the whole balance in one statement + /// and forked the one rule that decides what money means into a second + /// language, where nothing would fail the day the two disagreed. Grouping + /// instead keeps the aggregate ignorant of signs: it counts kinds, and + /// Rust still says what a kind does. A stored running total was the third + /// option and is a counter that can drift — a bug class this repo closes, + /// not one it opens. pub async fn balance_of(student: &UserId, db: &Database) -> Result { - Ok(Self::list_for_student(student, None, 0, db) + let totals: Vec = db + .query(format!( + "SELECT kind, math::sum(amount_minor) AS total \ + FROM {MEAL_LEDGER_TABLE} WHERE student = $student GROUP BY kind" + )) + .bind(("student", student.record())) .await? - .0 + .check()? + .take(0)?; + Ok(totals .iter() - .fold(0i64, |sum, line| { - sum + line.kind.sign() * line.amount_minor.as_minor() - })) + .fold(0i64, |sum, row| sum + row.kind.sign() * row.total)) } } +/// One kind's whole sum, as the `GROUP BY` in [`MealLedger::balance_of`] hands +/// it back — at most three rows, never the lines behind them. +#[derive(Debug, SurrealValue)] +struct KindTotal { + kind: MealLedgerKind, + total: i64, +} + #[cfg(test)] mod tests { use surrealdb::types::SurrealValue as _; @@ -602,6 +632,47 @@ mod tests { assert_eq!(balance, 10_000); } + /// The balance aggregate **against a real server**, and `#[ignore]`d for + /// it: `init_mem`'s embedded engine is not the store this runs on, and an + /// aggregate is exactly where the two are known to differ — a `count()` + /// over an indexed field comes back `{count: N}` from the server and a + /// bare int from memory, and `student` here *is* indexed. This asserts the + /// `GROUP BY` really decodes into [`KindTotal`] and folds to the + /// documented figure, per kind, scoped to one student. + #[tokio::test] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn the_balance_aggregate_decodes_on_a_real_server() { + let (db, _serialized) = crate::database::init_test_server("meal_balance_sum").await; + db.query( + "CREATE meal_ledger:a SET student = user:ali, kind = 'credit', \ + amount_minor = 10000, recorded_by = user:adm, created_at = 1; + CREATE meal_ledger:b SET student = user:ali, kind = 'charge', \ + amount_minor = 4500, recorded_by = user:adm, created_at = 2; + CREATE meal_ledger:c SET student = user:ali, kind = 'charge', \ + amount_minor = 1500, recorded_by = user:adm, created_at = 3; + CREATE meal_ledger:d SET student = user:ali, kind = 'reversal', \ + amount_minor = 4500, recorded_by = user:adm, created_at = 4; + CREATE meal_ledger:e SET student = user:veli, kind = 'credit', \ + amount_minor = 777, recorded_by = user:adm, created_at = 5;", + ) + .await + .unwrap() + .check() + .unwrap(); + let ali = UserId::from_key("ali"); + assert_eq!( + MealLedger::balance_of(&ali, &db).await.unwrap(), + 10_000 - 4_500 - 1_500 + 4_500 + ); + // Somebody with no lines at all: no groups come back, not an error. + assert_eq!( + MealLedger::balance_of(&UserId::from_key("nobody"), &db) + .await + .unwrap(), + 0 + ); + } + #[test] fn an_amount_is_positive_and_capped() { assert!(LedgerAmount::try_new(0).is_err()); diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 99f0ca4..6e43288 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -494,8 +494,11 @@ impl Settings { DEFAULT_MEAL_SLOTS .map(|name| MealSlotDef { name: name.to_string(), - // No built-in serving time: the shipped defaults keep the - // midnight-UTC cutoff until a school sets real hours. + // No built-in serving time, and the backend will not guess + // one: a slot with no hour has no instant for the cutoff to + // count back from, so the school's `meal_cancel_cutoff_ + // minutes` binds none of these slots until it sets real + // hours (see `check_cutoff`). serving_minute: None, }) .to_vec() diff --git a/src/web/meals.rs b/src/web/meals.rs index 7e22fc1..b9cba41 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -803,6 +803,12 @@ async fn booking_target( /// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat /// is never handed out unbilled. +/// +/// One seat may be taken at most `meal.max_booking_attempts` times (`GET +/// /limits`) — the first booking plus the re-bookings after a cancel. Past that +/// it is a `409`: every cycle appends a charge and its reversal, permanently, so +/// the ceiling bounds the student's statement rather than their mind changing. +/// A seat that really must move again is the canteen's to cancel. #[utoipa::path( post, path = "/menus/{id}/bookings", @@ -816,7 +822,7 @@ async fn booking_target( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), - (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), + (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), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -933,6 +939,12 @@ async fn list_menu_bookings( /// 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. +/// +/// **Who is asking is decided before the seat is looked up**, so an unauthorised +/// caller gets the same `403` whether or not the booking exists. Booking ids are +/// derivable (`{date}_{slot}_{student}`), and a `404` here would otherwise +/// answer "did this student book this meal?" — the manager-only list at +/// `GET /meals/menus/{id}/bookings`, one student at a time. #[utoipa::path( delete, path = "/bookings/{bid}", @@ -942,8 +954,8 @@ async fn list_menu_bookings( responses( (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse), (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 = 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), + (status = 404, description = "Not found (only for a caller who may cancel it)", body = ErrorResponse), (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), ), )] @@ -952,9 +964,7 @@ async fn cancel_booking( CurrentUser(user): CurrentUser, Path(bid): Path, ) -> Result, AppError> { - let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db) - .await? - .ok_or(AppError::NotFound)?; + let id = MealBookingId::from_key(&bid); // Manager+ may give back *any* seat. Not a convenience: `booking_target` // grants only students and parents, so a student promoted to staff (or a // parent unlinked) left a live seat nobody on the API could cancel — the @@ -964,9 +974,20 @@ async fn cancel_booking( // effect of a role change. let staff = user.get_role().at_least(Role::Manager); if !staff { + // Decided off the *id*, before the row is read: the id is + // `{date}_{slot}_{student}`, and a teacher may list both the menus and + // the users, so authorising after the read answered 403 for a seat that + // exists and 404 for one that does not — an existence oracle around the + // deliberate manager+ gate on `GET /menus/{id}/bookings`, and one any + // peer holding a user id could work too. An unauthorised caller now + // gets the same 403 either way, and learns nothing. + // // Same door as booking: whoever may take the seat may give it back. - let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?; - if &target != booking.get_student() { + let student = id + .student() + .ok_or(AppError::Forbidden("not your booking"))?; + let target = booking_target(&user, Some(student.key()), &st.db).await?; + if target != student { return Err(AppError::Forbidden("not your booking")); } } @@ -983,6 +1004,9 @@ async fn cancel_booking( }; // Flips the row and appends the reversal for that attempt's charge in one // transaction; the charge itself stays. + let booking = MealBooking::read(&id, &st.db) + .await? + .ok_or(AppError::NotFound)?; let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?; let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?; Ok(Json( diff --git a/src/web/settings.rs b/src/web/settings.rs index c5b5656..d6be898 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -200,8 +200,10 @@ struct UpdateSettings { #[schema(max_items = 20)] dietary_tags: Option>, /// Minutes before a slot's `serving_minute` at which booking *and* - /// cancelling close, `0`–`10080` (one week). A slot with no serving time - /// is measured from midnight UTC of the menu's date instead. Omit to keep the current value; send `null` for + /// cancelling close, `0`–`10080` (one week). It binds only the slots that + /// carry a `serving_minute`: with no serving hour there is no instant to + /// count back from, so that slot's menus close at no deadline until the + /// hour is set. Omit to keep the current value; send `null` for /// no cutoff at all. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = 120, minimum = 0, maximum = 10_080)] diff --git a/tests/integration.rs b/tests/integration.rs index 987ced5..0af71db 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -21769,12 +21769,18 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let booking = id_of(&res.body); + // The serving hour goes with the knob: a slot without one has no instant + // for the deadline to count back from, so the cutoff binds none of its + // menus (see `meal_cutoff_counts_back_from_the_slots_serving_time`). let res = send( &app, "PATCH", "/settings", Some(&mgr), - Some(json!({ "meal_cancel_cutoff_minutes": 60 })), + Some(json!({ + "meal_cancel_cutoff_minutes": 60, + "meal_slots": [{ "name": "lunch", "serving_minute": 720 }], + })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -21826,8 +21832,10 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() { /// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already /// inside it. Under the old midnight rule the seat is shut; measured from the /// serving time it is open for another ~24 hours. Then, with no serving time on -/// the slot, the very same menu falls back to midnight and shuts — the upgrade -/// path for every slot written before the field existed. +/// the slot, the very same menu closes at **nothing at all**: there is no +/// instant left to count the deadline back from, and counting from midnight — +/// as this did — shut every same-day menu of a school that had set the cutoff +/// knob without serving hours, which is how all three slots ship. #[tokio::test] async fn meal_cutoff_counts_back_from_the_slots_serving_time() { let (app, db) = app_and_db().await; @@ -21886,9 +21894,11 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() { ); let booking = id_of(&res.body); - // Drop the serving time from the same slot: the deadline snaps back to - // midnight of the menu's date, which the cutoff already covers. The slot - // list is read live, so the menu published under it moves with it. + // Drop the serving time from the same slot: there is now no instant to + // count the deadline back from, so this menu closes at nothing — it does + // *not* snap back to midnight, which used to shut the canteen of every + // school that set the cutoff without setting hours. The slot list is read + // live, so the menu published under it moves with the edit. let res = send( &app, "PATCH", @@ -21916,11 +21926,12 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() { .await; assert_eq!( res.status, - StatusCode::CONFLICT, - "with no serving time the cutoff falls back to midnight UTC: {}", + StatusCode::CREATED, + "an unset serving hour is an unenforced cutoff: {}", res.body ); - // Cancelling is closed by the same fallback deadline... + // …and the student holding a seat can still give it back themselves, + // which the midnight fallback took away from them. let res = send( &app, "DELETE", @@ -21929,27 +21940,28 @@ async fn meal_cutoff_counts_back_from_the_slots_serving_time() { None, ) .await; - assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); - // ...and re-serving lunch at 23:59 opens both ends again. + // Serving lunch at midnight instead makes the same cutoff bite: the + // deadline is that instant minus the cutoff, which is already past. let res = send( &app, "PATCH", "/settings", Some(&mgr), - Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }] })), + Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 0 }] })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); let res = send( &app, - "DELETE", - &format!("/meals/bookings/{booking}"), + "POST", + &format!("/meals/menus/{menu}/bookings"), Some(&ali), - None, + Some(json!({})), ) .await; - assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); } /// Who may take a seat: the student it is for, or a parent holding a link to diff --git a/tests/regress_meals.rs b/tests/regress_meals.rs index 308519c..7497a55 100644 --- a/tests/regress_meals.rs +++ b/tests/regress_meals.rs @@ -44,6 +44,20 @@ async fn add_dish(app: &axum::Router, mgr: &str, menu: &str, price: i64) -> Stri id_of(&res.body) } +/// One student's balance as the API answers it. +async fn balance_of(app: &axum::Router, cookie: &str, student: &str) -> i64 { + let res = send( + app, + "GET", + &format!("/meals/balance/{student}"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body["balance_minor"].as_i64().expect("a balance") +} + /// A repeat `POST` of a seat the student already holds must replay that seat, /// whatever the menu costs *now*. Pricing the menu before the already-booked /// 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() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); let booking = id_of(&res.body); - // The school sets a deadline, and it closed on this menu long ago. + // The school sets a deadline, and it closed on this menu long ago. The + // serving hour goes with it: a slot without one has no instant for the + // deadline to count back from, so the cutoff would bind nobody. let res = send( &app, "PATCH", "/settings", Some(&admin), - Some(json!({ "meal_cancel_cutoff_minutes": 60 })), + Some(json!({ + "meal_cancel_cutoff_minutes": 60, + "meal_slots": [{ "name": "lunch", "serving_minute": 720 }], + })), ) .await; assert_eq!(res.status, StatusCode::OK, "{}", res.body); @@ -759,3 +778,522 @@ async fn only_manager_reads_another_students_meal_money() { ); } } + +/// A booking id is fully derivable — `{date}_{slot}_{student}` — and both +/// halves are readable by any teacher (`GET /users`, `GET /meals/menus`). The +/// cancel read the row before it checked who was asking, so the status code +/// answered a question the route never meant to: `403` for a seat that exists, +/// `404` for one that does not. That is the whole-school booking list, whose +/// own route is deliberately manager+, handed out one student at a time — and +/// any peer holding a user id (every `PersonRef` carries one) could ask it too. +#[tokio::test] +async fn an_unauthorised_cancel_tells_nobody_whether_the_seat_exists() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "oracle_mgr", "manager").await; + let teacher = login_as(&app, &db, "oracle_teacher", "teacher").await; + let ali = login(&app, "oracle_ali").await; + let veli = login(&app, "oracle_veli").await; + let veli_id = me_id(&app, &veli).await; + let can_id = me_id(&app, &login(&app, "oracle_can").await).await; + let menu = publish(&app, &mgr, "2026-09-19").await; + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booked = id_of(&res.body); + // Never booked, and derived exactly as the seat that was: the menu key + // joined to a student key anyone can read off a response. + let never = format!("{menu}_{can_id}"); + + for (who, cookie) in [("a teacher", &teacher), ("a peer student", &veli)] { + let held = send( + &app, + "DELETE", + &format!("/meals/bookings/{booked}"), + Some(cookie), + None, + ) + .await; + let absent = send( + &app, + "DELETE", + &format!("/meals/bookings/{never}"), + Some(cookie), + None, + ) + .await; + assert_eq!( + held.status, absent.status, + "{who} can tell a held seat from an unbooked one: {} vs {}", + held.body, absent.body + ); + assert_eq!(held.status, StatusCode::FORBIDDEN, "{}", held.body); + } + + // The gate did not turn into a blanket 403: the student it is for still + // learns their own seat is gone, and still cancels the one they hold. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{menu}_{veli_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booked}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled", "{}", res.body); + // …and manager+, who may read the whole list anyway, still sees existence. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{never}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// Two first `PATCH`es of a profile nobody ever recorded both read "no row" and +/// both tried to `CREATE` it. The loser's create collided (on the id, and on +/// the `dietary_profile_student` UNIQUE index behind it) and propagated as a +/// `500` on a perfectly legitimate request. The winner's row is now written +/// over instead, which is what the second `PATCH` was asking for anyway. +#[tokio::test] +async fn two_first_profile_writes_land_without_a_500() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "first_mgr", "manager").await; + let ali = login(&app, "first_ali").await; + let ali_id = me_id(&app, &ali).await; + + let route = format!("/meals/profiles/{ali_id}"); + let (one, two) = tokio::join!( + send( + &app, + "PATCH", + &route, + Some(&mgr), + Some(json!({ "tags": ["vegan"] })), + ), + send( + &app, + "PATCH", + &route, + Some(&mgr), + Some(json!({ "note": "fındık" })), + ), + ); + for res in [&one, &two] { + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } + + // Stored state, never a reported win: whichever landed second, the row + // carries both writes — neither was dropped and neither 500'd. + let res = send(&app, "GET", &route, Some(&mgr), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["tags"], json!(["vegan"]), "{}", res.body); + assert_eq!(res.body["note"], "fındık", "{}", res.body); +} + +/// A repeat `POST` of a held seat answered off the row it read a round trip +/// earlier. A cancel committing in that gap frees the seat, refunds it and +/// leaves the row `cancelled` — and the `201` still said `"status": "booked"`, +/// `cancelled_at: null`, so a client trusting the answer thought it held a seat +/// the store had given away. The stored state was right throughout; only the +/// answer lied. +/// +/// The cancel is injected the way `regress_roles` does it: a `DEFINE EVENT` +/// fires inside the very write the replay makes — here the charge it replays, +/// which is why the ledger is stripped first (a charge already there is a +/// no-op). Fenced on `attempt = 1`, so the re-booked seat's own charge does not +/// trip it a second time. +#[tokio::test] +async fn a_replayed_booking_answers_off_the_row_the_store_holds() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "stale_mgr", "manager").await; + let ali = login(&app, "stale_ali").await; + let menu = publish(&app, &mgr, "2026-09-20").await; + add_dish(&app, &mgr, &menu, 1_000).await; + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + db.query(format!( + "DELETE meal_ledger; + DEFINE EVENT cancel_inside ON TABLE meal_ledger WHEN $event = 'CREATE' THEN {{ + UPDATE type::record('meal_booking', '{booking}') \ + SET status = 'cancelled', cancelled_at = 1 WHERE attempt = 1; + }};" + )) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // The answer against the store, field by field — that is the whole claim. + let stored = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await; + let row = &stored.body["items"][0]; + assert_eq!(row["id"], json!(booking), "{}", stored.body); + assert_eq!( + res.body["status"], row["status"], + "the answer disagrees with the row: {} vs {}", + res.body, stored.body + ); + assert_eq!( + res.body["cancelled_at"], row["cancelled_at"], + "the answer disagrees with the row: {} vs {}", + res.body, stored.body + ); + assert_eq!(res.body["status"], "booked", "{}", res.body); +} + +/// A slot with **no serving hour** has no instant for a deadline to count back +/// from, and the code counted from midnight UTC instead. All three shipped +/// slots carry no serving minute, so the day a school set +/// `meal_cancel_cutoff_minutes` — the one knob — every same-day menu was +/// already past its deadline: today's lunch could not be booked, and the seats +/// already held could not be given back by the students and parents holding +/// them, only by a manager. The fallback was chosen to keep the canteen up on +/// an upgrade and did the opposite. An unset hour is now an unenforced cutoff. +/// +/// The existing unit test never caught it because it only ever passed a slot +/// *with* an hour, and the `None` case was exercised against an impossible +/// date, where the refusal comes from the date instead. +#[tokio::test] +async fn a_slot_with_no_serving_hour_closes_nothing() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "hour_adm", "admin").await; + let mgr = login_as(&app, &db, "hour_mgr", "manager").await; + let ali = login(&app, "hour_ali").await; + + // The school sets its one cutoff knob and nothing else — the shipped + // slots still carry no `serving_minute`, which is the whole case. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_cancel_cutoff_minutes": 120 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!( + res.body["meal_slots"] + .as_array() + .unwrap() + .iter() + .all(|slot| slot["serving_minute"].is_null()), + "the case only exists while no slot has an hour: {}", + res.body + ); + + // Today's menu: midnight UTC is behind us for all but the first two hours + // of the day, so the fallback deadline had already passed. + let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc() + .format("%Y-%m-%d") + .to_string(); + let menu = publish(&app, &mgr, &today).await; + add_dish(&app, &mgr, &menu, 1_000).await; + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "today's menu must still be bookable: {}", + res.body + ); + let booking = id_of(&res.body); + + // …and the student can still free the seat themselves. This half is worse + // than the refusal: the seat was already held and only a manager could + // give it back. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled", "{}", res.body); + + // The deadline starts binding the moment the school sets the hour — on + // menus already published, since the slot list is read live. Midnight UTC + // plus two hours, minus a two-hour cutoff, is midnight: long past. + let res = send( + &app, + "PATCH", + "/settings", + Some(&admin), + Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 120 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); +} + +/// Nothing bounded how often one seat could be retaken, and every cycle +/// appends two permanent, undeletable ledger lines (the charge and its +/// reversal). At the API's own request ceiling that is hundreds of thousands +/// of rows a day against one account — and every later balance read used to +/// fold the lot. The cycle ceiling is the growth half of that fix. +#[tokio::test] +async fn a_seat_cannot_be_retaken_without_end() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "cycle_mgr", "manager").await; + let ali = login(&app, "cycle_ali").await; + let ali_id = me_id(&app, &ali).await; + let menu = publish(&app, &mgr, "2026-09-21").await; + add_dish(&app, &mgr, &menu, 1_000).await; + + // `max_booking_attempts` is published, so a client can say why before it + // sends the call that fails. + let limits = send(&app, "GET", "/limits", Some(&ali), None).await; + let ceiling = limits.body["meal"]["max_booking_attempts"] + .as_i64() + .unwrap_or_else(|| panic!("the ceiling is not published: {}", limits.body)); + + let seats = format!("/meals/menus/{menu}/bookings"); + for round in 1..=ceiling { + let res = send(&app, "POST", &seats, Some(&ali), Some(json!({}))).await; + assert_eq!( + res.status, + StatusCode::CREATED, + "round {round}: {}", + res.body + ); + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{}", id_of(&res.body)), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "round {round}: {}", res.body); + } + let res = send(&app, "POST", &seats, Some(&ali), Some(json!({}))).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert!( + res.body["error"].as_str().unwrap().contains("maximum"), + "the refusal must say what happened: {}", + res.body + ); + + // Stored state: the seat stayed cancelled, and the refusal wrote no line — + // ten cycles, twenty lines, and the balance nets to zero. + let res = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await; + assert_eq!(res.body["items"][0]["status"], "cancelled", "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["total"], ceiling * 2, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["balance_minor"], 0, "{}", res.body); +} + +/// The balance is summed **per kind by the database** now, not folded line by +/// line in this process — the reason the ledger's length stopped being a cost +/// on every read. What must not change with it is the answer: `credits + +/// reversals - charges`, with the signs still applied by `MealLedgerKind::sign` +/// rather than respelled in SQL. +#[tokio::test] +async fn the_balance_sums_every_kind_the_same_way_it_always_did() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "sum_adm", "admin").await; + let mgr = login_as(&app, &db, "sum_mgr", "manager").await; + let ali = login(&app, "sum_ali").await; + let ali_id = me_id(&app, &ali).await; + + // Nothing at all: no rows, so the aggregate returns no groups. + assert_eq!(balance_of(&app, &mgr, &ali_id).await, 0); + + // A credit, then two charges on different menus, then one reversal — every + // kind, and more than one line in two of the three groups. + let res = send( + &app, + "POST", + "/meals/credits", + Some(&admin), + Some(json!({ "student_id": ali_id, "amount_minor": 10_000 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(balance_of(&app, &mgr, &ali_id).await, 10_000); + + let mut bookings = Vec::new(); + for (day, price) in [("2026-09-23", 4_500), ("2026-09-24", 1_500)] { + let menu = publish(&app, &mgr, day).await; + add_dish(&app, &mgr, &menu, price).await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + bookings.push(id_of(&res.body)); + } + assert_eq!( + balance_of(&app, &mgr, &ali_id).await, + 10_000 - 4_500 - 1_500 + ); + + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{}", bookings[0]), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + balance_of(&app, &mgr, &ali_id).await, + 10_000 - 1_500, + "credit + reversal - charges" + ); + // A second student's lines are somebody else's: the aggregate is scoped by + // `WHERE student = …` exactly as the fold was. + let veli = login(&app, "sum_veli").await; + let res = send( + &app, + "POST", + "/meals/credits", + Some(&admin), + Some(json!({ "student_id": me_id(&app, &veli).await, "amount_minor": 777 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!( + balance_of(&app, &mgr, &ali_id).await, + 10_000 - 1_500, + "another student's credit leaked into this balance" + ); +} + +/// The stale-data half of the cycle ceiling: a live volume may already hold a +/// seat retaken more times than the new ceiling allows. Such a row must stay +/// **cancellable** — the ceiling binds the write that would add another cycle, +/// nothing else. A ceiling consulted on the cancel path instead would strand +/// exactly the seats it was meant to stop growing: the menu refuses its own +/// delete while a seat is held, and cancelling is the only route that reverses +/// a charge. +#[tokio::test] +async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "old_mgr", "manager").await; + let ali = login(&app, "old_ali").await; + // A free menu: the row is aged by hand below, and a charge keyed to an + // attempt this test never really made would only muddy what is asserted. + let menu = publish(&app, &mgr, "2026-09-25").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + // Aged past the ceiling, the way an older binary would have left it. + db.query(format!( + "UPDATE type::record('meal_booking', '{booking}') SET attempt = 25" + )) + .await + .unwrap() + .check() + .unwrap(); + + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!( + res.status, + StatusCode::OK, + "an over-ceiling seat must stay freeable: {}", + res.body + ); + assert_eq!(res.body["status"], "cancelled", "{}", res.body); + // …and with the seat back the menu is deletable again, which is the whole + // point of not letting the ceiling reach the cancel. + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); +}