forge
Explore
Log in

Don't you dare go Hollow

πŸ•› anchor the meal cutoff to when lunch is actually served

Browse files at this commit

21f464338284d4c57c5aefb5197526b49da8f293Ahmet Kaan GümüşParent: fd5cfd1
  • fix
    • πŸ•› anchor the meal cutoff to when lunch is actually served
Show full message
fix: πŸ•› anchor the meal cutoff to when lunch is actually served

The booking and cancel deadline counted back from midnight UTC of the
menu date, so a two-hour cutoff on lunch barred bookings from 22:00 the
day before. Meal slots now carry an optional serving time and the
deadline counts back from that; a slot without one keeps the old
midnight behaviour, so nothing changes until a school sets hours.

Times are minutes past midnight UTC. There is deliberately no school
timezone setting, so a UTC+3 school enters 09:00 to mean noon; the
field says so wherever it is described.

Serving time is looked up live rather than snapshotted onto the menu,
because the cutoff minutes already are β€” freezing one half of a
deadline and not the other would split a single policy in two.

Storing an Option inside an object turned out to break the settings
CAS. SurrealDB drops an object key whose value is NONE, and a stored
{name} never again equals the {name, serving_minute: NONE} the derive
emits, so every PATCH /settings would have answered 409 forever for any
school whose slots predate this field. The guard now compares a rebuilt
projection. Verified against the live volume, whose singleton is
exactly that aged shape.

Also: losing a race to write a ledger line returned 500 rather than the
line the winner had already written. A duplicate record id is now read
back instead, matched on the typed error so real database failures
still surface.
README.mdmodified+26 -7
@@ -240,6 +240,11 @@ Timezones and clock differences cannot corrupt data, by construction:
240 the writer's wall, not an instant: validation accepts up to UTC-tomorrow,240 the writer's wall, not an instant: validation accepts up to UTC-tomorrow,
241 since a client ahead of UTC (up to UTC+14) legitimately writes a date the241 since a client ahead of UTC (up to UTC+14) legitimately writes a date the
242 server's UTC calendar hasn't reached yet.242 server's UTC calendar hasn't reached yet.
243+- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's
244+ `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face
245+ value a school types in, and it is read as UTC on the menu's `date` β€” there
246+ is deliberately **no school-timezone setting** (a rejected feature), so a
247+ UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally.
243 - **Nothing schedules in the past.** A request-supplied schedule instant β€” an248 - **Nothing schedules in the past.** A request-supplied schedule instant β€” an
244 exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie249 exam window, a lesson's `starts_at`/`ends_at`, an event time β€” must not lie
245 before the server's now, on create and on every `PATCH` that sets it: a250 before the server's now, on create and on every `PATCH` that sets it: a
@@ -1181,7 +1186,8 @@ The school publishes **one menu per calendar day and meal slot** (`POST
1181 - **`slot` is a snapshot**, not a link into settings. It must be one of the1186 - **`slot` is a snapshot**, not a link into settings. It must be one of the
1182 school's `meal_slots` (`GET /settings`) *when the menu is written*, and it1187 school's `meal_slots` (`GET /settings`) *when the menu is written*, and it
1183 is stored as text β€” so retiring a slot later never rewrites a menu already1188 is stored as text β€” so retiring a slot later never rewrites a menu already
1184- published under it. The mirror of that rule lives in settings: a slot any1189+ published under it. The slot's `serving_minute` is *not* snapshotted: the
1190+ booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any
1185 menu was published for cannot be removed from the list (`409`), same1191 menu was published for cannot be removed from the list (`409`), same
1186 contract exam kinds have with graded exams.1192 contract exam kinds have with graded exams.
1187 1193
@@ -1256,12 +1262,25 @@ teacher or manager ordering a child's lunch is a `403`.
1256 otherwise all pass the count. The whole check-then-write runs under the same1262 otherwise all pass the count. The whole check-then-write runs under the same
1257 lock a menu publish takes, and the cap is re-read inside it.1263 lock a menu publish takes, and the cap is re-read inside it.
1258 - **One cutoff closes both ends.** Within the school's1264 - **One cutoff closes both ends.** Within the school's
1259- `meal_cancel_cutoff_minutes` of the meal's day, neither a new booking nor a1265+ `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new
1260- cancellation lands (`409`) β€” the kitchen's headcount has to settle at some1266+ booking nor a cancellation lands (`409`) β€” the kitchen's headcount has to
1261- point. `null` (the default) means no cutoff at all. The cutoff is measured1267+ settle at some point. `null` (the default) means no cutoff at all. The
1262- back from **midnight UTC starting the meal's day**: `date` carries no1268+ cutoff is measured back from the menu's `date` **plus the slot's
1263- timezone and the backend stores no school timezone, so that is the only1269+ `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served
1264- instant derivable from it.1270+ at `720` closes at 10:00 UTC that morning, not at 22:00 the night before.
1271+ **That minute is UTC**: `date` carries no timezone and the backend stores no
1272+ school timezone β€” deliberately, it is a rejected feature β€” so a UTC+3 school
1273+ enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no
1274+ `serving_minute` falls back to **midnight UTC starting the meal's day**, the
1275+ behaviour every booking had before the field existed; the booking is never
1276+ refused for want of a serving time.
1277+- **The serving time is read live, not snapshotted onto the menu.** The cutoff
1278+ minutes are already read live, so freezing the other half of the same
1279+ deadline would make one policy edit apply and its twin not; a kitchen that
1280+ moves lunch an hour later wants today's menus to move with it. The menu
1281+ still snapshots the slot *name* (that is what keeps a retired slot's history
1282+ readable), so a menu whose slot has since left the list simply has no
1283+ serving time and falls back to midnight UTC.
1265 - A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”1284 - A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”
1266 cancel the bookings first, so nothing is left pointing at a deleted meal.1285 cancel the bookings first, so nothing is left pointing at a deleted meal.
1267 1286
src/constant.rsmodified+16 -0
@@ -195,6 +195,16 @@ pub const MAX_LEDGER_NOTE_LEN: usize = 500;
195 /// a meal β€” one week. The knob itself is optional: absent means no cutoff.195 /// a meal β€” one week. The knob itself is optional: absent means no cutoff.
196 pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60;196 pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60;
197 197
198+/// Inclusive ceiling for a meal slot's `serving_minute` β€” minutes past
199+/// midnight on the menu's date, so `0` = 00:00 and `1439` = 23:59. The cutoff
200+/// above counts back from that instant.
201+///
202+/// **The clock is UTC.** This backend deliberately stores no school timezone
203+/// (rejected feature), so staff enter the serving time in UTC: a UTC+3 school
204+/// types `540` (09:00) to mean noon locally. Optional per slot β€” a slot
205+/// without one keeps the old behaviour, midnight UTC of the menu's date.
206+pub const MAX_MEAL_SERVING_MINUTE: i64 = 24 * 60 - 1;
207+
198 /// The only accepted course kinds. `course`: a regular class (ders). `study`:208 /// The only accepted course kinds. `course`: a regular class (ders). `study`:
199 /// a supervised study session (etΓΌt). Behaviorally identical β€” the kind is a209 /// a supervised study session (etΓΌt). Behaviorally identical β€” the kind is a
200 /// label for the UI, everything else (enrollment, exams, sessions, marks)210 /// label for the UI, everything else (enrollment, exams, sessions, marks)
@@ -965,6 +975,12 @@ pub const MIGRATION: &str = "
965 -- fine, which is why the food program needs no BACKFILL anywhere.975 -- fine, which is why the food program needs no BACKFILL anywhere.
966 DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;976 DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
967 DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;977 DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
978+ -- Minutes past midnight UTC at which the slot is served (2026-07-26).
979+ -- `option<int>` for the same reason the list itself is: slots written
980+ -- before the field existed simply have no key, and read back as NONE ->
981+ -- the booking cutoff falls back to midnight UTC, its old meaning. No
982+ -- BACKFILL, and no DEFAULT β€” see the note above.
983+ DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option<int>;
968 DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;984 DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
969 DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;985 DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
970 986
src/domain/meal_booking.rsmodified+92 -29
@@ -24,7 +24,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
24 use crate::constant::MEAL_BOOKING_TABLE;24 use crate::constant::MEAL_BOOKING_TABLE;
25 use crate::database::Database;25 use crate::database::Database;
26 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};26 use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
27-use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId};27+use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot};
28+use crate::domain::settings::{MealSlotDef, Settings};
28 use crate::domain::timestamp::Timestamp;29 use crate::domain::timestamp::Timestamp;
29 use crate::domain::user::UserId;30 use crate::domain::user::UserId;
30 use crate::error::AppError;31 use crate::error::AppError;
@@ -157,18 +158,18 @@ impl MealBooking {
157 /// line. The price is `None` when the menu is free, and that `None` is158 /// line. The price is `None` when the menu is free, and that `None` is
158 /// stored, so a dish added later never bills a seat retroactively.159 /// stored, so a dish added later never bills a seat retroactively.
159 ///160 ///
160- /// `cutoff_minutes` is the school's one meal cutoff (`None` = none): once161+ /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once
161- /// the meal's day is that close, the seat is fixed either way.162+ /// serving time is that close, the seat is fixed either way.
162 pub async fn book(163 pub async fn book(
163 menu: &MenuId,164 menu: &MenuId,
164 student: &UserId,165 student: &UserId,
165 booked_by: &UserId,166 booked_by: &UserId,
166- cutoff_minutes: Option<i64>,167+ cutoff: &MealCutoff,
167 db: &Database,168 db: &Database,
168 ) -> Result<MealBooking, AppError> {169 ) -> Result<MealBooking, AppError> {
169 let _guard = MENU_LOCK.lock().await;170 let _guard = MENU_LOCK.lock().await;
170 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;171 let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
171- check_cutoff(fresh.get_date(), cutoff_minutes)?;172+ check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?;
172 // Before the seat: an unchargeable menu (dishes summing past the cap)173 // Before the seat: an unchargeable menu (dishes summing past the cap)
173 // must refuse the booking outright, never leave a booked-but-unbilled174 // must refuse the booking outright, never leave a booked-but-unbilled
174 // row behind.175 // row behind.
@@ -233,7 +234,7 @@ impl MealBooking {
233 /// the meal has since closed would strand the money exactly as before.234 /// the meal has since closed would strand the money exactly as before.
234 pub async fn cancel(235 pub async fn cancel(
235 self,236 self,
236- cutoff_minutes: Option<i64>,237+ cutoff: &MealCutoff,
237 recorded_by: &UserId,238 recorded_by: &UserId,
238 db: &Database,239 db: &Database,
239 ) -> Result<MealBooking, AppError> {240 ) -> Result<MealBooking, AppError> {
@@ -246,7 +247,7 @@ impl MealBooking {
246 let menu = Menu::read(&fresh.menu, db)247 let menu = Menu::read(&fresh.menu, db)
247 .await?248 .await?
248 .ok_or(AppError::NotFound)?;249 .ok_or(AppError::NotFound)?;
249- check_cutoff(menu.get_date(), cutoff_minutes)?;250+ check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?;
250 let cancelled = MealBooking {251 let cancelled = MealBooking {
251 status: MealBookingStatus::Cancelled,252 status: MealBookingStatus::Cancelled,
252 cancelled_at: Some(Timestamp::now()),253 cancelled_at: Some(Timestamp::now()),
@@ -334,28 +335,66 @@ impl MealBooking {
334 }335 }
335 }336 }
336 337
337-/// The meal's day as an instant: **midnight UTC starting that day**. `date` is338+/// The school's meal deadline policy, resolved once per request: how many
338-/// text with no timezone (see [`MenuDate`]), and the backend stores no school339+/// minutes ahead booking and cancelling close, plus the slot list the serving
339-/// timezone, so the start of the UTC day is the only instant derivable from it.340+/// times live on. Built from [`Settings`] by the web layer and handed down, so
340-/// A school wanting "two hours before lunch" sets the cutoff relative to that.341+/// the domain never reaches for the singleton mid-lock.
341-// ponytail: exact β€” needs a school timezone + a per-slot serving time, neither342+///
342-// of which the settings singleton carries yet.343+/// The slots are read **live**, not snapshotted onto the menu, and that is
343-fn day_starts_at(date: &MenuDate) -> Option<Timestamp> {344+/// deliberate: `meal_cancel_cutoff_minutes` is already read live, so freezing
345+/// the other half of the same deadline would make one policy edit apply and
346+/// its twin not. A kitchen that moves lunch an hour later wants today's menus
347+/// to move with it; the menu still snapshots the slot *name*, which is what
348+/// keeps a retired slot's history readable.
349+#[derive(Debug, Clone, Default)]
350+pub struct MealCutoff {
351+ minutes: Option<i64>,
352+ slots: Vec<MealSlotDef>,
353+}
354+
355+impl MealCutoff {
356+ pub fn from_settings(settings: &Settings) -> Self {
357+ Self {
358+ minutes: settings.get_meal_cancel_cutoff_minutes(),
359+ slots: settings.get_meal_slots(),
360+ }
361+ }
362+
363+ /// Minutes past midnight UTC at which `slot` is served, or `None` when the
364+ /// school set none (or dropped the slot after a menu snapshotted its name).
365+ fn serving_minute(&self, slot: &MenuSlot) -> Option<i64> {
366+ self.slots
367+ .iter()
368+ .find(|def| def.get_name() == slot.as_str())
369+ .and_then(MealSlotDef::get_serving_minute)
370+ }
371+}
372+
373+/// The instant the meal is served: midnight UTC of `date` plus the slot's
374+/// `serving_minute`. `date` is text with no timezone (see [`MenuDate`]) and the
375+/// backend deliberately stores no school timezone, so the serving time is UTC
376+/// too β€” a UTC+3 school enters 09:00 for a noon lunch. A slot with no serving
377+/// time falls back to midnight UTC, exactly what every booking used before the
378+/// field existed; refusing the booking instead would take the canteen offline
379+/// on an upgrade.
380+fn served_at(date: &MenuDate, serving_minute: Option<i64>) -> Option<Timestamp> {
344 let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?;381 let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?;
345 Some(Timestamp::from_millis(382 Some(Timestamp::from_millis(
346- day.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis(),383+ day.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis()
384+ + serving_minute.unwrap_or(0).saturating_mul(60_000),
347 ))385 ))
348 }386 }
349 387
350-/// Booking and cancelling both close `cutoff_minutes` before the meal's day388+/// Booking and cancelling both close `cutoff.minutes` before the meal is
351-/// starts. `None` = the school set no cutoff, so neither ever closes.389+/// served. `None` = the school set no cutoff, so neither ever closes.
352-fn check_cutoff(date: &MenuDate, cutoff_minutes: Option<i64>) -> Result<(), AppError> {390+fn check_cutoff(date: &MenuDate, slot: &MenuSlot, cutoff: &MealCutoff) -> Result<(), AppError> {
353- let (Some(cutoff), Some(start)) = (cutoff_minutes, day_starts_at(date)) else {391+ let serving = served_at(date, cutoff.serving_minute(slot));
392+ let (Some(minutes), Some(serving)) = (cutoff.minutes, serving) else {
354 return Ok(());393 return Ok(());
355 };394 };
356- let deadline = start395+ let deadline = serving
357 .as_millis()396 .as_millis()
358- .saturating_sub(cutoff.saturating_mul(60_000));397+ .saturating_sub(minutes.saturating_mul(60_000));
359 if Timestamp::now().as_millis() >= deadline {398 if Timestamp::now().as_millis() >= deadline {
360 return Err(AppError::Conflict("the menu's booking cutoff has passed"));399 return Err(AppError::Conflict("the menu's booking cutoff has passed"));
361 }400 }
@@ -381,21 +420,45 @@ mod tests {
381 }420 }
382 }421 }
383 422
423+ fn cutoff(minutes: Option<i64>, serving_minute: Option<i64>) -> MealCutoff {
424+ MealCutoff {
425+ minutes,
426+ slots: vec![MealSlotDef::try_new("lunch", serving_minute).unwrap()],
427+ }
428+ }
429+
430+ fn lunch() -> MenuSlot {
431+ MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap()
432+ }
433+
384 #[test]434 #[test]
385 fn cutoff_closes_only_within_the_window() {435 fn cutoff_closes_only_within_the_window() {
386 let far = MenuDate::try_new("2999-01-01").unwrap();436 let far = MenuDate::try_new("2999-01-01").unwrap();
387 let past = MenuDate::try_new("2000-01-01").unwrap();437 let past = MenuDate::try_new("2000-01-01").unwrap();
388 // No cutoff configured: nothing ever closes, not even a past day.438 // No cutoff configured: nothing ever closes, not even a past day.
389- assert!(check_cutoff(&past, None).is_ok());439+ assert!(check_cutoff(&past, &lunch(), &cutoff(None, Some(720))).is_ok());
390 // A day far ahead is open; one long gone is shut.440 // A day far ahead is open; one long gone is shut.
391- assert!(check_cutoff(&far, Some(60)).is_ok());441+ assert!(check_cutoff(&far, &lunch(), &cutoff(Some(60), Some(720))).is_ok());
392- assert!(check_cutoff(&past, Some(60)).is_err());442+ assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err());
393- // The cutoff is measured back from midnight UTC of the meal's day.443+ }
444+
445+ /// The instant the deadline counts back from: midnight UTC of the day plus
446+ /// the slot's serving minute, and midnight itself when the slot has none.
447+ #[test]
448+ fn serving_instant_offsets_midnight_utc() {
449+ let day = MenuDate::try_new("1970-01-02").unwrap();
450+ assert_eq!(served_at(&day, None).unwrap().as_millis(), 86_400_000);
451+ assert_eq!(
452+ served_at(&day, Some(12 * 60)).unwrap().as_millis(),
453+ 86_400_000 + 12 * 60 * 60_000
454+ );
455+ // A slot the school no longer lists (renamed or retired after the
456+ // menu snapshotted its name) resolves to no serving time, i.e. the
457+ // midnight fallback rather than a refusal.
394 assert_eq!(458 assert_eq!(
395- day_starts_at(&MenuDate::try_new("1970-01-02").unwrap())459+ cutoff(Some(60), Some(720)).serving_minute(&lunch()),
396- .unwrap()460+ Some(720)
397- .as_millis(),
398- 86_400_000
399 );461 );
462+ assert_eq!(MealCutoff::default().serving_minute(&lunch()), None);
400 }463 }
401 }464 }
src/domain/meal_ledger.rsmodified+22 -3
@@ -42,7 +42,7 @@
42 42
43 use std::sync::LazyLock;43 use std::sync::LazyLock;
44 44
45-use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};45+use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue};
46 use ulid::Generator;46 use ulid::Generator;
47 47
48 use crate::constant::{48 use crate::constant::{
@@ -108,6 +108,17 @@ impl MealLedgerId {
108 }108 }
109 }109 }
110 110
111+/// Did this `CREATE` fail *only* because the row is already there? Matched on
112+/// the SDK's typed `AlreadyExists`/`Record` detail β€” never on the message text
113+/// and never on "any database error", because swallowing a real fault in money
114+/// code would be far worse than the 500 it saves.
115+fn is_duplicate_record(error: &surrealdb::Error) -> bool {
116+ matches!(
117+ error.already_exists_details(),
118+ Some(AlreadyExistsError::Record { .. })
119+ )
120+}
121+
111 /// The bare key of a record id β€” how every id leaves this API.122 /// The bare key of a record id β€” how every id leaves this API.
112 fn key_of(record: &RecordId) -> &str {123 fn key_of(record: &RecordId) -> &str {
113 match &record.key {124 match &record.key {
@@ -261,12 +272,20 @@ impl MealLedger {
261 /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same272 /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same
262 /// append is a no-op, never a second line and never an edit of the first.273 /// append is a no-op, never a second line and never an edit of the first.
263 /// The point read is on the id itself, so unlike a scan it cannot miss a274 /// The point read is on the id itself, so unlike a scan it cannot miss a
264- /// row a concurrent writer just made.275+ /// row a concurrent writer just made β€” but it is only a fast path. The
276+ /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves
277+ /// the row untouched, so the writer that lost the race reads back the
278+ /// winner's line instead of failing the request with a 500.
265 async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {279 async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {
266 if let Some(existing) = Self::read(&row.id, db).await? {280 if let Some(existing) = Self::read(&row.id, db).await? {
267 return Ok(existing);281 return Ok(existing);
268 }282 }
269- let created: Option<MealLedger> = db.create(row.id.record()).content(row).await?;283+ let id = row.id.clone();
284+ let created: Option<MealLedger> = match db.create(id.record()).content(row).await {
285+ Ok(created) => created,
286+ Err(e) if is_duplicate_record(&e) => Self::read(&id, db).await?,
287+ Err(e) => return Err(e.into()),
288+ };
270 created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into()))289 created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into()))
271 }290 }
272 291
src/domain/menu.rsmodified+1 -1
@@ -313,7 +313,7 @@ mod tests {
313 313
314 #[test]314 #[test]
315 fn slot_must_be_one_the_school_serves() {315 fn slot_must_be_one_the_school_serves() {
316- let allowed = vec![MealSlotDef::try_new("lunch").unwrap()];316+ let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()];
317 assert!(MenuSlot::try_new("lunch", &allowed).is_ok());317 assert!(MenuSlot::try_new("lunch", &allowed).is_ok());
318 assert!(MenuSlot::try_new("brunch", &allowed).is_err());318 assert!(MenuSlot::try_new("brunch", &allowed).is_err());
319 assert!(MenuSlot::try_new("lunch", &[]).is_err());319 assert!(MenuSlot::try_new("lunch", &[]).is_err());
src/domain/settings.rsmodified+49 -6
@@ -19,9 +19,9 @@ use crate::constant::{
19 DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT,19 DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT,
20 MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN,20 MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN,
21 MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES,21 MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES,
22- MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,22+ MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN,
23- MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES,23+ MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN,
24- SETTINGS_KEY, SETTINGS_TABLE,24+ MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE,
25 };25 };
26 use crate::database::Database;26 use crate::database::Database;
27 use crate::domain::text_fold;27 use crate::domain::text_fold;
@@ -70,14 +70,22 @@ impl ExamKindDef {
70 /// One meal slot the school serves (`"lunch"`, `"snack"`, …). A published menu70 /// One meal slot the school serves (`"lunch"`, `"snack"`, …). A published menu
71 /// snapshots the slot's *name* as text, so retiring a slot never rewrites a71 /// snapshots the slot's *name* as text, so retiring a slot never rewrites a
72 /// past menu β€” same contract exam kinds have with exams. An object, not a bare72 /// past menu β€” same contract exam kinds have with exams. An object, not a bare
73-/// string, so a slot can grow a serving window later without a migration.73+/// string, which is what let the serving time land here without a migration.
74+///
75+/// `serving_minute` is minutes past midnight **UTC** on the menu's date, and
76+/// it is what the booking/cancel cutoff counts back from. The backend stores
77+/// no school timezone (deliberately), so staff enter UTC: a UTC+3 school sets
78+/// `540` (09:00) for a meal served at noon locally. `None` β€” every slot
79+/// written before the field existed β€” falls back to midnight UTC, the old
80+/// behaviour.
74 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]81 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
75 pub struct MealSlotDef {82 pub struct MealSlotDef {
76 name: String,83 name: String,
84+ serving_minute: Option<i64>,
77 }85 }
78 86
79 impl MealSlotDef {87 impl MealSlotDef {
80- pub fn try_new(name: &str) -> Result<Self, ValidationError> {88+ pub fn try_new(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> {
81 let name = name.trim();89 let name = name.trim();
82 if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {90 if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {
83 return Err(ValidationError::Invalid {91 return Err(ValidationError::Invalid {
@@ -85,14 +93,29 @@ impl MealSlotDef {
85 reason: "slot names must be 1 to 50 characters",93 reason: "slot names must be 1 to 50 characters",
86 });94 });
87 }95 }
96+ if let Some(minute) = serving_minute {
97+ in_range(
98+ "meal_slots",
99+ minute,
100+ 0..=MAX_MEAL_SERVING_MINUTE,
101+ "serving minutes must be between 0 (00:00 UTC) and 1439 (23:59 UTC)",
102+ )?;
103+ }
88 Ok(Self {104 Ok(Self {
89 name: name.to_string(),105 name: name.to_string(),
106+ serving_minute,
90 })107 })
91 }108 }
92 109
93 pub fn get_name(&self) -> &str {110 pub fn get_name(&self) -> &str {
94 &self.name111 &self.name
95 }112 }
113+
114+ /// Minutes past midnight UTC at which this slot is served; `None` = unset,
115+ /// so the cutoff counts back from midnight UTC instead.
116+ pub fn get_serving_minute(&self) -> Option<i64> {
117+ self.serving_minute
118+ }
96 }119 }
97 120
98 /// One grade-display band: marks at or above `min` (and below the next band's121 /// One grade-display band: marks at or above `min` (and below the next band's
@@ -411,6 +434,9 @@ impl Settings {
411 DEFAULT_MEAL_SLOTS434 DEFAULT_MEAL_SLOTS
412 .map(|name| MealSlotDef {435 .map(|name| MealSlotDef {
413 name: name.to_string(),436 name: name.to_string(),
437+ // No built-in serving time: the shipped defaults keep the
438+ // midnight-UTC cutoff until a school sets real hours.
439+ serving_minute: None,
414 })440 })
415 .to_vec()441 .to_vec()
416 })442 })
@@ -468,6 +494,18 @@ impl Settings {
468 /// state when no row exists yet (`load` reported the defaults, so the494 /// state when no row exists yet (`load` reported the defaults, so the
469 /// defaults are what the caller merged over), then the guarded update495 /// defaults are what the caller merged over), then the guarded update
470 /// applies `self` only if the row (still) equals `expected`.496 /// applies `self` only if the row (still) equals `expected`.
497+ ///
498+ /// **`meal_slots` is compared through a projection, and it has to be.**
499+ /// SurrealDB *drops* an object key whose value is `NONE` on write, while
500+ /// the `SurrealValue` derive always emits `serving_minute: NONE` for a
501+ /// slot without one β€” so `{name: 'lunch'} = {name: 'lunch', serving_minute:
502+ /// NONE}` is **false** and a plain equality guard would never match again
503+ /// for any school with a serving-time-less slot (which is every school
504+ /// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding
505+ /// both sides as full objects normalizes the shapes. The NONE-ness of the
506+ /// column itself is compared separately, so "never set" stays distinguishable
507+ /// from "explicitly empty". Top-level optional columns need none of this:
508+ /// a missing field reads as `NONE`, and `NONE = NONE` holds.
471 pub async fn save_if_unchanged(509 pub async fn save_if_unchanged(
472 self,510 self,
473 expected: &Settings,511 expected: &Settings,
@@ -485,7 +523,11 @@ impl Settings {
485 AND chatbot_history_turns = $ct523 AND chatbot_history_turns = $ct
486 AND max_chatbot_threads = $cc524 AND max_chatbot_threads = $cc
487 AND max_chatbot_message_len = $cl525 AND max_chatbot_message_len = $cl
488- AND meal_slots = $ms526+ AND (meal_slots = NONE) = $ms_unset
527+ AND (meal_slots ?? []).map(|$s| {
528+ name: $s.name,
529+ serving_minute: $s.serving_minute
530+ }) = ($ms ?? [])
489 AND dietary_tags = $dt531 AND dietary_tags = $dt
490 AND meal_cancel_cutoff_minutes = $mc;532 AND meal_cancel_cutoff_minutes = $mc;
491 COMMIT TRANSACTION;",533 COMMIT TRANSACTION;",
@@ -500,6 +542,7 @@ impl Settings {
500 .bind(("ct", expected.chatbot_history_turns))542 .bind(("ct", expected.chatbot_history_turns))
501 .bind(("cc", expected.max_chatbot_threads))543 .bind(("cc", expected.max_chatbot_threads))
502 .bind(("cl", expected.max_chatbot_message_len))544 .bind(("cl", expected.max_chatbot_message_len))
545+ .bind(("ms_unset", expected.meal_slots.is_none()))
503 .bind(("ms", expected.meal_slots.clone()))546 .bind(("ms", expected.meal_slots.clone()))
504 .bind(("dt", expected.dietary_tags.clone()))547 .bind(("dt", expected.dietary_tags.clone()))
505 .bind(("mc", expected.meal_cancel_cutoff_minutes))548 .bind(("mc", expected.meal_cancel_cutoff_minutes))
src/lib.rsmodified+2 -2
@@ -56,9 +56,9 @@ use crate::state::AppState;
56 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),56 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),
57 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),57 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
58 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),58 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),
59- (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β€” `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β€” edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer β€” this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β€” own always, otherwise teacher+ or a parent link β€” and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β€” the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β€” staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β€” cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β€” inside that window neither booking nor cancelling lands (`409`) β€” measured back from midnight UTC starting the meal's day, the only instant a timezone-free `date` yields. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β€” the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β€” no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β€” the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β€” the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β€” `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β€” no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β€” the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"),59+ (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β€” `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β€” edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer β€” this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β€” own always, otherwise teacher+ or a parent link β€” and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β€” the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β€” staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β€” cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β€” inside that window neither booking nor cancelling lands (`409`) β€” measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** β€” this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β€” the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β€” no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β€” the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β€” the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β€” `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β€” no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β€” the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"),
60 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),60 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
61- (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for, the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a meal (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),61+ (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for β€” each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) β€” the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),
62 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),62 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
63 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),63 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),
64 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),64 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),
src/web/limits.rsmodified+5 -0
@@ -204,6 +204,10 @@ struct MealLimits {
204 /// Ceiling on the `/settings` knob that closes booking (and cancelling)204 /// Ceiling on the `/settings` knob that closes booking (and cancelling)
205 /// ahead of a meal, minutes; the live value is on `GET /settings`.205 /// ahead of a meal, minutes; the live value is on `GET /settings`.
206 max_cancel_cutoff_minutes: i64,206 max_cancel_cutoff_minutes: i64,
207+ /// Ceiling on a meal slot's `serving_minute` β€” minutes past midnight
208+ /// **UTC** on the menu's date, which is what the cutoff counts back from.
209+ /// `1439` = 23:59 UTC. There is no school timezone: staff enter UTC.
210+ max_serving_minute: i64,
207 /// The only accepted booking `status` values.211 /// The only accepted booking `status` values.
208 #[schema(example = json!(["booked", "cancelled"]))]212 #[schema(example = json!(["booked", "cancelled"]))]
209 booking_statuses: Vec<&'static str>,213 booking_statuses: Vec<&'static str>,
@@ -408,6 +412,7 @@ impl LimitsResponse {
408 max_ledger_method_len: MAX_LEDGER_METHOD_LEN,412 max_ledger_method_len: MAX_LEDGER_METHOD_LEN,
409 max_ledger_note_len: MAX_LEDGER_NOTE_LEN,413 max_ledger_note_len: MAX_LEDGER_NOTE_LEN,
410 max_cancel_cutoff_minutes: MAX_MEAL_CANCEL_CUTOFF_MINUTES,414 max_cancel_cutoff_minutes: MAX_MEAL_CANCEL_CUTOFF_MINUTES,
415+ max_serving_minute: MAX_MEAL_SERVING_MINUTE,
411 booking_statuses: MEAL_BOOKING_STATUSES.to_vec(),416 booking_statuses: MEAL_BOOKING_STATUSES.to_vec(),
412 attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(),417 attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(),
413 ledger_kinds: MEAL_LEDGER_KINDS.to_vec(),418 ledger_kinds: MEAL_LEDGER_KINDS.to_vec(),
src/web/meals.rsmodified+11 -8
@@ -20,7 +20,7 @@ use crate::constant::MAX_DISHES_PER_MENU;
20 use crate::database::Database;20 use crate::database::Database;
21 use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts};21 use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts};
22 use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};22 use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
23-use crate::domain::meal_booking::{MealBooking, MealBookingId};23+use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff};
24 use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger};24 use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger};
25 use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity};25 use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity};
26 use crate::domain::menu_dish::{26 use crate::domain::menu_dish::{
@@ -739,9 +739,12 @@ async fn booking_responses(
739 .collect())739 .collect())
740 }740 }
741 741
742-/// The school's one meal cutoff, applied to booking and cancelling alike.742+/// The school's one meal deadline, applied to booking and cancelling alike:
743-async fn cutoff_minutes(db: &Database) -> Result<Option<i64>, AppError> {743+/// the cutoff minutes plus the slot serving times they count back from. Read
744- Ok(Settings::load(db).await?.get_meal_cancel_cutoff_minutes())744+/// live on every call, so a serving time corrected today moves the deadline of
745+/// menus already published for it.
746+async fn meal_cutoff(db: &Database) -> Result<MealCutoff, AppError> {
747+ Ok(MealCutoff::from_settings(&Settings::load(db).await?))
745 }748 }
746 749
747 /// Whose seat is this? A student books only for themselves; a parent only for750 /// Whose seat is this? A student books only for themselves; a parent only for
@@ -818,13 +821,13 @@ async fn book_meal(
818 Json(req): Json<BookMeal>,821 Json(req): Json<BookMeal>,
819 ) -> Result<(StatusCode, Json<BookingResponse>), AppError> {822 ) -> Result<(StatusCode, Json<BookingResponse>), AppError> {
820 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;823 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
821- let cutoff = cutoff_minutes(&st.db).await?;824+ let cutoff = meal_cutoff(&st.db).await?;
822 let menu = MenuId::from_key(&id);825 let menu = MenuId::from_key(&id);
823 // Price, seat and charge all land together under `MENU_LOCK`, keyed by826 // Price, seat and charge all land together under `MENU_LOCK`, keyed by
824 // (seat, attempt) β€” a double-click books one seat and bills it once, and a827 // (seat, attempt) β€” a double-click books one seat and bills it once, and a
825 // dish cannot slip in between the price snapshot and the row it is frozen828 // dish cannot slip in between the price snapshot and the row it is frozen
826 // onto.829 // onto.
827- let booking = MealBooking::book(&menu, &student, user.get_id(), cutoff, &st.db).await?;830+ let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?;
828 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;831 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
829 Ok((832 Ok((
830 StatusCode::CREATED,833 StatusCode::CREATED,
@@ -943,10 +946,10 @@ async fn cancel_booking(
943 if &target != booking.get_student() {946 if &target != booking.get_student() {
944 return Err(AppError::Forbidden("not your booking"));947 return Err(AppError::Forbidden("not your booking"));
945 }948 }
946- let cutoff = cutoff_minutes(&st.db).await?;949+ let cutoff = meal_cutoff(&st.db).await?;
947 // Flips the row and appends the reversal for that attempt's charge950 // Flips the row and appends the reversal for that attempt's charge
948 // together, under the same lock booking uses; the charge itself stays.951 // together, under the same lock booking uses; the charge itself stays.
949- let cancelled = booking.cancel(cutoff, user.get_id(), &st.db).await?;952+ let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?;
950 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;953 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
951 Ok(Json(954 Ok(Json(
952 items.into_iter().next().expect("one booking in, one out"),955 items.into_iter().next().expect("one booking in, one out"),
src/web/settings.rsmodified+30 -10
@@ -39,6 +39,16 @@ struct MealSlotDto {
39 /// The `slot` value menus carry, 1–50 characters.39 /// The `slot` value menus carry, 1–50 characters.
40 #[schema(example = "lunch", max_length = 50)]40 #[schema(example = "lunch", max_length = 50)]
41 name: String,41 name: String,
42+ /// When the slot is served, as minutes past midnight **UTC** on the menu's
43+ /// date (`0`–`1439`; `720` = 12:00 UTC). `meal_cancel_cutoff_minutes`
44+ /// counts back from this instant.
45+ ///
46+ /// **The clock is UTC, not local time** β€” this API stores no school
47+ /// timezone, so a UTC+3 school enters `540` (09:00 UTC) for a meal served
48+ /// at noon locally. `null` = unset, and then the cutoff counts back from
49+ /// midnight UTC of the menu's date, the pre-serving-time behaviour.
50+ #[schema(example = 720, minimum = 0, maximum = 1_439)]
51+ serving_minute: Option<i64>,
42 }52 }
43 53
44 /// One grade-display band: marks at or above `min` (and below the next band's54 /// One grade-display band: marks at or above `min` (and below the next band's
@@ -84,15 +94,20 @@ struct SettingsResponse {
84 /// Character limit on one chat message.94 /// Character limit on one chat message.
85 #[schema(example = 4000)]95 #[schema(example = 4000)]
86 max_chatbot_message_len: i64,96 max_chatbot_message_len: i64,
87- /// Meal slots menus may be published for. Empty = the school runs no meal97+ /// Meal slots menus may be published for, each with the UTC minute it is
88- /// program.98+ /// served at (`null` = unset β†’ the cutoff counts back from midnight UTC).
89- #[schema(example = json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}]))]99+ /// Empty = the school runs no meal program.
100+ #[schema(example = json!([
101+ {"name": "breakfast", "serving_minute": 300},
102+ {"name": "lunch", "serving_minute": 720},
103+ {"name": "snack", "serving_minute": null},
104+ ]))]
90 meal_slots: Vec<MealSlotDto>,105 meal_slots: Vec<MealSlotDto>,
91 /// Dietary tags a dish and a student's profile may carry.106 /// Dietary tags a dish and a student's profile may carry.
92 #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))]107 #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))]
93 dietary_tags: Vec<String>,108 dietary_tags: Vec<String>,
94- /// How many minutes before a meal booking and cancelling close.109+ /// How many minutes before a slot's `serving_minute` booking and
95- /// `null` = no cutoff.110+ /// cancelling close. `null` = no cutoff.
96 #[schema(example = 120)]111 #[schema(example = 120)]
97 meal_cancel_cutoff_minutes: Option<i64>,112 meal_cancel_cutoff_minutes: Option<i64>,
98 }113 }
@@ -126,6 +141,7 @@ impl SettingsResponse {
126 .iter()141 .iter()
127 .map(|slot| MealSlotDto {142 .map(|slot| MealSlotDto {
128 name: slot.get_name().to_string(),143 name: slot.get_name().to_string(),
144+ serving_minute: slot.get_serving_minute(),
129 })145 })
130 .collect(),146 .collect(),
131 dietary_tags: settings.get_dietary_tags(),147 dietary_tags: settings.get_dietary_tags(),
@@ -166,16 +182,20 @@ struct UpdateSettings {
166 #[schema(example = 4000, minimum = 100, maximum = 8_000)]182 #[schema(example = 4000, minimum = 100, maximum = 8_000)]
167 max_chatbot_message_len: Option<i64>,183 max_chatbot_message_len: Option<i64>,
168 /// Replaces the whole list when present: at most 20 entries with unique184 /// Replaces the whole list when present: at most 20 entries with unique
169- /// names, each 1–50 characters. `[]` switches the meal program off. A slot185+ /// names, each 1–50 characters, each with an optional `serving_minute`
170- /// a menu was already published for cannot be removed (409).186+ /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts
187+ /// back from. `[]` switches the meal program off. A slot a menu was already
188+ /// published for cannot be removed (409); its serving time may be edited
189+ /// freely and applies live, to menus already published for it too.
171 #[schema(max_items = 20)]190 #[schema(max_items = 20)]
172 meal_slots: Option<Vec<MealSlotDto>>,191 meal_slots: Option<Vec<MealSlotDto>>,
173 /// Replaces the whole list when present: at most 20 unique entries, each192 /// Replaces the whole list when present: at most 20 unique entries, each
174 /// 1–50 characters. `[]` means the school tracks no dietary tags.193 /// 1–50 characters. `[]` means the school tracks no dietary tags.
175 #[schema(max_items = 20)]194 #[schema(max_items = 20)]
176 dietary_tags: Option<Vec<String>>,195 dietary_tags: Option<Vec<String>>,
177- /// Minutes before a meal at which booking *and* cancelling close,196+ /// Minutes before a slot's `serving_minute` at which booking *and*
178- /// `0`–`10080` (one week). Omit to keep the current value; send `null` for197+ /// cancelling close, `0`–`10080` (one week). A slot with no serving time
198+ /// is measured from midnight UTC of the menu's date instead. Omit to keep the current value; send `null` for
179 /// no cutoff at all.199 /// no cutoff at all.
180 #[serde(default, deserialize_with = "set_or_clear")]200 #[serde(default, deserialize_with = "set_or_clear")]
181 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]201 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
@@ -287,7 +307,7 @@ async fn update_settings(
287 let meal_slots = match &req.meal_slots {307 let meal_slots = match &req.meal_slots {
288 Some(slots) => slots308 Some(slots) => slots
289 .iter()309 .iter()
290- .map(|slot| MealSlotDef::try_new(&slot.name))310+ .map(|slot| MealSlotDef::try_new(&slot.name, slot.serving_minute))
291 .collect::<Result<Vec<_>, _>>()?,311 .collect::<Result<Vec<_>, _>>()?,
292 None => current.get_meal_slots(),312 None => current.get_meal_slots(),
293 };313 };
tests/integration.rsmodified+227 -4
@@ -10982,7 +10982,13 @@ async fn settings_round_trip_the_food_program_knobs() {
10982 let res = send(&app, "GET", "/settings", Some(&manager), None).await;10982 let res = send(&app, "GET", "/settings", Some(&manager), None).await;
10983 assert_eq!(10983 assert_eq!(
10984 res.body["meal_slots"],10984 res.body["meal_slots"],
10985- json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}])10985+ json!([
10986+ {"name": "breakfast", "serving_minute": null},
10987+ {"name": "lunch", "serving_minute": null},
10988+ {"name": "snack", "serving_minute": null},
10989+ ]),
10990+ "the shipped defaults carry no serving time, so the cutoff keeps its \
10991+ midnight-UTC meaning until a school sets real hours"
10986 );10992 );
10987 assert_eq!(10993 assert_eq!(
10988 res.body["dietary_tags"],10994 res.body["dietary_tags"],
@@ -11015,7 +11021,10 @@ async fn settings_round_trip_the_food_program_knobs() {
11015 "/settings",11021 "/settings",
11016 Some(&manager),11022 Some(&manager),
11017 Some(json!({11023 Some(json!({
11018- "meal_slots": [{"name": "lunch"}, {"name": " snack "}],11024+ "meal_slots": [
11025+ {"name": "lunch", "serving_minute": 720},
11026+ {"name": " snack "},
11027+ ],
11019 "dietary_tags": ["vegan"],11028 "dietary_tags": ["vegan"],
11020 "meal_cancel_cutoff_minutes": 120,11029 "meal_cancel_cutoff_minutes": 120,
11021 })),11030 })),
@@ -11024,7 +11033,11 @@ async fn settings_round_trip_the_food_program_knobs() {
11024 assert_eq!(res.status, StatusCode::OK);11033 assert_eq!(res.status, StatusCode::OK);
11025 assert_eq!(11034 assert_eq!(
11026 res.body["meal_slots"],11035 res.body["meal_slots"],
11027- json!([{"name": "lunch"}, {"name": "snack"}])11036+ json!([
11037+ {"name": "lunch", "serving_minute": 720},
11038+ {"name": "snack", "serving_minute": null},
11039+ ]),
11040+ "slots round-trip with and without a serving time"
11028 );11041 );
11029 assert_eq!(res.body["dietary_tags"], json!(["vegan"]));11042 assert_eq!(res.body["dietary_tags"], json!(["vegan"]));
11030 assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120);11043 assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120);
@@ -11062,6 +11075,8 @@ async fn settings_round_trip_the_food_program_knobs() {
11062 json!({ "meal_cancel_cutoff_minutes": -1 }),11075 json!({ "meal_cancel_cutoff_minutes": -1 }),
11063 json!({ "meal_slots": [{"name": " "}] }),11076 json!({ "meal_slots": [{"name": " "}] }),
11064 json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }),11077 json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }),
11078+ json!({ "meal_slots": [{"name": "lunch", "serving_minute": 1440}] }),
11079+ json!({ "meal_slots": [{"name": "lunch", "serving_minute": -1}] }),
11065 json!({ "dietary_tags": ["vegan", "VEGAN"] }),11080 json!({ "dietary_tags": ["vegan", "VEGAN"] }),
11066 ] {11081 ] {
11067 let res = send(11082 let res = send(
@@ -11105,7 +11120,10 @@ async fn settings_round_trip_the_food_program_knobs() {
11105 assert_eq!(res.status, StatusCode::OK);11120 assert_eq!(res.status, StatusCode::OK);
11106 assert_eq!(11121 assert_eq!(
11107 res.body["meal_slots"],11122 res.body["meal_slots"],
11108- json!([{"name": "lunch"}, {"name": "dinner"}])11123+ json!([
11124+ {"name": "lunch", "serving_minute": null},
11125+ {"name": "dinner", "serving_minute": null},
11126+ ])
11109 );11127 );
11110 }11128 }
11111 11129
@@ -20700,6 +20718,80 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() {
20700 assert_eq!(common::total(&res.body), 3, "and only three rows exist");20718 assert_eq!(common::total(&res.body), 3, "and only three rows exist");
20701 }20719 }
20702 20720
20721+/// Two appends of one ledger id must both succeed: the id is the idempotence
20722+/// key, so the loser reads back the winner's line instead of surfacing the
20723+/// duplicate-key error as a 500. Driven at the domain level on purpose β€” every
20724+/// HTTP path into the ledger runs under `MENU_LOCK`, which serializes the two
20725+/// writers before they can ever collide.
20726+#[tokio::test]
20727+async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() {
20728+ use hezarfen_backend::domain::meal_booking::{MealBooking, MealBookingId};
20729+ use hezarfen_backend::domain::meal_ledger::MealLedger;
20730+
20731+ let (app, db) = app_and_db().await;
20732+ let mgr = login_as(&app, &db, "ledger_race_mgr", "manager").await;
20733+ let ali = login(&app, "ledger_race_ali").await;
20734+
20735+ let res = send(
20736+ &app,
20737+ "POST",
20738+ "/meals/menus",
20739+ Some(&mgr),
20740+ Some(json!({ "date": "2026-09-15", "slot": "lunch" })),
20741+ )
20742+ .await;
20743+ let menu = id_of(&res.body);
20744+ let res = send(
20745+ &app,
20746+ "POST",
20747+ &format!("/meals/menus/{menu}/dishes"),
20748+ Some(&mgr),
20749+ Some(json!({ "name": "Pilav", "price_minor": 1000 })),
20750+ )
20751+ .await;
20752+ assert_eq!(res.status, StatusCode::CREATED);
20753+
20754+ // The seat charges 1000; its reversal line does not exist yet, so both
20755+ // racers below derive the same unwritten id.
20756+ let res = send(
20757+ &app,
20758+ "POST",
20759+ &format!("/meals/menus/{menu}/bookings"),
20760+ Some(&ali),
20761+ Some(json!({})),
20762+ )
20763+ .await;
20764+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20765+ let booking = MealBooking::read(&MealBookingId::from_key(&id_of(&res.body)), &db)
20766+ .await
20767+ .expect("read the booking")
20768+ .expect("the booking exists");
20769+ let student = booking.get_student().clone();
20770+ assert_eq!(
20771+ MealLedger::balance_of(&student, &db).await.unwrap(),
20772+ -1000,
20773+ "the seat was charged once"
20774+ );
20775+
20776+ let (first, second) = tokio::join!(
20777+ MealLedger::reverse_booking(&booking, &student, &db),
20778+ MealLedger::reverse_booking(&booking, &student, &db),
20779+ );
20780+ assert!(first.is_ok(), "the winner appended: {first:?}");
20781+ assert!(
20782+ second.is_ok(),
20783+ "the loser must read back the winner's line, not fail: {second:?}"
20784+ );
20785+
20786+ let lines = MealLedger::list_for_student(&student, &db).await.unwrap();
20787+ assert_eq!(lines.len(), 2, "one charge and exactly one reversal");
20788+ assert_eq!(
20789+ MealLedger::balance_of(&student, &db).await.unwrap(),
20790+ 0,
20791+ "the money moved back exactly once"
20792+ );
20793+}
20794+
20703 /// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes`20795 /// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes`
20704 /// neither a new booking nor a cancellation lands.20796 /// neither a new booking nor a cancellation lands.
20705 #[tokio::test]20797 #[tokio::test]
@@ -20781,6 +20873,137 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() {
20781 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);20873 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20782 }20874 }
20783 20875
20876+/// The cutoff counts back from the slot's **serving time**, not from midnight.
20877+/// The discriminating case: a menu on tomorrow's date whose lunch is served at
20878+/// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already
20879+/// inside it. Under the old midnight rule the seat is shut; measured from the
20880+/// serving time it is open for another ~24 hours. Then, with no serving time on
20881+/// the slot, the very same menu falls back to midnight and shuts β€” the upgrade
20882+/// path for every slot written before the field existed.
20883+#[tokio::test]
20884+async fn meal_cutoff_counts_back_from_the_slots_serving_time() {
20885+ let (app, db) = app_and_db().await;
20886+ let mgr = login_as(&app, &db, "serve_mgr", "manager").await;
20887+ let ali = login(&app, "serve_ali").await;
20888+
20889+ // Tomorrow UTC, so midnight of the menu's date is 0–1440 minutes ahead.
20890+ let now = Timestamp::now().as_millis();
20891+ let tomorrow = Timestamp::today_utc() + chrono::Days::new(1);
20892+ let midnight = tomorrow
20893+ .and_hms_opt(0, 0, 0)
20894+ .unwrap()
20895+ .and_utc()
20896+ .timestamp_millis();
20897+ // Five minutes wider than the gap to midnight: the midnight deadline is
20898+ // now in the past, while the 23:59 serving deadline is ~24 hours out.
20899+ let cutoff = (midnight - now).div_euclid(60_000) + 5;
20900+ let res = send(
20901+ &app,
20902+ "PATCH",
20903+ "/settings",
20904+ Some(&mgr),
20905+ Some(json!({
20906+ "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }],
20907+ "meal_cancel_cutoff_minutes": cutoff,
20908+ })),
20909+ )
20910+ .await;
20911+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20912+
20913+ let res = send(
20914+ &app,
20915+ "POST",
20916+ "/meals/menus",
20917+ Some(&mgr),
20918+ Some(json!({ "date": tomorrow.to_string(), "slot": "lunch" })),
20919+ )
20920+ .await;
20921+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20922+ let menu = id_of(&res.body);
20923+
20924+ let res = send(
20925+ &app,
20926+ "POST",
20927+ &format!("/meals/menus/{menu}/bookings"),
20928+ Some(&ali),
20929+ Some(json!({})),
20930+ )
20931+ .await;
20932+ assert_eq!(
20933+ res.status,
20934+ StatusCode::CREATED,
20935+ "measured from 23:59 the seat is still open; the midnight rule would \
20936+ have refused it: {}",
20937+ res.body
20938+ );
20939+ let booking = id_of(&res.body);
20940+
20941+ // Drop the serving time from the same slot: the deadline snaps back to
20942+ // midnight of the menu's date, which the cutoff already covers. The slot
20943+ // list is read live, so the menu published under it moves with it.
20944+ let res = send(
20945+ &app,
20946+ "PATCH",
20947+ "/settings",
20948+ Some(&mgr),
20949+ Some(json!({ "meal_slots": [{ "name": "lunch" }] })),
20950+ )
20951+ .await;
20952+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20953+ assert_eq!(
20954+ res.body["meal_slots"],
20955+ json!([{ "name": "lunch", "serving_minute": null }]),
20956+ "{}",
20957+ res.body
20958+ );
20959+
20960+ let veli = login(&app, "serve_veli").await;
20961+ let res = send(
20962+ &app,
20963+ "POST",
20964+ &format!("/meals/menus/{menu}/bookings"),
20965+ Some(&veli),
20966+ Some(json!({})),
20967+ )
20968+ .await;
20969+ assert_eq!(
20970+ res.status,
20971+ StatusCode::CONFLICT,
20972+ "with no serving time the cutoff falls back to midnight UTC: {}",
20973+ res.body
20974+ );
20975+ // Cancelling is closed by the same fallback deadline...
20976+ let res = send(
20977+ &app,
20978+ "DELETE",
20979+ &format!("/meals/bookings/{booking}"),
20980+ Some(&ali),
20981+ None,
20982+ )
20983+ .await;
20984+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
20985+
20986+ // ...and re-serving lunch at 23:59 opens both ends again.
20987+ let res = send(
20988+ &app,
20989+ "PATCH",
20990+ "/settings",
20991+ Some(&mgr),
20992+ Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }] })),
20993+ )
20994+ .await;
20995+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20996+ let res = send(
20997+ &app,
20998+ "DELETE",
20999+ &format!("/meals/bookings/{booking}"),
21000+ Some(&ali),
21001+ None,
21002+ )
21003+ .await;
21004+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21005+}
21006+
20784 /// Who may take a seat: the student it is for, or a parent holding a link to21007 /// Who may take a seat: the student it is for, or a parent holding a link to
20785 /// them. Nobody else β€” a teacher does not order lunch for a child.21008 /// them. Nobody else β€” a teacher does not order lunch for a child.
20786 #[tokio::test]21009 #[tokio::test]
tests/persistence.rsmodified+85 -0
@@ -1092,3 +1092,88 @@ async fn legacy_chat_turns_backfill_to_untruncated() {
1092 assert_eq!(turn["truncated"], false, "{turn}");1092 assert_eq!(turn["truncated"], false, "{turn}");
1093 }1093 }
1094 }1094 }
1095+
1096+/// A settings singleton whose `meal_slots` predate `serving_minute` β€” the live
1097+/// podman volume's shape β€” still reads, and still **saves**. The trap is the
1098+/// compare-and-set in `save_if_unchanged`: it re-binds the loaded slot list as
1099+/// the expected value, so if a slot object without the key round-tripped to one
1100+/// *with* `serving_minute: NONE`, the guard would never match again and every
1101+/// `PATCH /settings` would 409 forever on an upgraded database.
1102+#[tokio::test]
1103+async fn settings_slots_without_a_serving_minute_still_patch() {
1104+ let (app, db) = common::app_and_db().await;
1105+
1106+ let creds = json!({ "username": "boss", "password": "secret1" });
1107+ send(&app, "POST", "/auth/register", None, Some(creds.clone())).await;
1108+ set_role(&db, "boss", "manager").await;
1109+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone()))
1110+ .await
1111+ .cookie
1112+ .unwrap();
1113+
1114+ // Materialize the singleton, then age its slots into the pre-serving-time
1115+ // shape: objects carrying nothing but a name.
1116+ let res = send(
1117+ &app,
1118+ "PATCH",
1119+ "/settings",
1120+ Some(&cookie),
1121+ Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }] })),
1122+ )
1123+ .await;
1124+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1125+ db.query("UPDATE settings:school SET meal_slots = [{ name: 'lunch' }];")
1126+ .await
1127+ .expect("age slots")
1128+ .check()
1129+ .expect("age slots check");
1130+
1131+ // Second boot over that row: it reads back, with the field simply absent.
1132+ let app = reboot(&db).await;
1133+ let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
1134+ .await
1135+ .cookie
1136+ .unwrap();
1137+ let res = send(&app, "GET", "/settings", Some(&cookie), None).await;
1138+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1139+ assert_eq!(res.body["meal_slots"][0]["name"], "lunch", "{}", res.body);
1140+ assert!(
1141+ res.body["meal_slots"][0]["serving_minute"].is_null(),
1142+ "{}",
1143+ res.body
1144+ );
1145+
1146+ // And a PATCH of an unrelated knob still lands: the CAS matched the aged
1147+ // row. This is the assertion that would have caught a `DEFAULT []` column.
1148+ let res = send(
1149+ &app,
1150+ "PATCH",
1151+ "/settings",
1152+ Some(&cookie),
1153+ Some(json!({ "max_file_bytes": 2048 })),
1154+ )
1155+ .await;
1156+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1157+ assert_eq!(res.body["max_file_bytes"], 2048, "{}", res.body);
1158+ assert!(
1159+ res.body["meal_slots"][0]["serving_minute"].is_null(),
1160+ "{}",
1161+ res.body
1162+ );
1163+
1164+ // Setting the serving time on that legacy slot round-trips too.
1165+ let res = send(
1166+ &app,
1167+ "PATCH",
1168+ "/settings",
1169+ Some(&cookie),
1170+ Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 615 }] })),
1171+ )
1172+ .await;
1173+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1174+ assert_eq!(
1175+ res.body["meal_slots"][0]["serving_minute"], 615,
1176+ "{}",
1177+ res.body
1178+ );
1179+}
tests/spec_bounds.rsmodified+7 -0
@@ -578,6 +578,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
578 "maxLength",578 "maxLength",
579 MAX_SETTINGS_ITEM_LEN as i64,579 MAX_SETTINGS_ITEM_LEN as i64,
580 ),580 ),
581+ ("MealSlotDto", "serving_minute", "minimum", 0),
582+ (
583+ "MealSlotDto",
584+ "serving_minute",
585+ "maximum",
586+ MAX_MEAL_SERVING_MINUTE,
587+ ),
581 (588 (
582 "UpdateSettings",589 "UpdateSettings",
583 "meal_slots",590 "meal_slots",