diff --git a/README.md b/README.md index ae368c4..b75152a 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,18 @@ inference outlives a request: the turn plus an empty `pending` answer are written *first*, the call goes out after, so a reload never loses an answer; the client then polls the message or reads it off an SSE stream (see "Chatbot"). +The school's **food program** is published here too: a manager puts up one +**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot` +drawn from the school's `meal_slots`, unique per pair), lists its **dishes** +with dietary tags from the school's own list, and prices them in **minor +units** (kuruş) as integers — this API never speaks decimals or floats about +money. A student's own **dietary profile** is tagged from that same list +(manager-written — an allergen list is a school record, not a self-service +preference), so every dish a menu read returns names the tags it `conflicts` +with for whoever is reading. Every authenticated user reads what is being +served; students (or their parents) book a seat, and every seat writes a line into an +**append-only** meal ledger whose balance is derived and never stored (see +"Food program: menus, dishes, bookings & the ledger"). Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) constructed only after its restrictions pass — invalid input can't be @@ -748,6 +760,28 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/terms/{id}` | student | Get one term | | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) | | DELETE | `/terms/{id}` | manager | Delete a term — `409` while any course still links to it | +| POST | `/meals/menus` | manager | `{date, slot, capacity?}` — publish a menu; `date` is `YYYY-MM-DD` text, `slot` must be one of the school's `meal_slots`; `409` when that day+slot is already published | +| GET | `/meals/menus` | student | List menus with their dishes, newest day first · `?from=&to=` inclusive `YYYY-MM-DD` range · paged | +| GET | `/meals/menus/{id}` | student | One menu with its dishes | +| PATCH | `/meals/menus/{id}` | manager | `{capacity}` — the only mutable field (`null` = uncapped); `date` and `slot` are immutable | +| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat | +| POST | `/meals/menus/{id}/dishes` | manager | `{name, description?, price_minor, tags?}` — add a dish (≤ 50 per menu, `409` at the cap); `tags` must come from the school's `dietary_tags` | +| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it) | +| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu | +| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) | +| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link | +| PATCH | `/meals/profiles/{user}` | manager | `{tags?, note?}` — record what a student may not eat (`tags` replaces the list, `"note": null` clears it); **manager+**, a student never edits their own | +| POST | `/meals/menus/{id}/bookings` | student | `{student_id?}` — take a seat; a student books for themselves, a parent for a linked student; `409` when the menu is full or its cutoff has passed | +| GET | `/meals/bookings/me` | student | The caller's own bookings (seats held for them + for a parent, their currently linked children's), newest first · paged | +| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included · paged | +| DELETE | `/meals/bookings/{bid}` | student | Cancel a booking (status flip, the row stays); idempotent — cancelling again is a `200` that replays the refund; `409` past the cutoff | +| POST | `/meals/menus/{id}/attendance` | teacher | `{student_id, status}` — mark who was served (`served`/`missed`); one row per (menu, student), re-marking flips it; **moves no money** | +| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu · paged | +| GET | `/meals/attendance/{user}` | student | One student's meal-attendance history · `?from=&to=` inclusive `YYYY-MM-DD` range over the menu's day · paged · own id always, otherwise teacher+ or a parent link | +| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) | +| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link | +| GET | `/meals/ledger/{user}` | student | That student's statement — every charge, credit, reversal — newest first · paged · same gate | +| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` — record money received; **admin only**, appends a `credit` line | | POST | `/chatbot/threads` | student | `{title?}` — start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` | | GET | `/chatbot/threads` | student | The caller's threads, newest activity first · paged | | PATCH | `/chatbot/threads/{id}` | student | `{title}` — rename own thread (`null` or blank clears it back to untitled); counts as activity, so the thread moves to the top. Nothing auto-titles a thread | @@ -1116,6 +1150,8 @@ the later write silently reverting the earlier one. Editing a list never rewrites history: an exam keeps its retired kind, a roll-call row keeps its retired status — only **new writes** are held to the current lists. +The kitchen is data too: a manager publishes a **menu** per calendar day and meal slot, with its dishes, their dietary tags, and prices in minor units; booking a seat charges that price as a snapshot and an admin records the cash that comes back in (see "Food program: menus, dishes, bookings & the ledger"). + Academic structure is data too. **Terms** (`/terms`) model whatever calendar the school runs — semester, trimester, quarter systems are just rows with a name and a date range. Courses may link to one via `term_id` (nullable), and @@ -1132,6 +1168,204 @@ validation bounds, and the UTC time policy are invariants, not preferences environment variables — the model is **one school per deployment**, which keeps every school's data physically isolated. +## Food program: menus, dishes, bookings, attendance & the ledger + +The school publishes **one menu per calendar day and meal slot** (`POST +/meals/menus`). Two shapes there are deliberate: + +- **`date` is text**, `YYYY-MM-DD`, not a timestamp. "One menu per day and + slot" is an equality test on the school's own day, and a midnight-in-millis + day is only unique for one timezone. Fixed-width and zero-padded, so the + text sorts chronologically — which is what the inclusive `?from=&to=` range + filter and the newest-day-first ordering are built on. +- **`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 + menu was published for cannot be removed from the list (`409`), same + contract exam kinds have with graded exams. + +The day+slot pair is unique: a second publish for the same meal answers `409` +— edit the first one instead. Only `capacity` is patchable (`null` = uncapped) +— `date` and `slot` are immutable, because a menu on another day is another +menu. + +**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then +`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional +description (blank or `null` clears it), dietary `tags` drawn from the +school's `dietary_tags` list — an unknown tag is a `400`, never a stored +string — and a `price_minor`. + +### Dietary profiles and conflicts + +A student carries a **dietary profile**: a list of tags plus a free-text note +for the kitchen, one row per student (the record key *is* the student's id). +The tags come from the *same* `dietary_tags` list a dish is tagged from — +there is deliberately no second vocabulary, because one shared list is exactly +what makes "is this dish a problem for this student" answerable as a set +intersection, without the backend knowing any nutrition. + +Writing it is **manager+** (`PATCH /meals/profiles/{user}`, first write +creates the row). A student does *not* edit their own allergen list: it is a +safety record the school keeps on their behalf, and a mistyped — or quietly +removed — allergy would otherwise reach the kitchen with the school's +authority behind it. Reading is `GET /meals/profiles/me`, or +`GET /meals/profiles/{user}` under the usual per-student gate (own id always, +otherwise teacher+ or a parent link). A student who was never recorded reads +back as an *empty* profile rather than a `404` — "nothing known" is an answer. + +Every dish a menu read returns therefore carries a **`conflicts`** list: the +intersection of that dish's `tags` with the **calling user's** profile tags. +It is empty when the two do not overlap, and empty for every reader without a +profile — a manager reading a menu sees `conflicts: []`, which is correct and +not a bug (the field answers "may *I* eat this", and there is no "conflicts +for student X" parameter). The caller's profile is loaded **once per request**, +not per dish, so the menu list stays at its fixed query count no matter how +many menus or dishes the page holds. + +**Money is minor units** (kuruş) as an integer, at every layer: `4550` is +45,50 ₺. This API never speaks decimals or floats about money, so no rounding +is ever introduced by transport or by a client's JSON number parser. + +Reads are open to every authenticated user — a student has to see what is +being served — and every write is manager+. Deleting a menu takes its dishes +with it: a dish has no meaning apart from the menu it was published on. + +**Bookings** are seats on a published menu (`POST +/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a +deterministic composite id, so booking twice is the same seat and never a +second one. A **student books only for themselves**; a **parent books for a +student they hold a link to** — the one write a `parent_link` authorises, since +paying for lunch is a parent's job. Nobody else books through this route: a +teacher or manager ordering a child's lunch is a `403`. + +- **Cancelling is a status flip, not a delete** (`DELETE + /meals/bookings/{bid}` answers `200` with the flipped row): the row survives + as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable + against the money it moved. Only `booked` rows count against `capacity`, + which is what genuinely frees the seat — and re-booking is the same row + flipped back. The call is **idempotent**: cancelling an already-cancelled + seat answers `200` with the row as it stands *and replays the refund*, so a + cancel cut short between the flip and the reversal (the tab closed, a proxy + timed out) is recovered by sending it again. Refusing it as a `409` — as it + once did — made that state permanent: no route could append the missing + reversal, and the student stayed billed for a seat they no longer held. +- **The capacity check is serialized in-process.** Counting rows and then + writing one is write-skew: SurrealDB does not conflict-check a cross-record + count against a concurrent insert, so 24 students racing for 3 seats would + 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. +- 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. + +`GET /meals/bookings/me` is the caller's own list: the seats held *for* them +plus, for a parent, the seats held for every student they **currently** hold a +link to — so a parent's list is their children's meals. The links are re-read +on every call rather than trusted from the booking's `booked_by` stamp: an +unlinked parent stops seeing the child's seats at once, including the ones +they booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for +one menu (manager+), cancelled rows included so the changes are visible. + +### Meal attendance + +Whoever stands at the canteen door records who actually ate: +`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a +student never marks, not even themselves). The status is the fixed pair +`served` / `missed` — deliberately **not** the school's editable +`attendance_statuses`, since a canteen line has no "late" or "excused", and one +list meaning two things would let a school change one by editing the other. +One row per (menu, student) keyed by a composite id, so a correction re-marks +the same row instead of stacking a second one. + +**Attendance has zero billing effect.** Booking is the sole charge trigger, so +a student who booked and did not eat still pays — the kitchen bought the food. +There is no no-show penalty, no refund-on-missed, and no auto-reversal: +nothing under `meal_attendance` writes to the ledger. A walk-in with no live +booking *can* be marked `served` (the record is operationally true) and is +likewise not charged for it — charging there would be a ledger write. The +target only has to *exist*: a canteen also feeds staff, so any user may be +marked, not only a student. A mark is a record of what happened, not a check +of who was entitled, and since it moves no money it costs nobody anything. + +`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and +`GET /meals/attendance/{user}` is one student's history, narrowable with +`?from=&to=` — inclusive `YYYY-MM-DD` bounds compared against the *menu's* +day, a lexical compare that is chronological for that format. Same gate as the +balance and the ledger: the caller's own id always passes, anyone else's needs +teacher+ or a `parent_link` to that student. + +### The ledger + +The money is an **append-only ledger** (`meal_ledger`): one line per `charge`, +`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere +that updates or deletes one**. A ledger line that can be edited or dropped +silently rewrites a student's financial history with no trace of the rewrite — +this is the one genuinely irreversible part of the food program, so a mistake +is corrected by appending the opposing line, which leaves both the mistake and +the correction visible. + +**No balance is stored, anywhere.** It is always derived: + +```text +balance = SUM(credit) + SUM(reversal) - SUM(charge) +``` + +in **minor units** (kuruş) as an `i64` — no float, no decimal, at any layer. +A *negative* balance means the student owes the school; a positive one is +money on account. Amounts are stored positive; the sign lives in the `kind`. + +- **Booking is what charges, at a price snapshot.** The menu's dishes are + summed the moment the seat is taken and that number is frozen onto the + charge. Editing a dish's price afterwards moves no existing charge — what a + student owes is what the menu cost the day they booked. The price is + snapshotted *before* the seat is given, so a menu that cannot be charged + refuses the booking rather than leaving a booked-but-unbilled row (`400`, + when the dishes sum past 10 000 000). A free menu writes no line at all — + but the booking row records that it *was* free, so "free when taken" is + never confused with "not billed yet": pricing the menu afterwards leaves + every seat already taken on it free. +- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its + money move together under one in-process lock, and the ledger id is derived + from the seat plus how many times it has been taken — so eight simultaneous + `POST`s of one seat write one charge, a retried cancel refunds once, and a + write that failed halfway heals when the request is repeated. Booking the + same seat twice bills once because the *identity* is the same, never + because a scan happened to see the first charge in time. +- **Cancelling appends a `reversal`** for the charge's exact amount, with + `source` pointing at the charge it undoes. The charge row itself stays. A + cancel past the cutoff is already a `409`, so a reversal only ever follows a + legal cancel — and repeating a cancel replays the reversal, which is what + makes the refund recoverable rather than a one-shot the network can lose. + Re-booking afterwards is a **fresh** charge at the then-current price. +- **The price snapshot is taken under the booking lock**, and dish + create/edit/delete take that same lock. Taken outside it, a dish added + between the sum and the seat would be frozen onto the row as "the menu was + free then" — and nothing heals it, since a seat already held is returned + as-is, never re-priced. +- **A no-show still pays.** Meal attendance has zero billing effect — nothing + in the ledger reads or writes it. The seat was reserved and the food was + cooked; there is no no-show penalty and no no-show refund. +- **`POST /meals/credits` is admin-only**, not manager: writing down cash + received is the highest-trust action in the app. It appends a `credit` for a + student with a positive `amount_minor` (≤ 10 000 000), an optional `method` + ("cash", "havale", …) and `note`, and records the admin as `recorded_by`. + There is no payment gateway and no card data, ever. An over-credit is + corrected with a compensating line, never a fix-up. + +`GET /meals/balance/me` is the caller's own balance. `GET +/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line +first) read a student's: your own id always passes, anyone else's needs +teacher+ or a `parent_link` to that student. A charge's `source` is the +booking id it came from, a reversal's is the charge line it reverses, and a +credit has none. + ## Exam modes, attempts, retakes, rejoin & live monitoring Preparing an exam is slow work, so an exam can be created as a **draft** @@ -2058,6 +2292,21 @@ src/ registration.rs RegistrationId · Registration (a seat on a registration event's signup list) subject.rs SubjectId · SubjectName · SubjectDescription · Subject (course curriculum) term.rs TermId · TermName · Term (school term window) + menu.rs MenuId · MenuDate · MenuSlot · Menu (one published menu per + calendar day + meal slot; slot snapshotted as text) + menu_dish.rs MenuDishId · DishName · DishDescription · DishPrice · + DishTags · MenuDish (a dish on a menu; price in minor units) + dietary_profile.rs DietaryProfileId · DietaryTags · DietaryNote · + DietaryProfile (what one student may not eat; keyed by the + student, tagged from the same `dietary_tags` list a dish is) + meal_booking.rs MealBookingId · MealBookingStatus · MealBooking (one seat + per (menu, student); a cancel flips the status, never deletes) + meal_attendance.rs MealAttendanceId · MealAttendanceStatus · MealAttendance + (who actually ate; one row per (menu, student), reporting + only — it never touches the ledger) + meal_ledger.rs MealLedgerId · MealLedgerKind · LedgerAmount · LedgerMethod · + LedgerNote · MealLedger (append-only money; the balance is + always the fold, never a stored field) settings.rs ExamKindDef · GradeBand · Settings (per-school policy) chatbot_thread.rs ChatbotThreadId · ChatbotThreadTitle · ChatbotThread (one chatbot thread, private to its owner) @@ -2098,7 +2347,7 @@ src/ auth.rs users.rs notes.rs messages.rs events.rs appointments.rs courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs - settings.rs terms.rs ai.rs chatbot.rs + settings.rs terms.rs meals.rs ai.rs chatbot.rs limits.rs GET /limits: every constant.rs bound served as JSON ``` diff --git a/src/constant.rs b/src/constant.rs index 4901219..1e8c5b9 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -149,6 +149,52 @@ pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000; /// (a decade out) is refused instead of writing thousands of rows. pub const MAX_SLOT_OCCURRENCES: usize = 52; +/// The default meal slots; schools replace the list via `PATCH /settings`, and +/// a published menu snapshots the slot it was written for, so retiring a slot +/// never rewrites history. +pub const DEFAULT_MEAL_SLOTS: [&str; 3] = ["breakfast", "lunch", "snack"]; + +/// The default dietary tags. A student's profile and a dish both carry tags +/// from this school-editable list, which is how "this dish is safe for them" +/// is answered without the backend knowing any nutrition. +pub const DEFAULT_DIETARY_TAGS: [&str; 5] = [ + "vegetarian", + "vegan", + "gluten_free", + "lactose_free", + "nut_allergy", +]; + +/// Bounds on one menu and the dishes hanging off it. +pub const MAX_DISH_NAME_LEN: usize = 100; +pub const MAX_DISH_DESCRIPTION_LEN: usize = 500; +pub const MAX_DISHES_PER_MENU: usize = 50; +pub const MAX_DISH_TAGS: usize = 10; + +/// How many students one menu may seat. Absent capacity means uncapped, the +/// same shape a course's `capacity` uses. +pub const MAX_MENU_CAPACITY: i64 = 10_000; + +/// Bounds on a student's dietary profile: one row per student, so the tag list +/// is the whole payload plus a free-text note for the kitchen. +pub const MAX_DIETARY_TAGS: usize = 10; +pub const MAX_DIETARY_NOTE_LEN: usize = 500; + +/// Money is **minor units** (kuruş) as `i64` everywhere — never a decimal and +/// never a float. `MAX_DISH_PRICE_MINOR` caps one dish (10 000 ₺); +/// `MAX_LEDGER_AMOUNT_MINOR` caps one ledger line (100 000 ₺), which is wide +/// enough for a term's prepayment. +pub const MAX_DISH_PRICE_MINOR: i64 = 1_000_000; +pub const MAX_LEDGER_AMOUNT_MINOR: i64 = 10_000_000; + +/// Bounds on the free-text a ledger line carries: how the money moved, and why. +pub const MAX_LEDGER_METHOD_LEN: usize = 50; +pub const MAX_LEDGER_NOTE_LEN: usize = 500; + +/// Ceiling on the settings knob that closes booking (and cancelling) ahead of +/// a meal — one week. The knob itself is optional: absent means no cutoff. +pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60; + /// 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) @@ -169,6 +215,23 @@ pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"]; /// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`. pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"]; +/// The only accepted meal-booking states. A cancel flips the status and stamps +/// `cancelled_at` instead of deleting the row, so a seat freed after the cutoff +/// is still auditable against the ledger line it charged. +pub const MEAL_BOOKING_STATUSES: [&str; 2] = ["booked", "cancelled"]; + +/// The only accepted meal-attendance states — did the student actually eat. +/// Deliberately *not* the school's `attendance_statuses`: a canteen line has no +/// "late" or "excused", and mixing the two would let a school edit one meaning +/// while changing the other. +pub const MEAL_ATTENDANCE_STATUSES: [&str; 2] = ["served", "missed"]; + +/// The only accepted ledger kinds. `charge`: a booking billed the student. +/// `credit`: money in (a payment, or an opening balance). `reversal`: a charge +/// undone — the ledger is append-only, so a cancelled booking writes a new +/// opposing line rather than editing or deleting the charge. +pub const MEAL_LEDGER_KINDS: [&str; 3] = ["charge", "credit", "reversal"]; + /// Inclusive bounds for an exam's per-attempt duration, milliseconds /// (1 minute to 24 hours). Required for `async`, optional for `open`. pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000; @@ -502,6 +565,12 @@ pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread"; pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message"; pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot"; pub const APPOINTMENT_TABLE: &str = "appointment"; +pub const MENU_TABLE: &str = "menu"; +pub const MENU_DISH_TABLE: &str = "menu_dish"; +pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile"; +pub const MEAL_BOOKING_TABLE: &str = "meal_booking"; +pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance"; +pub const MEAL_LEDGER_TABLE: &str = "meal_ledger"; // --- schema migration SQL ---------------------------------------------- @@ -884,6 +953,20 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option; DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option; DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option; + -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape — + -- a named list a menu snapshots from — and `dietary_tags` mirrors + -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both + -- the booking and the cancel deadline; absent means no cutoff at all. All + -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`. + -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole + -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer + -- omits coerces to NONE and fails every settings write until the domain + -- struct carries it. `option<>` also means the existing singleton reads + -- 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; + DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option>; + DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option; -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students -- submit files + optional text, a teacher grades a status + optional mark. @@ -963,6 +1046,83 @@ pub const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot; DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester; DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status; + + -- Food program (greenfield, 2026-07-26): a published menu per day+slot, + -- dishes on it, a dietary profile per student, bookings against a menu's + -- capacity, who actually ate, and the money that moved. `date` is a + -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is + -- an equality test and a midnight-in-millis day is only unique for one + -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in + -- settings never rewrites a past menu. Stamps stay `int` millis like the + -- rest of the schema. No BACKFILL: all six tables are new. + DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option; + DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE; + + DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string; + DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option; + -- Money is minor units (kuruş) as an integer, everywhere. Never decimal. + DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int; + DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array DEFAULT []; + DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string; + DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu; + + DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array DEFAULT []; + DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string; + DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option; + DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record; + DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int; + DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE; + + -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the + -- freed seat is still auditable against the ledger line it charged. + DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked'; + -- How many times this seat has been taken, and what it cost when the + -- *current* attempt took it (NONE = the menu was free then). Together they + -- key the attempt's ledger lines, which is what makes billing idempotent + -- by identity rather than by scanning for an outstanding charge. + DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1; + DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option; + DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option; + DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu; + DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student; + + DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string; + DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int; + DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE; + + -- APPEND-ONLY by design: a mistake is corrected with an opposing + -- `reversal` line, never by editing or deleting one. Hence every field is + -- READONLY. `source` is untyped on purpose — a charge points at the + -- booking that caused it, a reversal at the line it undoes. + DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY; + DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY; + DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option READONLY; + DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record READONLY; + DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY; + DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student; "; /// Data backfills for rows written by older binaries. Runs *after* (and apart diff --git a/src/domain/dietary_profile.rs b/src/domain/dietary_profile.rs new file mode 100644 index 0000000..8e72393 --- /dev/null +++ b/src/domain/dietary_profile.rs @@ -0,0 +1,211 @@ +//! What one student may not eat: the school's record of their dietary tags +//! plus a free-text note for the kitchen. +//! +//! One row per student, so the record key **is** the student's key — no +//! generated id and no composite. Tags are validated against the same +//! `dietary_tags` vocabulary a dish's tags come from ([`Settings::get_dietary_tags`]); +//! that single shared list is what makes "this dish conflicts with this +//! student" answerable as a set intersection, without the backend knowing any +//! nutrition. +//! +//! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS}; +use crate::database::Database; +use crate::domain::field_update::FieldUpdate; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_optional; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DietaryProfileId(RecordId); + +impl DietaryProfileId { + /// The profile of one student — deterministic, so "read the caller's + /// profile" is a single `SELECT` by id and never a scan. + pub fn of(student: &UserId) -> Self { + Self(RecordId::new(DIETARY_PROFILE_TABLE, student.key())) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// The tags a student's diet carries, drawn from the school's `dietary_tags` +/// list — the same vocabulary a dish is tagged from, deduplicated and in the +/// order given. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DietaryTags(Vec); + +impl DietaryTags { + pub fn try_new(values: &[String], allowed: &[String]) -> Result { + let mut tags: Vec = Vec::new(); + for value in values { + let value = value.trim(); + if !allowed.iter().any(|tag| tag == value) { + return Err(ValidationError::Invalid { + field: "tags", + reason: "not one of the school's dietary tags (see GET /settings)", + }); + } + if !tags.iter().any(|tag| tag == value) { + tags.push(value.to_string()); + } + } + if tags.len() > MAX_DIETARY_TAGS { + return Err(ValidationError::Invalid { + field: "tags", + reason: "at most 10 tags per student", + }); + } + Ok(Self(tags)) + } + + pub fn as_slice(&self) -> &[String] { + &self.0 + } +} + +/// Anything the tag list cannot say — "carries an EpiPen", "no pork". +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DietaryNote(String); + +impl DietaryNote { + /// Blank (or whitespace-only) means "no note" — `None`, not an empty + /// string, so the column is absent rather than falsely present. + pub fn try_new(value: &str) -> Result, ValidationError> { + validate_optional("note", value, MAX_DIETARY_NOTE_LEN)?; + let value = value.trim(); + Ok((!value.is_empty()).then(|| Self(value.to_string()))) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct DietaryProfile { + id: DietaryProfileId, + student: UserId, + tags: DietaryTags, + note: Option, + updated_by: UserId, + updated_at: Timestamp, +} + +impl DietaryProfile { + pub fn get_student(&self) -> &UserId { + &self.student + } + + pub fn get_tags(&self) -> &DietaryTags { + &self.tags + } + + pub fn get_note(&self) -> Option<&DietaryNote> { + self.note.as_ref() + } + + pub fn get_updated_by(&self) -> &UserId { + &self.updated_by + } + + pub fn get_updated_at(&self) -> Timestamp { + self.updated_at + } + + /// One student's profile, or `None` while the school never recorded one. + /// A single `SELECT` by record id — this is what a menu read joins on. + pub async fn read(student: &UserId, db: &Database) -> Result, AppError> { + Ok(db.select(DietaryProfileId::of(student).record()).await?) + } + + /// The tags a menu read matches its dishes against: the caller's, or an + /// empty list when they have no profile (every manager, every teacher). + pub async fn tags_of(student: &UserId, db: &Database) -> Result, AppError> { + Ok(Self::read(student, db) + .await? + .map(|profile| profile.tags.as_slice().to_vec()) + .unwrap_or_default()) + } + + /// Write the fields the PATCH carried. Creates the row on first write; + /// afterwards only the named fields move, because `student` is `READONLY` + /// and a whole-row save would also revert a concurrent edit of the other + /// field (see [`FieldUpdate`]). + pub async fn save( + student: &UserId, + tags: Option, + note: Option>, + by: &UserId, + db: &Database, + ) -> Result { + if Self::read(student, db).await?.is_none() { + let profile = Self { + id: DietaryProfileId::of(student), + student: student.clone(), + tags: tags.unwrap_or(DietaryTags(Vec::new())), + note: note.flatten(), + updated_by: by.clone(), + updated_at: Timestamp::now(), + }; + let created: Option = db.create(profile.id.record()).content(profile).await?; + return created.ok_or_else(|| AppError::Internal("failed to save the profile".into())); + } + FieldUpdate::new(DietaryProfileId::of(student).record()) + .set("tags", tags) + .set("note", note) + .set("updated_by", Some(by.clone())) + .set("updated_at", Some(Timestamp::now())) + .run::(db) + .await + } +} + +/// Which of a dish's tags the reader's own profile flags. Empty when there is +/// no overlap, and empty for every reader without a profile. +pub fn conflicts(dish_tags: &[String], profile_tags: &[String]) -> Vec { + dish_tags + .iter() + .filter(|tag| profile_tags.iter().any(|held| held == *tag)) + .cloned() + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tags_must_come_from_the_school_list_and_dedupe() { + let allowed = vec!["vegan".to_string(), "nut_allergy".to_string()]; + let tags = + DietaryTags::try_new(&["vegan".to_string(), "vegan".to_string()], &allowed).unwrap(); + assert_eq!(tags.as_slice(), ["vegan"]); + assert!(DietaryTags::try_new(&["halal".to_string()], &allowed).is_err()); + } + + #[test] + fn conflicts_are_the_intersection_in_dish_order() { + let held = vec!["nut_allergy".to_string(), "vegan".to_string()]; + assert_eq!( + conflicts(&["vegan".to_string(), "nut_allergy".to_string()], &held), + ["vegan", "nut_allergy"] + ); + assert!(conflicts(&["gluten_free".to_string()], &held).is_empty()); + // No profile is no conflict, never "everything conflicts". + assert!(conflicts(&["vegan".to_string()], &[]).is_empty()); + } +} diff --git a/src/domain/meal_attendance.rs b/src/domain/meal_attendance.rs new file mode 100644 index 0000000..623f3c3 --- /dev/null +++ b/src/domain/meal_attendance.rs @@ -0,0 +1,191 @@ +//! Who actually ate. One row per (menu, student), keyed by a deterministic +//! composite id — the same pair always maps to the same record, so marking is a +//! single atomic UPSERT with no find-then-insert race, and re-marking flips the +//! status instead of stacking a second row. +//! +//! **Attendance is reporting only — it has zero billing effect.** Booking is +//! the sole charge trigger: a student who booked and did not eat still pays, +//! because the kitchen bought the food. Nothing here ever writes to +//! [`MealLedger`](crate::domain::meal_ledger::MealLedger) — no no-show penalty, +//! no refund-on-missed, no auto-reversal. A walk-in with no booking can still +//! be marked `served` (the record is operationally true) and is likewise never +//! charged for it. +//! +//! The statuses are the fixed [`MEAL_ATTENDANCE_STATUSES`] pair, deliberately +//! *not* the school's editable `attendance_statuses`: a canteen line has no +//! "late" or "excused". + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE}; +use crate::database::Database; +use crate::domain::menu::{MenuDate, MenuId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MealAttendanceId(RecordId); + +impl MealAttendanceId { + /// A deterministic id for the (menu, student) pair — same trick as + /// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). ULID keys + /// are alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(menu: &MenuId, student: &UserId) -> Self { + Self(RecordId::new( + MEAL_ATTENDANCE_TABLE, + format!("{}_{}", menu.key(), student.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// `served` or `missed`, and nothing else — see the module header. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MealAttendanceStatus(String); + +impl MealAttendanceStatus { + pub fn try_new(value: &str) -> Result { + let value = value.trim(); + if !MEAL_ATTENDANCE_STATUSES.contains(&value) { + return Err(ValidationError::Invalid { + field: "status", + reason: "must be 'served' or 'missed'", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct MealAttendance { + id: MealAttendanceId, + menu: MenuId, + student: UserId, + status: MealAttendanceStatus, + marked_by: UserId, + marked_at: Timestamp, +} + +impl MealAttendance { + pub fn get_id(&self) -> &MealAttendanceId { + &self.id + } + + pub fn get_menu(&self) -> &MenuId { + &self.menu + } + + pub fn get_student(&self) -> &UserId { + &self.student + } + + pub fn get_status(&self) -> &MealAttendanceStatus { + &self.status + } + + pub fn get_marked_by(&self) -> &UserId { + &self.marked_by + } + + pub fn get_marked_at(&self) -> Timestamp { + self.marked_at + } + + /// Record (or overwrite) whether `student` ate off `menu`. One row per + /// pair by construction, so a correction is the same UPSERT flipping the + /// status. No ledger line, ever — see the module header. + pub async fn mark( + menu: &MenuId, + student: &UserId, + status: MealAttendanceStatus, + marked_by: &UserId, + db: &Database, + ) -> Result { + let row = MealAttendance { + id: MealAttendanceId::composite(menu, student), + menu: menu.clone(), + student: student.clone(), + status, + marked_by: marked_by.clone(), + marked_at: Timestamp::now(), + }; + let saved: Option = db.upsert(row.id.record()).content(row).await?; + saved.ok_or_else(|| AppError::Internal("failed to mark meal attendance".into())) + } + + /// The kitchen's list for one menu. + pub async fn list_for_menu( + menu: &MenuId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM meal_attendance WHERE menu = $menu \ + ORDER BY marked_at DESC, id DESC", + ) + .bind(("menu", menu.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// One student's marks, newest first. `from`/`to` are inclusive + /// `YYYY-MM-DD` bounds on the *menu's* day — the comparison is lexical, + /// which is chronological for that format (see [`MenuDate`]), and the link + /// is followed rather than denormalized so a row can never disagree with + /// the menu it belongs to. + pub async fn list_for_student( + student: &UserId, + from: Option<&MenuDate>, + to: Option<&MenuDate>, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM meal_attendance WHERE student = $usr \ + AND ($from = NONE OR menu.date >= $from) \ + AND ($to = NONE OR menu.date <= $to) \ + ORDER BY marked_at DESC, id DESC", + ) + .bind(("usr", student.record())) + .bind(("from", from.map(|date| date.as_str().to_string()))) + .bind(("to", to.map(|date| date.as_str().to_string()))) + .await? + .check()?; + Ok(result.take::>(0)?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_is_the_fixed_canteen_pair() { + for status in MEAL_ATTENDANCE_STATUSES { + assert_eq!( + MealAttendanceStatus::try_new(status).unwrap().as_str(), + status + ); + } + // The school's roll-call vocabulary is not this vocabulary. + assert!(MealAttendanceStatus::try_new("present").is_err()); + assert!(MealAttendanceStatus::try_new("excused").is_err()); + assert!(MealAttendanceStatus::try_new("").is_err()); + } +} diff --git a/src/domain/meal_booking.rs b/src/domain/meal_booking.rs new file mode 100644 index 0000000..f49bd57 --- /dev/null +++ b/src/domain/meal_booking.rs @@ -0,0 +1,401 @@ +//! A student's seat on a published [`Menu`]. One row per (menu, student), +//! keyed by a deterministic composite id — the same pair always maps to the +//! same record, so booking is a single atomic UPSERT with no find-then-insert +//! race and one-row-per-pair by construction. +//! +//! Two things are deliberate: +//! +//! - **A cancel is a status transition, not a delete.** The row stays, flipped +//! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still +//! auditable against the money it moved. Only `booked` rows count against +//! the menu's capacity, which is what makes the seat genuinely free again — +//! and re-booking is the same UPSERT flipping it back. +//! - **The capacity check runs under [`MENU_LOCK`]**, the lock that already +//! serializes everything counting rows against one menu. Count-then-write is +//! write-skew: SurrealDB's transactions do not conflict-check a cross-record +//! count against a concurrent insert, so an unlocked check over-admits. +//! - **The seat and its money move together, inside that lock.** Booking +//! charges and cancelling reverses right here, not in the web layer after the +//! lock was dropped — a seam between the two let concurrent `POST`s bill one +//! seat twice. The lock stays a *leaf*: nothing below it takes another. + +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::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MealBookingId(RecordId); + +impl MealBookingId { + /// A deterministic id for the (menu, student) pair — same trick as + /// `EnrollmentId`. ULID keys are alphanumeric, so `_` is an unambiguous + /// joiner. + pub fn composite(menu: &MenuId, student: &UserId) -> Self { + Self(RecordId::new( + MEAL_BOOKING_TABLE, + format!("{}_{}", menu.key(), student.key()), + )) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(MEAL_BOOKING_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// Where a booking stands. `untagged` + `rename_all` store it as the bare +/// lowercase string the `status` column types as, exactly like +/// [`AppointmentStatus`](crate::domain::appointment::AppointmentStatus). +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[surreal(untagged, rename_all = "lowercase")] +pub enum MealBookingStatus { + Booked, + Cancelled, +} + +impl MealBookingStatus { + /// The wire/storage form. Must stay in lockstep with `rename_all`. + pub fn as_str(self) -> &'static str { + match self { + MealBookingStatus::Booked => "booked", + MealBookingStatus::Cancelled => "cancelled", + } + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct MealBooking { + id: MealBookingId, + menu: MenuId, + student: UserId, + booked_by: UserId, + status: MealBookingStatus, + /// How many times this seat has been taken: 1 on the first booking, +1 on + /// every revival after a cancel. It is the *attempt* half of the ledger's + /// idempotence key, so a re-book bills afresh while a repeat `POST` of a + /// seat already held bills nothing. + attempt: i64, + /// What the menu cost when the current attempt took the seat; `None` means + /// it was free *then*. Recorded rather than inferred: without it, "the menu + /// was free" is indistinguishable from "not billed yet", and a dish added + /// afterwards bills a seat that was free when taken. + price_minor: Option, + cancelled_at: Option, + created_at: Timestamp, +} + +impl MealBooking { + pub fn get_id(&self) -> &MealBookingId { + &self.id + } + + pub fn get_menu(&self) -> &MenuId { + &self.menu + } + + pub fn get_student(&self) -> &UserId { + &self.student + } + + pub fn get_booked_by(&self) -> &UserId { + &self.booked_by + } + + pub fn get_status(&self) -> MealBookingStatus { + self.status + } + + pub fn get_attempt(&self) -> i64 { + self.attempt + } + + pub fn get_price_minor(&self) -> Option { + self.price_minor + } + + pub fn get_cancelled_at(&self) -> Option { + self.cancelled_at + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already + /// booked is returned as-is; a cancelled row is revived by the same UPSERT, + /// as a fresh attempt at the current `price`. When the menu carries a + /// capacity, a full one refuses new seats (409) — the whole + /// check-then-write runs under [`MENU_LOCK`], and the cap is re-derived + /// from a fresh menu read inside it, since neither the transaction model + /// nor a caller-supplied menu survives a concurrent capacity PATCH. + /// + /// The price is snapshotted **inside that same lock**, not handed in by the + /// web layer: dish writes take the lock too, so the sum frozen onto the row + /// is the menu as it stood the instant the seat was taken. Snapshotted + /// outside it, a dish landing in the gap was stored as `None` = "was free + /// then" — and no repeat `POST` ever heals that, since a held seat is + /// returned as-is. + /// + /// The charge is appended inside the lock too, keyed by (seat, attempt): + /// eight concurrent `POST`s of one seat hold one seat and write one charge + /// 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. + pub async fn book( + menu: &MenuId, + student: &UserId, + booked_by: &UserId, + cutoff_minutes: Option, + 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)?; + // Before the seat: an unchargeable menu (dishes summing past the cap) + // must refuse the booking outright, never leave a booked-but-unbilled + // row behind. + let price = MealLedger::price_snapshot(menu, db).await?; + let id = MealBookingId::composite(menu, student); + let existing: Option = db.select(id.record()).await?; + let booking = match existing { + // The seat is already held: same attempt, same price it was taken + // at. Today's menu price bills nobody who booked yesterday's. + Some(held) if held.status == MealBookingStatus::Booked => held, + existing => { + if let Some(capacity) = fresh.get_capacity() + && Self::list_live_for_menu(menu, db).await?.len() as i64 >= capacity + { + return Err(AppError::Conflict("the menu is fully booked")); + } + let booking = MealBooking { + id, + menu: menu.clone(), + student: student.clone(), + // `booked_by` and `created_at` are READONLY columns: a + // revived row keeps whoever opened the seat, and when. + booked_by: existing + .as_ref() + .map_or_else(|| booked_by.clone(), |row| row.booked_by.clone()), + status: MealBookingStatus::Booked, + attempt: existing.as_ref().map_or(1, |row| row.attempt + 1), + price_minor: price, + cancelled_at: None, + created_at: existing + .as_ref() + .map_or_else(Timestamp::now, |row| row.created_at), + }; + let saved: Option = + db.upsert(booking.id.record()).content(booking).await?; + saved.ok_or_else(|| AppError::Internal("failed to book the meal".into()))? + } + }; + // Writes nothing when this attempt is already billed, so the repeat + // POST above costs nothing and a charge that failed once self-heals. + MealLedger::charge_booking(&booking, booked_by, db).await?; + Ok(booking) + } + + /// Free the seat: flip to `cancelled`, stamp the moment, **and give the + /// money back**. Refused (409) only once the cutoff has passed. + /// + /// Under [`MENU_LOCK`] like [`Self::book`], and the row is re-read inside + /// it: the caller's copy may predate a concurrent re-book, and cancelling a + /// stale attempt would strand that attempt's charge forever. The reversal + /// is keyed to the attempt, so a retried cancel refunds exactly once. + /// + /// **Idempotent, and that is what makes the refund recoverable.** The flip + /// and the reversal are two writes; a handler future dropped between them + /// (the client closed the tab, a proxy timed out) or a `create` that errors + /// leaves the seat free and the charge standing. Refusing an + /// already-cancelled row — as this used to — made that state permanent: + /// no route on the API could ever append the missing reversal. So a + /// cancelled row replays the reversal instead, which either heals the gap + /// or writes nothing at all. The cutoff is not re-checked on that path: the + /// seat is already given back, and refusing to finish the refund because + /// the meal has since closed would strand the money exactly as before. + pub async fn cancel( + self, + cutoff_minutes: Option, + recorded_by: &UserId, + db: &Database, + ) -> Result { + let _guard = MENU_LOCK.lock().await; + let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?; + if fresh.status == MealBookingStatus::Cancelled { + MealLedger::reverse_booking(&fresh, recorded_by, db).await?; + return Ok(fresh); + } + let menu = Menu::read(&fresh.menu, db) + .await? + .ok_or(AppError::NotFound)?; + check_cutoff(menu.get_date(), cutoff_minutes)?; + let cancelled = MealBooking { + status: MealBookingStatus::Cancelled, + cancelled_at: Some(Timestamp::now()), + ..fresh + }; + let saved: Option = + db.upsert(cancelled.id.record()).content(cancelled).await?; + let saved = + saved.ok_or_else(|| AppError::Internal("failed to cancel the booking".into()))?; + MealLedger::reverse_booking(&saved, recorded_by, db).await?; + Ok(saved) + } + + pub async fn read(id: &MealBookingId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every booking on a menu, cancelled ones included — the kitchen's list. + pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM meal_booking WHERE menu = $menu \ + ORDER BY created_at DESC, id DESC", + ) + .bind(("menu", menu.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The seats actually held — the capacity count. + pub async fn list_live_for_menu( + menu: &MenuId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM meal_booking WHERE menu = $menu AND status = 'booked'") + .bind(("menu", menu.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// True iff a seat on the menu is still held — the menu delete guard. + /// Callers hold [`MENU_LOCK`] so a booking cannot slip in behind it. + pub async fn any_live_for_menu(menu: &MenuId, db: &Database) -> Result { + let mut result = db + .query( + "SELECT VALUE id FROM meal_booking \ + WHERE menu = $menu AND status = 'booked' LIMIT 1", + ) + .bind(("menu", menu.record())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + + /// Every seat held for one of `students`, newest first — a caller's own + /// list is themselves plus whoever they hold a *live* parent link to. + /// + /// Deliberately **not** `booked_by = $usr`: who placed a booking is history + /// written onto a READONLY column, and history is not a read grant. A + /// parent whose link was revoked (by an unlink or by the student-side role + /// sweep) would otherwise keep a live view of the child's seat, watching + /// cancellations made long after the link died — exactly what + /// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The + /// caller re-derives the list from the links on every read, so the view + /// dies with the link. + pub async fn list_for_students( + students: &[UserId], + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM meal_booking WHERE student IN $students \ + ORDER BY created_at DESC, id DESC", + ) + .bind(( + "students", + students.iter().map(UserId::record).collect::>(), + )) + .await? + .check()?; + Ok(result.take::>(0)?) + } +} + +/// 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 { + 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(), + )) +} + +/// 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 { + return Ok(()); + }; + let deadline = start + .as_millis() + .saturating_sub(cutoff.saturating_mul(60_000)); + if Timestamp::now().as_millis() >= deadline { + return Err(AppError::Conflict("the menu's booking cutoff has passed")); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use surrealdb::types::SurrealValue as _; + use surrealdb::types::Value; + + use super::*; + + /// The `status` column is `TYPE string`: an object-wrapped enum would be + /// rejected on write, and the `status = 'booked'` capacity count would + /// silently match nothing. + #[test] + fn status_stores_as_a_bare_string() { + for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] { + let value = status.into_value(); + assert_eq!(value, Value::String(status.as_str().to_string())); + assert_eq!(MealBookingStatus::from_value(value).unwrap(), status); + } + } + + #[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()); + // 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_eq!( + day_starts_at(&MenuDate::try_new("1970-01-02").unwrap()) + .unwrap() + .as_millis(), + 86_400_000 + ); + } +} diff --git a/src/domain/meal_ledger.rs b/src/domain/meal_ledger.rs new file mode 100644 index 0000000..3f60561 --- /dev/null +++ b/src/domain/meal_ledger.rs @@ -0,0 +1,496 @@ +//! The food program's money: an **append-only** ledger of what a student was +//! charged and what they paid. +//! +//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists — +//! every field is `READONLY` in the schema as well. A ledger line that can be +//! edited or dropped silently rewrites a student's financial history with no +//! trace of the rewrite; a mistake is corrected by appending the opposing +//! line, which leaves both the mistake and the correction visible. +//! +//! **The balance is never stored.** It is always the fold +//! +//! ```text +//! balance = SUM(credit) + SUM(reversal) - SUM(charge) +//! ``` +//! +//! so a *negative* balance means the student owes the school, and a positive +//! one is money on account. Every amount on a row is stored positive; the sign +//! lives in the `kind`, so a line's meaning never depends on how it was read. +//! +//! Three more rules the code depends on: +//! +//! - **Booking is the charge trigger, at a price snapshot.** The menu's dishes +//! are summed when the seat is taken and that number is frozen onto the +//! *booking row*. Editing a dish's price afterwards moves no existing charge +//! — what a student owes is what the menu cost the day they booked — and a +//! seat taken while the menu was free stays free, because "free" is recorded +//! on the row rather than inferred from the absence of a charge. +//! - **A cancel appends a `reversal`**, for the charge's exact amount, with +//! `source` pointing at the charge it undoes. The charge row stays. Booking +//! again after a cancel is a *fresh* charge at the then-current price. +//! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge +//! and its reversal derive their record id from the seat and the attempt +//! number, so replaying either writes nothing at all. Money must never +//! depend on a "has this been billed yet?" scan: two concurrent `POST`s of +//! one seat can both read "no charge yet" and both append, which is how a +//! double-click used to bill a seat twice. +//! - **A no-show still pays.** Meal attendance has zero billing effect — +//! nothing in this file reads or writes it. Do not add a no-show penalty +//! here: the seat was reserved and the food was cooked. +//! +//! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever. + +use std::sync::LazyLock; + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Generator; + +use crate::constant::{ + MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE, +}; +use crate::database::Database; +use crate::domain::meal_booking::{MealBooking, MealBookingId}; +use crate::domain::menu::MenuId; +use crate::domain::menu_dish::MenuDish; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_optional; + +/// Mints ledger ids in write order — `Ulid::new()`'s random low bits sort +/// arbitrarily within one millisecond, which would scramble the `id` tie-break +/// of the newest-first statement below. +static IDS: LazyLock> = + LazyLock::new(|| std::sync::Mutex::new(Generator::new())); + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MealLedgerId(RecordId); + +impl MealLedgerId { + pub fn generate() -> Self { + let mut ids = IDS.lock().expect("meal ledger id generator poisoned"); + // The only error is exhausting the random bits within one millisecond + // (2^80 ids deep); it clears itself as the clock ticks, so retry. + let ulid = loop { + if let Ok(ulid) = ids.generate() { + break ulid; + } + }; + Self(RecordId::new(MEAL_LEDGER_TABLE, ulid.to_string())) + } + + /// The one line a booking attempt may ever write of this `kind` — a + /// deterministic id, exactly like [`MealBookingId::composite`]. Two racing + /// `POST`s of one seat derive the *same* id and so cannot become two + /// charges: idempotence rests on identity, never on a scan that a + /// concurrent writer can slip past. The `attempt` counter is what keeps a + /// re-book after a cancel a genuinely fresh charge. Booking keys are + /// `_`, so the `c`/`r` marker keeps the two kinds apart. + pub fn for_attempt(booking: &MealBookingId, attempt: i64, kind: MealLedgerKind) -> Self { + let marker = match kind { + MealLedgerKind::Charge => 'c', + MealLedgerKind::Reversal => 'r', + // A credit is money arriving out of the blue, tied to no booking. + MealLedgerKind::Credit => 'k', + }; + Self(RecordId::new( + MEAL_LEDGER_TABLE, + format!("{}_{marker}{attempt}", booking.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + key_of(&self.0) + } +} + +/// The bare key of a record id — how every id leaves this API. +fn key_of(record: &RecordId) -> &str { + match &record.key { + RecordIdKey::String(key) => key, + _ => "", + } +} + +/// What a line means. `untagged` + `rename_all` store it as the bare lowercase +/// string the `kind` column types as, in lockstep with `MEAL_LEDGER_KINDS`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +#[surreal(untagged, rename_all = "lowercase")] +pub enum MealLedgerKind { + Charge, + Credit, + Reversal, +} + +impl MealLedgerKind { + /// The wire/storage form. Must stay in lockstep with `rename_all`. + pub fn as_str(self) -> &'static str { + match self { + MealLedgerKind::Charge => "charge", + MealLedgerKind::Credit => "credit", + MealLedgerKind::Reversal => "reversal", + } + } + + /// How the line folds into the balance: a charge is the only thing that + /// takes money away. This is the *single* place the sign convention lives. + fn sign(self) -> i64 { + match self { + MealLedgerKind::Charge => -1, + MealLedgerKind::Credit | MealLedgerKind::Reversal => 1, + } + } +} + +/// One line's amount, always positive — the sign is the [`MealLedgerKind`]'s +/// business. Capped so a slipped keystroke cannot book a fortune. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct LedgerAmount(i64); + +impl LedgerAmount { + pub fn try_new(value: i64) -> Result { + if !(1..=MAX_LEDGER_AMOUNT_MINOR).contains(&value) { + return Err(ValidationError::Invalid { + field: "amount_minor", + reason: "must be between 1 and 10000000 minor units", + }); + } + Ok(Self(value)) + } + + pub fn as_minor(self) -> i64 { + self.0 + } +} + +/// How the money arrived ("cash", "havale", …). Free text: the backend never +/// speaks to a payment gateway and stores no card data, ever. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct LedgerMethod(String); + +impl LedgerMethod { + pub fn try_new(value: &str) -> Result, ValidationError> { + let value = value.trim(); + validate_optional("method", value, MAX_LEDGER_METHOD_LEN)?; + Ok((!value.is_empty()).then(|| Self(value.to_string()))) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The bookkeeper's own words about a line — a receipt number, whose envelope +/// it came in. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct LedgerNote(String); + +impl LedgerNote { + pub fn try_new(value: &str) -> Result, ValidationError> { + let value = value.trim(); + validate_optional("note", value, MAX_LEDGER_NOTE_LEN)?; + Ok((!value.is_empty()).then(|| Self(value.to_string()))) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct MealLedger { + id: MealLedgerId, + student: UserId, + kind: MealLedgerKind, + amount_minor: LedgerAmount, + /// What caused the line: a charge points at its `meal_booking`, a reversal + /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`. + source: Option, + method: Option, + note: Option, + recorded_by: UserId, + created_at: Timestamp, +} + +impl MealLedger { + pub fn get_id(&self) -> &MealLedgerId { + &self.id + } + + pub fn get_student(&self) -> &UserId { + &self.student + } + + pub fn get_kind(&self) -> MealLedgerKind { + self.kind + } + + pub fn get_amount_minor(&self) -> LedgerAmount { + self.amount_minor + } + + /// The cause's bare key; which table it lives in follows from the kind. + pub fn get_source_key(&self) -> Option<&str> { + self.source.as_ref().map(key_of) + } + + pub fn get_method(&self) -> Option<&LedgerMethod> { + self.method.as_ref() + } + + pub fn get_note(&self) -> Option<&LedgerNote> { + self.note.as_ref() + } + + pub fn get_recorded_by(&self) -> &UserId { + &self.recorded_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// The only writer: one `CREATE`, no update path anywhere in this module. + /// + /// A line whose id already exists is left exactly as it is — the row wins, + /// the write is dropped. That is what makes a deterministic id (see + /// [`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. + 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?; + created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into())) + } + + pub async fn read(id: &MealLedgerId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// What a seat on `menu` costs *right now*: the sum of its dishes. `None` + /// when the menu is free (or empty) — a zero line is noise, not history. + /// + /// Called before the seat is taken so an unchargeable menu (one summing + /// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of + /// leaving a booked-but-unbilled row behind. + pub async fn price_snapshot( + menu: &MenuId, + db: &Database, + ) -> Result, AppError> { + let total = MenuDish::list_for_menu(menu, db) + .await? + .iter() + .fold(0i64, |sum, dish| { + sum.saturating_add(dish.get_price_minor().as_minor()) + }); + if total == 0 { + return Ok(None); + } + Ok(Some(LedgerAmount::try_new(total)?)) + } + + /// Bill `booking`'s current attempt at the price frozen onto it when that + /// attempt took the seat. + /// + /// The price comes off the *booking row*, never off the menu as it stands + /// now: a seat taken while the menu was free carries `None` forever, so + /// "was free" is a recorded fact and a later dish never bills a seat + /// retroactively. Called under + /// [`MENU_LOCK`](crate::domain::menu::MENU_LOCK), from + /// [`MealBooking::book`] alone, so the seat and its money move together. + /// + /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate + /// `POST` writes nothing, and an attempt whose charge failed the first time + /// self-heals on the next `POST` of the same seat. + pub async fn charge_booking( + booking: &MealBooking, + recorded_by: &UserId, + db: &Database, + ) -> Result<(), AppError> { + let Some(amount) = booking.get_price_minor() else { + return Ok(()); + }; + Self::append( + MealLedger { + id: MealLedgerId::for_attempt( + booking.get_id(), + booking.get_attempt(), + MealLedgerKind::Charge, + ), + student: booking.get_student().clone(), + kind: MealLedgerKind::Charge, + amount_minor: amount, + source: Some(booking.get_id().record()), + method: None, + note: None, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + db, + ) + .await?; + Ok(()) + } + + /// Give the money back for a cancelled `booking`: a new `reversal` line for + /// the charge's exact amount, pointing at it. The charge is never touched. + /// A booking that was never billed (a free menu) reverses nothing, and + /// neither does one whose charge never landed — the reversal is keyed to + /// the very charge it undoes, so it can only exist alongside it. + /// + /// Keyed by `(booking, attempt)` like the charge, so a retried cancel + /// refunds once. A cancel cut short between the status flip and this + /// reversal is recovered by repeating the cancel — which is precisely why + /// [`MealBooking::cancel`] replays this on an already-cancelled row instead + /// of refusing it. Nothing else on the API can append the missing line. + pub async fn reverse_booking( + booking: &MealBooking, + recorded_by: &UserId, + db: &Database, + ) -> Result<(), AppError> { + let Some(amount) = booking.get_price_minor() else { + return Ok(()); + }; + let charge = MealLedgerId::for_attempt( + booking.get_id(), + booking.get_attempt(), + MealLedgerKind::Charge, + ); + if Self::read(&charge, db).await?.is_none() { + return Ok(()); + } + Self::append( + MealLedger { + id: MealLedgerId::for_attempt( + booking.get_id(), + booking.get_attempt(), + MealLedgerKind::Reversal, + ), + student: booking.get_student().clone(), + kind: MealLedgerKind::Reversal, + amount_minor: amount, + source: Some(charge.record()), + method: None, + note: None, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + db, + ) + .await?; + Ok(()) + } + + /// Money in: a payment received, or an opening balance. + pub async fn credit( + student: &UserId, + amount_minor: LedgerAmount, + method: Option, + note: Option, + recorded_by: &UserId, + db: &Database, + ) -> Result { + Self::append( + MealLedger { + id: MealLedgerId::generate(), + student: student.clone(), + kind: MealLedgerKind::Credit, + amount_minor, + source: None, + method, + note, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + db, + ) + .await + } + + /// A student's whole statement, newest first. + pub async fn list_for_student( + student: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM meal_ledger WHERE student = $student \ + ORDER BY created_at DESC, id DESC", + ) + .bind(("student", student.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The derived balance: `credits + reversals - charges`, in minor units. + /// Negative means the student owes the school. Never stored anywhere. + // ponytail: folds the student's lines in-process (a few hundred a year); + // push it into a `math::sum` aggregate if a statement ever gets long. + pub async fn balance_of(student: &UserId, db: &Database) -> Result { + Ok(Self::list_for_student(student, db) + .await? + .iter() + .fold(0i64, |sum, line| { + sum + line.kind.sign() * line.amount_minor.as_minor() + })) + } +} + +#[cfg(test)] +mod tests { + use surrealdb::types::SurrealValue as _; + use surrealdb::types::Value; + + use super::*; + + /// The `kind` column is `TYPE string`: an object-wrapped enum would be + /// rejected on write, and the `kind = 'charge'` lookup would silently + /// match nothing — which would double-charge every re-booking. + #[test] + fn kind_stores_as_a_bare_string() { + for kind in [ + MealLedgerKind::Charge, + MealLedgerKind::Credit, + MealLedgerKind::Reversal, + ] { + let value = kind.into_value(); + assert_eq!(value, Value::String(kind.as_str().to_string())); + assert_eq!(MealLedgerKind::from_value(value).unwrap(), kind); + } + } + + /// The one fold: a charge subtracts, a credit and a reversal add. A booked + /// meal that was cancelled nets to exactly zero, never to a rounding scrap. + #[test] + fn the_balance_fold_is_credit_plus_reversal_minus_charge() { + assert_eq!(MealLedgerKind::Charge.sign(), -1); + assert_eq!(MealLedgerKind::Credit.sign(), 1); + assert_eq!(MealLedgerKind::Reversal.sign(), 1); + let lines = [ + (MealLedgerKind::Credit, 10_000), + (MealLedgerKind::Charge, 4_500), + (MealLedgerKind::Reversal, 4_500), + ]; + let balance: i64 = lines + .iter() + .map(|(kind, amount)| kind.sign() * amount) + .sum(); + assert_eq!(balance, 10_000); + } + + #[test] + fn an_amount_is_positive_and_capped() { + assert!(LedgerAmount::try_new(0).is_err()); + assert!(LedgerAmount::try_new(-1).is_err()); + assert!(LedgerAmount::try_new(MAX_LEDGER_AMOUNT_MINOR + 1).is_err()); + assert_eq!(LedgerAmount::try_new(1).unwrap().as_minor(), 1); + } +} diff --git a/src/domain/menu.rs b/src/domain/menu.rs new file mode 100644 index 0000000..9d7da04 --- /dev/null +++ b/src/domain/menu.rs @@ -0,0 +1,330 @@ +//! A published menu: what the kitchen serves on one calendar day in one meal +//! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)), +//! and bookings will hang off its `capacity`. +//! +//! Two things are deliberate: +//! +//! - **`date` is text** (`YYYY-MM-DD`), not a timestamp. The uniqueness rule is +//! "one menu per day and slot", an equality test — and a midnight-in-millis +//! day is only one school's day. +//! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must +//! never rewrite a menu already published under it. + +use std::sync::LazyLock; + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use tokio::sync::Mutex; +use ulid::Generator; + +use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE}; +use crate::database::Database; +use crate::domain::field_update::FieldUpdate; +use crate::domain::menu_dish::MenuDish; +use crate::domain::settings::MealSlotDef; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; + +/// Serializes "is there already a menu for this day and slot?" against the +/// publish it authorizes — a count-then-write pair SurrealDB does not +/// conflict-check, so the UNIQUE index would otherwise be the only thing +/// standing between two racing publishes and a 500. Also held by the settings +/// slot-removal guard, whose check ("was any menu published for this slot?") +/// is the mirror image. +/// +/// Lock order: `EXAM_LOCK` (taken by the same settings write) is always taken +/// *before* this one; nothing here ever takes `EXAM_LOCK`, so the two cannot +/// deadlock. +pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(()); + +/// Mints menu ids in write order — `Ulid::new()`'s random low bits sort +/// arbitrarily within one millisecond, which would scramble the `id` tie-break +/// of the listings below. +static IDS: LazyLock> = + LazyLock::new(|| std::sync::Mutex::new(Generator::new())); + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MenuId(RecordId); + +impl MenuId { + pub fn generate() -> Self { + let mut ids = IDS.lock().expect("menu id generator poisoned"); + // The only error is exhausting the random bits within one millisecond + // (2^80 ids deep); it clears itself as the clock ticks, so retry. + let ulid = loop { + if let Ok(ulid) = ids.generate() { + break ulid; + } + }; + Self(RecordId::new(MENU_TABLE, ulid.to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(MENU_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose: +/// that makes the text sort chronologically, so the `?from=&to=` range filter +/// and the newest-first ordering are plain string comparisons. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, SurrealValue)] +pub struct MenuDate(String); + +impl MenuDate { + pub fn try_new(value: &str) -> Result { + let invalid = ValidationError::Invalid { + field: "date", + reason: "must be a calendar day as YYYY-MM-DD", + }; + let value = value.trim(); + let bytes = value.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return Err(invalid); + } + let digits = + |from: usize, to: usize| -> Option { value.get(from..to)?.parse::().ok() }; + let (Some(_year), Some(month), Some(day)) = (digits(0, 4), digits(5, 7), digits(8, 10)) + else { + return Err(invalid); + }; + // Day count per month is not checked: the calendar rules (leap years) + // would be the only thing this file knows about time, and a 31st of + // February menu is a typo nobody can act on, not a data hazard. + if !(1..=12).contains(&month) || !(1..=31).contains(&day) { + return Err(invalid); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// The meal slot a menu was published for, snapshotted as text. Validated +/// against the school's *current* list at write time — that list is the only +/// place slot names are defined, and this is the sole funnel into the column. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MenuSlot(String); + +impl MenuSlot { + pub fn try_new(value: &str, allowed: &[MealSlotDef]) -> Result { + let value = value.trim(); + if !allowed.iter().any(|slot| slot.get_name() == value) { + return Err(ValidationError::Invalid { + field: "slot", + reason: "not one of the school's meal slots (see GET /settings)", + }); + } + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// How many students the menu may seat. `None` = uncapped, the shape a +/// course's `capacity` already uses. +pub fn validate_capacity(value: Option) -> Result<(), ValidationError> { + match value { + Some(capacity) if !(0..=MAX_MENU_CAPACITY).contains(&capacity) => { + Err(ValidationError::Invalid { + field: "capacity", + reason: "must be between 0 and 10000", + }) + } + _ => Ok(()), + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct Menu { + id: MenuId, + date: MenuDate, + slot: MenuSlot, + capacity: Option, + created_by: UserId, + created_at: Timestamp, +} + +impl Menu { + pub fn get_id(&self) -> &MenuId { + &self.id + } + + pub fn get_date(&self) -> &MenuDate { + &self.date + } + + pub fn get_slot(&self) -> &MenuSlot { + &self.slot + } + + pub fn get_capacity(&self) -> Option { + self.capacity + } + + pub fn get_created_by(&self) -> &UserId { + &self.created_by + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + /// Publish a menu. Refused (409) when the day+slot already carries one — + /// re-checked under [`MENU_LOCK`], so two racing publishes cannot both find + /// the day free and trip the UNIQUE index into a 500. + pub async fn create( + date: MenuDate, + slot: MenuSlot, + capacity: Option, + created_by: &UserId, + db: &Database, + ) -> Result { + let _guard = MENU_LOCK.lock().await; + if Self::find(&date, &slot, db).await?.is_some() { + return Err(AppError::Conflict( + "a menu is already published for that date and slot", + )); + } + let menu = Menu { + id: MenuId::generate(), + date, + slot, + capacity, + created_by: created_by.clone(), + created_at: Timestamp::now(), + }; + let created: Option = db.create(menu.id.record()).content(menu).await?; + created.ok_or_else(|| AppError::Internal("failed to publish the menu".into())) + } + + pub async fn read(id: &MenuId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// The menu for one day and slot, if any — the uniqueness check. + pub async fn find( + date: &MenuDate, + slot: &MenuSlot, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1") + .bind(("date", date.as_str().to_string())) + .bind(("slot", slot.as_str().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds; + /// either may be omitted. The comparison is lexical, which is chronological + /// for this format. + pub async fn list( + from: Option<&MenuDate>, + to: Option<&MenuDate>, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM menu \ + WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to) \ + ORDER BY date DESC, slot ASC, id DESC", + ) + .bind(("from", from.map(|date| date.as_str().to_string()))) + .bind(("to", to.map(|date| date.as_str().to_string()))) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns, + /// because moving a published menu to another day is a different menu. + /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped. + pub async fn update( + self, + capacity: Option>, + db: &Database, + ) -> Result { + FieldUpdate::new(self.id.record()) + .set("capacity", capacity) + .run::(db) + .await + } + + /// Whether any menu was ever published for this slot name — the guard + /// behind removing a slot from `meal_slots`, mirroring + /// [`ExamResult::any_for_kind`](crate::domain::exam_result::ExamResult::any_for_kind). + /// Menus snapshot the slot as text, so this is a plain string match. + /// Callers hold [`MENU_LOCK`] so a publish cannot slip in behind the check. + pub async fn any_for_slot(slot: &str, db: &Database) -> Result { + let mut result = db + .query("SELECT VALUE id FROM menu WHERE slot = $slot LIMIT 1") + .bind(("slot", slot.to_string())) + .await? + .check()?; + Ok(!result.take::>(0)?.is_empty()) + } + + /// Delete the menu and the dishes on it — a dish has no meaning without + /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed. + pub async fn delete(self, db: &Database) -> Result { + MenuDish::delete_for_menu(&self.id, db).await?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn date_accepts_only_padded_calendar_days() { + assert!(MenuDate::try_new("2026-07-26").is_ok()); + assert!(MenuDate::try_new("2026-7-26").is_err()); + assert!(MenuDate::try_new("2026-13-01").is_err()); + assert!(MenuDate::try_new("2026-00-01").is_err()); + assert!(MenuDate::try_new("2026-01-32").is_err()); + assert!(MenuDate::try_new("26-01-02").is_err()); + assert!(MenuDate::try_new("").is_err()); + // Sorting the text must sort the calendar — the range filter relies on it. + assert!( + MenuDate::try_new("2026-01-09").unwrap() < MenuDate::try_new("2026-01-10").unwrap() + ); + assert!( + MenuDate::try_new("2026-09-01").unwrap() < MenuDate::try_new("2026-10-01").unwrap() + ); + } + + #[test] + fn slot_must_be_one_the_school_serves() { + let allowed = vec![MealSlotDef::try_new("lunch").unwrap()]; + assert!(MenuSlot::try_new("lunch", &allowed).is_ok()); + assert!(MenuSlot::try_new("brunch", &allowed).is_err()); + assert!(MenuSlot::try_new("lunch", &[]).is_err()); + } + + #[test] + fn capacity_is_bounded_but_optional() { + assert!(validate_capacity(None).is_ok()); + assert!(validate_capacity(Some(0)).is_ok()); + assert!(validate_capacity(Some(MAX_MENU_CAPACITY)).is_ok()); + assert!(validate_capacity(Some(-1)).is_err()); + assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err()); + } +} diff --git a/src/domain/menu_dish.rs b/src/domain/menu_dish.rs new file mode 100644 index 0000000..0dd0803 --- /dev/null +++ b/src/domain/menu_dish.rs @@ -0,0 +1,304 @@ +//! One dish on a published [`Menu`](crate::domain::menu::Menu): what it is, +//! what it costs, and which dietary tags it carries. +//! +//! Money is **minor units** (kuruş) as `i64` — never a float, never a decimal, +//! at any layer. `tags` are validated against the school's `dietary_tags` +//! list, the same contract a menu's `slot` has with `meal_slots`. + +use std::sync::LazyLock; + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Generator; + +use crate::constant::{ + MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS, + MENU_DISH_TABLE, +}; +use crate::database::Database; +use crate::domain::field_update::FieldUpdate; +use crate::domain::menu::MenuId; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +/// Mints dish ids in write order — see [`MenuId::generate`]; the listings below +/// order by `id` within a menu, which random low bits would scramble. +static IDS: LazyLock> = + LazyLock::new(|| std::sync::Mutex::new(Generator::new())); + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MenuDishId(RecordId); + +impl MenuDishId { + pub fn generate() -> Self { + let mut ids = IDS.lock().expect("menu dish id generator poisoned"); + // The only error is exhausting the random bits within one millisecond + // (2^80 ids deep); it clears itself as the clock ticks, so retry. + let ulid = loop { + if let Ok(ulid) = ids.generate() { + break ulid; + } + }; + Self(RecordId::new(MENU_DISH_TABLE, ulid.to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(MENU_DISH_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DishName(String); + +impl DishName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_DISH_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DishDescription(String); + +impl DishDescription { + /// Blank (or whitespace-only) means "no description" — `None`, not an + /// empty string, so the column is absent rather than falsely present. + pub fn try_new(value: &str) -> Result, ValidationError> { + validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?; + let value = value.trim(); + Ok((!value.is_empty()).then(|| Self(value.to_string()))) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// What one serving costs, in **minor units** (kuruş). Never negative — a +/// giveaway dish is `0`, and money that flows the other way is a ledger line. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct DishPrice(i64); + +impl DishPrice { + pub fn try_new(value: i64) -> Result { + if !(0..=MAX_DISH_PRICE_MINOR).contains(&value) { + return Err(ValidationError::Invalid { + field: "price_minor", + reason: "must be between 0 and 1000000 minor units", + }); + } + Ok(Self(value)) + } + + pub fn as_minor(self) -> i64 { + self.0 + } +} + +/// The dietary tags a dish carries, drawn from the school's `dietary_tags` +/// list. Deduplicated, order preserved — the list is what a student's profile +/// is matched against, so a repeat carries no extra meaning. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct DishTags(Vec); + +impl DishTags { + pub fn try_new(values: &[String], allowed: &[String]) -> Result { + let mut tags: Vec = Vec::new(); + for value in values { + let value = value.trim(); + if !allowed.iter().any(|tag| tag == value) { + return Err(ValidationError::Invalid { + field: "tags", + reason: "not one of the school's dietary tags (see GET /settings)", + }); + } + if !tags.iter().any(|tag| tag == value) { + tags.push(value.to_string()); + } + } + if tags.len() > MAX_DISH_TAGS { + return Err(ValidationError::Invalid { + field: "tags", + reason: "at most 10 tags per dish", + }); + } + Ok(Self(tags)) + } + + pub fn as_slice(&self) -> &[String] { + &self.0 + } +} + +#[derive(Debug, Clone, SurrealValue)] +pub struct MenuDish { + id: MenuDishId, + menu: MenuId, + name: DishName, + description: Option, + price_minor: DishPrice, + tags: DishTags, + created_at: Timestamp, +} + +impl MenuDish { + pub fn get_id(&self) -> &MenuDishId { + &self.id + } + + pub fn get_menu(&self) -> &MenuId { + &self.menu + } + + pub fn get_name(&self) -> &DishName { + &self.name + } + + pub fn get_description(&self) -> Option<&DishDescription> { + self.description.as_ref() + } + + pub fn get_price_minor(&self) -> DishPrice { + self.price_minor + } + + pub fn get_tags(&self) -> &DishTags { + &self.tags + } + + pub fn get_created_at(&self) -> Timestamp { + self.created_at + } + + pub async fn create( + menu: &MenuId, + name: DishName, + description: Option, + price_minor: DishPrice, + tags: DishTags, + db: &Database, + ) -> Result { + let dish = MenuDish { + id: MenuDishId::generate(), + menu: menu.clone(), + name, + description, + price_minor, + tags, + created_at: Timestamp::now(), + }; + let created: Option = db.create(dish.id.record()).content(dish).await?; + created.ok_or_else(|| AppError::Internal("failed to add the dish".into())) + } + + pub async fn read(id: &MenuDishId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every dish on one menu, in the order they were added. + pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result, AppError> { + Self::list_for_menus(std::slice::from_ref(menu), db).await + } + + /// Dishes for a whole page of menus in one round trip — the alternative is + /// a query per menu, which is the N+1 the pagination slice exists to avoid. + pub async fn list_for_menus( + menus: &[MenuId], + db: &Database, + ) -> Result, AppError> { + if menus.is_empty() { + return Ok(Vec::new()); + } + let mut result = db + .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC") + .bind(( + "menus", + menus.iter().map(MenuId::record).collect::>(), + )) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// How many dishes the menu already carries — the `MAX_DISHES_PER_MENU` gate. + pub async fn count_for_menu(menu: &MenuId, db: &Database) -> Result { + Ok(Self::list_for_menu(menu, db).await?.len()) + } + + /// Write only the fields the PATCH carried. `description` is nullable, so + /// it takes the three-way shape: absent = keep, `Some(None)` = clear. + pub async fn update( + self, + name: Option, + description: Option>, + price_minor: Option, + tags: Option, + db: &Database, + ) -> Result { + FieldUpdate::new(self.id.record()) + .set("name", name) + .set("description", description) + .set("price_minor", price_minor) + .set("tags", tags) + .run::(db) + .await + } + + pub async fn delete(self, db: &Database) -> Result { + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } + + /// Drop every dish on a menu — the menu delete's cascade. + pub async fn delete_for_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> { + db.query("DELETE menu_dish WHERE menu = $menu") + .bind(("menu", menu.record())) + .await? + .check()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn price_is_bounded_non_negative_minor_units() { + assert_eq!(DishPrice::try_new(0).unwrap().as_minor(), 0); + assert_eq!(DishPrice::try_new(4550).unwrap().as_minor(), 4550); + assert!(DishPrice::try_new(-1).is_err()); + assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR).is_ok()); + assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR + 1).is_err()); + } + + #[test] + fn tags_must_come_from_the_school_list_and_dedupe() { + let allowed = vec!["vegan".to_string(), "nut_allergy".to_string()]; + let tags = + DishTags::try_new(&["vegan".to_string(), "vegan".to_string()], &allowed).unwrap(); + assert_eq!(tags.as_slice(), ["vegan"]); + assert!(DishTags::try_new(&["halal".to_string()], &allowed).is_err()); + assert!( + DishTags::try_new(&[], &allowed) + .unwrap() + .as_slice() + .is_empty() + ); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 3ebb9b0..385095a 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -12,6 +12,7 @@ pub mod chatbot_message; pub mod chatbot_thread; pub mod course; pub mod course_session; +pub mod dietary_profile; pub mod enrollment; pub mod event; pub mod exam; @@ -24,6 +25,11 @@ pub mod homework; pub mod homework_file; pub mod homework_result; pub mod homework_submission; +pub mod meal_attendance; +pub mod meal_booking; +pub mod meal_ledger; +pub mod menu; +pub mod menu_dish; pub mod message; pub mod monotonic_id; pub mod note; diff --git a/src/domain/parent_link.rs b/src/domain/parent_link.rs index 3ac522a..a9fad23 100644 --- a/src/domain/parent_link.rs +++ b/src/domain/parent_link.rs @@ -32,9 +32,11 @@ impl ParentLinkId { } } -/// A parent account's tie to one student it may observe. Purely a read grant: -/// it gates the parent's access to the student's reports (marks, attendance, -/// pomodoro) and nothing else — a parent never writes through it. +/// A parent account's tie to one student it may observe. Almost entirely a +/// read grant: it gates the parent's access to the student's reports (marks, +/// attendance, pomodoro). The single write it authorizes is the food program — +/// a parent books and cancels a linked child's meals, since paying for lunch +/// is a parent's job and a small child cannot do it themselves. #[derive(Debug, Clone, SurrealValue)] pub struct ParentLink { id: ParentLinkId, diff --git a/src/domain/settings.rs b/src/domain/settings.rs index dd13e6c..3a03085 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -14,10 +14,11 @@ use surrealdb::types::{RecordId, SurrealValue}; use crate::constant::{ - DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS, - DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, - 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, + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, + DEFAULT_EXAM_KINDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS, + 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, @@ -66,6 +67,34 @@ 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. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct MealSlotDef { + name: String, +} + +impl MealSlotDef { + pub fn try_new(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { + return Err(ValidationError::Invalid { + field: "meal_slots", + reason: "slot names must be 1 to 50 characters", + }); + } + Ok(Self { + name: name.to_string(), + }) + } + + pub fn get_name(&self) -> &str { + &self.name + } +} + /// One grade-display band: marks at or above `min` (and below the next band's /// `min`) render as `label`. Display only — storage and averaging stay numeric. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -120,6 +149,16 @@ pub struct Settings { chatbot_history_turns: Option, max_chatbot_threads: Option, max_chatbot_message_len: Option, + /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` — + /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` + /// writes the whole row, so a field this struct did not carry would coerce + /// to `NONE` and abort the transaction. + meal_slots: Option>, + dietary_tags: Option>, + /// Minutes before a meal at which booking *and* cancelling close. One knob + /// for both deadlines; `None` = no cutoff at all, which is also what an + /// unset column reads as. + meal_cancel_cutoff_minutes: Option, } /// Everything [`Settings::try_new`] validates, in one struct — the knobs @@ -134,6 +173,10 @@ pub struct SettingsParams { pub chatbot_history_turns: i64, pub max_chatbot_threads: i64, pub max_chatbot_message_len: i64, + pub meal_slots: Vec, + pub dietary_tags: Vec, + /// `None` = no booking/cancel cutoff. + pub meal_cancel_cutoff_minutes: Option, } impl Settings { @@ -158,6 +201,9 @@ impl Settings { chatbot_history_turns: None, max_chatbot_threads: None, max_chatbot_message_len: None, + meal_slots: None, + dietary_tags: None, + meal_cancel_cutoff_minutes: None, } } @@ -172,6 +218,9 @@ impl Settings { chatbot_history_turns: self.get_chatbot_history_turns(), max_chatbot_threads: self.get_max_chatbot_threads(), max_chatbot_message_len: self.get_max_chatbot_message_len(), + meal_slots: self.get_meal_slots(), + dietary_tags: self.get_dietary_tags(), + meal_cancel_cutoff_minutes: self.meal_cancel_cutoff_minutes, } } @@ -192,6 +241,9 @@ impl Settings { chatbot_history_turns, max_chatbot_threads, max_chatbot_message_len, + meal_slots, + dietary_tags, + meal_cancel_cutoff_minutes, } = params; in_range( "max_file_bytes", @@ -260,6 +312,32 @@ impl Settings { let mut grade_bands = grade_bands; grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min())); + // The food lists follow the same list rules as the kinds and statuses + // above, with one difference: empty is legal on both. A school that + // runs no canteen has no slots and no dietary tags, and refusing that + // would force it to keep a list it never uses. + let slot_names: Vec = meal_slots + .iter() + .map(|slot| slot.get_name().to_string()) + .collect(); + if !slot_names.is_empty() { + validate_list("meal_slots", slot_names)?; + } + let dietary_tags = if dietary_tags.is_empty() { + dietary_tags + } else { + validate_list("dietary_tags", dietary_tags)? + }; + // One knob for both deadlines: 0 = closes exactly at serving time. + if let Some(minutes) = meal_cancel_cutoff_minutes { + in_range( + "meal_cancel_cutoff_minutes", + minutes, + 0..=MAX_MEAL_CANCEL_CUTOFF_MINUTES, + "must be between 0 and 10080 (one week) minutes", + )?; + } + Ok(Self { id: Self::record_id(), exam_kinds, @@ -269,6 +347,9 @@ impl Settings { chatbot_history_turns: Some(chatbot_history_turns), max_chatbot_threads: Some(max_chatbot_threads), max_chatbot_message_len: Some(max_chatbot_message_len), + meal_slots: Some(meal_slots), + dietary_tags: Some(dietary_tags), + meal_cancel_cutoff_minutes, }) } @@ -322,6 +403,33 @@ impl Settings { .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN) } + /// The meal slots the school serves; the built-in list while it never set + /// one (including rows saved before the field existed). An explicitly + /// stored empty list stays empty — that is "no meal program", not "unset". + pub fn get_meal_slots(&self) -> Vec { + self.meal_slots.clone().unwrap_or_else(|| { + DEFAULT_MEAL_SLOTS + .map(|name| MealSlotDef { + name: name.to_string(), + }) + .to_vec() + }) + } + + /// The dietary tags a dish and a student's profile may carry; the built-in + /// list while the school never set one. + pub fn get_dietary_tags(&self) -> Vec { + self.dietary_tags + .clone() + .unwrap_or_else(|| DEFAULT_DIETARY_TAGS.map(String::from).to_vec()) + } + + /// Minutes before a meal at which booking and cancelling close; `None` = + /// no cutoff, the default while the school never set one. + pub fn get_meal_cancel_cutoff_minutes(&self) -> Option { + self.meal_cancel_cutoff_minutes + } + /// The label of the band `mark` falls into: the band with the greatest /// `min` at or below it. `None` when no bands are configured. Takes an /// `f64` so course averages label the same way plain marks do. @@ -376,7 +484,10 @@ impl Settings { AND max_file_bytes = $mf AND chatbot_history_turns = $ct AND max_chatbot_threads = $cc - AND max_chatbot_message_len = $cl; + AND max_chatbot_message_len = $cl + AND meal_slots = $ms + AND dietary_tags = $dt + AND meal_cancel_cutoff_minutes = $mc; COMMIT TRANSACTION;", ) .bind(("expected", expected.clone())) @@ -389,6 +500,9 @@ impl Settings { .bind(("ct", expected.chatbot_history_turns)) .bind(("cc", expected.max_chatbot_threads)) .bind(("cl", expected.max_chatbot_message_len)) + .bind(("ms", expected.meal_slots.clone())) + .bind(("dt", expected.dietary_tags.clone())) + .bind(("mc", expected.meal_cancel_cutoff_minutes)) .await? .check()?; // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An diff --git a/src/lib.rs b/src/lib.rs index 0976818..7720c70 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,8 +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 = "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. 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, 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 = "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+"), @@ -102,6 +103,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/sessions", web::sessions::routes()) .nest("/exams", web::exams::routes()) .nest("/marks", web::marks::routes()) + .nest("/meals", web::meals::routes()) .nest("/work", web::work::routes()) .nest("/pomodoro", web::pomodoro::routes()) .nest("/questions", web::questions::routes()) diff --git a/src/web/limits.rs b/src/web/limits.rs index e03389b..fe85112 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -177,6 +177,45 @@ struct AppointmentLimits { max_slot_occurrences: usize, } +/// The food program: menus and their dishes, dietary profiles, bookings and +/// the meal ledger. The school's own lists (`meal_slots`, `dietary_tags`) and +/// its booking cutoff are on `GET /settings`; what stands here is the fixed +/// range those must stay inside. +#[derive(Serialize, ToSchema)] +struct MealLimits { + max_dish_name_len: usize, + max_dish_description_len: usize, + /// How many dishes one menu may list. + max_dishes_per_menu: usize, + /// Dietary tags one dish may carry. + max_dish_tags: usize, + /// Upper bound for a menu's optional `capacity`; absent = uncapped. + max_menu_capacity: i64, + /// Dietary tags one student's profile may carry, and its kitchen note. + max_dietary_tags: usize, + max_dietary_note_len: usize, + /// Money is **minor units** (kuruş) as an integer everywhere — never a + /// decimal, never a float. These cap one dish and one ledger line. + max_dish_price_minor: i64, + max_ledger_amount_minor: i64, + /// How the money moved, and why. + max_ledger_method_len: usize, + max_ledger_note_len: usize, + /// 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, + /// The only accepted booking `status` values. + #[schema(example = json!(["booked", "cancelled"]))] + booking_statuses: Vec<&'static str>, + /// The only accepted meal-attendance `status` values — deliberately not + /// the school's lesson attendance statuses. + #[schema(example = json!(["served", "missed"]))] + attendance_statuses: Vec<&'static str>, + /// The only accepted ledger `kind` values. + #[schema(example = json!(["charge", "credit", "reversal"]))] + ledger_kinds: Vec<&'static str>, +} + /// The AI chatbot. Each range bounds the matching `/settings` knob; the live /// values are on `GET /settings`. #[derive(Serialize, ToSchema)] @@ -260,6 +299,7 @@ struct LimitsResponse { homework: HomeworkLimits, question_pool: QuestionPoolLimits, appointment: AppointmentLimits, + meal: MealLimits, chatbot: ChatbotLimits, settings: SettingsLimits, request: RequestLimits, @@ -355,6 +395,23 @@ impl LimitsResponse { max_reason_len: MAX_APPOINTMENT_REASON_LEN, max_slot_occurrences: MAX_SLOT_OCCURRENCES, }, + meal: MealLimits { + max_dish_name_len: MAX_DISH_NAME_LEN, + max_dish_description_len: MAX_DISH_DESCRIPTION_LEN, + max_dishes_per_menu: MAX_DISHES_PER_MENU, + max_dish_tags: MAX_DISH_TAGS, + max_menu_capacity: MAX_MENU_CAPACITY, + max_dietary_tags: MAX_DIETARY_TAGS, + max_dietary_note_len: MAX_DIETARY_NOTE_LEN, + max_dish_price_minor: MAX_DISH_PRICE_MINOR, + max_ledger_amount_minor: MAX_LEDGER_AMOUNT_MINOR, + 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, + booking_statuses: MEAL_BOOKING_STATUSES.to_vec(), + attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(), + ledger_kinds: MEAL_LEDGER_KINDS.to_vec(), + }, chatbot: ChatbotLimits { max_message_len: MAX_CHATBOT_MESSAGE_LEN, max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN, diff --git a/src/web/meals.rs b/src/web/meals.rs new file mode 100644 index 0000000..2365c82 --- /dev/null +++ b/src/web/meals.rs @@ -0,0 +1,1376 @@ +//! The food program: menus and the dishes on them, the seats booked against +//! them, and the money that moved. +//! +//! Reads are open to every authenticated user (a student picks their lunch), +//! writes are manager+ — publishing what the school serves is kitchen +//! administration, not teaching. +//! +//! Money only ever *appends* here (see [`MealLedger`]): booking charges a price +//! snapshot, cancelling reverses it, and recording a payment is admin-only. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::{IntoParams, ToSchema}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +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_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; +use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; +use crate::domain::menu_dish::{ + DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, +}; +use crate::domain::parent_link::ParentLink; +use crate::domain::role::Role; +use crate::domain::settings::Settings; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{ + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher, + paginate, person_map, set_or_clear, +}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_menu, list_menus)) + .routes(routes!(get_menu, update_menu, delete_menu)) + .routes(routes!(add_dish)) + .routes(routes!(update_dish, delete_dish)) + .routes(routes!(book_meal, list_menu_bookings)) + .routes(routes!(my_bookings)) + .routes(routes!(cancel_booking)) + .routes(routes!(mark_attendance, list_menu_attendance)) + .routes(routes!(user_attendance)) + .routes(routes!(my_profile)) + .routes(routes!(user_profile, update_profile)) + .routes(routes!(my_balance)) + .routes(routes!(user_balance)) + .routes(routes!(user_ledger)) + .routes(routes!(record_credit)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateMenu { + /// The calendar day, `YYYY-MM-DD`. Text, not a timestamp: "one menu per + /// day and slot" is the school's own day, not UTC midnight. + #[schema(example = "2026-09-14", min_length = 10, max_length = 10)] + date: String, + /// One of the school's `meal_slots` (see `GET /settings`). + #[schema(example = "lunch")] + slot: String, + /// How many students may book it. Omit (or `null`) for uncapped. + #[schema(minimum = 0, maximum = 10000, example = 120)] + capacity: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateMenu { + /// New seat cap; `null` clears it back to uncapped. `date` and `slot` are + /// immutable — a menu on another day is another menu. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, minimum = 0, maximum = 10000)] + capacity: Option>, +} + +/// Inclusive `YYYY-MM-DD` bounds on `GET /meals/menus`. Either may be omitted. +#[derive(Debug, Deserialize, IntoParams)] +struct MenuRange { + /// Keep menus on or after this day. + #[param(example = "2026-09-01")] + from: Option, + /// Keep menus on or before this day. + #[param(example = "2026-09-30")] + to: Option, +} + +#[derive(Deserialize, ToSchema)] +struct CreateDish { + #[schema(example = "Mercimek çorbası", max_length = 100)] + name: String, + #[schema(max_length = 500)] + description: Option, + /// Price in **minor units** (kuruş) — `4550` is 45,50 ₺. Integer only: + /// this API never speaks decimals or floats about money. + #[schema(minimum = 0, maximum = 1000000, example = 4550_i64)] + price_minor: i64, + /// Dietary tags, each one of the school's `dietary_tags` (`GET /settings`). + #[schema(max_items = 10, example = json!(["vegetarian"]))] + #[serde(default)] + tags: Vec, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateDish { + #[schema(max_length = 100)] + name: Option, + /// `null` (or blank) clears the description. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, max_length = 500)] + description: Option>, + #[schema(minimum = 0, maximum = 1000000)] + price_minor: Option, + #[schema(max_items = 10)] + tags: Option>, +} + +#[derive(Serialize, ToSchema)] +struct DishResponse { + id: String, + #[schema(example = "Mercimek çorbası")] + name: String, + description: Option, + /// Minor units (kuruş). + price_minor: i64, + tags: Vec, + /// Which of `tags` the **calling user's** own dietary profile flags — the + /// set intersection of the two lists. Empty when they do not overlap, and + /// empty for every reader without a profile (staff included). + #[schema(example = json!(["nut_allergy"]))] + conflicts: Vec, + created_at: i64, +} + +impl DishResponse { + fn new(dish: &MenuDish, viewer_tags: &[String]) -> Self { + Self { + id: dish.get_id().key().to_string(), + name: dish.get_name().as_str().to_string(), + description: dish.get_description().map(|text| text.as_str().to_string()), + price_minor: dish.get_price_minor().as_minor(), + tags: dish.get_tags().as_slice().to_vec(), + conflicts: conflicts(dish.get_tags().as_slice(), viewer_tags), + created_at: dish.get_created_at().as_millis(), + } + } +} + +#[derive(Serialize, ToSchema)] +struct MenuResponse { + id: String, + /// The calendar day, `YYYY-MM-DD`. + #[schema(example = "2026-09-14")] + date: String, + /// The meal slot, snapshotted when the menu was published — it stays as it + /// was even if the school later retires the slot. + #[schema(example = "lunch")] + slot: String, + /// Seat cap; `null` = uncapped. + capacity: Option, + /// Everything on offer, in the order it was added. + dishes: Vec, + created_by: PersonRef, + created_at: i64, +} + +impl MenuResponse { + fn new( + menu: &Menu, + dishes: &[MenuDish], + people: &std::collections::HashMap, + viewer_tags: &[String], + ) -> Self { + Self { + id: menu.get_id().key().to_string(), + date: menu.get_date().as_str().to_string(), + slot: menu.get_slot().as_str().to_string(), + capacity: menu.get_capacity(), + dishes: dishes + .iter() + .filter(|dish| dish.get_menu() == menu.get_id()) + .map(|dish| DishResponse::new(dish, viewer_tags)) + .collect(), + created_by: PersonRef::resolve(people, menu.get_created_by()), + created_at: menu.get_created_at().as_millis(), + } + } +} + +/// Join dishes, publishers, and the reader's own dietary tags onto a page of +/// menus — three queries for the whole page, never one per row. The profile in +/// particular is read **once**, not per dish. +async fn menu_responses( + menus: &[Menu], + viewer: &UserId, + db: &Database, +) -> Result, AppError> { + let ids: Vec = menus.iter().map(|menu| menu.get_id().clone()).collect(); + let dishes = MenuDish::list_for_menus(&ids, db).await?; + let people = person_map(menus.iter().map(|menu| menu.get_created_by().clone()), db).await?; + let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; + Ok(menus + .iter() + .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags)) + .collect()) +} + +/// One menu, with its dishes. +async fn one_menu( + menu: &Menu, + viewer: &UserId, + db: &Database, +) -> Result, AppError> { + let dishes = MenuDish::list_for_menu(menu.get_id(), db).await?; + let people = person_map([menu.get_created_by().clone()], db).await?; + let viewer_tags = DietaryProfile::tags_of(viewer, db).await?; + Ok(Json(MenuResponse::new( + menu, + &dishes, + &people, + &viewer_tags, + ))) +} + +/// Publish a menu for one day and meal slot. Requires manager+. The slot must +/// be one the school currently serves, and a day+slot already published is a +/// `409` — edit that menu instead of publishing a second one. +#[utoipa::path( + post, + path = "/menus", + tag = "meals", + security(("session_cookie" = [])), + request_body = CreateMenu, + responses( + (status = 201, description = "Menu published", body = MenuResponse), + (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 409, description = "A menu already exists for that date and slot", body = ErrorResponse), + ), +)] +async fn create_menu( + State(st): State, + RequireManager(user): RequireManager, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let date = MenuDate::try_new(&req.date)?; + let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?; + validate_capacity(req.capacity)?; + let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?; + let body = one_menu(&menu, user.get_id(), &st.db).await?; + Ok((StatusCode::CREATED, body)) +} + +/// List published menus, newest day first, each with its dishes. Any +/// authenticated user. Narrow to a date range with `?from=&to=` (inclusive, +/// `YYYY-MM-DD`). Paged via `?limit=&offset=` (omit `limit` for the full list); +/// returns a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/menus", + tag = "meals", + security(("session_cookie" = [])), + params(MenuRange, PageParams), + responses( + (status = 200, description = "A page of menus (the full list when unpaged)", body = Page), + (status = 400, description = "Malformed date bound, limit, or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_menus( + State(st): State, + CurrentUser(user): CurrentUser, + Query(range): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; + let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; + let menus = Menu::list(from.as_ref(), to.as_ref(), &st.db).await?; + let total = menus.len() as i64; + // The dish/people join runs over the page alone, so it shrinks with it. + let items = menu_responses(paginate(&menus, limit, offset), user.get_id(), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch one menu with its dishes. +#[utoipa::path( + get, + path = "/menus/{id}", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + responses( + (status = 200, description = "The menu", body = MenuResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_menu( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + one_menu(&menu, user.get_id(), &st.db).await +} + +/// Change a menu's seat cap. Requires manager+. `date` and `slot` are +/// immutable; `"capacity": null` goes back to uncapped. +#[utoipa::path( + patch, + path = "/menus/{id}", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + request_body = UpdateMenu, + responses( + (status = 200, description = "Updated menu", body = MenuResponse), + (status = 400, description = "Capacity out of range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_menu( + State(st): State, + RequireManager(user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + if let Some(capacity) = req.capacity { + validate_capacity(capacity)?; + } + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let updated = menu.update(req.capacity, &st.db).await?; + one_menu(&updated, user.get_id(), &st.db).await +} + +/// Unpublish a menu. Requires manager+. Its dishes go with it — a dish has no +/// meaning apart from the menu it was published on. A menu somebody still +/// holds a seat on is a `409`: cancel the bookings first. +#[utoipa::path( + delete, + path = "/menus/{id}", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "The menu still has live bookings", body = ErrorResponse), + ), +)] +async fn delete_menu( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result { + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + // [`MENU_LOCK`] holds the seat check and the delete together, so a booking + // cannot land on a menu that is already on its way out. + let _guard = MENU_LOCK.lock().await; + if MealBooking::any_live_for_menu(menu.get_id(), &st.db).await? { + return Err(AppError::Conflict( + "the menu still has live bookings — cancel them first", + )); + } + menu.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +/// Add a dish to a menu. Requires manager+. Tags must come from the school's +/// `dietary_tags`, and a menu holds at most 50 dishes (`409` at the cap). +#[utoipa::path( + post, + path = "/menus/{id}/dishes", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + request_body = CreateDish, + responses( + (status = 201, description = "Dish added", body = DishResponse), + (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "No such menu", body = ErrorResponse), + (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse), + ), +)] +async fn add_dish( + State(st): State, + RequireManager(user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let name = DishName::try_new(&req.name)?; + let description = req + .description + .as_deref() + .map(DishDescription::try_new) + .transpose()? + .flatten(); + let price = DishPrice::try_new(req.price_minor)?; + let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?; + // Dish writes take [`MENU_LOCK`] because a booking snapshots the menu's + // price under it: a dish landing mid-booking would be stored on the seat as + // "the menu was free", and a held seat is never re-priced. It also makes + // the dish cap a real cap — count-then-write is write-skew otherwise. The + // lock stays a leaf: nothing below here takes another. + let _guard = MENU_LOCK.lock().await; + // The menu is read *inside* the lock, like `MealBooking::book` does: read + // before it, a `DELETE /menus/{id}` running in the gap takes its cascade + // with it and this dish lands on a menu that no longer exists. + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if MenuDish::count_for_menu(menu.get_id(), &st.db).await? >= MAX_DISHES_PER_MENU { + return Err(AppError::Conflict( + "the menu already carries the maximum number of dishes", + )); + } + let dish = MenuDish::create(menu.get_id(), name, description, price, tags, &st.db).await?; + let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(DishResponse::new(&dish, &viewer_tags)), + )) +} + +/// Edit a dish. Requires manager+. Omitted fields keep their value; +/// `"description": null` clears it, and `tags` replaces the whole list. +#[utoipa::path( + patch, + path = "/dishes/{did}", + tag = "meals", + security(("session_cookie" = [])), + params(("did" = String, Path, description = "Dish id")), + request_body = UpdateDish, + responses( + (status = 200, description = "Updated dish", body = DishResponse), + (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_dish( + State(st): State, + RequireManager(user): RequireManager, + Path(did): Path, + Json(req): Json, +) -> Result, AppError> { + let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let name = req.name.as_deref().map(DishName::try_new).transpose()?; + // Absent keeps, `null` clears, and a blank string clears too — an empty + // description is the absence of one, never a stored empty string. + let description = match req.description { + None => None, + Some(None) => Some(None), + Some(Some(text)) => Some(DishDescription::try_new(&text)?), + }; + let price = req.price_minor.map(DishPrice::try_new).transpose()?; + let tags = match &req.tags { + Some(tags) => Some(DishTags::try_new( + tags, + &Settings::load(&st.db).await?.get_dietary_tags(), + )?), + None => None, + }; + // Under [`MENU_LOCK`] like every dish write — see `add_dish`. + let _guard = MENU_LOCK.lock().await; + let updated = dish.update(name, description, price, tags, &st.db).await?; + let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?; + Ok(Json(DishResponse::new(&updated, &viewer_tags))) +} + +/// Remove a dish from its menu. Requires manager+. +#[utoipa::path( + delete, + path = "/dishes/{did}", + tag = "meals", + security(("session_cookie" = [])), + params(("did" = String, Path, description = "Dish id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_dish( + State(st): State, + RequireManager(_user): RequireManager, + Path(did): Path, +) -> Result { + let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db) + .await? + .ok_or(AppError::NotFound)?; + // Under [`MENU_LOCK`] like every dish write — see `add_dish`. + let _guard = MENU_LOCK.lock().await; + dish.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- dietary profiles ----------------------------------------------------- + +#[derive(Deserialize, ToSchema)] +struct UpdateDietaryProfile { + /// Replaces the whole tag list; each entry must be one of the school's + /// `dietary_tags` (`GET /settings`) — the same vocabulary a dish is tagged + /// from, which is what makes a menu's `conflicts` computable. + #[schema(max_items = 10, example = json!(["nut_allergy"]))] + tags: Option>, + /// Free text for the kitchen; `null` (or blank) clears it. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, max_length = 500, example = "carries an EpiPen")] + note: Option>, +} + +#[derive(Serialize, ToSchema)] +struct DietaryProfileResponse { + student: PersonRef, + /// The tags the school recorded; empty while there is no profile. + tags: Vec, + note: Option, + /// Who last wrote it, and when — both absent while no profile exists. + updated_by: Option, + updated_at: Option, +} + +/// One student's profile, or the empty one. A student who was never recorded +/// has *no* restrictions, so that reads back as an empty profile rather than a +/// `404` — the caller asked "what may they not eat", and "nothing known" is an +/// answer. +async fn profile_response( + student: &UserId, + db: &Database, +) -> Result, AppError> { + let profile = DietaryProfile::read(student, db).await?; + let people = person_map( + std::iter::once(student.clone()) + .chain(profile.as_ref().map(|row| row.get_updated_by().clone())), + db, + ) + .await?; + Ok(Json(DietaryProfileResponse { + student: PersonRef::resolve(&people, student), + tags: profile + .as_ref() + .map(|row| row.get_tags().as_slice().to_vec()) + .unwrap_or_default(), + note: profile + .as_ref() + .and_then(|row| row.get_note()) + .map(|note| note.as_str().to_string()), + updated_by: profile + .as_ref() + .map(|row| PersonRef::resolve(&people, row.get_updated_by())), + updated_at: profile.as_ref().map(|row| row.get_updated_at().as_millis()), + })) +} + +/// The caller's own dietary profile — what the school recorded about their +/// diet. Empty tags mean nothing was ever recorded. +#[utoipa::path( + get, + path = "/profiles/me", + tag = "meals", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's dietary profile", body = DietaryProfileResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_profile( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + profile_response(user.get_id(), &st.db).await +} + +/// One student's dietary profile. Requires teacher+, or a parent link to them +/// — the caller's own id always passes. +#[utoipa::path( + get, + path = "/profiles/{user}", + tag = "meals", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "Student id")), + responses( + (status = 200, description = "The student's dietary profile", body = DietaryProfileResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + ), +)] +async fn user_profile( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(user): Path, +) -> Result, AppError> { + let target = UserId::from_key(&user); + ensure_can_read_student(&caller, &target, &st.db).await?; + profile_response(&target, &st.db).await +} + +/// Record what a student may not eat. **Manager+**, deliberately: an allergen +/// list is a safety record the school keeps on the student's behalf, not a +/// self-service preference — a student editing their own would let a mistyped +/// (or removed) allergy reach the kitchen with the school's authority behind +/// it. Omitted fields keep their value; `tags` replaces the whole list, and +/// `"note": null` clears the note. First write creates the row. +#[utoipa::path( + patch, + path = "/profiles/{user}", + tag = "meals", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "Student id")), + request_body = UpdateDietaryProfile, + responses( + (status = 200, description = "The stored profile", body = DietaryProfileResponse), + (status = 400, description = "Unknown dietary tag, too many tags, an over-long note, or a non-student target", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "No such user", body = ErrorResponse), + ), +)] +async fn update_profile( + State(st): State, + RequireManager(manager): RequireManager, + Path(user): Path, + Json(req): Json, +) -> Result, AppError> { + let target = UserId::from_key(&user); + // Only a student eats off the school's menus; a profile on anyone else is + // a typo, and a typo here is an allergy filed against the wrong person. + if User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_role() + != Role::Student + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user", + reason: "only a student carries a dietary profile", + })); + } + let tags = match &req.tags { + Some(tags) => Some(DietaryTags::try_new( + tags, + &Settings::load(&st.db).await?.get_dietary_tags(), + )?), + None => None, + }; + // Absent keeps, `null` clears, and a blank string clears too — an empty + // note is the absence of one, never a stored empty string. + let note = match req.note { + None => None, + Some(None) => Some(None), + Some(Some(text)) => Some(DietaryNote::try_new(&text)?), + }; + DietaryProfile::save(&target, tags, note, manager.get_id(), &st.db).await?; + profile_response(&target, &st.db).await +} + +// ---- bookings ------------------------------------------------------------- + +#[derive(Deserialize, ToSchema)] +struct BookMeal { + /// Who the seat is for. Omit to book for yourself (a student's own lunch); + /// a parent must name one of their linked students. + student_id: Option, +} + +#[derive(Serialize, ToSchema)] +struct BookingResponse { + id: String, + /// The menu the seat is on. + menu_id: String, + student: PersonRef, + /// Who placed it — the student themselves, or their parent. + booked_by: PersonRef, + /// `booked` or `cancelled`. A cancel keeps the row (audit), it only stops + /// the seat counting against the menu's capacity. + #[schema(example = "booked")] + status: String, + cancelled_at: Option, + created_at: i64, +} + +impl BookingResponse { + fn new(booking: &MealBooking, people: &std::collections::HashMap) -> Self { + Self { + id: booking.get_id().key().to_string(), + menu_id: booking.get_menu().key().to_string(), + student: PersonRef::resolve(people, booking.get_student()), + booked_by: PersonRef::resolve(people, booking.get_booked_by()), + status: booking.get_status().as_str().to_string(), + cancelled_at: booking.get_cancelled_at().map(|at| at.as_millis()), + created_at: booking.get_created_at().as_millis(), + } + } +} + +/// Join the people onto a page of bookings — one query for the whole page. +async fn booking_responses( + bookings: &[MealBooking], + db: &Database, +) -> Result, AppError> { + let people = person_map( + bookings.iter().flat_map(|booking| { + [ + booking.get_student().clone(), + booking.get_booked_by().clone(), + ] + }), + db, + ) + .await?; + Ok(bookings + .iter() + .map(|booking| BookingResponse::new(booking, &people)) + .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()) +} + +/// Whose seat is this? A student books only for themselves; a parent only for +/// a student they hold a link to. Nobody else books through this route — a +/// teacher or manager arranging someone's lunch is not a thing this API does. +/// +/// The link row alone is not the grant: like a stale enrollment, a link whose +/// student side changed role must be inert, so the target's live role is +/// re-read here. A missing or non-student target falls through to the same +/// 403 — a parent never gets an existence oracle. +async fn booking_target( + caller: &User, + student_id: Option<&str>, + db: &Database, +) -> Result { + match caller.get_role() { + Role::Student => match student_id { + Some(id) if id != caller.get_id().key() => Err(AppError::Forbidden( + "a student books meals only for themselves", + )), + _ => Ok(caller.get_id().clone()), + }, + Role::Parent => { + let target = UserId::from_key(student_id.ok_or(AppError::Validation( + ValidationError::Invalid { + field: "student_id", + reason: "a parent must name the student the seat is for", + }, + ))?); + if ParentLink::exists(caller.get_id(), &target, db).await? + && User::read(&target, db) + .await? + .is_some_and(|target| target.get_role() == Role::Student) + { + return Ok(target); + } + Err(AppError::Forbidden( + "a parent books meals only for a linked student", + )) + } + _ => Err(AppError::Forbidden( + "only students and their parents book meals", + )), + } +} + +/// Take a seat on a published menu. A student books for themselves (omit +/// `student_id`); a parent books for a linked student by naming them. Booking +/// twice is the same seat, not a second one — and bills once, at the price the +/// menu carried when the seat was first taken. Refused (`409`) when the menu is +/// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and +/// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat +/// is never handed out unbilled. +#[utoipa::path( + post, + path = "/menus/{id}/bookings", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + request_body = BookMeal, + responses( + (status = 201, description = "Seat booked (or the seat already held)", body = BookingResponse), + (status = 400, description = "A parent named no student, or the menu's dishes sum past the chargeable maximum", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), + (status = 404, description = "No such menu", body = ErrorResponse), + (status = 409, description = "The menu is full, or its cutoff has passed", body = ErrorResponse), + ), +)] +async fn book_meal( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + 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 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 items = booking_responses(std::slice::from_ref(&booking), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(items.into_iter().next().expect("one booking in, one out")), + )) +} + +/// The caller's own bookings, newest first: the seats held *for* them, plus — +/// for a parent — the seats held for every student they currently hold a link +/// to. The links are re-read on every call, so an unlinked parent stops seeing +/// the child's meals at once, even the ones they booked themselves. Cancelled +/// bookings stay in the list, flagged. Paged via `?limit=&offset=` (omit +/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/bookings/me", + tag = "meals", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_bookings( + State(st): State, + CurrentUser(user): CurrentUser, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // Own seats always; a parent's children only while the link is live — the + // booking row's `booked_by` is history, never a standing read grant. + let mut students = vec![user.get_id().clone()]; + if user.get_role() == Role::Parent { + students.extend( + ParentLink::list_for_parent(user.get_id(), &st.db) + .await? + .iter() + .map(|link| link.get_student().clone()), + ); + } + let rows = MealBooking::list_for_students(&students, &st.db).await?; + let total = rows.len() as i64; + let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Who is eating: every booking on one menu, cancelled ones included so the +/// kitchen can see what changed. Requires manager+ — this is the whole school's +/// list, not one family's. Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/menus/{id}/bookings", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id"), PageParams), + responses( + (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "No such menu", body = ErrorResponse), + ), +)] +async fn list_menu_bookings( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let rows = MealBooking::list_for_menu(menu.get_id(), &st.db).await?; + let total = rows.len() as i64; + let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Give the seat back. The row survives, flipped to `cancelled` — the seat is +/// free for someone else, and the cancellation stays auditable. Only the +/// student it is for, or their parent, may cancel it. Refused (`409`) once the +/// school's `meal_cancel_cutoff_minutes` has closed the meal. +/// +/// **Idempotent**: cancelling an already-cancelled booking is a `200` with the +/// row as it stands, not a `409`. Repeating it also replays the refund, so a +/// cancel that was cut short mid-flight (the tab closed, a proxy timed out) is +/// recovered by simply sending it again — the reversal is keyed to the seat's +/// attempt, so the money comes back exactly once however often it is retried. +#[utoipa::path( + delete, + path = "/bookings/{bid}", + tag = "meals", + security(("session_cookie" = [])), + params(("bid" = String, Path, description = "Booking id")), + responses( + (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "The cutoff has passed", body = ErrorResponse), + ), +)] +async fn cancel_booking( + State(st): State, + CurrentUser(user): CurrentUser, + Path(bid): Path, +) -> Result, AppError> { + let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db) + .await? + .ok_or(AppError::NotFound)?; + // Same door as booking: whoever may take the seat may give it back. + let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?; + if &target != booking.get_student() { + return Err(AppError::Forbidden("not your booking")); + } + let cutoff = cutoff_minutes(&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 items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?; + Ok(Json( + items.into_iter().next().expect("one booking in, one out"), + )) +} + +// ---- attendance ----------------------------------------------------------- +// +// Reporting only: nothing in this section touches [`MealLedger`]. Booking is +// what charges, so a no-show still pays — the kitchen bought the food. + +#[derive(Deserialize, ToSchema)] +struct MarkMealAttendance { + /// Who was (or was not) served — usually a student, but the canteen also + /// feeds staff, so any existing user may be marked. The mark moves no money. + student_id: String, + /// `served` or `missed` — the canteen's own fixed pair, not the school's + /// editable roll-call statuses. + #[schema(example = "served")] + status: String, +} + +#[derive(Serialize, ToSchema)] +struct MealAttendanceResponse { + id: String, + /// The menu the mark is against. + menu_id: String, + student: PersonRef, + #[schema(example = "served")] + status: String, + marked_by: PersonRef, + marked_at: i64, +} + +impl MealAttendanceResponse { + fn new(row: &MealAttendance, people: &std::collections::HashMap) -> Self { + Self { + id: row.get_id().key().to_string(), + menu_id: row.get_menu().key().to_string(), + student: PersonRef::resolve(people, row.get_student()), + status: row.get_status().as_str().to_string(), + marked_by: PersonRef::resolve(people, row.get_marked_by()), + marked_at: row.get_marked_at().as_millis(), + } + } +} + +/// Join the people onto a page of marks — one query for the whole page. +async fn attendance_responses( + rows: &[MealAttendance], + db: &Database, +) -> Result, AppError> { + let people = person_map( + rows.iter() + .flat_map(|row| [row.get_student().clone(), row.get_marked_by().clone()]), + db, + ) + .await?; + Ok(rows + .iter() + .map(|row| MealAttendanceResponse::new(row, &people)) + .collect()) +} + +/// Record whether someone ate off a menu. Requires teacher+ — whoever stands +/// at the canteen door marks, students never mark themselves. One row per +/// (menu, person), so re-marking corrects the row rather than adding another. +/// +/// The target need only *exist*: a canteen also serves staff, and a walk-in +/// with no booking is still someone the kitchen fed. Marking is a record of +/// what happened, not a check of who was entitled — and since it moves no +/// money, a non-student mark costs nobody anything. +/// +/// **This moves no money.** A booked student who did not show is still charged +/// (the food was cooked), and a walk-in marked `served` without a booking is +/// not charged either — booking is the only charge trigger. +#[utoipa::path( + post, + path = "/menus/{id}/attendance", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id")), + request_body = MarkMealAttendance, + responses( + (status = 200, description = "Attendance recorded", body = MealAttendanceResponse), + (status = 400, description = "Invalid status, or no such user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such menu", body = ErrorResponse), + ), +)] +async fn mark_attendance( + State(st): State, + RequireTeacher(marker): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let status = MealAttendanceStatus::try_new(&req.status)?; + let student = UserId::from_key(&req.student_id); + // The target must exist; no booking is required, since a walk-in was still + // served and the record is operationally true. + if User::read(&student, &st.db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "student_id", + reason: "target user does not exist", + })); + } + let row = + MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?; + let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; + Ok(Json( + items.into_iter().next().expect("one mark in, one out"), + )) +} + +/// Who ate off one menu. Requires teacher+. Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/menus/{id}/attendance", + tag = "meals", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Menu id"), PageParams), + responses( + (status = 200, description = "A page of marks (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "No such menu", body = ErrorResponse), + ), +)] +async fn list_menu_attendance( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // Menu must exist — a missing menu is a 404, not an empty list. + let menu = Menu::read(&MenuId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let rows = MealAttendance::list_for_menu(menu.get_id(), &st.db).await?; + let total = rows.len() as i64; + let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// One student's meal-attendance history, newest mark first. Requires teacher+, +/// or a parent linked to them — the caller's own id always passes, like the +/// balance and ledger reads. Narrow to a date range with `?from=&to=` +/// (inclusive `YYYY-MM-DD` bounds on the menu's day). Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/attendance/{user}", + tag = "meals", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "Student id"), MenuRange, PageParams), + responses( + (status = 200, description = "A page of marks (all of them when unpaged)", body = Page), + (status = 400, description = "Malformed date bound, limit, or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + ), +)] +async fn user_attendance( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(user): Path, + Query(range): Query, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let target = UserId::from_key(&user); + ensure_can_read_student(&caller, &target, &st.db).await?; + let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; + let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; + let rows = + MealAttendance::list_for_student(&target, from.as_ref(), to.as_ref(), &st.db).await?; + let total = rows.len() as i64; + let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +// ---- money ---------------------------------------------------------------- + +#[derive(Serialize, ToSchema)] +struct BalanceResponse { + student: PersonRef, + /// `credits + reversals - charges`, in **minor units** (kuruş). Negative + /// means the student owes the school. Derived on every read, never stored. + #[schema(example = -4500)] + balance_minor: i64, +} + +#[derive(Serialize, ToSchema)] +struct LedgerResponse { + id: String, + student: PersonRef, + /// `charge`, `credit`, or `reversal`. + #[schema(example = "charge")] + kind: String, + /// Always positive — the sign is the `kind`'s business. + #[schema(example = 4500)] + amount_minor: i64, + /// What caused the line: a booking id on a `charge`, the reversed charge's + /// own id on a `reversal`, absent on a `credit`. + source: Option, + method: Option, + note: Option, + /// Who wrote it: the booker on a charge or reversal, the admin on a credit. + recorded_by: PersonRef, + created_at: i64, +} + +impl LedgerResponse { + fn new(line: &MealLedger, people: &std::collections::HashMap) -> Self { + Self { + id: line.get_id().key().to_string(), + student: PersonRef::resolve(people, line.get_student()), + kind: line.get_kind().as_str().to_string(), + amount_minor: line.get_amount_minor().as_minor(), + source: line.get_source_key().map(str::to_string), + method: line.get_method().map(|m| m.as_str().to_string()), + note: line.get_note().map(|n| n.as_str().to_string()), + recorded_by: PersonRef::resolve(people, line.get_recorded_by()), + created_at: line.get_created_at().as_millis(), + } + } +} + +/// Join the people onto a page of ledger lines — one query for the whole page. +async fn ledger_responses( + lines: &[MealLedger], + db: &Database, +) -> Result, AppError> { + let people = person_map( + lines + .iter() + .flat_map(|line| [line.get_student().clone(), line.get_recorded_by().clone()]), + db, + ) + .await?; + Ok(lines + .iter() + .map(|line| LedgerResponse::new(line, &people)) + .collect()) +} + +/// One student's balance, resolved to a response. Shared by both balance routes. +async fn balance_response( + student: &UserId, + db: &Database, +) -> Result, AppError> { + let people = person_map(std::iter::once(student.clone()), db).await?; + Ok(Json(BalanceResponse { + student: PersonRef::resolve(&people, student), + balance_minor: MealLedger::balance_of(student, db).await?, + })) +} + +/// Reading someone else's meal record — money, attendance, dietary profile: +/// teacher+, or a parent linked to the student. Reading your *own* is always +/// allowed, since every `{user}` route here accepts the caller's own id; that +/// is the one way this gate differs from [`super::ensure_can_observe`], which +/// 403s a self-read because its subjects have their own `/me` routes. +async fn ensure_can_read_student( + caller: &User, + target: &UserId, + db: &Database, +) -> Result<(), AppError> { + if caller.get_id() == target { + return Ok(()); + } + super::ensure_can_observe(caller, target, db).await +} + +/// What the caller owes or has on account. +#[utoipa::path( + get, + path = "/balance/me", + tag = "meals", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's meal balance", body = BalanceResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_balance( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + balance_response(user.get_id(), &st.db).await +} + +/// One student's meal balance. Requires teacher+, or a parent link to them — +/// the caller's own id always passes. +#[utoipa::path( + get, + path = "/balance/{user}", + tag = "meals", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "Student id")), + responses( + (status = 200, description = "The student's meal balance", body = BalanceResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + ), +)] +async fn user_balance( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(user): Path, +) -> Result, AppError> { + let target = UserId::from_key(&user); + ensure_can_read_student(&caller, &target, &st.db).await?; + balance_response(&target, &st.db).await +} + +/// One student's statement, newest line first: every charge, credit, and +/// reversal. Nothing here is ever edited or deleted — a correction is another +/// line. Same gate as the balance. Paged via `?limit=&offset=`. +#[utoipa::path( + get, + path = "/ledger/{user}", + tag = "meals", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "Student id"), PageParams), + responses( + (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), + ), +)] +async fn user_ledger( + State(st): State, + CurrentUser(caller): CurrentUser, + Path(user): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let target = UserId::from_key(&user); + ensure_can_read_student(&caller, &target, &st.db).await?; + let rows = MealLedger::list_for_student(&target, &st.db).await?; + let total = rows.len() as i64; + let items = ledger_responses(paginate(&rows, limit, offset), &st.db).await?; + Ok(Json(Page::new(items, total, limit, offset))) +} + +#[derive(Deserialize, ToSchema)] +struct RecordCredit { + /// The student the money is for. + student_id: String, + /// How much came in, **minor units** (kuruş), positive. + #[schema(minimum = 1, maximum = 10000000, example = 25000)] + amount_minor: i64, + /// How it arrived ("cash", "havale", …). Free text — the backend speaks to + /// no payment gateway and stores no card data. + #[schema(max_length = 50, example = "cash")] + method: Option, + #[schema(max_length = 500, example = "receipt 2026-114")] + note: Option, +} + +/// Record money received from a student. **Admin only** — not manager: writing +/// down cash is the highest-trust action in the app. Appends a `credit` line; +/// nothing in the ledger is ever edited or removed, so an over-credit is +/// corrected by a compensating line, not by a fix-up. +#[utoipa::path( + post, + path = "/credits", + tag = "meals", + security(("session_cookie" = [])), + request_body = RecordCredit, + responses( + (status = 201, description = "Credit recorded", body = LedgerResponse), + (status = 400, description = "Invalid amount, method, note, or a non-student target", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the admin role", body = ErrorResponse), + (status = 404, description = "No such user", body = ErrorResponse), + ), +)] +async fn record_credit( + State(st): State, + RequireAdmin(admin): RequireAdmin, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let student = UserId::from_key(&req.student_id); + // Only a student carries a meal balance; crediting anyone else is a typo, + // and a typo here is money in the wrong ledger. + if User::read(&student, &st.db) + .await? + .ok_or(AppError::NotFound)? + .get_role() + != Role::Student + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "student_id", + reason: "only a student carries a meal balance", + })); + } + let line = MealLedger::credit( + &student, + LedgerAmount::try_new(req.amount_minor)?, + req.method + .as_deref() + .map(LedgerMethod::try_new) + .transpose()? + .flatten(), + req.note + .as_deref() + .map(LedgerNote::try_new) + .transpose()? + .flatten(), + admin.get_id(), + &st.db, + ) + .await?; + let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?; + Ok(( + StatusCode::CREATED, + Json(items.into_iter().next().expect("one line in, one out")), + )) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 3584363..444e850 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -17,6 +17,7 @@ pub mod exams; pub mod homework; pub mod limits; pub mod marks; +pub mod meals; pub mod messages; pub mod notes; pub mod pomodoro; diff --git a/src/web/settings.rs b/src/web/settings.rs index 83fcfa3..88ddb50 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -7,12 +7,13 @@ use utoipa_axum::routes; use crate::constant::SETTINGS_UPDATE_RETRIES; use crate::domain::exam_result::ExamResult; -use crate::domain::settings::{ExamKindDef, GradeBand, Settings}; +use crate::domain::menu::{MENU_LOCK, Menu}; +use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; use super::exams::EXAM_LOCK; -use super::{CurrentUser, RequireManager}; +use super::{CurrentUser, RequireManager, set_or_clear}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new().routes(routes!(get_settings, update_settings)) @@ -31,6 +32,15 @@ struct ExamKindDto { weight: i64, } +/// One meal slot the school serves. A published menu snapshots this name, so +/// renaming or retiring a slot never rewrites a past menu. +#[derive(Serialize, Deserialize, ToSchema)] +struct MealSlotDto { + /// The `slot` value menus carry, 1–50 characters. + #[schema(example = "lunch", max_length = 50)] + name: String, +} + /// One grade-display band: marks at or above `min` (and below the next band's /// `min`) render as `label`. #[derive(Serialize, Deserialize, ToSchema)] @@ -74,6 +84,17 @@ 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: 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. + #[schema(example = 120)] + meal_cancel_cutoff_minutes: Option, } impl SettingsResponse { @@ -100,6 +121,15 @@ impl SettingsResponse { chatbot_history_turns: settings.get_chatbot_history_turns(), max_chatbot_threads: settings.get_max_chatbot_threads(), max_chatbot_message_len: settings.get_max_chatbot_message_len(), + meal_slots: settings + .get_meal_slots() + .iter() + .map(|slot| MealSlotDto { + name: slot.get_name().to_string(), + }) + .collect(), + dietary_tags: settings.get_dietary_tags(), + meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(), } } } @@ -135,6 +165,21 @@ struct UpdateSettings { /// server hard cap. #[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). + #[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 + /// no cutoff at all. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option, example = 120, minimum = 0, maximum = 10_080)] + meal_cancel_cutoff_minutes: Option>, } /// The school's current policy. Any authenticated user — clients need it to @@ -168,7 +213,9 @@ async fn get_settings( /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is /// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise /// applies at upload time only — already-stored files keep their size, and the -/// chatbot knobs apply to the next chat request only. +/// chatbot knobs apply to the next chat request only. `meal_slots` follows the +/// exam-kind rule: a slot a menu was already published for cannot be dropped +/// (409), because the menu snapshotted its name. #[utoipa::path( patch, path = "/", @@ -180,7 +227,7 @@ async fn get_settings( (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), - (status = 409, description = "A removed exam kind still has graded exams, or concurrent edits kept changing the settings mid-save", body = ErrorResponse), + (status = 409, description = "A removed exam kind still has graded exams, a removed meal slot still has published menus, or concurrent edits kept changing the settings mid-save", body = ErrorResponse), ), )] async fn update_settings( @@ -199,6 +246,14 @@ async fn update_settings( Some(_) => Some(EXAM_LOCK.write().await), None => None, }; + // Same shape for the slot list: the "was a menu ever published for it?" + // check and the save are one unit, so a publish cannot land on a slot that + // is being dropped mid-flight. Taken after EXAM_LOCK; nothing under + // MENU_LOCK ever takes EXAM_LOCK, so the pair cannot deadlock. + let _menu_guard = match req.meal_slots { + Some(_) => Some(MENU_LOCK.lock().await), + None => None, + }; for _ in 0..SETTINGS_UPDATE_RETRIES { let current = Settings::load(&st.db).await?; @@ -225,6 +280,29 @@ async fn update_settings( ))); } } + // Same shape for meal slots: a slot a menu was already published for + // cannot leave the list — the menu snapshotted the name as text, and a + // slot no longer offered would leave that menu unreachable from the + // school's own list. + let meal_slots = match &req.meal_slots { + Some(slots) => slots + .iter() + .map(|slot| MealSlotDef::try_new(&slot.name)) + .collect::, _>>()?, + None => current.get_meal_slots(), + }; + for gone in current.get_meal_slots().iter().filter(|slot| { + !meal_slots + .iter() + .any(|new| new.get_name() == slot.get_name()) + }) { + if Menu::any_for_slot(gone.get_name(), &st.db).await? { + return Err(AppError::ConflictOwned(format!( + "menus are already published for the '{}' slot — it cannot be removed", + gone.get_name() + ))); + } + } let attendance_statuses = req .attendance_statuses .clone() @@ -252,6 +330,15 @@ async fn update_settings( params.max_chatbot_message_len = req .max_chatbot_message_len .unwrap_or(params.max_chatbot_message_len); + params.meal_slots = meal_slots; + params.dietary_tags = req + .dietary_tags + .clone() + .unwrap_or_else(|| current.get_dietary_tags()); + // Double option: absent keeps the knob, `null` clears it (no cutoff). + params.meal_cancel_cutoff_minutes = req + .meal_cancel_cutoff_minutes + .unwrap_or(params.meal_cancel_cutoff_minutes); let settings = Settings::try_new(params)?; if let Some(saved) = settings.save_if_unchanged(¤t, &st.db).await? { diff --git a/tests/integration.rs b/tests/integration.rs index 34224e0..3ba051e 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10969,6 +10969,146 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() { ); } +/// The food-program knobs are `option<…>` columns, and every settings save +/// rewrites the whole row — so a PATCH that never mentions them must still +/// round-trip them. (A `DEFAULT []` column plus a struct that dropped the field +/// aborts the transaction with a coercion error instead.) +#[tokio::test] +async fn settings_round_trip_the_food_program_knobs() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "meal.manager", "manager").await; + + // Unset columns read as the built-in seeds; an absent cutoff is no cutoff. + let res = send(&app, "GET", "/settings", Some(&manager), None).await; + assert_eq!( + res.body["meal_slots"], + json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}]) + ); + assert_eq!( + res.body["dietary_tags"], + json!([ + "vegetarian", + "vegan", + "gluten_free", + "lactose_free", + "nut_allergy" + ]) + ); + assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null)); + + // A PATCH of an unrelated field still writes the whole row. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "max_file_bytes": 4096 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 3); + + // All three set at once; slot names arrive trimmed. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ + "meal_slots": [{"name": "lunch"}, {"name": " snack "}], + "dietary_tags": ["vegan"], + "meal_cancel_cutoff_minutes": 120, + })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!( + res.body["meal_slots"], + json!([{"name": "lunch"}, {"name": "snack"}]) + ); + assert_eq!(res.body["dietary_tags"], json!(["vegan"])); + assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120); + + // A later PATCH that omits them keeps them — now over a row that really + // carries the columns. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "chatbot_history_turns": 3 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2); + assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120); + + // `null` clears the cutoff (no cutoff at all); the lists stay. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "meal_cancel_cutoff_minutes": null })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null)); + assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2); + + // Bounds hold on the way in. + for body in [ + json!({ "meal_cancel_cutoff_minutes": 10_081 }), + json!({ "meal_cancel_cutoff_minutes": -1 }), + json!({ "meal_slots": [{"name": " "}] }), + json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }), + json!({ "dietary_tags": ["vegan", "VEGAN"] }), + ] { + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(body.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}"); + } + + // A published menu pins the slot it snapshotted: dropping it is a 409. + db.query( + "CREATE menu SET date = '2026-07-27', slot = 'lunch', + created_by = (SELECT VALUE id FROM user LIMIT 1)[0], created_at = 0", + ) + .await + .unwrap() + .check() + .unwrap(); + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "meal_slots": [{"name": "snack"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + // Keeping it is fine; an unused slot still leaves freely. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "meal_slots": [{"name": "lunch"}, {"name": "dinner"}] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!( + res.body["meal_slots"], + json!([{"name": "lunch"}, {"name": "dinner"}]) + ); +} + // --- question images --------------------------------------------------------- /// POST `bytes` as a multipart image upload to `path`; returns (status, json). @@ -20022,3 +20162,1988 @@ async fn exams_schedule_window_applies_after_visibility_and_drafts() { let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await; assert_eq!(res.status, StatusCode::BAD_REQUEST); } + +// --- meals: menus and dishes --------------------------------------------- + +/// The whole published side, end to end: publish, list, patch the cap, add and +/// edit and drop a dish, and the unique day+slot rule. +#[tokio::test] +async fn menus_and_dishes_round_trip() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "meal_mgr", "manager").await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 120 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let menu = id_of(&res.body); + assert_eq!(res.body["slot"], "lunch"); + assert_eq!(res.body["capacity"], 120); + assert_eq!(res.body["created_by"]["username"], "meal_mgr"); + + // A second menu for the same day and slot is the UNIQUE rule, as a 409 — + // never a 500 out of the index. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT); + + // Same day, another slot is a different meal and lands fine. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "breakfast" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + + // Dishes: money is minor units, tags come from the school's list. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ + "name": "Mercimek çorbası", + "description": " ", + "price_minor": 4550, + "tags": ["vegetarian", "vegetarian"], + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + let dish = id_of(&res.body); + assert_eq!(res.body["price_minor"], 4550); + // A whitespace-only description is the absence of one, and repeated tags + // collapse. + assert_eq!(res.body["description"], json!(null)); + assert_eq!(res.body["tags"], json!(["vegetarian"])); + + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "price_minor": 5000, "description": "günlük" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["price_minor"], 5000); + assert_eq!(res.body["description"], "günlük"); + assert_eq!(res.body["name"], "Mercimek çorbası"); + + // The menu read carries its dishes, and `null` clears the cap. + let res = send( + &app, + "PATCH", + &format!("/meals/menus/{menu}"), + Some(&mgr), + Some(json!({ "capacity": null })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["capacity"], json!(null)); + assert_eq!(res.body["dishes"].as_array().expect("dishes").len(), 1); + + // Any authenticated user reads; the range filter is inclusive. + let student = login(&app, "meal_student").await; + let res = send( + &app, + "GET", + "/meals/menus?from=2026-09-14&to=2026-09-14", + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(common::total(&res.body), 2); + let res = send( + &app, + "GET", + "/meals/menus?from=2026-09-15", + Some(&student), + None, + ) + .await; + assert_eq!(common::total(&res.body), 0); + + let res = send( + &app, + "DELETE", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.body["dishes"], json!([])); + + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND); +} + +/// Publishing is manager+, and both school-editable lists are enforced: a slot +/// nobody serves and a tag nobody defined are 400s, not stored strings. +#[tokio::test] +async fn menu_writes_are_manager_only_and_validate_against_settings() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "meal_mgr2", "manager").await; + let teacher = login_as(&app, &db, "meal_teacher", "teacher").await; + + let body = json!({ "date": "2026-09-15", "slot": "lunch" }); + let res = send( + &app, + "POST", + "/meals/menus", + Some(&teacher), + Some(body.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // A slot outside the school's `meal_slots` never reaches the column. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-15", "slot": "brunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // Neither does a malformed day. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-9-15", "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(body)).await; + assert_eq!(res.status, StatusCode::CREATED); + let menu = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&teacher), + Some(json!({ "name": "Pilav", "price_minor": 1000 })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + + // A tag outside the school's `dietary_tags` is a 400, on create... + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": 1000, "tags": ["halal"] })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + + // ...and on patch, and negative money never lands either. + 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); + let dish = id_of(&res.body); + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "tags": ["halal"] })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "price_minor": -1 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST); +} + +// --- meals: bookings ------------------------------------------------------ + +/// A seat, end to end: book, see it on both listings, cancel it (the row stays, +/// flipped), re-book the same seat, and the menu-delete guard in between. +#[tokio::test] +async fn meal_bookings_round_trip() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "booking_mgr", "manager").await; + let ali = login(&app, "booking_ali").await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })), + ) + .await; + 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, "{}", res.body); + let booking = id_of(&res.body); + assert_eq!(res.body["status"], "booked"); + assert_eq!(res.body["student"]["username"], "booking_ali"); + assert_eq!(res.body["booked_by"]["username"], "booking_ali"); + assert_eq!(res.body["cancelled_at"], json!(null)); + + // Booking twice is the same seat, not a second one — the composite id. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(id_of(&res.body), booking); + + let res = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(common::total(&res.body), 1); + assert_eq!(res.body["items"][0]["id"], json!(booking)); + + // The kitchen's list is manager+; nobody else's `/me` shows the seat. + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/bookings"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1); + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send(&app, "GET", "/meals/bookings/me", Some(&mgr), None).await; + assert_eq!(common::total(&res.body), 0); + + // A menu somebody still holds a seat on cannot be unpublished. + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // Cancelling flips the row, it never deletes it. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled"); + let stamp = res.body["cancelled_at"].as_i64().expect("stamped"); + assert!(stamp > 0); + // Cancelling again is idempotent — a `200` with the row as it stands, so a + // cancel interrupted before its refund can be recovered by repeating it. + // The stamp is not re-written: the seat was freed once. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled"); + assert_eq!(res.body["cancelled_at"], stamp); + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/bookings"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "the cancelled row survives"); + + // Re-booking is the same row flipped back — one seat, never two. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(id_of(&res.body), booking); + assert_eq!(res.body["status"], "booked"); + assert_eq!(res.body["cancelled_at"], json!(null)); + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/bookings"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1); + + // Cancelled, the menu is free to go. + send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + let res = send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::NO_CONTENT); +} + +/// The cap refuses the seat that would overflow it, and a cancel genuinely +/// gives that seat back. +#[tokio::test] +async fn meal_booking_capacity_caps_and_a_cancel_frees_a_seat() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "cap_mgr", "manager").await; + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })), + ) + .await; + let menu = id_of(&res.body); + + let students: Vec = { + let mut cookies = Vec::new(); + for i in 0..3 { + cookies.push(login(&app, &format!("cap_student{i}")).await); + } + cookies + }; + let book = |who: String| { + let app = app.clone(); + let menu = menu.clone(); + async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&who), + Some(json!({})), + ) + .await + } + }; + + let first = book(students[0].clone()).await; + assert_eq!(first.status, StatusCode::CREATED); + assert_eq!(book(students[1].clone()).await.status, StatusCode::CREATED); + assert_eq!(book(students[2].clone()).await.status, StatusCode::CONFLICT); + + // Cancelling frees the seat — a cancelled row must not count. + let booking = id_of(&first.body); + send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&students[0]), + None, + ) + .await; + assert_eq!(book(students[2].clone()).await.status, StatusCode::CREATED); + // …and the freed seat is gone again, so the first student cannot return. + assert_eq!(book(students[0].clone()).await.status, StatusCode::CONFLICT); +} + +/// The cap is a count-then-write pair, which SurrealDB does not serialize: +/// under a stampede it must still admit exactly `capacity` seats, and the +/// losers must get a 409 rather than a 500. Mirrors +/// `concurrent_duplicate_registrations_conflict_not_500`. +#[tokio::test] +async fn concurrent_meal_bookings_never_exceed_the_capacity() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "race_mgr", "manager").await; + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 3 })), + ) + .await; + let menu = id_of(&res.body); + + let mut students = Vec::new(); + for i in 0..24 { + students.push(login(&app, &format!("race_student{i}")).await); + } + + let mut handles = Vec::new(); + for cookie in students { + let app = app.clone(); + let menu = menu.clone(); + handles.push(tokio::spawn(async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&cookie), + Some(json!({})), + ) + .await + .status + })); + } + + let mut booked = 0; + for h in handles { + let status = h.await.unwrap(); + assert!( + status == StatusCode::CREATED || status == StatusCode::CONFLICT, + "a lost race must be a 409, never a 500: {status}" + ); + booked += i32::from(status == StatusCode::CREATED); + } + assert_eq!(booked, 3, "exactly the capacity was admitted"); + + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}/bookings"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 3, "and only three rows exist"); +} + +/// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes` +/// neither a new booking nor a cancellation lands. +#[tokio::test] +async fn meal_cutoff_closes_booking_and_cancelling_alike() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "cutoff_mgr", "manager").await; + let ali = login(&app, "cutoff_ali").await; + + // No cutoff configured yet, so a menu whose day is long gone still books. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2020-01-06", "slot": "lunch" })), + ) + .await; + 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, "{}", res.body); + let booking = id_of(&res.body); + + let res = send( + &app, + "PATCH", + "/settings", + Some(&mgr), + Some(json!({ "meal_cancel_cutoff_minutes": 60 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Both ends now refuse: the meal is settled. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + let veli = login(&app, "cutoff_veli").await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&veli), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + + // A meal far enough ahead is untouched by the same cutoff. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2099-01-06", "slot": "lunch" })), + ) + .await; + let later = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{later}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", 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] +async fn meal_bookings_are_student_or_linked_parent_only() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "boss", "admin").await; + let mgr = login_as(&app, &db, "kin_mgr", "manager").await; + let teacher = login_as(&app, &db, "kin_teacher", "teacher").await; + let mom = login_as(&app, &db, "kin_mom", "parent").await; + let mom_id = me_id(&app, &mom).await; + let ali = login(&app, "kin_ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "kin_veli").await; + let veli_id = me_id(&app, &veli).await; + + let res = send( + &app, + "POST", + &format!("/users/{mom_id}/students"), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + let path = format!("/meals/menus/{menu}/bookings"); + + // The parent books for their own child. + let res = send( + &app, + "POST", + &path, + Some(&mom), + Some(json!({ "student_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["student"]["username"], "kin_ali"); + assert_eq!(res.body["booked_by"]["username"], "kin_mom"); + let booking = id_of(&res.body); + // …and sees it on their own list, though the seat is not theirs. + let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; + assert_eq!(common::total(&res.body), 1); + + // Never for someone else's child, and never without naming one. + let res = send( + &app, + "POST", + &path, + Some(&mom), + Some(json!({ "student_id": veli_id })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send(&app, "POST", &path, Some(&mom), Some(json!({}))).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // Staff do not order for children through this route. + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + &path, + Some(&mgr), + Some(json!({ "student_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // A student books only for themselves, and cancels only their own. + let res = send( + &app, + "POST", + &path, + Some(&veli), + Some(json!({ "student_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // The linked parent may give the seat back. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled"); +} + +// --- meals: the ledger ---------------------------------------------------- + +/// The money, end to end: booking charges the menu's price *snapshot*, editing +/// a dish afterwards never moves that charge, cancelling appends a reversal +/// (leaving the charge standing — the append-only proof), and re-booking bills +/// the new price. +#[tokio::test] +async fn meal_booking_charges_a_price_snapshot_and_a_cancel_reverses_it() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "money_mgr", "manager").await; + let ali = login(&app, "money_ali").await; + let ali_id = me_id(&app, &ali).await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Çorba", "price_minor": 4_500 })), + ) + .await; + let dish = id_of(&res.body); + send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": 2_000 })), + ) + .await; + + // A fresh student owes nothing. + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["balance_minor"], 0); + + // Booking charges the sum of the dishes — negative means "owes". + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], -6_500); + + // Booking again is the same seat, so it must not bill twice. + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], -6_500, "one seat, one charge"); + + // A price edit is not retroactive: what the student owes is what the menu + // cost the day they booked. + let res = send( + &app, + "PATCH", + &format!("/meals/dishes/{dish}"), + Some(&mgr), + Some(json!({ "price_minor": 9_900 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], -6_500, "the snapshot is frozen"); + + // Cancelling appends a reversal; the charge row stays right where it was. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], 0); + + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 2, "both lines survive the cancel"); + let lines = res.body["items"].as_array().unwrap().clone(); + // Newest first: the reversal, then the charge it points at. + assert_eq!(lines[0]["kind"], "reversal"); + assert_eq!(lines[0]["amount_minor"], 6_500); + assert_eq!(lines[1]["kind"], "charge"); + assert_eq!(lines[1]["amount_minor"], 6_500); + assert_eq!(lines[1]["source"], json!(booking)); + assert_eq!(lines[0]["source"], lines[1]["id"]); + + // Re-booking is a fresh charge, at the *new* price. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], -11_900); + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 3); +} + +/// Recording cash is admin-only — a manager runs the kitchen, not the till. +#[tokio::test] +async fn meal_credits_are_admin_only_and_raise_the_balance() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "till_admin", "admin").await; + let mgr = login_as(&app, &db, "till_mgr", "manager").await; + let ali = login(&app, "till_ali").await; + let ali_id = me_id(&app, &ali).await; + + let body = json!({ "student_id": ali_id, "amount_minor": 25_000, "method": "cash" }); + let res = send( + &app, + "POST", + "/meals/credits", + Some(&mgr), + Some(body.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + "/meals/credits", + Some(&ali), + Some(body.clone()), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(body)).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + assert_eq!(res.body["kind"], "credit"); + assert_eq!(res.body["amount_minor"], 25_000); + assert_eq!(res.body["method"], "cash"); + assert_eq!(res.body["note"], json!(null)); + assert_eq!(res.body["source"], json!(null)); + assert_eq!(res.body["recorded_by"]["username"], "till_admin"); + + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], 25_000); + + // The amount is bounded and positive; the target must be a student. + for bad in [ + json!({ "student_id": ali_id, "amount_minor": 0 }), + json!({ "student_id": ali_id, "amount_minor": -100 }), + json!({ "student_id": ali_id, "amount_minor": 10_000_001 }), + ] { + let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(bad)).await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + } + let mgr_id = me_id(&app, &mgr).await; + let res = send( + &app, + "POST", + "/meals/credits", + Some(&admin), + Some(json!({ "student_id": mgr_id, "amount_minor": 100 })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + // …and the failed writes left the balance exactly where it was. + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], 25_000); +} + +/// Whose money a caller may read: their own, their linked child's, or — as +/// teacher+ — anyone's. Never another family's. +#[tokio::test] +async fn meal_balance_reads_follow_the_observer_gate() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "wallet_boss", "admin").await; + let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await; + let mom = login_as(&app, &db, "wallet_mom", "parent").await; + let mom_id = me_id(&app, &mom).await; + let ali = login(&app, "wallet_ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "wallet_veli").await; + let veli_id = me_id(&app, &veli).await; + + let res = send( + &app, + "POST", + &format!("/users/{mom_id}/students"), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The linked parent reads their child's balance and statement. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["student"]["username"], "wallet_ali"); + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Someone else's child is a 403, on both routes. + for path in [ + format!("/meals/balance/{veli_id}"), + format!("/meals/ledger/{veli_id}"), + ] { + let res = send(&app, "GET", &path, Some(&mom), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + } + + // A student reads their own money, never a classmate's. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // Teacher+ reads any student's. + let res = send( + &app, + "GET", + &format!("/meals/balance/{ali_id}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} + +// --- meals: attendance ---------------------------------------------------- + +/// Marking who ate is reporting, never billing: a booked no-show still owes the +/// full price, and a walk-in served without a booking owes nothing. Also covers +/// the composite id (re-marking flips the row) and the teacher+ gate. +#[tokio::test] +async fn meal_attendance_never_moves_money() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "ate_mgr", "manager").await; + let teacher = login_as(&app, &db, "ate_teacher", "teacher").await; + let ali = login(&app, "ate_ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "ate_veli").await; + let veli_id = me_id(&app, &veli).await; + + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Çorba", "price_minor": 4_500 })), + ) + .await; + + // Ali books (and is charged); Veli never books. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&ali), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!(res.body["balance_minor"], -4_500); + + let path = format!("/meals/menus/{menu}/attendance"); + + // Served shows up on the menu's list. + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let mark = id_of(&res.body); + assert_eq!(res.body["status"], "served"); + assert_eq!(res.body["student"]["username"], "ate_ali"); + assert_eq!(res.body["marked_by"]["username"], "ate_teacher"); + assert_eq!(res.body["menu_id"], json!(menu)); + let res = send(&app, "GET", &path, Some(&teacher), None).await; + assert_eq!(common::total(&res.body), 1); + assert_eq!(res.body["items"][0]["id"], json!(mark)); + + // Re-marking the same student flips the row — one row per (menu, student). + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "missed" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(id_of(&res.body), mark); + assert_eq!(res.body["status"], "missed"); + let res = send(&app, "GET", &path, Some(&teacher), None).await; + assert_eq!( + common::total(&res.body), + 1, + "the mark was flipped, not doubled" + ); + + // THE BILLING-ISOLATION PROOF: the no-show still owes the whole price, and + // his statement grew no reversal line. The kitchen bought the food. + let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await; + assert_eq!( + res.body["balance_minor"], -4_500, + "attendance must never move money" + ); + let res = send( + &app, + "GET", + &format!("/meals/ledger/{ali_id}"), + Some(&mgr), + None, + ) + .await; + assert_eq!(common::total(&res.body), 1, "only the booking's charge"); + assert_eq!(res.body["items"][0]["kind"], "charge"); + + // A walk-in with no booking is recordable — and still not charged. + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": veli_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&veli), None).await; + assert_eq!(res.body["balance_minor"], 0, "a walk-in is never billed"); + + // Students never mark, not even themselves, and never read the list. + let res = send( + &app, + "POST", + &path, + Some(&ali), + Some(json!({ "student_id": ali_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send(&app, "GET", &path, Some(&ali), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // Bad inputs: a roll-call status is not a canteen status, and the menu and + // the student both have to exist. + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "excused" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + let res = send( + &app, + "POST", + &path, + Some(&teacher), + Some(json!({ "student_id": "nobody", "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + let res = send( + &app, + "POST", + "/meals/menus/missing/attendance", + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body); +} + +/// The per-student report: a lexical `?from=&to=` window over the menu's day, +/// readable by teacher+ or a linked parent and by nobody else. +#[tokio::test] +async fn meal_attendance_report_is_ranged_and_gated() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "ate_boss", "admin").await; + let mgr = login_as(&app, &db, "range_mgr", "manager").await; + let teacher = login_as(&app, &db, "range_teacher", "teacher").await; + let mom = login_as(&app, &db, "range_mom", "parent").await; + let mom_id = me_id(&app, &mom).await; + let ali = login(&app, "range_ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "range_veli").await; + let veli_id = me_id(&app, &veli).await; + + let res = send( + &app, + "POST", + &format!("/users/{mom_id}/students"), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Three days, one mark each for Ali. + for date in ["2026-09-01", "2026-09-15", "2026-09-30"] { + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": date, "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/attendance"), + Some(&teacher), + Some(json!({ "student_id": ali_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + } + + // Unbounded, then each bound, then both — the window is the menu's day. + for (query, expected) in [ + ("", 3), + ("?from=2026-09-15", 2), + ("?to=2026-09-15", 2), + ("?from=2026-09-10&to=2026-09-20", 1), + ("?from=2026-10-01", 0), + ] { + let res = send( + &app, + "GET", + &format!("/meals/attendance/{ali_id}{query}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), expected, "range {query}"); + } + + // A malformed bound is a 400, never a silently ignored filter. + let res = send( + &app, + "GET", + &format!("/meals/attendance/{ali_id}?from=2026-9-1"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // The linked parent reads her child's report; another child's is a 403, + // and a classmate never reads it at all. + let res = send( + &app, + "GET", + &format!("/meals/attendance/{ali_id}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 3); + let res = send( + &app, + "GET", + &format!("/meals/attendance/{veli_id}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/attendance/{ali_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); +} + +/// The dietary profile and the `conflicts` it produces on a menu read: the +/// school writes it, everyone in the reading gate sees it, and the overlap is +/// computed against the *caller's* own tags. +#[tokio::test] +async fn dietary_profile_drives_menu_conflicts() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "diet_boss", "admin").await; + let mgr = login_as(&app, &db, "diet_mgr", "manager").await; + let teacher = login_as(&app, &db, "diet_teacher", "teacher").await; + let mom = login_as(&app, &db, "diet_mom", "parent").await; + let mom_id = me_id(&app, &mom).await; + let other_mom = login_as(&app, &db, "diet_aunt", "parent").await; + let ali = login(&app, "diet_ali").await; + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "diet_veli").await; + let veli_id = me_id(&app, &veli).await; + + let res = send( + &app, + "POST", + &format!("/users/{mom_id}/students"), + Some(&admin), + Some(json!({ "user_id": ali_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // No profile yet: empty, never a 404. + let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["tags"], json!([])); + assert_eq!(res.body["note"], json!(null)); + assert_eq!(res.body["updated_at"], json!(null)); + + // A student does not write their own allergen list, and neither does a + // teacher — this is a manager+ safety record. + for actor in [&ali, &teacher] { + let res = send( + &app, + "PATCH", + &format!("/meals/profiles/{ali_id}"), + Some(actor), + Some(json!({ "tags": ["nut_allergy"] })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + } + + // A tag outside the school's list is a 400, never a stored string. + let res = send( + &app, + "PATCH", + &format!("/meals/profiles/{ali_id}"), + Some(&mgr), + Some(json!({ "tags": ["halal"] })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + let res = send( + &app, + "PATCH", + &format!("/meals/profiles/{ali_id}"), + Some(&mgr), + Some(json!({ "tags": ["nut_allergy", "nut_allergy"], "note": " EpiPen " })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["tags"], json!(["nut_allergy"])); + assert_eq!(res.body["note"], "EpiPen"); + assert_eq!(res.body["updated_by"]["username"], "diet_mgr"); + + // The student reads it back at `/me`; a second PATCH edits the same row. + let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["tags"], json!(["nut_allergy"])); + assert_eq!(res.body["student"]["username"], "diet_ali"); + + let res = send( + &app, + "PATCH", + &format!("/meals/profiles/{ali_id}"), + Some(&mgr), + Some(json!({ "note": null })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["note"], json!(null)); + assert_eq!(res.body["tags"], json!(["nut_allergy"]), "tags kept"); + + // The linked parent reads her child's; an unlinked one does not. + let res = send( + &app, + "GET", + &format!("/meals/profiles/{ali_id}"), + Some(&mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["tags"], json!(["nut_allergy"])); + let res = send( + &app, + "GET", + &format!("/meals/profiles/{ali_id}"), + Some(&other_mom), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // A profile is a student's thing — a teacher never carries one. + let teacher_id = me_id(&app, &teacher).await; + let res = send( + &app, + "PATCH", + &format!("/meals/profiles/{teacher_id}"), + Some(&mgr), + Some(json!({ "tags": ["vegan"] })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // One menu, two dishes: one Ali must avoid, one he must not. + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-10-05", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + for (name, tags) in [ + ("Fıstıklı baklava", json!(["nut_allergy", "vegetarian"])), + ("Pilav", json!(["vegan"])), + ] { + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": name, "price_minor": 1000, "tags": tags })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + + // Ali sees his own conflict on the one dish, and nothing on the other. + for path in [format!("/meals/menus/{menu}"), "/meals/menus".to_string()] { + let res = send(&app, "GET", &path, Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let menu_body = if path == "/meals/menus" { + res.body["items"][0].clone() + } else { + res.body.clone() + }; + assert_eq!( + menu_body["dishes"][0]["conflicts"], + json!(["nut_allergy"]), + "{path}: the tag Ali holds, and only it" + ); + assert_eq!(menu_body["dishes"][1]["conflicts"], json!([]), "{path}"); + } + + // A student with no profile, and a manager (who never has one), both read + // empty conflicts — that is correct, not a bug. + for actor in [&veli, &mgr] { + let res = send( + &app, + "GET", + &format!("/meals/menus/{menu}"), + Some(actor), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["dishes"][0]["conflicts"], json!([])); + assert_eq!(res.body["dishes"][1]["conflicts"], json!([])); + } + + // Cleanup 1: a student reads their OWN meal-attendance history, like they + // already read their own balance and statement. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/attendance"), + Some(&teacher), + Some(json!({ "student_id": veli_id, "status": "served" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "GET", + &format!("/meals/attendance/{veli_id}"), + Some(&veli), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::total(&res.body), 1); +} + +// --- meals: money under concurrency and stale grants ---------------------- + +/// Publish a lunch menu carrying one dish at `price`; returns (menu id, +/// student cookie). Every money-race test below needs the same three rows. +async fn priced_menu(tag: &str, price: i64) -> (axum::Router, String, String) { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, &format!("{tag}_mgr"), "manager").await; + let stu = login(&app, &format!("{tag}_stu")).await; + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "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}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": price })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + (app, menu, stu) +} + +/// The sequential "booking twice bills once" test cannot see this: idempotence +/// that rests on a "is there already a charge?" scan is no idempotence at all, +/// since eight simultaneous POSTs of one seat all read "not yet" and all +/// append. One seat must mean one charge, so the ledger line is keyed by +/// (booking, attempt) and written under the same lock as the seat. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn concurrent_bookings_of_one_seat_bill_it_once() { + let (app, menu, stu) = priced_menu("race", 5_000).await; + + let mut tasks = Vec::new(); + for _ in 0..8 { + let app = app.clone(); + let stu = stu.clone(); + let menu = menu.clone(); + tasks.push(tokio::spawn(async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await + })); + } + for task in tasks { + let res = task.await.unwrap(); + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + } + + let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; + assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!( + res.body["balance_minor"], -5_000, + "one seat, one charge: {}", + res.body + ); +} + +/// A repeat POST racing the cancel. A cancel that reverses whatever charge it +/// can find, off a booking row read before the lock, can flip the seat to +/// `cancelled` while the charge of a newer attempt stands — the student owes +/// for a seat they do not hold. Keying the reversal to the attempt, and +/// re-reading the row inside the lock, is what closes it. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn a_cancelled_seat_never_keeps_its_charge() { + let (app, menu, stu) = priced_menu("race2", 3_000).await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + let booking = id_of(&res.body); + + for round in 0..20 { + let book = { + let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone()); + tokio::spawn(async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await + }) + }; + let cancel = { + let (app, stu, booking) = (app.clone(), stu.clone(), booking.clone()); + tokio::spawn(async move { + send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&stu), + None, + ) + .await + }) + }; + book.await.unwrap(); + cancel.await.unwrap(); + // Settle the seat into `cancelled`, then the money must be back. + send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&stu), + None, + ) + .await; + let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; + assert_eq!( + common::items(&res.body)[0]["status"], + "cancelled", + "round {round}: {}", + res.body + ); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!( + res.body["balance_minor"], 0, + "round {round}: a cancelled seat still owes: {}", + res.body + ); + } +} + +/// "Was free" is a recorded fact, not the absence of a charge. A seat taken +/// off a dishless menu writes no ledger line; if that were all the code knew, +/// a dish added afterwards would make the next POST of the *same held seat* +/// look unbilled and charge it — a price the student never agreed to. +#[tokio::test] +async fn a_repeat_post_never_bills_a_seat_that_was_free_when_taken() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "free_mgr", "manager").await; + let stu = login(&app, "free_stu").await; + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2026-09-14", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + + // The seat is taken while the menu carries no dishes at all. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!(res.body["balance_minor"], 0, "a free menu bills nothing"); + + // The kitchen prices the menu afterwards. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": 9_000 })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + // A refresh re-POSTs the seat the student already holds. + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!( + res.body["balance_minor"], 0, + "a repeat POST on a held seat moves no money: {}", + res.body + ); + + // Cancelling and taking the seat again *is* a fresh attempt, at the price + // the menu carries now — that is the same rule, not an exception to it. + let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await; + let booking = common::items(&res.body)[0]["id"] + .as_str() + .unwrap() + .to_string(); + send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&stu), + None, + ) + .await; + send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!(res.body["balance_minor"], -9_000, "{}", res.body); +} + +/// A revoked parent link must go inert everywhere, `booked_by` included: the +/// seats a parent paid for stay visible while the link lives, and vanish with +/// it. The leak this catches was a *live* one — the unlinked parent kept +/// watching the child's row, seeing a cancellation made after the unlink. +#[tokio::test] +async fn an_unlinked_parent_loses_the_live_view_of_a_childs_bookings() { + let (app, db) = app_and_db().await; + let admin = login_as(&app, &db, "lv_boss", "admin").await; + let mgr = login_as(&app, &db, "lv_mgr", "manager").await; + let mom = login_as(&app, &db, "lv_mom", "parent").await; + let mom_id = me_id(&app, &mom).await; + let kid = login(&app, "lv_kid").await; + let kid_id = me_id(&app, &kid).await; + let res = send( + &app, + "POST", + &format!("/users/{mom_id}/students"), + Some(&admin), + Some(json!({ "user_id": kid_id })), + ) + .await; + assert!(res.status.is_success(), "link: {}", res.body); + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": "2027-08-01", "slot": "lunch" })), + ) + .await; + let menu = id_of(&res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&mom), + Some(json!({ "student_id": kid_id })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + + // While the link lives, mom sees the seat she booked. + let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; + assert_eq!(common::total(&res.body), 1, "{}", res.body); + + let res = send( + &app, + "DELETE", + &format!("/users/{mom_id}/students/{kid_id}"), + Some(&admin), + None, + ) + .await; + assert!(res.status.is_success(), "unlink: {}", res.body); + + // The kid cancels *after* the link is gone — mom must not see that. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&kid), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await; + assert_eq!( + common::total(&res.body), + 0, + "an unlinked parent still reads the child's seat: {}", + res.body + ); + // The child's own view is untouched. + let res = send(&app, "GET", "/meals/bookings/me", Some(&kid), None).await; + assert_eq!(common::total(&res.body), 1, "{}", res.body); +} + +/// A cancel is two writes — the status flip, then the reversal — and axum drops +/// the handler future when the client goes away (tab closed, proxy timeout). A +/// drop landing between them freed the seat and left the charge standing, and +/// while an already-cancelled row was a `409` **no route on the API could ever +/// append the missing reversal**: the student stayed billed for a meal they had +/// given back, and re-booking billed them a second time. So the cancel is +/// idempotent — repeating it replays the reversal, keyed by (seat, attempt), so +/// it heals the gap exactly once. +#[tokio::test] +async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() { + let (app, menu, stu) = priced_menu("cutshort", 3_000).await; + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let booking = id_of(&res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!(res.body["balance_minor"], -3_000, "{}", res.body); + + // The DELETE, polled just far enough to flip the row, then dropped. + let req = Request::builder() + .method("DELETE") + .uri(format!("/meals/bookings/{booking}")) + .header("cookie", &stu) + .body(Body::empty()) + .unwrap(); + let mut fut = Box::pin(app.clone().oneshot(req)); + for _ in 0..7 { + assert!( + futures_util::poll!(fut.as_mut()).is_pending(), + "the cancel finished before it could be interrupted" + ); + tokio::task::yield_now().await; + } + drop(fut); + + // Repeating the cancel is the documented recovery: a `200`, not a `409`. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&stu), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["status"], "cancelled", "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!( + res.body["balance_minor"], 0, + "still billed for a cancelled seat: {}", + res.body + ); + + // And a third cancel refunds nothing extra — the reversal is keyed, not + // counted — while a re-book is one fresh charge, not a doubled one. + let res = send( + &app, + "DELETE", + &format!("/meals/bookings/{booking}"), + Some(&stu), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!(res.body["balance_minor"], 0, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/meals/menus/{menu}/bookings"), + Some(&stu), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await; + assert_eq!( + res.body["balance_minor"], -3_000, + "one meal, one charge: {}", + res.body + ); +} + +/// A dish must never land on a menu that is already gone. `add_dish` reading +/// the menu *before* `MENU_LOCK` left a window: `DELETE /menus/{id}` ran its +/// cascade in the gap, the create landed after it, and the row survived +/// pointing at a menu the API 404s. Unreachable, but real orphaned data — so +/// the read moved inside the lock, the way `MealBooking::book` does it. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn a_dish_never_lands_on_a_deleted_menu() { + let (app, db) = app_and_db().await; + let mgr = login_as(&app, &db, "orphan_mgr", "manager").await; + for round in 0..40 { + let res = send( + &app, + "POST", + "/meals/menus", + Some(&mgr), + Some(json!({ "date": format!("2027-10-{:02}", round % 28 + 1), "slot": "lunch" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let menu = id_of(&res.body); + + let add = { + let (app, menu, mgr) = (app.clone(), menu.clone(), mgr.clone()); + tokio::spawn(async move { + send( + &app, + "POST", + &format!("/meals/menus/{menu}/dishes"), + Some(&mgr), + Some(json!({ "name": "Pilav", "price_minor": 1 })), + ) + .await + }) + }; + let remove = { + let (app, menu, mgr) = (app.clone(), menu.clone(), mgr.clone()); + tokio::spawn(async move { + send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await + }) + }; + add.await.unwrap(); + remove.await.unwrap(); + + let gone = send( + &app, + "GET", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await + .status + == StatusCode::NOT_FOUND; + if gone { + let mut res = db + .query("SELECT VALUE id FROM menu_dish WHERE menu = $menu") + .bind(( + "menu", + surrealdb::types::RecordId::new("menu", menu.clone()), + )) + .await + .unwrap(); + let left: Vec = res.take(0).unwrap(); + assert!( + left.is_empty(), + "round {round}: a dish outlived its menu: {left:?}" + ); + } + send( + &app, + "DELETE", + &format!("/meals/menus/{menu}"), + Some(&mgr), + None, + ) + .await; + } +} diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 346176f..2c6347d 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -78,6 +78,14 @@ const EXCLUDED: &[(&str, &str)] = &[ "DEFAULT_EXAM_KINDS", "settings seed; the live list is on GET /settings", ), + ( + "DEFAULT_MEAL_SLOTS", + "settings seed; the live list is on GET /settings", + ), + ( + "DEFAULT_DIETARY_TAGS", + "settings seed; the live list is on GET /settings", + ), // Schema and query text. `constant.rs` is the single home for every // constant, so the migration batches live there too — a client never sees // a byte of SurrealQL. diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index 392f76c..b971967 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -571,6 +571,92 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { "maximum", MAX_MAX_CHATBOT_MESSAGE_LEN, ), + // --- food program (the school-editable lists live in /settings) --- + ( + "MealSlotDto", + "name", + "maxLength", + MAX_SETTINGS_ITEM_LEN as i64, + ), + ( + "UpdateSettings", + "meal_slots", + "maxItems", + MAX_SETTINGS_LIST_LEN as i64, + ), + ( + "UpdateSettings", + "dietary_tags", + "maxItems", + MAX_SETTINGS_LIST_LEN as i64, + ), + ("UpdateSettings", "meal_cancel_cutoff_minutes", "minimum", 0), + ( + "UpdateSettings", + "meal_cancel_cutoff_minutes", + "maximum", + MAX_MEAL_CANCEL_CUTOFF_MINUTES, + ), + // --- menus and dishes --- + // `date` is a fixed-width `YYYY-MM-DD`, so both length bounds are 10 — + // the shape itself, not a constant anyone could tune. + ("CreateMenu", "date", "minLength", 10), + ("CreateMenu", "date", "maxLength", 10), + ("CreateMenu", "capacity", "minimum", 0), + ("CreateMenu", "capacity", "maximum", MAX_MENU_CAPACITY), + ("UpdateMenu", "capacity", "minimum", 0), + ("UpdateMenu", "capacity", "maximum", MAX_MENU_CAPACITY), + ("CreateDish", "price_minor", "minimum", 0), + ("UpdateDish", "price_minor", "minimum", 0), + ("CreateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64), + ("UpdateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64), + ( + "CreateDish", + "description", + "maxLength", + MAX_DISH_DESCRIPTION_LEN as i64, + ), + ( + "UpdateDish", + "description", + "maxLength", + MAX_DISH_DESCRIPTION_LEN as i64, + ), + ("CreateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR), + ("UpdateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR), + ("CreateDish", "tags", "maxItems", MAX_DISH_TAGS as i64), + ("UpdateDish", "tags", "maxItems", MAX_DISH_TAGS as i64), + ( + "UpdateDietaryProfile", + "tags", + "maxItems", + MAX_DIETARY_TAGS as i64, + ), + ( + "UpdateDietaryProfile", + "note", + "maxLength", + MAX_DIETARY_NOTE_LEN as i64, + ), + ("RecordCredit", "amount_minor", "minimum", 1), + ( + "RecordCredit", + "amount_minor", + "maximum", + MAX_LEDGER_AMOUNT_MINOR, + ), + ( + "RecordCredit", + "method", + "maxLength", + MAX_LEDGER_METHOD_LEN as i64, + ), + ( + "RecordCredit", + "note", + "maxLength", + MAX_LEDGER_NOTE_LEN as i64, + ), ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64), ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64), (