forge
Explore
Log in

Don't you dare go Hollow

Stop the canteen billing meals that were already served

Browse files at this commit

0894a5e0067f94e6a4462930c3c4dd466830543dAhmet Kaan GümüşParent: cd6a00a
  • fix
    • stop the canteen billing meals that were already served
Show full message
🥗 fix: stop the canteen billing meals that were already served

A menu dated 2020 was publishable, bookable and BILLABLE under the shipped
defaults. `check_cutoff` was the only gate a booking passed, and it returns
early twice: with `meal_cancel_cutoff_minutes` unset (the default) and with a
slot carrying no `serving_minute` (the default for all three shipped slots).
`POST /meals/menus` was also the one create path in the crate with no
`check_not_past`. So a manager published `2020-01-01_lunch`, a student booked
it, and `MealLedger::charge_for` wrote a real, permanent charge line for food
nobody could be served.

Both halves, because the create-side check alone does not close it: a menu
published legitimately last week, for a day that has SINCE passed, stays on
the volume and stays addressable. `check_not_past("date", date.day_end())`
refuses publishing a day already over (400, measured against the end of the
day so today publishes at any hour), and `check_day_not_past` refuses a
booking on one (409).

That guard is deliberately NOT part of `check_cutoff` and takes no settings:
the cutoff is policy about the serving *hour* and is unenforced by design when
the school has set none — the decision that keeps the canteen online — while
this is the calendar day itself being over, which no configuration makes
untrue. Today's menu on a slot with no serving hour books exactly as before.
It binds `book` alone: cancelling stays open on a past day, since a cancel
reverses a charge and money already taken has to stay reachable — the same
reason manager+ bypasses the cutoff. Nothing bypasses the past-day guard, and
nothing needs to: only students and their parents book at all.

`MenuDate::try_new` also stops disagreeing with chrono. `"+1".parse::<u32>()`
is `Ok(1)`, so `2026-+1-01` passed the calendar-day check and minted a SECOND
record id for the 1st of January — its own capacity and seat counter, missing
from every `?from=&to=` read (`+` sorts below `0`) and unbookable besides,
since the serving-instant parser could not read it back. The date is now
parsed by chrono and compared to the text it came from, so the two parsers
agree by construction rather than by two checks that can drift.

Test dates in the meal suites move beyond the calendar (2026-09 → 2099-09):
under the new rule a fixture dated next month is a suite that expires. The two
tests that used a past date as a shortcut to "the cutoff has closed" now reach
the cutoff the way a deployment does — today's menu, served at 00:00 UTC, with
the knob set.

Live volume: zero menus, zero bookings, zero ledger lines, so no residue to
repair. The defect was future-affecting only.
README.mdmodified+25 -7
@@ -595,10 +595,23 @@ own seats by hand. Seats on lists that have already closed (the event started,
595 or its `ends_at`-only deadline passed) are never touched — that roster is595 or its `ends_at`-only deadline passed) are never touched — that roster is
596 history, and re-registering is refused.596 history, and re-registering is refused.
597 597
598+A demotion below `teacher` additionally **withdraws the published appointment
599+calendar** and cancels the live bookings on it. Nothing else could: a slot is
600+listed only on its own teacher's calendar and deleted only by a teacher+, so
601+after the demotion no route yields its id, and a booking on it can be decided
602+only by a teacher+ and cancelled only by its requester — who is refused once
603+the window opens, leaving the slot's seat held for good. The requester keeps
604+the booking, `cancelled`, with the ex-teacher on `cancelled_by` and the reason
605+on `cancel_reason`; its slot is gone, so it renders without a window. A slot
606+published while the demotion runs claims the publisher's own row, so either
607+the sweep sees the slot or the publish sees the new role (a `403`), and a
608+booking racing it collides on the slot row the sweep deletes.
609+
598 The role write and every sweep it implies — class memberships and their610 The role write and every sweep it implies — class memberships and their
599 counters, all enrollments and their seats, parent ties on both sides, a611 counters, all enrollments and their seats, parent ties on both sides, a
600 demoted parent's still-freeable event seats, whiteboard rosters, course612 demoted parent's still-freeable event seats, whiteboard rosters, course
601-staffing and homeroom-teacher columns — commit as **one transaction**. It613+staffing and homeroom-teacher columns, the appointment calendar and the
614+bookings on it — commit as **one transaction**. It
602 either all lands or none of it does: a failure answers `500` with the account615 either all lands or none of it does: a failure answers `500` with the account
603 still holding its old role and every grant of it still standing, and the same616 still holding its old role and every grant of it still standing, and the same
604 `PATCH` retried applies the lot. Signup lists that have already frozen are617 `PATCH` retried applies the lot. Signup lists that have already frozen are
@@ -803,7 +816,7 @@ window filtering, before paging; negative values are a `400` naming the field.
803 | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile |816 | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile |
804 | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path |817 | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path |
805 | GET | `/users/{id}` | admin | Get one user |818 | GET | `/users/{id}` | admin | Get one user |
806-| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists; demoting the school's **last** admin is refused (`409`) |819+| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), a demotion below `teacher` withdraws their appointment slots and cancels the bookings on them, and a demotion to `parent` also frees their seats on still-open event signup lists; demoting the school's **last** admin is refused (`409`) |
807 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included |820 | PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included |
808 | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |821 | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences |
809 | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |822 | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant |
@@ -1475,9 +1488,13 @@ POST /appointments/slots
1475 **bookable** calendar — slots that have **not started yet**, earliest first.1488 **bookable** calendar — slots that have **not started yet**, earliest first.
1476 That bound is `starts_at`, the same one booking enforces, so a slot already1489 That bound is `starts_at`, the same one booking enforces, so a slot already
1477 underway is left out rather than offered for a request that could only answer1490 underway is left out rather than offered for a request that could only answer
1478-`409`; the 60-second publish-time skew grace does not widen it either. A teacher demoted1491+`409`; the 60-second publish-time skew grace does not widen it either. A
1479-after publishing leaves **inert** slots: their live role is re-read, so those1492+demotion below `teacher` **withdraws** that account's calendar outright, in the
1480-slots drop out of the bookable list and booking one is refused with a `409`.1493+role change's own transaction, and cancels the live bookings on it (see
1494+`PATCH /users/{id}/role`): a slot nobody can list and nobody can delete would
1495+otherwise sit there forever, holding a booking nobody can settle. The live-role
1496+re-read stays as the belt for a slot an older build stranded — such a slot
1497+drops out of the bookable list and booking one is refused with a `409`.
1481 The list does not say whether a slot is already taken — booking a taken one1498 The list does not say whether a slot is already taken — booking a taken one
1482 answers `409`.1499 answers `409`.
1483 1500
@@ -1497,8 +1514,9 @@ concurrent bookings can both read as free). The decisions:
1497 1514
1498 - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms; the1515 - `PATCH /{id}/approve` — the slot's teacher (or manager+) confirms; the
1499 slot's `teacher` is history, not a standing grant, so an owner demoted below1516 slot's `teacher` is history, not a standing grant, so an owner demoted below
1500- `teacher` decides nothing on it any more — manager+ still can, and the1517+ `teacher` decides nothing on it any more — and nothing is left for anyone
1501- requester can still cancel. Refused1518+ else to decide either, since that demotion cancelled the bookings along with
1519+ the slots. Refused
1502 (`409`) when the effective window has already started, and refused while a1520 (`409`) when the effective window has already started, and refused while a
1503 counter-proposal stands: the proposal is the teacher's own, so approving it1521 counter-proposal stands: the proposal is the teacher's own, so approving it
1504 here would let them confirm a time the requester never accepted.1522 here would let them confirm a time the requester never accepted.
src/domain/meal_booking.rsmodified+173 -2
@@ -200,6 +200,7 @@ impl MealBooking {
200 for attempt in 0..CAP_WRITE_TRIES {200 for attempt in 0..CAP_WRITE_TRIES {
201 backoff(attempt).await;201 backoff(attempt).await;
202 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;202 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
203+ check_day_not_past(fresh.get_date())?;
203 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;204 check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
204 let existing: Option<MealBooking> = db.select(id.record()).await?;205 let existing: Option<MealBooking> = db.select(id.record()).await?;
205 // The seat is already held: same attempt, same price it was taken206 // The seat is already held: same attempt, same price it was taken
@@ -723,6 +724,40 @@ fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp>
723 ))724 ))
724 }725 }
725 726
727+/// A meal whose **calendar day is over** takes no more seats, whatever the
728+/// school configured. The booking is what charges (attendance never moves
729+/// money), so a seat taken on a day already served mints a real ledger line for
730+/// food nobody can be served — the one thing no route may do.
731+///
732+/// Deliberately **not** part of [`check_cutoff`], and deliberately not
733+/// configurable:
734+///
735+/// - The cutoff is a *policy* about the serving hour, and it is unenforced by
736+/// design when the school sets no `meal_cancel_cutoff_minutes` or the slot no
737+/// `serving_minute` (all three shipped slots carry none) — see the note there
738+/// for why the canteen must not go offline over an unset hour. This is not a
739+/// deadline before the meal at all: it is the day itself having passed, which
740+/// no configuration can make untrue. **Today's menu is untouched by it** —
741+/// with or without a serving hour, at any time of day.
742+/// - It binds `book` only. Cancelling stays open on a past day, cutoff bypass
743+/// or not: a cancel *reverses* a charge, and money already taken has to stay
744+/// reachable (that is the same reason manager+ bypasses the cutoff in
745+/// [`cancel_booking`](crate::web::meals)).
746+fn check_day_not_past(date: &MenuDate) -> Result<(), AppError> {
747+ // An unparsable day is left to `check_cutoff`, which fails it closed
748+ // whenever a cutoff is configured: guessing "past" from text no calendar
749+ // can place would shut the canteen for a school that set no deadline.
750+ let Some(over) = date.day_end() else {
751+ return Ok(());
752+ };
753+ if Timestamp::now().as_millis() >= over.as_millis() {
754+ return Err(AppError::Conflict(
755+ "that meal's day has passed, so its menu takes no more bookings",
756+ ));
757+ }
758+ Ok(())
759+}
760+
726 /// Booking and cancelling both close `cutoff.minutes` before the meal is761 /// Booking and cancelling both close `cutoff.minutes` before the meal is
727 /// served. `None` = the school set no cutoff, so neither ever closes.762 /// served. `None` = the school set no cutoff, so neither ever closes.
728 ///763 ///
@@ -794,12 +829,18 @@ mod tests {
794 }829 }
795 }830 }
796 831
797- /// A published menu on a fresh in-memory database, plus a student.832+ /// A published menu on a fresh in-memory database, plus a student. Dated
833+ /// well ahead on purpose: a menu whose day has passed refuses every
834+ /// booking, so a date the calendar overtakes would fail this whole module.
798 async fn menu(capacity: Option<i64>) -> (Database, MenuId) {835 async fn menu(capacity: Option<i64>) -> (Database, MenuId) {
836+ menu_on("2099-09-14", capacity).await
837+ }
838+
839+ async fn menu_on(date: &str, capacity: Option<i64>) -> (Database, MenuId) {
799 let db = crate::database::init_mem().await.unwrap();840 let db = crate::database::init_mem().await.unwrap();
800 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];841 let slots = vec![MealSlotDef::try_new("lunch", None).unwrap()];
801 let menu = Menu::create(842 let menu = Menu::create(
802- MenuDate::try_new("2026-09-14").unwrap(),843+ MenuDate::try_new(date).unwrap(),
803 MenuSlot::try_new("lunch", &slots).unwrap(),844 MenuSlot::try_new("lunch", &slots).unwrap(),
804 capacity,845 capacity,
805 &UserId::generate(),846 &UserId::generate(),
@@ -1303,6 +1344,136 @@ mod tests {
1303 assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err());1344 assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err());
1304 }1345 }
1305 1346
1347+ fn today() -> String {
1348+ chrono::Utc::now()
1349+ .date_naive()
1350+ .format("%Y-%m-%d")
1351+ .to_string()
1352+ }
1353+
1354+ /// The day being over is not the cutoff. It binds with no
1355+ /// `meal_cancel_cutoff_minutes` set and no `serving_minute` on the slot —
1356+ /// the shipped defaults, under which the cutoff deliberately closes nothing
1357+ /// — and it never binds today, at any hour.
1358+ #[test]
1359+ fn the_past_day_guard_is_not_the_serving_hour_cutoff() {
1360+ let yesterday = (chrono::Utc::now().date_naive() - chrono::Duration::days(1))
1361+ .format("%Y-%m-%d")
1362+ .to_string();
1363+ assert!(check_day_not_past(&MenuDate::try_new(&yesterday).unwrap()).is_err());
1364+ assert!(check_day_not_past(&MenuDate::try_new(&today()).unwrap()).is_ok());
1365+ assert!(check_day_not_past(&MenuDate::try_new("2999-01-01").unwrap()).is_ok());
1366+ // Today's menu is open all day *and* carries no deadline at all under
1367+ // the shipped defaults — the two answers stay separate.
1368+ assert!(
1369+ check_cutoff(
1370+ &MenuDate::try_new(&today()).unwrap(),
1371+ &lunch(),
1372+ &cutoff(Some(60), None)
1373+ )
1374+ .is_ok()
1375+ );
1376+ // A day no calendar can place is left to the cutoff, which fails it
1377+ // closed when one is configured; guessing "past" here would shut the
1378+ // canteen for a school that set no deadline.
1379+ let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap();
1380+ assert!(check_day_not_past(&impossible).is_ok());
1381+ }
1382+
1383+ /// The charge hole itself: a menu whose day has gone by must take no seat
1384+ /// and mint no ledger line, with the shipped defaults in force.
1385+ #[tokio::test]
1386+ async fn a_past_day_takes_no_seat_and_writes_no_charge() {
1387+ let (db, menu) = menu_on("2020-01-06", None).await;
1388+ let ali = UserId::generate();
1389+ add_dish(&menu, 4550, &db).await;
1390+
1391+ assert!(matches!(
1392+ MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await,
1393+ Err(AppError::Conflict(_))
1394+ ));
1395+ assert_eq!(seats(&menu, &db).await, 0);
1396+ let (lines, total) = MealLedger::list_for_student(&ali, None, 0, &db)
1397+ .await
1398+ .unwrap();
1399+ assert!(
1400+ lines.is_empty() && total == 0,
1401+ "a refused booking bills nothing"
1402+ );
1403+ }
1404+
1405+ /// The documented decision the past-day guard must not swallow: today's
1406+ /// menu, on a slot with no serving hour, books exactly as it always did —
1407+ /// with the cutoff knob set *and* unset.
1408+ #[tokio::test]
1409+ async fn todays_menu_still_books_without_a_serving_hour() {
1410+ let (db, menu) = menu_on(&today(), None).await;
1411+ let ali = UserId::generate();
1412+ MealBooking::book(&menu, &ali, &ali, &cutoff(Some(60), None), &db)
1413+ .await
1414+ .expect("an unset serving hour is an unenforced cutoff");
1415+ assert_eq!(seats(&menu, &db).await, 1);
1416+ }
1417+
1418+ /// Cancelling stays open on a day already gone — that is how money already
1419+ /// taken is given back, and it is the same reason manager+ bypasses the
1420+ /// cutoff. The guard binds `book` alone.
1421+ #[tokio::test]
1422+ async fn a_past_day_still_gives_the_seat_and_the_money_back() {
1423+ let (db, menu) = menu_on("2020-01-06", None).await;
1424+ let ali = UserId::generate();
1425+ add_dish(&menu, 4550, &db).await;
1426+ // The seat this student is holding was taken while the day was still
1427+ // ahead — the shape the create-side check cannot reach. A test cannot
1428+ // age a menu (`date` is READONLY), so the seat is placed on an
1429+ // already-past menu by the very transaction `book` places it with.
1430+ let fresh = Menu::read(&menu, &db).await.unwrap().unwrap();
1431+ let price = MealLedger::price_snapshot(&menu, &db).await.unwrap();
1432+ let row = MealBooking {
1433+ id: MealBookingId::composite(&menu, &ali),
1434+ menu: menu.clone(),
1435+ student: ali.clone(),
1436+ booked_by: ali.clone(),
1437+ status: MealBookingStatus::Booked,
1438+ attempt: 1,
1439+ price_minor: price,
1440+ cancelled_at: None,
1441+ created_at: Timestamp::now(),
1442+ };
1443+ let charge = MealLedger::charge_for(&row, &ali);
1444+ let booked = match MealBooking::claim_and_place(
1445+ &menu.record(),
1446+ cap::UNLIMITED,
1447+ fresh.get_version(),
1448+ &row,
1449+ price,
1450+ charge.as_ref(),
1451+ &db,
1452+ )
1453+ .await
1454+ .unwrap()
1455+ {
1456+ Claimed::Made(booking) => booking,
1457+ _ => panic!("the seat was free"),
1458+ };
1459+ assert_eq!(seats(&menu, &db).await, 1);
1460+
1461+ assert!(matches!(
1462+ MealBooking::book(&menu, &ali, &ali, &MealCutoff::default(), &db).await,
1463+ Err(AppError::Conflict(_)),
1464+ ));
1465+ let cancelled = booked
1466+ .cancel(&MealCutoff::default(), &ali, &db)
1467+ .await
1468+ .expect("a cancel on a past day still frees the seat");
1469+ assert_eq!(cancelled.get_status(), MealBookingStatus::Cancelled);
1470+ assert_eq!(seats(&menu, &db).await, 0);
1471+ let (lines, _) = MealLedger::list_for_student(&ali, None, 0, &db)
1472+ .await
1473+ .unwrap();
1474+ assert_eq!(lines.len(), 2, "the charge and its reversal");
1475+ }
1476+
1306 /// The instant the deadline counts back from: midnight UTC of the day plus1477 /// The instant the deadline counts back from: midnight UTC of the day plus
1307 /// the slot's serving minute. The `None` case still resolves to midnight,1478 /// 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 a1479 /// but only as the date's validity probe — `check_cutoff` never counts a
src/domain/menu.rsmodified+89 -12
@@ -173,20 +173,25 @@ impl MenuDate {
173 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {173 if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
174 return Err(invalid);174 return Err(invalid);
175 }175 }
176- let digits =176+ // Parsed by **chrono** and compared back to the text it came from, so
177- |from: usize, to: usize| -> Option<u32> { value.get(from..to)?.parse::<u32>().ok() };177+ // this parser and the one that computes the serving instant
178- let (Some(year), Some(month), Some(day)) = (digits(0, 4), digits(5, 7), digits(8, 10))178+ // ([`served_at`](crate::domain::meal_booking)) agree by construction
179- else {179+ // rather than by two independent checks that can drift apart. They did:
180+ // a hand-rolled `"+1".parse::<u32>()` accepted a signed component (std
181+ // does), `from_ymd_opt` was then handed the normalized number and said
182+ // yes, and `2026-+1-01` became a *second* record id for the 1st of
183+ // January — its own capacity and seat counter, invisible to every
184+ // `date >= $from` range read ('+' sorts below '0'), and unbookable
185+ // besides, since chrono refuses to parse it back.
186+ //
187+ // The round trip also keeps the day a **real** one, leap years and all
188+ // (a 31st of February is fully actionable — seats, charges, dishes,
189+ // marks — with no instant any cutoff can count back from), and pins the
190+ // zero-padding the text ordering rests on.
191+ let Ok(day) = chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d") else {
180 return Err(invalid);192 return Err(invalid);
181 };193 };
182- // The day has to be a **real** one, leap years and all. A 31st of194+ if day.format("%Y-%m-%d").to_string() != value {
183- // February is not the harmless typo it looks: a menu is published on it
184- // and is then fully actionable — seats, charges, dishes, attendance
185- // marks — but no instant can be computed for it, so the booking and
186- // cancel cutoff has nothing to count back from and never closes at all.
187- // The month/day ranges are this check's own business, hence no separate
188- // bounds test above (`from_ymd_opt` refuses month 0 and day 32 alike).
189- if chrono::NaiveDate::from_ymd_opt(year as i32, month, day).is_none() {
190 return Err(invalid);195 return Err(invalid);
191 }196 }
192 Ok(Self(value.to_string()))197 Ok(Self(value.to_string()))
@@ -195,6 +200,25 @@ impl MenuDate {
195 pub fn as_str(&self) -> &str {200 pub fn as_str(&self) -> &str {
196 &self.0201 &self.0
197 }202 }
203+
204+ /// The instant this calendar day is over: midnight UTC opening the next
205+ /// one. UTC because the backend stores no school timezone, the same choice
206+ /// [`served_at`](crate::domain::meal_booking) makes for the serving instant.
207+ ///
208+ /// This is the whole day's deadline, not the meal's: a menu for *today* is
209+ /// still publishable and still bookable at any hour, whatever the slot's
210+ /// serving time says — that is [`MealCutoff`](crate::domain::meal_booking::MealCutoff)'s
211+ /// separate business. `None` for a day that cannot be parsed (a row written
212+ /// before `try_new` rejected impossible days).
213+ pub fn day_end(&self) -> Option<Timestamp> {
214+ let day = chrono::NaiveDate::parse_from_str(&self.0, "%Y-%m-%d").ok()?;
215+ Some(Timestamp::from_millis(
216+ day.succ_opt()?
217+ .and_hms_opt(0, 0, 0)?
218+ .and_utc()
219+ .timestamp_millis(),
220+ ))
221+ }
198 }222 }
199 223
200 /// The meal slot a menu was published for, snapshotted as text. Validated224 /// The meal slot a menu was published for, snapshotted as text. Validated
@@ -530,6 +554,59 @@ mod tests {
530 );554 );
531 }555 }
532 556
557+ /// A signed component is not a calendar day, however willingly
558+ /// `"+1".parse::<u32>()` reads one out of it. Accepting one minted a
559+ /// *second* record id for the same day — its own capacity and seat counter
560+ /// — that sorted below every `?from=` bound (`+` is 0x2B, `0` is 0x30) and
561+ /// that the serving-instant parser could not read at all.
562+ #[test]
563+ fn date_refuses_a_signed_component() {
564+ for signed in ["2026-+1-01", "2026-01-+1", "+026-01-01", "2026-01-+2"] {
565+ assert!(
566+ MenuDate::try_new(signed).is_err(),
567+ "{signed} is not a calendar day"
568+ );
569+ }
570+ }
571+
572+ /// The drift guard: whatever this accepts must be exactly what the calendar
573+ /// library writes back for that day. Two parsers that merely *agree today*
574+ /// are what let the signed form through — one normalized the sign away
575+ /// before the other ever saw it.
576+ #[test]
577+ fn every_accepted_date_round_trips_through_the_calendar() {
578+ for candidate in [
579+ "2026-07-26",
580+ "2024-02-29",
581+ "2026-+1-01",
582+ "2026-1-1",
583+ "0001-01-01",
584+ "2026-02-29",
585+ ] {
586+ let stored = MenuDate::try_new(candidate).ok();
587+ let round_tripped = chrono::NaiveDate::parse_from_str(candidate, "%Y-%m-%d")
588+ .ok()
589+ .map(|day| day.format("%Y-%m-%d").to_string())
590+ .filter(|text| text == candidate);
591+ assert_eq!(
592+ stored.map(|date| date.as_str().to_string()),
593+ round_tripped,
594+ "{candidate} must be stored exactly as the calendar writes it, or not at all"
595+ );
596+ }
597+ }
598+
599+ /// The day is over at midnight UTC opening the next one — not at the meal's
600+ /// serving hour, which is the cutoff's separate business.
601+ #[test]
602+ fn a_day_ends_at_the_next_midnight_utc() {
603+ let day = MenuDate::try_new("1970-01-01").unwrap();
604+ assert_eq!(day.day_end().unwrap().as_millis(), 86_400_000);
605+ // A row written before `try_new` refused impossible days has no end.
606+ let impossible = MenuDate::from_value(Value::String("2026-02-29".into())).unwrap();
607+ assert!(impossible.day_end().is_none());
608+ }
609+
533 #[test]610 #[test]
534 fn slot_must_be_one_the_school_serves() {611 fn slot_must_be_one_the_school_serves() {
535 let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()];612 let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()];
src/lib.rsmodified+1 -1
@@ -47,7 +47,7 @@ use crate::state::AppState;
47 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),47 (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
48 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),48 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
49 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),49 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
50- (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),50+ (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused"),
51 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),51 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),
52 (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),52 (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
53 (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),53 (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),
src/web/meals.rsmodified+17 -4
@@ -38,7 +38,7 @@ use crate::state::AppState;
38 38
39 use super::{39 use super::{
40 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,40 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,
41- person_map, set_or_clear,41+ check_not_past, person_map, set_or_clear,
42 };42 };
43 43
44 pub fn routes() -> OpenApiRouter<AppState> {44 pub fn routes() -> OpenApiRouter<AppState> {
@@ -234,6 +234,10 @@ async fn one_menu(
234 /// Publish a menu for one day and meal slot. Requires manager+. The slot must234 /// Publish a menu for one day and meal slot. Requires manager+. The slot must
235 /// be one the school currently serves, and a day+slot already published is a235 /// be one the school currently serves, and a day+slot already published is a
236 /// `409` — edit that menu instead of publishing a second one.236 /// `409` — edit that menu instead of publishing a second one.
237+///
238+/// The day must not already be over (`400`): a published menu is a bookable
239+/// one, and a booking is what charges the student. Today counts as ahead, all
240+/// day long.
237 #[utoipa::path(241 #[utoipa::path(
238 post,242 post,
239 path = "/menus",243 path = "/menus",
@@ -242,7 +246,7 @@ async fn one_menu(
242 request_body = CreateMenu,246 request_body = CreateMenu,
243 responses(247 responses(
244 (status = 201, description = "Menu published", body = MenuResponse),248 (status = 201, description = "Menu published", body = MenuResponse),
245- (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse),249+ (status = 400, description = "Malformed date, a day that is already over, unknown slot, or out-of-range capacity", body = ErrorResponse),
246 (status = 401, description = "Not authenticated", body = ErrorResponse),250 (status = 401, description = "Not authenticated", body = ErrorResponse),
247 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),251 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
248 (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse),252 (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse),
@@ -255,6 +259,12 @@ async fn create_menu(
255 Json(req): Json<CreateMenu>,259 Json(req): Json<CreateMenu>,
256 ) -> Result<(StatusCode, Json<MenuResponse>), AppError> {260 ) -> Result<(StatusCode, Json<MenuResponse>), AppError> {
257 let date = MenuDate::try_new(&req.date)?;261 let date = MenuDate::try_new(&req.date)?;
262+ // The kitchen publishes ahead, never behind: a menu on a day already over
263+ // is bookable and therefore *billable* (booking is the charge trigger), so
264+ // this is the same door every other create path in the crate has. Measured
265+ // against the end of the day, so today's menu is publishable all day — the
266+ // meal's own deadline is `meal_cancel_cutoff_minutes`, not this.
267+ check_not_past("date", date.day_end())?;
258 let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?;268 let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?;
259 validate_capacity(req.capacity)?;269 validate_capacity(req.capacity)?;
260 let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?;270 let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?;
@@ -800,7 +810,10 @@ async fn booking_target(
800 /// `student_id`); a parent books for a linked student by naming them. Booking810 /// `student_id`); a parent books for a linked student by naming them. Booking
801 /// twice is the same seat, not a second one — and bills once, at the price the811 /// twice is the same seat, not a second one — and bills once, at the price the
802 /// menu carried when the seat was first taken. Refused (`409`) when the menu is812 /// menu carried when the seat was first taken. Refused (`409`) when the menu is
803-/// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and813+/// full, when its **day has already passed** (a seat taken then would bill a
814+/// meal nobody can be served — and no role bypasses that, since only students
815+/// and their parents book at all), or when the school's
816+/// `meal_cancel_cutoff_minutes` has closed the meal, and
804 /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat817 /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat
805 /// is never handed out unbilled.818 /// is never handed out unbilled.
806 ///819 ///
@@ -822,7 +835,7 @@ async fn booking_target(
822 (status = 401, description = "Not authenticated", body = ErrorResponse),835 (status = 401, description = "Not authenticated", body = ErrorResponse),
823 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),836 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
824 (status = 404, description = "No such menu", body = ErrorResponse),837 (status = 404, description = "No such menu", 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),838+ (status = 409, description = "The menu is full, its day has already passed, 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),
826 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),839 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
827 ),840 ),
828 )]841 )]
tests/integration.rsmodified+36 -30
@@ -11836,7 +11836,7 @@ async fn settings_round_trip_the_food_program_knobs() {
11836 "POST",11836 "POST",
11837 "/meals/menus",11837 "/meals/menus",
11838 Some(&manager),11838 Some(&manager),
11839- Some(json!({ "date": "2026-07-27", "slot": "lunch" })),11839+ Some(json!({ "date": "2099-07-27", "slot": "lunch" })),
11840 )11840 )
11841 .await;11841 .await;
11842 assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body);11842 assert_eq!(menu.status, StatusCode::CREATED, "{}", menu.body);
@@ -21085,7 +21085,7 @@ async fn menus_and_dishes_round_trip() {
21085 "POST",21085 "POST",
21086 "/meals/menus",21086 "/meals/menus",
21087 Some(&mgr),21087 Some(&mgr),
21088- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 120 })),21088+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 120 })),
21089 )21089 )
21090 .await;21090 .await;
21091 assert_eq!(res.status, StatusCode::CREATED);21091 assert_eq!(res.status, StatusCode::CREATED);
@@ -21101,7 +21101,7 @@ async fn menus_and_dishes_round_trip() {
21101 "POST",21101 "POST",
21102 "/meals/menus",21102 "/meals/menus",
21103 Some(&mgr),21103 Some(&mgr),
21104- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),21104+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
21105 )21105 )
21106 .await;21106 .await;
21107 assert_eq!(res.status, StatusCode::CONFLICT);21107 assert_eq!(res.status, StatusCode::CONFLICT);
@@ -21112,7 +21112,7 @@ async fn menus_and_dishes_round_trip() {
21112 "POST",21112 "POST",
21113 "/meals/menus",21113 "/meals/menus",
21114 Some(&mgr),21114 Some(&mgr),
21115- Some(json!({ "date": "2026-09-14", "slot": "breakfast" })),21115+ Some(json!({ "date": "2099-09-14", "slot": "breakfast" })),
21116 )21116 )
21117 .await;21117 .await;
21118 assert_eq!(res.status, StatusCode::CREATED);21118 assert_eq!(res.status, StatusCode::CREATED);
@@ -21170,7 +21170,7 @@ async fn menus_and_dishes_round_trip() {
21170 let res = send(21170 let res = send(
21171 &app,21171 &app,
21172 "GET",21172 "GET",
21173- "/meals/menus?from=2026-09-14&to=2026-09-14",21173+ "/meals/menus?from=2099-09-14&to=2099-09-14",
21174 Some(&student),21174 Some(&student),
21175 None,21175 None,
21176 )21176 )
@@ -21180,7 +21180,7 @@ async fn menus_and_dishes_round_trip() {
21180 let res = send(21180 let res = send(
21181 &app,21181 &app,
21182 "GET",21182 "GET",
21183- "/meals/menus?from=2026-09-15",21183+ "/meals/menus?from=2099-09-15",
21184 Some(&student),21184 Some(&student),
21185 None,21185 None,
21186 )21186 )
@@ -21234,7 +21234,7 @@ async fn menu_writes_are_manager_only_and_validate_against_settings() {
21234 let mgr = login_as(&app, &db, "meal_mgr2", "manager").await;21234 let mgr = login_as(&app, &db, "meal_mgr2", "manager").await;
21235 let teacher = login_as(&app, &db, "meal_teacher", "teacher").await;21235 let teacher = login_as(&app, &db, "meal_teacher", "teacher").await;
21236 21236
21237- let body = json!({ "date": "2026-09-15", "slot": "lunch" });21237+ let body = json!({ "date": "2099-09-15", "slot": "lunch" });
21238 let res = send(21238 let res = send(
21239 &app,21239 &app,
21240 "POST",21240 "POST",
@@ -21251,7 +21251,7 @@ async fn menu_writes_are_manager_only_and_validate_against_settings() {
21251 "POST",21251 "POST",
21252 "/meals/menus",21252 "/meals/menus",
21253 Some(&mgr),21253 Some(&mgr),
21254- Some(json!({ "date": "2026-09-15", "slot": "brunch" })),21254+ Some(json!({ "date": "2099-09-15", "slot": "brunch" })),
21255 )21255 )
21256 .await;21256 .await;
21257 assert_eq!(res.status, StatusCode::BAD_REQUEST);21257 assert_eq!(res.status, StatusCode::BAD_REQUEST);
@@ -21338,7 +21338,7 @@ async fn meal_bookings_round_trip() {
21338 "POST",21338 "POST",
21339 "/meals/menus",21339 "/meals/menus",
21340 Some(&mgr),21340 Some(&mgr),
21341- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),21341+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })),
21342 )21342 )
21343 .await;21343 .await;
21344 let menu = id_of(&res.body);21344 let menu = id_of(&res.body);
@@ -21499,7 +21499,7 @@ async fn meal_booking_capacity_caps_and_a_cancel_frees_a_seat() {
21499 "POST",21499 "POST",
21500 "/meals/menus",21500 "/meals/menus",
21501 Some(&mgr),21501 Some(&mgr),
21502- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),21502+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })),
21503 )21503 )
21504 .await;21504 .await;
21505 let menu = id_of(&res.body);21505 let menu = id_of(&res.body);
@@ -21559,7 +21559,7 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
21559 "POST",21559 "POST",
21560 "/meals/menus",21560 "/meals/menus",
21561 Some(&mgr),21561 Some(&mgr),
21562- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 3 })),21562+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 3 })),
21563 )21563 )
21564 .await;21564 .await;
21565 let menu = id_of(&res.body);21565 let menu = id_of(&res.body);
@@ -21643,7 +21643,7 @@ async fn concurrent_duplicate_menu_publishes_conflict_not_500() {
21643 "POST",21643 "POST",
21644 "/meals/menus",21644 "/meals/menus",
21645 Some(&mgr),21645 Some(&mgr),
21646- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),21646+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
21647 )21647 )
21648 .await21648 .await
21649 .status21649 .status
@@ -21683,7 +21683,7 @@ async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {
21683 "POST",21683 "POST",
21684 "/meals/menus",21684 "/meals/menus",
21685 Some(&mgr),21685 Some(&mgr),
21686- Some(json!({ "date": "2026-09-15", "slot": "lunch" })),21686+ Some(json!({ "date": "2099-09-15", "slot": "lunch" })),
21687 )21687 )
21688 .await;21688 .await;
21689 let menu = id_of(&res.body);21689 let menu = id_of(&res.body);
@@ -21748,13 +21748,17 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
21748 let mgr = login_as(&app, &db, "cutoff_mgr", "manager").await;21748 let mgr = login_as(&app, &db, "cutoff_mgr", "manager").await;
21749 let ali = login(&app, "cutoff_ali").await;21749 let ali = login(&app, "cutoff_ali").await;
21750 21750
21751- // No cutoff configured yet, so a menu whose day is long gone still books.21751+ // No cutoff configured yet, so today's meal books at any hour — the day
21752+ // being over is the *other* refusal, and today's is not over.
21753+ let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc()
21754+ .format("%Y-%m-%d")
21755+ .to_string();
21752 let res = send(21756 let res = send(
21753 &app,21757 &app,
21754 "POST",21758 "POST",
21755 "/meals/menus",21759 "/meals/menus",
21756 Some(&mgr),21760 Some(&mgr),
21757- Some(json!({ "date": "2020-01-06", "slot": "lunch" })),21761+ Some(json!({ "date": today, "slot": "lunch" })),
21758 )21762 )
21759 .await;21763 .await;
21760 let menu = id_of(&res.body);21764 let menu = id_of(&res.body);
@@ -21771,7 +21775,9 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
21771 21775
21772 // The serving hour goes with the knob: a slot without one has no instant21776 // 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 its21777 // 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`).21778+ // menus (see `meal_cutoff_counts_back_from_the_slots_serving_time`). Lunch
21779+ // is served at 00:00 UTC, so today's deadline passed an hour before the day
21780+ // began — whatever hour this test runs at.
21775 let res = send(21781 let res = send(
21776 &app,21782 &app,
21777 "PATCH",21783 "PATCH",
@@ -21779,7 +21785,7 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
21779 Some(&mgr),21785 Some(&mgr),
21780 Some(json!({21786 Some(json!({
21781 "meal_cancel_cutoff_minutes": 60,21787 "meal_cancel_cutoff_minutes": 60,
21782- "meal_slots": [{ "name": "lunch", "serving_minute": 720 }],21788+ "meal_slots": [{ "name": "lunch", "serving_minute": 0 }],
21783 })),21789 })),
21784 )21790 )
21785 .await;21791 .await;
@@ -21994,7 +22000,7 @@ async fn meal_bookings_are_student_or_linked_parent_only() {
21994 "POST",22000 "POST",
21995 "/meals/menus",22001 "/meals/menus",
21996 Some(&mgr),22002 Some(&mgr),
21997- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),22003+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
21998 )22004 )
21999 .await;22005 .await;
22000 let menu = id_of(&res.body);22006 let menu = id_of(&res.body);
@@ -22101,7 +22107,7 @@ async fn meal_booking_charges_a_price_snapshot_and_a_cancel_reverses_it() {
22101 "POST",22107 "POST",
22102 "/meals/menus",22108 "/meals/menus",
22103 Some(&mgr),22109 Some(&mgr),
22104- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),22110+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
22105 )22111 )
22106 .await;22112 .await;
22107 let menu = id_of(&res.body);22113 let menu = id_of(&res.body);
@@ -22406,7 +22412,7 @@ async fn meal_attendance_never_moves_money() {
22406 "POST",22412 "POST",
22407 "/meals/menus",22413 "/meals/menus",
22408 Some(&mgr),22414 Some(&mgr),
22409- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),22415+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
22410 )22416 )
22411 .await;22417 .await;
22412 let menu = id_of(&res.body);22418 let menu = id_of(&res.body);
@@ -22560,7 +22566,7 @@ async fn deleting_a_menu_takes_its_attendance_with_it() {
22560 let ali = login(&app, "ghost_ali").await;22566 let ali = login(&app, "ghost_ali").await;
22561 let ali_id = me_id(&app, &ali).await;22567 let ali_id = me_id(&app, &ali).await;
22562 22568
22563- let publish = json!({ "date": "2026-10-05", "slot": "lunch" });22569+ let publish = json!({ "date": "2099-10-05", "slot": "lunch" });
22564 let res = send(22570 let res = send(
22565 &app,22571 &app,
22566 "POST",22572 "POST",
@@ -22657,7 +22663,7 @@ async fn meal_attendance_report_is_ranged_and_gated() {
22657 assert_eq!(res.status, StatusCode::OK, "{}", res.body);22663 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
22658 22664
22659 // Three days, one mark each for Ali.22665 // Three days, one mark each for Ali.
22660- for date in ["2026-09-01", "2026-09-15", "2026-09-30"] {22666+ for date in ["2099-09-01", "2099-09-15", "2099-09-30"] {
22661 let res = send(22667 let res = send(
22662 &app,22668 &app,
22663 "POST",22669 "POST",
@@ -22681,10 +22687,10 @@ async fn meal_attendance_report_is_ranged_and_gated() {
22681 // Unbounded, then each bound, then both — the window is the menu's day.22687 // Unbounded, then each bound, then both — the window is the menu's day.
22682 for (query, expected) in [22688 for (query, expected) in [
22683 ("", 3),22689 ("", 3),
22684- ("?from=2026-09-15", 2),22690+ ("?from=2099-09-15", 2),
22685- ("?to=2026-09-15", 2),22691+ ("?to=2099-09-15", 2),
22686- ("?from=2026-09-10&to=2026-09-20", 1),22692+ ("?from=2099-09-10&to=2099-09-20", 1),
22687- ("?from=2026-10-01", 0),22693+ ("?from=2099-10-01", 0),
22688 ] {22694 ] {
22689 let res = send(22695 let res = send(
22690 &app,22696 &app,
@@ -22870,7 +22876,7 @@ async fn dietary_profile_drives_menu_conflicts() {
22870 "POST",22876 "POST",
22871 "/meals/menus",22877 "/meals/menus",
22872 Some(&mgr),22878 Some(&mgr),
22873- Some(json!({ "date": "2026-10-05", "slot": "lunch" })),22879+ Some(json!({ "date": "2099-10-05", "slot": "lunch" })),
22874 )22880 )
22875 .await;22881 .await;
22876 let menu = id_of(&res.body);22882 let menu = id_of(&res.body);
@@ -22958,7 +22964,7 @@ async fn priced_menu(tag: &str, price: i64) -> (axum::Router, String, String) {
22958 "POST",22964 "POST",
22959 "/meals/menus",22965 "/meals/menus",
22960 Some(&mgr),22966 Some(&mgr),
22961- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),22967+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
22962 )22968 )
22963 .await;22969 .await;
22964 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);22970 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
@@ -23031,7 +23037,7 @@ async fn concurrent_bookings_of_one_seat_never_refuse_their_own_winner() {
23031 "POST",23037 "POST",
23032 "/meals/menus",23038 "/meals/menus",
23033 Some(&mgr),23039 Some(&mgr),
23034- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 1 })),23040+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 1 })),
23035 )23041 )
23036 .await;23042 .await;
23037 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);23043 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
@@ -23163,7 +23169,7 @@ async fn a_repeat_post_never_bills_a_seat_that_was_free_when_taken() {
23163 "POST",23169 "POST",
23164 "/meals/menus",23170 "/meals/menus",
23165 Some(&mgr),23171 Some(&mgr),
23166- Some(json!({ "date": "2026-09-14", "slot": "lunch" })),23172+ Some(json!({ "date": "2099-09-14", "slot": "lunch" })),
23167 )23173 )
23168 .await;23174 .await;
23169 let menu = id_of(&res.body);23175 let menu = id_of(&res.body);
tests/persistence.rsmodified+2 -2
@@ -1606,7 +1606,7 @@ async fn menu_seats_are_seeded_from_the_bookings_that_are_still_held() {
1606 "POST",1606 "POST",
1607 "/meals/menus",1607 "/meals/menus",
1608 Some(&mgr),1608 Some(&mgr),
1609- Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),1609+ Some(json!({ "date": "2099-09-14", "slot": "lunch", "capacity": 2 })),
1610 )1610 )
1611 .await;1611 .await;
1612 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);1612 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
@@ -1867,7 +1867,7 @@ async fn settings_reference_counts_are_seeded_from_the_marks_and_menus_that_pred
1867 }1867 }
1868 1868
1869 // Two menus under `lunch`, none under any other slot.1869 // Two menus under `lunch`, none under any other slot.
1870- for date in ["2026-09-21", "2026-09-22"] {1870+ for date in ["2099-09-21", "2099-09-22"] {
1871 let res = send(1871 let res = send(
1872 &app,1872 &app,
1873 "POST",1873 "POST",
tests/regress_meals.rsmodified+117 -24
@@ -12,7 +12,8 @@ mod common;
12 use axum::http::StatusCode;12 use axum::http::StatusCode;
13 use common::{app_and_db, id_of, login, login_as, me_id, send, set_role};13 use common::{app_and_db, id_of, login, login_as, me_id, send, set_role};
14 use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};14 use hezarfen_backend::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
15-use hezarfen_backend::domain::menu::MenuId;15+use hezarfen_backend::domain::menu::{Menu, MenuDate, MenuId, MenuSlot};
16+use hezarfen_backend::domain::settings::MealSlotDef;
16 use hezarfen_backend::domain::user::UserId;17 use hezarfen_backend::domain::user::UserId;
17 use hezarfen_backend::error::AppError;18 use hezarfen_backend::error::AppError;
18 use serde_json::json;19 use serde_json::json;
@@ -58,6 +59,92 @@ async fn balance_of(app: &axum::Router, cookie: &str, student: &str) -> i64 {
58 res.body["balance_minor"].as_i64().expect("a balance")59 res.body["balance_minor"].as_i64().expect("a balance")
59 }60 }
60 61
62+/// The canteen may not mint a charge for a meal that was already served.
63+/// Booking is the charge trigger, and with the *shipped defaults* — no
64+/// `meal_cancel_cutoff_minutes`, no `serving_minute` on any slot — nothing
65+/// refused a seat on a menu dated 2020: a manager published it, a student
66+/// booked it, and the ledger carried a real charge for food nobody could eat.
67+///
68+/// Both halves are here because the create-side check alone does not close it:
69+/// a menu published legitimately last week, for a day that has *since* passed,
70+/// is still on the volume and still addressable.
71+#[tokio::test]
72+async fn a_menu_behind_the_calendar_is_neither_publishable_nor_bookable() {
73+ let (app, db) = app_and_db().await;
74+ let mgr = login_as(&app, &db, "gone_mgr", "manager").await;
75+ let ali = login(&app, "gone_ali").await;
76+ let ali_id = me_id(&app, &ali).await;
77+
78+ // Half one: the same door every other create path in the app has.
79+ let res = send(
80+ &app,
81+ "POST",
82+ "/meals/menus",
83+ Some(&mgr),
84+ Some(json!({ "date": "2020-01-01", "slot": "lunch" })),
85+ )
86+ .await;
87+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
88+
89+ // Today is not past — the whole day is publishable and bookable at any
90+ // hour, and on a slot with no `serving_minute` (the shipped default) the
91+ // cutoff still closes nothing. That decision must survive this fix.
92+ let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc()
93+ .format("%Y-%m-%d")
94+ .to_string();
95+ let menu = publish(&app, &mgr, &today).await;
96+ add_dish(&app, &mgr, &menu, 4_500).await;
97+ let res = send(
98+ &app,
99+ "POST",
100+ &format!("/meals/menus/{menu}/bookings"),
101+ Some(&ali),
102+ Some(json!({})),
103+ )
104+ .await;
105+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
106+ assert_eq!(balance_of(&app, &mgr, &ali_id).await, -4_500);
107+
108+ // Half two: the menu the create-side check cannot reach — published while
109+ // its day was still ahead, written here as the store holds it, since no
110+ // route publishes one any more.
111+ let stale = Menu::create(
112+ MenuDate::try_new("2020-01-02").unwrap(),
113+ MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap(),
114+ None,
115+ &UserId::from_key(&me_id(&app, &mgr).await),
116+ &db,
117+ )
118+ .await
119+ .expect("the domain still writes what the volume may hold");
120+ let stale = stale.get_id().key().to_string();
121+ let res = send(
122+ &app,
123+ "POST",
124+ &format!("/meals/menus/{stale}/bookings"),
125+ Some(&ali),
126+ Some(json!({})),
127+ )
128+ .await;
129+ assert_eq!(
130+ res.status,
131+ StatusCode::CONFLICT,
132+ "a meal already served takes no seat: {}",
133+ res.body
134+ );
135+ // The refusal moved no money — the whole point of the guard.
136+ assert_eq!(balance_of(&app, &mgr, &ali_id).await, -4_500);
137+ let res = send(
138+ &app,
139+ "GET",
140+ &format!("/meals/ledger/{ali_id}"),
141+ Some(&mgr),
142+ None,
143+ )
144+ .await;
145+ assert_eq!(res.body["total"], 1, "one line, today's: {}", res.body);
146+}
147+
61 /// A repeat `POST` of a seat the student already holds must replay that seat,148 /// A repeat `POST` of a seat the student already holds must replay that seat,
62 /// whatever the menu costs *now*. Pricing the menu before the already-booked149 /// whatever the menu costs *now*. Pricing the menu before the already-booked
63 /// short circuit made it a `400` ("amount_minor must be between…") the moment150 /// short circuit made it a `400` ("amount_minor must be between…") the moment
@@ -68,7 +155,7 @@ async fn a_repeat_booking_replays_the_held_seat_however_dear_the_menu_gets() {
68 let (app, db) = app_and_db().await;155 let (app, db) = app_and_db().await;
69 let mgr = login_as(&app, &db, "dear_mgr", "manager").await;156 let mgr = login_as(&app, &db, "dear_mgr", "manager").await;
70 let ali = login(&app, "dear_ali").await;157 let ali = login(&app, "dear_ali").await;
71- let menu = publish(&app, &mgr, "2026-09-14").await;158+ let menu = publish(&app, &mgr, "2099-09-14").await;
72 add_dish(&app, &mgr, &menu, 1_000).await;159 add_dish(&app, &mgr, &menu, 1_000).await;
73 160
74 let res = send(161 let res = send(
@@ -137,7 +224,7 @@ async fn a_manager_can_cancel_the_seat_of_someone_who_is_no_longer_a_student() {
137 let mgr = login_as(&app, &db, "promo_mgr", "manager").await;224 let mgr = login_as(&app, &db, "promo_mgr", "manager").await;
138 let ali = login(&app, "promo_ali").await;225 let ali = login(&app, "promo_ali").await;
139 let ali_id = me_id(&app, &ali).await;226 let ali_id = me_id(&app, &ali).await;
140- let menu = publish(&app, &mgr, "2026-09-15").await;227+ let menu = publish(&app, &mgr, "2099-09-15").await;
141 add_dish(&app, &mgr, &menu, 4_500).await;228 add_dish(&app, &mgr, &menu, 4_500).await;
142 229
143 let res = send(230 let res = send(
@@ -200,7 +287,7 @@ async fn a_manager_can_cancel_the_seat_of_someone_who_is_no_longer_a_student() {
200 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);287 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
201 288
202 // A classmate still cannot cancel someone else's seat.289 // A classmate still cannot cancel someone else's seat.
203- let menu = publish(&app, &mgr, "2026-09-16").await;290+ let menu = publish(&app, &mgr, "2099-09-16").await;
204 let veli = login(&app, "promo_veli").await;291 let veli = login(&app, "promo_veli").await;
205 let res = send(292 let res = send(
206 &app,293 &app,
@@ -233,7 +320,7 @@ async fn a_credit_settles_a_debt_that_outlived_the_students_role() {
233 let admin = login_as(&app, &db, "credit_admin", "admin").await;320 let admin = login_as(&app, &db, "credit_admin", "admin").await;
234 let ali = login(&app, "credit_ali").await;321 let ali = login(&app, "credit_ali").await;
235 let ali_id = me_id(&app, &ali).await;322 let ali_id = me_id(&app, &ali).await;
236- let menu = publish(&app, &admin, "2026-09-17").await;323+ let menu = publish(&app, &admin, "2099-09-17").await;
237 add_dish(&app, &admin, &menu, 4_500).await;324 add_dish(&app, &admin, &menu, 4_500).await;
238 let res = send(325 let res = send(
239 &app,326 &app,
@@ -367,7 +454,7 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() {
367 let ali = login(&app, "mark_ali").await;454 let ali = login(&app, "mark_ali").await;
368 let ali_id = UserId::from_key(&me_id(&app, &ali).await);455 let ali_id = UserId::from_key(&me_id(&app, &ali).await);
369 let mgr_id = UserId::from_key(&me_id(&app, &mgr).await);456 let mgr_id = UserId::from_key(&me_id(&app, &mgr).await);
370- let menu = MenuId::from_key(&publish(&app, &mgr, "2026-09-18").await);457+ let menu = MenuId::from_key(&publish(&app, &mgr, "2099-09-18").await);
371 458
372 // The menu goes while the mark is on its way down.459 // The menu goes while the mark is on its way down.
373 let res = send(460 let res = send(
@@ -404,7 +491,7 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() {
404 491
405 // Republishing that very day and slot mints the same id — and must not492 // Republishing that very day and slot mints the same id — and must not
406 // inherit a mark for a meal nobody attended.493 // inherit a mark for a meal nobody attended.
407- let again = publish(&app, &mgr, "2026-09-18").await;494+ let again = publish(&app, &mgr, "2099-09-18").await;
408 assert_eq!(again, menu.key(), "the id is deterministic on date+slot");495 assert_eq!(again, menu.key(), "the id is deterministic on date+slot");
409 let res = send(496 let res = send(
410 &app,497 &app,
@@ -448,7 +535,7 @@ async fn a_mark_for_a_menu_that_is_gone_writes_no_row() {
448 async fn a_dish_write_is_refused_once_its_menu_is_gone() {535 async fn a_dish_write_is_refused_once_its_menu_is_gone() {
449 let (app, db) = app_and_db().await;536 let (app, db) = app_and_db().await;
450 let mgr = login_as(&app, &db, "orphan_mgr", "manager").await;537 let mgr = login_as(&app, &db, "orphan_mgr", "manager").await;
451- let menu = publish(&app, &mgr, "2026-09-19").await;538+ let menu = publish(&app, &mgr, "2099-09-19").await;
452 let dish = add_dish(&app, &mgr, &menu, 1_000).await;539 let dish = add_dish(&app, &mgr, &menu, 1_000).await;
453 540
454 // The menu row alone is removed, leaving the dish exactly as a delete541 // The menu row alone is removed, leaving the dish exactly as a delete
@@ -480,7 +567,7 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() {
480 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);567 assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
481 568
482 // …and on a live menu both still work, at a fresh revision each time.569 // …and on a live menu both still work, at a fresh revision each time.
483- let menu = publish(&app, &mgr, "2026-09-20").await;570+ let menu = publish(&app, &mgr, "2099-09-20").await;
484 let dish = add_dish(&app, &mgr, &menu, 1_000).await;571 let dish = add_dish(&app, &mgr, &menu, 1_000).await;
485 let res = send(572 let res = send(
486 &app,573 &app,
@@ -510,7 +597,7 @@ async fn a_dish_write_is_refused_once_its_menu_is_gone() {
510 async fn unpublishing_takes_the_dishes_with_the_row() {597 async fn unpublishing_takes_the_dishes_with_the_row() {
511 let (app, db) = app_and_db().await;598 let (app, db) = app_and_db().await;
512 let mgr = login_as(&app, &db, "cascade_mgr", "manager").await;599 let mgr = login_as(&app, &db, "cascade_mgr", "manager").await;
513- let menu = publish(&app, &mgr, "2026-09-21").await;600+ let menu = publish(&app, &mgr, "2099-09-21").await;
514 add_dish(&app, &mgr, &menu, 1_000).await;601 add_dish(&app, &mgr, &menu, 1_000).await;
515 send(602 send(
516 &app,603 &app,
@@ -521,7 +608,7 @@ async fn unpublishing_takes_the_dishes_with_the_row() {
521 )608 )
522 .await;609 .await;
523 610
524- let again = publish(&app, &mgr, "2026-09-21").await;611+ let again = publish(&app, &mgr, "2099-09-21").await;
525 assert_eq!(again, menu, "the id is deterministic on date+slot");612 assert_eq!(again, menu, "the id is deterministic on date+slot");
526 let res = send(613 let res = send(
527 &app,614 &app,
@@ -613,7 +700,7 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() {
613 "POST",700 "POST",
614 "/meals/menus",701 "/meals/menus",
615 Some(&admin),702 Some(&admin),
616- Some(json!({ "date": "2026-09-22", "slot": "a/b" })),703+ Some(json!({ "date": "2099-09-22", "slot": "a/b" })),
617 )704 )
618 .await;705 .await;
619 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);706 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
@@ -623,7 +710,7 @@ async fn a_slot_whose_name_would_break_the_menu_url_cannot_be_published() {
623 "POST",710 "POST",
624 "/meals/menus",711 "/meals/menus",
625 Some(&admin),712 Some(&admin),
626- Some(json!({ "date": "2026-09-22", "slot": "lunch" })),713+ Some(json!({ "date": "2099-09-22", "slot": "lunch" })),
627 )714 )
628 .await;715 .await;
629 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);716 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
@@ -642,8 +729,13 @@ async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() {
642 let mgr = login_as(&app, &db, "shut_mgr", "manager").await;729 let mgr = login_as(&app, &db, "shut_mgr", "manager").await;
643 let ali = login(&app, "shut_ali").await;730 let ali = login(&app, "shut_ali").await;
644 let ali_id = me_id(&app, &ali).await;731 let ali_id = me_id(&app, &ali).await;
645- // A day long past — booked while the school ran no deadline at all.732+ // Today's meal, booked while the school ran no deadline at all. It cannot
646- let menu = publish(&app, &mgr, "2020-01-02").await;733+ // be a day long past any more: a menu behind the calendar takes no booking
734+ // at all, since the booking is what charges.
735+ let today = hezarfen_backend::domain::timestamp::Timestamp::today_utc()
736+ .format("%Y-%m-%d")
737+ .to_string();
738+ let menu = publish(&app, &mgr, &today).await;
647 add_dish(&app, &mgr, &menu, 1_000).await;739 add_dish(&app, &mgr, &menu, 1_000).await;
648 let res = send(740 let res = send(
649 &app,741 &app,
@@ -656,9 +748,10 @@ async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() {
656 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);748 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
657 let booking = id_of(&res.body);749 let booking = id_of(&res.body);
658 750
659- // The school sets a deadline, and it closed on this menu long ago. The751+ // The school sets a deadline, and it closed on this menu hours ago: lunch
660- // serving hour goes with it: a slot without one has no instant for the752+ // is served at 00:00 UTC, so the deadline was an hour before that. The
661- // deadline to count back from, so the cutoff would bind nobody.753+ // serving hour has to go with the knob — a slot without one has no instant
754+ // for the deadline to count back from, so the cutoff would bind nobody.
662 let res = send(755 let res = send(
663 &app,756 &app,
664 "PATCH",757 "PATCH",
@@ -666,7 +759,7 @@ async fn a_closed_cutoff_still_lets_a_manager_free_the_seat() {
666 Some(&admin),759 Some(&admin),
667 Some(json!({760 Some(json!({
668 "meal_cancel_cutoff_minutes": 60,761 "meal_cancel_cutoff_minutes": 60,
669- "meal_slots": [{ "name": "lunch", "serving_minute": 720 }],762+ "meal_slots": [{ "name": "lunch", "serving_minute": 0 }],
670 })),763 })),
671 )764 )
672 .await;765 .await;
@@ -795,7 +888,7 @@ async fn an_unauthorised_cancel_tells_nobody_whether_the_seat_exists() {
795 let veli = login(&app, "oracle_veli").await;888 let veli = login(&app, "oracle_veli").await;
796 let veli_id = me_id(&app, &veli).await;889 let veli_id = me_id(&app, &veli).await;
797 let can_id = me_id(&app, &login(&app, "oracle_can").await).await;890 let can_id = me_id(&app, &login(&app, "oracle_can").await).await;
798- let menu = publish(&app, &mgr, "2026-09-19").await;891+ let menu = publish(&app, &mgr, "2099-09-19").await;
799 892
800 let res = send(893 let res = send(
801 &app,894 &app,
@@ -927,7 +1020,7 @@ async fn a_replayed_booking_answers_off_the_row_the_store_holds() {
927 let (app, db) = app_and_db().await;1020 let (app, db) = app_and_db().await;
928 let mgr = login_as(&app, &db, "stale_mgr", "manager").await;1021 let mgr = login_as(&app, &db, "stale_mgr", "manager").await;
929 let ali = login(&app, "stale_ali").await;1022 let ali = login(&app, "stale_ali").await;
930- let menu = publish(&app, &mgr, "2026-09-20").await;1023+ let menu = publish(&app, &mgr, "2099-09-20").await;
931 add_dish(&app, &mgr, &menu, 1_000).await;1024 add_dish(&app, &mgr, &menu, 1_000).await;
932 1025
933 let res = send(1026 let res = send(
@@ -1092,7 +1185,7 @@ async fn a_seat_cannot_be_retaken_without_end() {
1092 let mgr = login_as(&app, &db, "cycle_mgr", "manager").await;1185 let mgr = login_as(&app, &db, "cycle_mgr", "manager").await;
1093 let ali = login(&app, "cycle_ali").await;1186 let ali = login(&app, "cycle_ali").await;
1094 let ali_id = me_id(&app, &ali).await;1187 let ali_id = me_id(&app, &ali).await;
1095- let menu = publish(&app, &mgr, "2026-09-21").await;1188+ let menu = publish(&app, &mgr, "2099-09-21").await;
1096 add_dish(&app, &mgr, &menu, 1_000).await;1189 add_dish(&app, &mgr, &menu, 1_000).await;
1097 1190
1098 // `max_booking_attempts` is published, so a client can say why before it1191 // `max_booking_attempts` is published, so a client can say why before it
@@ -1183,7 +1276,7 @@ async fn the_balance_sums_every_kind_the_same_way_it_always_did() {
1183 assert_eq!(balance_of(&app, &mgr, &ali_id).await, 10_000);1276 assert_eq!(balance_of(&app, &mgr, &ali_id).await, 10_000);
1184 1277
1185 let mut bookings = Vec::new();1278 let mut bookings = Vec::new();
1186- for (day, price) in [("2026-09-23", 4_500), ("2026-09-24", 1_500)] {1279+ for (day, price) in [("2099-09-23", 4_500), ("2099-09-24", 1_500)] {
1187 let menu = publish(&app, &mgr, day).await;1280 let menu = publish(&app, &mgr, day).await;
1188 add_dish(&app, &mgr, &menu, price).await;1281 add_dish(&app, &mgr, &menu, price).await;
1189 let res = send(1282 let res = send(
@@ -1249,7 +1342,7 @@ async fn an_over_ceiling_seat_from_an_older_build_is_still_cancellable() {
1249 let ali = login(&app, "old_ali").await;1342 let ali = login(&app, "old_ali").await;
1250 // A free menu: the row is aged by hand below, and a charge keyed to an1343 // 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.1344 // attempt this test never really made would only muddy what is asserted.
1252- let menu = publish(&app, &mgr, "2026-09-25").await;1345+ let menu = publish(&app, &mgr, "2099-09-25").await;
1253 let res = send(1346 let res = send(
1254 &app,1347 &app,
1255 "POST",1348 "POST",