diff --git a/README.md b/README.md index b75152a..6e735f0 100644 --- a/README.md +++ b/README.md @@ -240,6 +240,11 @@ Timezones and clock differences cannot corrupt data, by construction: the writer's wall, not an instant: validation accepts up to UTC-tomorrow, since a client ahead of UTC (up to UTC+14) legitimately writes a date the server's UTC calendar hasn't reached yet. +- **Times-of-day are UTC too, and staff enter them that way.** A meal slot's + `serving_minute` (minutes past midnight, `0`–`1439`) is the one clock-face + value a school types in, and it is read as UTC on the menu's `date` — there + is deliberately **no school-timezone setting** (a rejected feature), so a + UTC+3 school enters `540` (09:00 UTC) for a meal served at noon locally. - **Nothing schedules in the past.** A request-supplied schedule instant — an exam window, a lesson's `starts_at`/`ends_at`, an event time — must not lie 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 - **`slot` is a snapshot**, not a link into settings. It must be one of the school's `meal_slots` (`GET /settings`) *when the menu is written*, and it is stored as text — so retiring a slot later never rewrites a menu already - published under it. The mirror of that rule lives in settings: a slot any + published under it. The slot's `serving_minute` is *not* snapshotted: the + booking cutoff resolves it live from the current list. The mirror of that rule lives in settings: a slot any menu was published for cannot be removed from the list (`409`), same contract exam kinds have with graded exams. @@ -1256,12 +1262,25 @@ teacher or manager ordering a child's lunch is a `403`. otherwise all pass the count. The whole check-then-write runs under the same lock a menu publish takes, and the cap is re-read inside it. - **One cutoff closes both ends.** Within the school's - `meal_cancel_cutoff_minutes` of the meal's day, neither a new booking nor a - cancellation lands (`409`) — the kitchen's headcount has to settle at some - point. `null` (the default) means no cutoff at all. The cutoff is measured - back from **midnight UTC starting the meal's day**: `date` carries no - timezone and the backend stores no school timezone, so that is the only - instant derivable from it. + `meal_cancel_cutoff_minutes` of the meal's serving time, neither a new + booking nor a cancellation lands (`409`) — the kitchen's headcount has to + settle at some point. `null` (the default) means no cutoff at all. The + cutoff is measured back from the menu's `date` **plus the slot's + `serving_minute`** (`GET /settings`), so a two-hour cutoff on a lunch served + at `720` closes at 10:00 UTC that morning, not at 22:00 the night before. + **That minute is UTC**: `date` carries no timezone and the backend stores no + school timezone — deliberately, it is a rejected feature — so a UTC+3 school + enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no + `serving_minute` falls back to **midnight UTC starting the meal's day**, the + behaviour every booking had before the field existed; the booking is never + refused for want of a serving time. +- **The serving time is read live, not snapshotted onto the menu.** The cutoff + minutes are already read live, so freezing the other half of the same + deadline would make one policy edit apply and its twin not; a kitchen that + moves lunch an hour later wants today's menus to move with it. The menu + still snapshots the slot *name* (that is what keeps a retired slot's history + readable), so a menu whose slot has since left the list simply has no + serving time and falls back to midnight UTC. - A menu somebody still holds a seat on **cannot be unpublished** (`409`) — cancel the bookings first, so nothing is left pointing at a deleted meal. diff --git a/src/constant.rs b/src/constant.rs index 1e8c5b9..16bd649 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -195,6 +195,16 @@ pub const MAX_LEDGER_NOTE_LEN: usize = 500; /// a meal — one week. The knob itself is optional: absent means no cutoff. pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60; +/// Inclusive ceiling for a meal slot's `serving_minute` — minutes past +/// midnight on the menu's date, so `0` = 00:00 and `1439` = 23:59. The cutoff +/// above counts back from that instant. +/// +/// **The clock is UTC.** This backend deliberately stores no school timezone +/// (rejected feature), so staff enter the serving time in UTC: a UTC+3 school +/// types `540` (09:00) to mean noon locally. Optional per slot — a slot +/// without one keeps the old behaviour, midnight UTC of the menu's date. +pub const MAX_MEAL_SERVING_MINUTE: i64 = 24 * 60 - 1; + /// The only accepted course kinds. `course`: a regular class (ders). `study`: /// a supervised study session (etüt). Behaviorally identical — the kind is a /// label for the UI, everything else (enrollment, exams, sessions, marks) @@ -965,6 +975,12 @@ pub const MIGRATION: &str = " -- fine, which is why the food program needs no BACKFILL anywhere. DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option>; DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string; + -- Minutes past midnight UTC at which the slot is served (2026-07-26). + -- `option` for the same reason the list itself is: slots written + -- before the field existed simply have no key, and read back as NONE -> + -- the booking cutoff falls back to midnight UTC, its old meaning. No + -- BACKFILL, and no DEFAULT — see the note above. + DEFINE FIELD IF NOT EXISTS meal_slots.*.serving_minute ON settings TYPE option; DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option>; DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option; diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs index f49bd57..e4feac6 100644 --- a/src/domain/meal_booking.rs +++ b/src/domain/meal_booking.rs @@ -24,7 +24,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::MEAL_BOOKING_TABLE; use crate::database::Database; use crate::domain::meal_ledger::{LedgerAmount, MealLedger}; -use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId}; +use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot}; +use crate::domain::settings::{MealSlotDef, Settings}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -157,18 +158,18 @@ impl MealBooking { /// line. The price is `None` when the menu is free, and that `None` is /// stored, so a dish added later never bills a seat retroactively. /// - /// `cutoff_minutes` is the school's one meal cutoff (`None` = none): once - /// the meal's day is that close, the seat is fixed either way. + /// `cutoff` is the school's one meal deadline (see [`MealCutoff`]): once + /// serving time is that close, the seat is fixed either way. pub async fn book( menu: &MenuId, student: &UserId, booked_by: &UserId, - cutoff_minutes: Option, + cutoff: &MealCutoff, db: &Database, ) -> Result { let _guard = MENU_LOCK.lock().await; let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?; - check_cutoff(fresh.get_date(), cutoff_minutes)?; + check_cutoff(fresh.get_date(), fresh.get_slot(), cutoff)?; // Before the seat: an unchargeable menu (dishes summing past the cap) // must refuse the booking outright, never leave a booked-but-unbilled // row behind. @@ -233,7 +234,7 @@ impl MealBooking { /// the meal has since closed would strand the money exactly as before. pub async fn cancel( self, - cutoff_minutes: Option, + cutoff: &MealCutoff, recorded_by: &UserId, db: &Database, ) -> Result { @@ -246,7 +247,7 @@ impl MealBooking { let menu = Menu::read(&fresh.menu, db) .await? .ok_or(AppError::NotFound)?; - check_cutoff(menu.get_date(), cutoff_minutes)?; + check_cutoff(menu.get_date(), menu.get_slot(), cutoff)?; let cancelled = MealBooking { status: MealBookingStatus::Cancelled, cancelled_at: Some(Timestamp::now()), @@ -334,28 +335,66 @@ impl MealBooking { } } -/// The meal's day as an instant: **midnight UTC starting that day**. `date` is -/// text with no timezone (see [`MenuDate`]), and the backend stores no school -/// timezone, so the start of the UTC day is the only instant derivable from it. -/// A school wanting "two hours before lunch" sets the cutoff relative to that. -// ponytail: exact — needs a school timezone + a per-slot serving time, neither -// of which the settings singleton carries yet. -fn day_starts_at(date: &MenuDate) -> Option { +/// The school's meal deadline policy, resolved once per request: how many +/// minutes ahead booking and cancelling close, plus the slot list the serving +/// times live on. Built from [`Settings`] by the web layer and handed down, so +/// the domain never reaches for the singleton mid-lock. +/// +/// The slots are read **live**, not snapshotted onto the menu, and that is +/// deliberate: `meal_cancel_cutoff_minutes` is already read live, so freezing +/// the other half of the same deadline would make one policy edit apply and +/// its twin not. A kitchen that moves lunch an hour later wants today's menus +/// to move with it; the menu still snapshots the slot *name*, which is what +/// keeps a retired slot's history readable. +#[derive(Debug, Clone, Default)] +pub struct MealCutoff { + minutes: Option, + slots: Vec, +} + +impl MealCutoff { + pub fn from_settings(settings: &Settings) -> Self { + Self { + minutes: settings.get_meal_cancel_cutoff_minutes(), + slots: settings.get_meal_slots(), + } + } + + /// Minutes past midnight UTC at which `slot` is served, or `None` when the + /// school set none (or dropped the slot after a menu snapshotted its name). + fn serving_minute(&self, slot: &MenuSlot) -> Option { + self.slots + .iter() + .find(|def| def.get_name() == slot.as_str()) + .and_then(MealSlotDef::get_serving_minute) + } +} + +/// The instant the meal is served: midnight UTC of `date` plus the slot's +/// `serving_minute`. `date` is text with no timezone (see [`MenuDate`]) and the +/// backend deliberately stores no school timezone, so the serving time is UTC +/// too — a UTC+3 school enters 09:00 for a noon lunch. A slot with no serving +/// time falls back to midnight UTC, exactly what every booking used before the +/// field existed; refusing the booking instead would take the canteen offline +/// on an upgrade. +fn served_at(date: &MenuDate, serving_minute: Option) -> Option { let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?; Some(Timestamp::from_millis( - day.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis(), + day.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis() + + serving_minute.unwrap_or(0).saturating_mul(60_000), )) } -/// Booking and cancelling both close `cutoff_minutes` before the meal's day -/// starts. `None` = the school set no cutoff, so neither ever closes. -fn check_cutoff(date: &MenuDate, cutoff_minutes: Option) -> Result<(), AppError> { - let (Some(cutoff), Some(start)) = (cutoff_minutes, day_starts_at(date)) else { +/// Booking and cancelling both close `cutoff.minutes` before the meal is +/// served. `None` = the school set no cutoff, so neither ever closes. +fn check_cutoff(date: &MenuDate, slot: &MenuSlot, cutoff: &MealCutoff) -> Result<(), AppError> { + let serving = served_at(date, cutoff.serving_minute(slot)); + let (Some(minutes), Some(serving)) = (cutoff.minutes, serving) else { return Ok(()); }; - let deadline = start + let deadline = serving .as_millis() - .saturating_sub(cutoff.saturating_mul(60_000)); + .saturating_sub(minutes.saturating_mul(60_000)); if Timestamp::now().as_millis() >= deadline { return Err(AppError::Conflict("the menu's booking cutoff has passed")); } @@ -381,21 +420,45 @@ mod tests { } } + fn cutoff(minutes: Option, serving_minute: Option) -> MealCutoff { + MealCutoff { + minutes, + slots: vec![MealSlotDef::try_new("lunch", serving_minute).unwrap()], + } + } + + fn lunch() -> MenuSlot { + MenuSlot::try_new("lunch", &[MealSlotDef::try_new("lunch", None).unwrap()]).unwrap() + } + #[test] fn cutoff_closes_only_within_the_window() { let far = MenuDate::try_new("2999-01-01").unwrap(); let past = MenuDate::try_new("2000-01-01").unwrap(); // No cutoff configured: nothing ever closes, not even a past day. - assert!(check_cutoff(&past, None).is_ok()); + assert!(check_cutoff(&past, &lunch(), &cutoff(None, Some(720))).is_ok()); // A day far ahead is open; one long gone is shut. - assert!(check_cutoff(&far, Some(60)).is_ok()); - assert!(check_cutoff(&past, Some(60)).is_err()); - // The cutoff is measured back from midnight UTC of the meal's day. + assert!(check_cutoff(&far, &lunch(), &cutoff(Some(60), Some(720))).is_ok()); + assert!(check_cutoff(&past, &lunch(), &cutoff(Some(60), Some(720))).is_err()); + } + + /// The instant the deadline counts back from: midnight UTC of the day plus + /// the slot's serving minute, and midnight itself when the slot has none. + #[test] + fn serving_instant_offsets_midnight_utc() { + let day = MenuDate::try_new("1970-01-02").unwrap(); + assert_eq!(served_at(&day, None).unwrap().as_millis(), 86_400_000); + assert_eq!( + served_at(&day, Some(12 * 60)).unwrap().as_millis(), + 86_400_000 + 12 * 60 * 60_000 + ); + // A slot the school no longer lists (renamed or retired after the + // menu snapshotted its name) resolves to no serving time, i.e. the + // midnight fallback rather than a refusal. assert_eq!( - day_starts_at(&MenuDate::try_new("1970-01-02").unwrap()) - .unwrap() - .as_millis(), - 86_400_000 + cutoff(Some(60), Some(720)).serving_minute(&lunch()), + Some(720) ); + assert_eq!(MealCutoff::default().serving_minute(&lunch()), None); } } diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs index 3f60561..0bb87ce 100644 --- a/src/domain/meal_ledger.rs +++ b/src/domain/meal_ledger.rs @@ -42,7 +42,7 @@ use std::sync::LazyLock; -use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use surrealdb::types::{AlreadyExistsError, RecordId, RecordIdKey, SurrealValue}; use ulid::Generator; use crate::constant::{ @@ -108,6 +108,17 @@ impl MealLedgerId { } } +/// Did this `CREATE` fail *only* because the row is already there? Matched on +/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text +/// and never on "any database error", because swallowing a real fault in money +/// code would be far worse than the 500 it saves. +fn is_duplicate_record(error: &surrealdb::Error) -> bool { + matches!( + error.already_exists_details(), + Some(AlreadyExistsError::Record { .. }) + ) +} + /// The bare key of a record id — how every id leaves this API. fn key_of(record: &RecordId) -> &str { match &record.key { @@ -261,12 +272,20 @@ impl MealLedger { /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same /// append is a no-op, never a second line and never an edit of the first. /// The point read is on the id itself, so unlike a scan it cannot miss a - /// row a concurrent writer just made. + /// row a concurrent writer just made — but it is only a fast path. The + /// guarantee is `CREATE`'s own: on an existing id it *errors* and leaves + /// the row untouched, so the writer that lost the race reads back the + /// winner's line instead of failing the request with a 500. async fn append(row: MealLedger, db: &Database) -> Result { if let Some(existing) = Self::read(&row.id, db).await? { return Ok(existing); } - let created: Option = db.create(row.id.record()).content(row).await?; + let id = row.id.clone(); + let created: Option = match db.create(id.record()).content(row).await { + Ok(created) => created, + Err(e) if is_duplicate_record(&e) => Self::read(&id, db).await?, + Err(e) => return Err(e.into()), + }; created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into())) } diff --git a/src/domain/menu.rs b/src/domain/menu.rs index 9d7da04..5f209cc 100644 --- a/src/domain/menu.rs +++ b/src/domain/menu.rs @@ -313,7 +313,7 @@ mod tests { #[test] fn slot_must_be_one_the_school_serves() { - let allowed = vec![MealSlotDef::try_new("lunch").unwrap()]; + let allowed = vec![MealSlotDef::try_new("lunch", None).unwrap()]; assert!(MenuSlot::try_new("lunch", &allowed).is_ok()); assert!(MenuSlot::try_new("brunch", &allowed).is_err()); assert!(MenuSlot::try_new("lunch", &[]).is_err()); diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 3a03085..daecb69 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -19,9 +19,9 @@ use crate::constant::{ DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, - MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, - MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, - SETTINGS_KEY, SETTINGS_TABLE, + MAX_MEAL_SERVING_MINUTE, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, + MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, + MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, SETTINGS_KEY, SETTINGS_TABLE, }; use crate::database::Database; use crate::domain::text_fold; @@ -70,14 +70,22 @@ impl ExamKindDef { /// One meal slot the school serves (`"lunch"`, `"snack"`, …). A published menu /// snapshots the slot's *name* as text, so retiring a slot never rewrites a /// past menu — same contract exam kinds have with exams. An object, not a bare -/// string, so a slot can grow a serving window later without a migration. +/// string, which is what let the serving time land here without a migration. +/// +/// `serving_minute` is minutes past midnight **UTC** on the menu's date, and +/// it is what the booking/cancel cutoff counts back from. The backend stores +/// no school timezone (deliberately), so staff enter UTC: a UTC+3 school sets +/// `540` (09:00) for a meal served at noon locally. `None` — every slot +/// written before the field existed — falls back to midnight UTC, the old +/// behaviour. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct MealSlotDef { name: String, + serving_minute: Option, } impl MealSlotDef { - pub fn try_new(name: &str) -> Result { + pub fn try_new(name: &str, serving_minute: Option) -> Result { let name = name.trim(); if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { return Err(ValidationError::Invalid { @@ -85,14 +93,29 @@ impl MealSlotDef { reason: "slot names must be 1 to 50 characters", }); } + if let Some(minute) = serving_minute { + in_range( + "meal_slots", + minute, + 0..=MAX_MEAL_SERVING_MINUTE, + "serving minutes must be between 0 (00:00 UTC) and 1439 (23:59 UTC)", + )?; + } Ok(Self { name: name.to_string(), + serving_minute, }) } pub fn get_name(&self) -> &str { &self.name } + + /// Minutes past midnight UTC at which this slot is served; `None` = unset, + /// so the cutoff counts back from midnight UTC instead. + pub fn get_serving_minute(&self) -> Option { + self.serving_minute + } } /// One grade-display band: marks at or above `min` (and below the next band's @@ -411,6 +434,9 @@ impl Settings { DEFAULT_MEAL_SLOTS .map(|name| MealSlotDef { name: name.to_string(), + // No built-in serving time: the shipped defaults keep the + // midnight-UTC cutoff until a school sets real hours. + serving_minute: None, }) .to_vec() }) @@ -468,6 +494,18 @@ impl Settings { /// state when no row exists yet (`load` reported the defaults, so the /// defaults are what the caller merged over), then the guarded update /// applies `self` only if the row (still) equals `expected`. + /// + /// **`meal_slots` is compared through a projection, and it has to be.** + /// SurrealDB *drops* an object key whose value is `NONE` on write, while + /// the `SurrealValue` derive always emits `serving_minute: NONE` for a + /// slot without one — so `{name: 'lunch'} = {name: 'lunch', serving_minute: + /// NONE}` is **false** and a plain equality guard would never match again + /// for any school with a serving-time-less slot (which is every school + /// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding + /// both sides as full objects normalizes the shapes. The NONE-ness of the + /// column itself is compared separately, so "never set" stays distinguishable + /// from "explicitly empty". Top-level optional columns need none of this: + /// a missing field reads as `NONE`, and `NONE = NONE` holds. pub async fn save_if_unchanged( self, expected: &Settings, @@ -485,7 +523,11 @@ impl Settings { AND chatbot_history_turns = $ct AND max_chatbot_threads = $cc AND max_chatbot_message_len = $cl - AND meal_slots = $ms + AND (meal_slots = NONE) = $ms_unset + AND (meal_slots ?? []).map(|$s| { + name: $s.name, + serving_minute: $s.serving_minute + }) = ($ms ?? []) AND dietary_tags = $dt AND meal_cancel_cutoff_minutes = $mc; COMMIT TRANSACTION;", @@ -500,6 +542,7 @@ impl Settings { .bind(("ct", expected.chatbot_history_turns)) .bind(("cc", expected.max_chatbot_threads)) .bind(("cl", expected.max_chatbot_message_len)) + .bind(("ms_unset", expected.meal_slots.is_none())) .bind(("ms", expected.meal_slots.clone())) .bind(("dt", expected.dietary_tags.clone())) .bind(("mc", expected.meal_cancel_cutoff_minutes)) diff --git a/src/lib.rs b/src/lib.rs index 7720c70..3cffc4d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,9 +56,9 @@ use crate::state::AppState; (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), - (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), 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"), + (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"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for, 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+"), + (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+"), (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"), (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"), (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+"), diff --git a/src/web/limits.rs b/src/web/limits.rs index fe85112..dfd82df 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -204,6 +204,10 @@ struct MealLimits { /// Ceiling on the `/settings` knob that closes booking (and cancelling) /// ahead of a meal, minutes; the live value is on `GET /settings`. max_cancel_cutoff_minutes: i64, + /// Ceiling on a meal slot's `serving_minute` — minutes past midnight + /// **UTC** on the menu's date, which is what the cutoff counts back from. + /// `1439` = 23:59 UTC. There is no school timezone: staff enter UTC. + max_serving_minute: i64, /// The only accepted booking `status` values. #[schema(example = json!(["booked", "cancelled"]))] booking_statuses: Vec<&'static str>, @@ -408,6 +412,7 @@ impl LimitsResponse { max_ledger_method_len: MAX_LEDGER_METHOD_LEN, max_ledger_note_len: MAX_LEDGER_NOTE_LEN, max_cancel_cutoff_minutes: MAX_MEAL_CANCEL_CUTOFF_MINUTES, + max_serving_minute: MAX_MEAL_SERVING_MINUTE, booking_statuses: MEAL_BOOKING_STATUSES.to_vec(), attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(), ledger_kinds: MEAL_LEDGER_KINDS.to_vec(), diff --git a/src/web/meals.rs b/src/web/meals.rs index 2365c82..4d8a9d1 100644 --- a/src/web/meals.rs +++ b/src/web/meals.rs @@ -20,7 +20,7 @@ use crate::constant::MAX_DISHES_PER_MENU; use crate::database::Database; use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts}; use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus}; -use crate::domain::meal_booking::{MealBooking, MealBookingId}; +use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; use crate::domain::menu_dish::{ @@ -739,9 +739,12 @@ async fn booking_responses( .collect()) } -/// The school's one meal cutoff, applied to booking and cancelling alike. -async fn cutoff_minutes(db: &Database) -> Result, AppError> { - Ok(Settings::load(db).await?.get_meal_cancel_cutoff_minutes()) +/// The school's one meal deadline, applied to booking and cancelling alike: +/// the cutoff minutes plus the slot serving times they count back from. Read +/// live on every call, so a serving time corrected today moves the deadline of +/// menus already published for it. +async fn meal_cutoff(db: &Database) -> Result { + Ok(MealCutoff::from_settings(&Settings::load(db).await?)) } /// Whose seat is this? A student books only for themselves; a parent only for @@ -818,13 +821,13 @@ async fn book_meal( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?; - let cutoff = cutoff_minutes(&st.db).await?; + let cutoff = meal_cutoff(&st.db).await?; let menu = MenuId::from_key(&id); // Price, seat and charge all land together under `MENU_LOCK`, keyed by // (seat, attempt) — a double-click books one seat and bills it once, and a // dish cannot slip in between the price snapshot and the row it is frozen // onto. - let booking = MealBooking::book(&menu, &student, user.get_id(), cutoff, &st.db).await?; + let booking = MealBooking::book(&menu, &student, user.get_id(), &cutoff, &st.db).await?; let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?; Ok(( StatusCode::CREATED, @@ -943,10 +946,10 @@ async fn cancel_booking( if &target != booking.get_student() { return Err(AppError::Forbidden("not your booking")); } - let cutoff = cutoff_minutes(&st.db).await?; + let cutoff = meal_cutoff(&st.db).await?; // Flips the row and appends the reversal for that attempt's charge // together, under the same lock booking uses; the charge itself stays. - let cancelled = booking.cancel(cutoff, user.get_id(), &st.db).await?; + let cancelled = booking.cancel(&cutoff, user.get_id(), &st.db).await?; let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?; Ok(Json( items.into_iter().next().expect("one booking in, one out"), diff --git a/src/web/settings.rs b/src/web/settings.rs index 88ddb50..94cead6 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -39,6 +39,16 @@ struct MealSlotDto { /// The `slot` value menus carry, 1–50 characters. #[schema(example = "lunch", max_length = 50)] name: String, + /// When the slot is served, as minutes past midnight **UTC** on the menu's + /// date (`0`–`1439`; `720` = 12:00 UTC). `meal_cancel_cutoff_minutes` + /// counts back from this instant. + /// + /// **The clock is UTC, not local time** — this API stores no school + /// timezone, so a UTC+3 school enters `540` (09:00 UTC) for a meal served + /// at noon locally. `null` = unset, and then the cutoff counts back from + /// midnight UTC of the menu's date, the pre-serving-time behaviour. + #[schema(example = 720, minimum = 0, maximum = 1_439)] + serving_minute: Option, } /// One grade-display band: marks at or above `min` (and below the next band's @@ -84,15 +94,20 @@ struct SettingsResponse { /// Character limit on one chat message. #[schema(example = 4000)] max_chatbot_message_len: i64, - /// Meal slots menus may be published for. Empty = the school runs no meal - /// program. - #[schema(example = json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}]))] + /// Meal slots menus may be published for, each with the UTC minute it is + /// served at (`null` = unset → the cutoff counts back from midnight UTC). + /// Empty = the school runs no meal program. + #[schema(example = json!([ + {"name": "breakfast", "serving_minute": 300}, + {"name": "lunch", "serving_minute": 720}, + {"name": "snack", "serving_minute": null}, + ]))] meal_slots: Vec, /// Dietary tags a dish and a student's profile may carry. #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))] dietary_tags: Vec, - /// How many minutes before a meal booking and cancelling close. - /// `null` = no cutoff. + /// How many minutes before a slot's `serving_minute` booking and + /// cancelling close. `null` = no cutoff. #[schema(example = 120)] meal_cancel_cutoff_minutes: Option, } @@ -126,6 +141,7 @@ impl SettingsResponse { .iter() .map(|slot| MealSlotDto { name: slot.get_name().to_string(), + serving_minute: slot.get_serving_minute(), }) .collect(), dietary_tags: settings.get_dietary_tags(), @@ -166,16 +182,20 @@ struct UpdateSettings { #[schema(example = 4000, minimum = 100, maximum = 8_000)] max_chatbot_message_len: Option, /// Replaces the whole list when present: at most 20 entries with unique - /// names, each 1–50 characters. `[]` switches the meal program off. A slot - /// a menu was already published for cannot be removed (409). + /// names, each 1–50 characters, each with an optional `serving_minute` + /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts + /// back from. `[]` switches the meal program off. A slot a menu was already + /// published for cannot be removed (409); its serving time may be edited + /// freely and applies live, to menus already published for it too. #[schema(max_items = 20)] meal_slots: Option>, /// Replaces the whole list when present: at most 20 unique entries, each /// 1–50 characters. `[]` means the school tracks no dietary tags. #[schema(max_items = 20)] dietary_tags: Option>, - /// Minutes before a meal at which booking *and* cancelling close, - /// `0`–`10080` (one week). Omit to keep the current value; send `null` for + /// Minutes before a slot's `serving_minute` at which booking *and* + /// cancelling close, `0`–`10080` (one week). A slot with no serving time + /// is measured from midnight UTC of the menu's date instead. Omit to keep the current value; send `null` for /// no cutoff at all. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = 120, minimum = 0, maximum = 10_080)] @@ -287,7 +307,7 @@ async fn update_settings( let meal_slots = match &req.meal_slots { Some(slots) => slots .iter() - .map(|slot| MealSlotDef::try_new(&slot.name)) + .map(|slot| MealSlotDef::try_new(&slot.name, slot.serving_minute)) .collect::, _>>()?, None => current.get_meal_slots(), }; diff --git a/tests/integration.rs b/tests/integration.rs index 3ba051e..16f6cf7 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10982,7 +10982,13 @@ async fn settings_round_trip_the_food_program_knobs() { let res = send(&app, "GET", "/settings", Some(&manager), None).await; assert_eq!( res.body["meal_slots"], - json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}]) + json!([ + {"name": "breakfast", "serving_minute": null}, + {"name": "lunch", "serving_minute": null}, + {"name": "snack", "serving_minute": null}, + ]), + "the shipped defaults carry no serving time, so the cutoff keeps its \ + midnight-UTC meaning until a school sets real hours" ); assert_eq!( res.body["dietary_tags"], @@ -11015,7 +11021,10 @@ async fn settings_round_trip_the_food_program_knobs() { "/settings", Some(&manager), Some(json!({ - "meal_slots": [{"name": "lunch"}, {"name": " snack "}], + "meal_slots": [ + {"name": "lunch", "serving_minute": 720}, + {"name": " snack "}, + ], "dietary_tags": ["vegan"], "meal_cancel_cutoff_minutes": 120, })), @@ -11024,7 +11033,11 @@ async fn settings_round_trip_the_food_program_knobs() { assert_eq!(res.status, StatusCode::OK); assert_eq!( res.body["meal_slots"], - json!([{"name": "lunch"}, {"name": "snack"}]) + json!([ + {"name": "lunch", "serving_minute": 720}, + {"name": "snack", "serving_minute": null}, + ]), + "slots round-trip with and without a serving time" ); assert_eq!(res.body["dietary_tags"], json!(["vegan"])); assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120); @@ -11062,6 +11075,8 @@ async fn settings_round_trip_the_food_program_knobs() { json!({ "meal_cancel_cutoff_minutes": -1 }), json!({ "meal_slots": [{"name": " "}] }), json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }), + json!({ "meal_slots": [{"name": "lunch", "serving_minute": 1440}] }), + json!({ "meal_slots": [{"name": "lunch", "serving_minute": -1}] }), json!({ "dietary_tags": ["vegan", "VEGAN"] }), ] { let res = send( @@ -11105,7 +11120,10 @@ async fn settings_round_trip_the_food_program_knobs() { assert_eq!(res.status, StatusCode::OK); assert_eq!( res.body["meal_slots"], - json!([{"name": "lunch"}, {"name": "dinner"}]) + json!([ + {"name": "lunch", "serving_minute": null}, + {"name": "dinner", "serving_minute": null}, + ]) ); } @@ -20700,6 +20718,80 @@ async fn concurrent_meal_bookings_never_exceed_the_capacity() { assert_eq!(common::total(&res.body), 3, "and only three rows exist"); } +/// Two appends of one ledger id must both succeed: the id is the idempotence +/// key, so the loser reads back the winner's line instead of surfacing the +/// duplicate-key error as a 500. Driven at the domain level on purpose — every +/// HTTP path into the ledger runs under `MENU_LOCK`, which serializes the two +/// writers before they can ever collide. +#[tokio::test] +async fn concurrent_ledger_appends_of_one_id_write_one_line_not_a_500() { + use hezarfen_backend::domain::meal_booking::{MealBooking, MealBookingId}; + use hezarfen_backend::domain::meal_ledger::MealLedger; + + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "ledger_race_mgr", "manager").await; + let ali = login(&app, "ledger_race_ali").await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-15", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": 1000 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + + // The seat charges 1000; its reversal line does not exist yet, so both + // racers below derive the same unwritten id. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = MealBooking::read(&MealBookingId::from_key(&id_of(&res.body)), &db) + .await + .expect("read the booking") + .expect("the booking exists"); + let student = booking.get_student().clone(); + assert_eq!( + MealLedger::balance_of(&student, &db).await.unwrap(), + -1000, + "the seat was charged once" + ); + + let (first, second) = tokio::join!( + MealLedger::reverse_booking(&booking, &student, &db), + MealLedger::reverse_booking(&booking, &student, &db), + ); + assert!(first.is_ok(), "the winner appended: {first:?}"); + assert!( + second.is_ok(), + "the loser must read back the winner's line, not fail: {second:?}" + ); + + let lines = MealLedger::list_for_student(&student, &db).await.unwrap(); + assert_eq!(lines.len(), 2, "one charge and exactly one reversal"); + assert_eq!( + MealLedger::balance_of(&student, &db).await.unwrap(), + 0, + "the money moved back exactly once" + ); +} + /// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes` /// neither a new booking nor a cancellation lands. #[tokio::test] @@ -20781,6 +20873,137 @@ async fn meal_cutoff_closes_booking_and_cancelling_alike() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); } +/// The cutoff counts back from the slot's **serving time**, not from midnight. +/// The discriminating case: a menu on tomorrow's date whose lunch is served at +/// 23:59 UTC, with a cutoff wide enough that *midnight* of that date is already +/// inside it. Under the old midnight rule the seat is shut; measured from the +/// serving time it is open for another ~24 hours. Then, with no serving time on +/// the slot, the very same menu falls back to midnight and shuts — the upgrade +/// path for every slot written before the field existed. +#[tokio::test] +async fn meal_cutoff_counts_back_from_the_slots_serving_time() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "serve_mgr", "manager").await; + let ali = login(&app, "serve_ali").await; + + // Tomorrow UTC, so midnight of the menu's date is 0–1440 minutes ahead. + let now = Timestamp::now().as_millis(); + let tomorrow = Timestamp::today_utc() + chrono::Days::new(1); + let midnight = tomorrow + .and_hms_opt(0, 0, 0) + .unwrap() + .and_utc() + .timestamp_millis(); + // Five minutes wider than the gap to midnight: the midnight deadline is + // now in the past, while the 23:59 serving deadline is ~24 hours out. + let cutoff = (midnight - now).div_euclid(60_000) + 5; + let res = send( + &app, + "PATCH", + "/settings", + Some(&mgr), + Some(json!({ + "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }], + "meal_cancel_cutoff_minutes": cutoff, + })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": tomorrow.to_string(), "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let menu = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "measured from 23:59 the seat is still open; the midnight rule would \ + have refused it: {}", + res.body + ); + let booking = id_of(&res.body); + + // Drop the serving time from the same slot: the deadline snaps back to + // midnight of the menu's date, which the cutoff already covers. The slot + // list is read live, so the menu published under it moves with it. + let res = send( + &app, + "PATCH", + "/settings", + Some(&mgr), + Some(json!({ "meal_slots": [{ "name": "lunch" }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + res.body["meal_slots"], + json!([{ "name": "lunch", "serving_minute": null }]), + "{}", + res.body + ); + + let veli = login(&app, "serve_veli").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&veli), + Some(json!({})), + ) + .await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "with no serving time the cutoff falls back to midnight UTC: {}", + res.body + ); + // Cancelling is closed by the same fallback deadline... + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // ...and re-serving lunch at 23:59 opens both ends again. + let res = send( + &app, + "PATCH", + "/settings", + Some(&mgr), + Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 1439 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + /// Who may take a seat: the student it is for, or a parent holding a link to /// them. Nobody else — a teacher does not order lunch for a child. #[tokio::test] diff --git a/tests/persistence.rs b/tests/persistence.rs index f1a5d49..5c7dc15 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -1092,3 +1092,88 @@ async fn legacy_chat_turns_backfill_to_untruncated() { assert_eq!(turn["truncated"], false, "{turn}"); } } + +/// A settings singleton whose `meal_slots` predate `serving_minute` — the live +/// podman volume's shape — still reads, and still **saves**. The trap is the +/// compare-and-set in `save_if_unchanged`: it re-binds the loaded slot list as +/// the expected value, so if a slot object without the key round-tripped to one +/// *with* `serving_minute: NONE`, the guard would never match again and every +/// `PATCH /settings` would 409 forever on an upgraded database. +#[tokio::test] +async fn settings_slots_without_a_serving_minute_still_patch() { + let (app, db) = common::app_and_db().await; + + let creds = json!({ "username": "boss", "password": "secret1" }); + send(&app, "POST", "/auth/register", None, Some(creds.clone())).await; + set_role(&db, "boss", "manager").await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds.clone())) + .await + .cookie + .unwrap(); + + // Materialize the singleton, then age its slots into the pre-serving-time + // shape: objects carrying nothing but a name. + let res = send( + &app, + "PATCH", + "/settings", + Some(&cookie), + Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 720 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + db.query("UPDATE settings:school SET meal_slots = [{ name: 'lunch' }];") + .await + .expect("age slots") + .check() + .expect("age slots check"); + + // Second boot over that row: it reads back, with the field simply absent. + let app = reboot(&db).await; + let cookie = send(&app, "POST", "/auth/login", None, Some(creds)) + .await + .cookie + .unwrap(); + let res = send(&app, "GET", "/settings", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["meal_slots"][0]["name"], "lunch", "{}", res.body); + assert!( + res.body["meal_slots"][0]["serving_minute"].is_null(), + "{}", + res.body + ); + + // And a PATCH of an unrelated knob still lands: the CAS matched the aged + // row. This is the assertion that would have caught a `DEFAULT []` column. + let res = send( + &app, + "PATCH", + "/settings", + Some(&cookie), + Some(json!({ "max_file_bytes": 2048 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["max_file_bytes"], 2048, "{}", res.body); + assert!( + res.body["meal_slots"][0]["serving_minute"].is_null(), + "{}", + res.body + ); + + // Setting the serving time on that legacy slot round-trips too. + let res = send( + &app, + "PATCH", + "/settings", + Some(&cookie), + Some(json!({ "meal_slots": [{ "name": "lunch", "serving_minute": 615 }] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!( + res.body["meal_slots"][0]["serving_minute"], 615, + "{}", + res.body + ); +} diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index b971967..5396630 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -578,6 +578,13 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maxLength", MAX_SETTINGS_ITEM_LEN as i64, ), + ("MealSlotDto", "serving_minute", "minimum", 0), + ( + "MealSlotDto", + "serving_minute", + "maximum", + MAX_MEAL_SERVING_MINUTE, + ), ( "UpdateSettings", "meal_slots",