forge
Explore
Log in

Don't you dare go Hollow

🍽️ run the canteen: menus, seats, allergens and a ledger

Browse files at this commit

fd5cfd118c24a3d8b204119b169cb841fff74b68Ahmet Kaan GümüşParent: 78b25b5
  • feat
    • 🍽️ run the canteen: menus, seats, allergens and a ledger
Show full message
feat: 🍽️ run the canteen: menus, seats, allergens and a ledger

Published menu calendar (manager+ authors, everyone reads), per-student
dietary profiles that mark conflicting dishes, meal booking with an
optional per-menu capacity, meal attendance, and booking-triggered
billing.

Booking is the charge trigger: reserving a seat stamps a charge at a
price snapshot, so later dish edits never rewrite what a student owes.
No-show still pays, because the kitchen already bought the food, which
is why attendance has no billing effect at all. Money enters only as
admin-recorded credit entries; there is no gateway and no card data.

The ledger is append-only. Cancelling appends a reversal rather than
deleting the charge, balance is always folded from the rows, and the
sign lives in exactly one function. A deletable ledger row would
rewrite a student's financial history leaving no trace.

Charges and reversals are keyed per (booking, attempt) and written
under MENU_LOCK alongside the seat, so a double-click, a retry, or a
cancel cut short mid-flight all settle to one charge and one refund.
That lock is in-process only: a second replica would break every
capacity and charge guarantee here.

A parent may book for a linked student, the first write parent_link
has ever authorised, and sees only seats whose link is still live.
README.mdmodified+250 -1
@@ -109,6 +109,18 @@ inference outlives a request: the turn plus an empty `pending` answer are
109 written *first*, the call goes out after, so a reload never loses an answer;109 written *first*, the call goes out after, so a reload never loses an answer;
110 the client then polls the message or reads it off an SSE stream (see110 the client then polls the message or reads it off an SSE stream (see
111 "Chatbot").111 "Chatbot").
112+The school's **food program** is published here too: a manager puts up one
113+**menu** per calendar day and meal slot (`date` as `YYYY-MM-DD` text, `slot`
114+drawn from the school's `meal_slots`, unique per pair), lists its **dishes**
115+with dietary tags from the school's own list, and prices them in **minor
116+units** (kuruş) as integers β€” this API never speaks decimals or floats about
117+money. A student's own **dietary profile** is tagged from that same list
118+(manager-written β€” an allergen list is a school record, not a self-service
119+preference), so every dish a menu read returns names the tags it `conflicts`
120+with for whoever is reading. Every authenticated user reads what is being
121+served; students (or their parents) book a seat, and every seat writes a line into an
122+**append-only** meal ledger whose balance is derived and never stored (see
123+"Food program: menus, dishes, bookings & the ledger").
112 124
113 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)125 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)
114 constructed only after its restrictions pass β€” invalid input can't be126 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.
748 | GET | `/terms/{id}` | student | Get one term |760 | GET | `/terms/{id}` | student | Get one term |
749 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |761 | PATCH | `/terms/{id}` | manager | Edit a term (the merged range must stay ordered) |
750 | DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |762 | DELETE | `/terms/{id}` | manager | Delete a term β€” `409` while any course still links to it |
763+| 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 |
764+| GET | `/meals/menus` | student | List menus with their dishes, newest day first Β· `?from=&to=` inclusive `YYYY-MM-DD` range Β· paged |
765+| GET | `/meals/menus/{id}` | student | One menu with its dishes |
766+| PATCH | `/meals/menus/{id}` | manager | `{capacity}` β€” the only mutable field (`null` = uncapped); `date` and `slot` are immutable |
767+| DELETE | `/meals/menus/{id}` | manager | Unpublish a menu; its dishes go with it; `409` while anyone still holds a seat |
768+| 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` |
769+| PATCH | `/meals/dishes/{did}` | manager | Edit a dish (`tags` replaces the list, `"description": null` clears it) |
770+| DELETE | `/meals/dishes/{did}` | manager | Remove a dish from its menu |
771+| GET | `/meals/profiles/me` | student | The caller's own dietary profile (empty when the school recorded none) |
772+| GET | `/meals/profiles/{user}` | student | One student's dietary profile; own id always, otherwise teacher+ or a parent link |
773+| 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 |
774+| 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 |
775+| 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 |
776+| GET | `/meals/menus/{id}/bookings` | manager | Every booking on one menu, cancelled ones included Β· paged |
777+| 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 |
778+| 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** |
779+| GET | `/meals/menus/{id}/attendance` | teacher | Who ate off one menu Β· paged |
780+| 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 |
781+| GET | `/meals/balance/me` | student | The caller's meal balance, minor units (negative = owes) |
782+| GET | `/meals/balance/{user}` | student | One student's balance; own id always, otherwise teacher+ or a parent link |
783+| GET | `/meals/ledger/{user}` | student | That student's statement β€” every charge, credit, reversal β€” newest first Β· paged Β· same gate |
784+| POST | `/meals/credits` | admin | `{student_id, amount_minor, method?, note?}` β€” record money received; **admin only**, appends a `credit` line |
751 | POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |785 | POST | `/chatbot/threads` | student | `{title?}` β€” start a chatbot thread (every role incl. `parent`, always private to its owner); `409` at `max_chatbot_threads` |
752 | GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |786 | GET | `/chatbot/threads` | student | The caller's threads, newest activity first Β· paged |
753 | 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 |787 | 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
1116 rewrites history: an exam keeps its retired kind, a roll-call row keeps its1150 rewrites history: an exam keeps its retired kind, a roll-call row keeps its
1117 retired status β€” only **new writes** are held to the current lists.1151 retired status β€” only **new writes** are held to the current lists.
1118 1152
1153+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").
1154+
1119 Academic structure is data too. **Terms** (`/terms`) model whatever calendar1155 Academic structure is data too. **Terms** (`/terms`) model whatever calendar
1120 the school runs β€” semester, trimester, quarter systems are just rows with a1156 the school runs β€” semester, trimester, quarter systems are just rows with a
1121 name and a date range. Courses may link to one via `term_id` (nullable), and1157 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
1132 environment variables β€” the model is **one school per deployment**, which1168 environment variables β€” the model is **one school per deployment**, which
1133 keeps every school's data physically isolated.1169 keeps every school's data physically isolated.
1134 1170
1171+## Food program: menus, dishes, bookings, attendance & the ledger
1172+
1173+The school publishes **one menu per calendar day and meal slot** (`POST
1174+/meals/menus`). Two shapes there are deliberate:
1175+
1176+- **`date` is text**, `YYYY-MM-DD`, not a timestamp. "One menu per day and
1177+ slot" is an equality test on the school's own day, and a midnight-in-millis
1178+ day is only unique for one timezone. Fixed-width and zero-padded, so the
1179+ text sorts chronologically β€” which is what the inclusive `?from=&to=` range
1180+ filter and the newest-day-first ordering are built on.
1181+- **`slot` is a snapshot**, not a link into settings. It must be one of the
1182+ school's `meal_slots` (`GET /settings`) *when the menu is written*, and it
1183+ is stored as text β€” so retiring a slot later never rewrites a menu already
1184+ published under it. The mirror of that rule lives in settings: a slot any
1185+ menu was published for cannot be removed from the list (`409`), same
1186+ contract exam kinds have with graded exams.
1187+
1188+The day+slot pair is unique: a second publish for the same meal answers `409`
1189+β€” edit the first one instead. Only `capacity` is patchable (`null` = uncapped)
1190+β€” `date` and `slot` are immutable, because a menu on another day is another
1191+menu.
1192+
1193+**Dishes** hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, then
1194+`PATCH`/`DELETE /meals/dishes/{did}`). Each carries a name, an optional
1195+description (blank or `null` clears it), dietary `tags` drawn from the
1196+school's `dietary_tags` list β€” an unknown tag is a `400`, never a stored
1197+string β€” and a `price_minor`.
1198+
1199+### Dietary profiles and conflicts
1200+
1201+A student carries a **dietary profile**: a list of tags plus a free-text note
1202+for the kitchen, one row per student (the record key *is* the student's id).
1203+The tags come from the *same* `dietary_tags` list a dish is tagged from β€”
1204+there is deliberately no second vocabulary, because one shared list is exactly
1205+what makes "is this dish a problem for this student" answerable as a set
1206+intersection, without the backend knowing any nutrition.
1207+
1208+Writing it is **manager+** (`PATCH /meals/profiles/{user}`, first write
1209+creates the row). A student does *not* edit their own allergen list: it is a
1210+safety record the school keeps on their behalf, and a mistyped β€” or quietly
1211+removed β€” allergy would otherwise reach the kitchen with the school's
1212+authority behind it. Reading is `GET /meals/profiles/me`, or
1213+`GET /meals/profiles/{user}` under the usual per-student gate (own id always,
1214+otherwise teacher+ or a parent link). A student who was never recorded reads
1215+back as an *empty* profile rather than a `404` β€” "nothing known" is an answer.
1216+
1217+Every dish a menu read returns therefore carries a **`conflicts`** list: the
1218+intersection of that dish's `tags` with the **calling user's** profile tags.
1219+It is empty when the two do not overlap, and empty for every reader without a
1220+profile β€” a manager reading a menu sees `conflicts: []`, which is correct and
1221+not a bug (the field answers "may *I* eat this", and there is no "conflicts
1222+for student X" parameter). The caller's profile is loaded **once per request**,
1223+not per dish, so the menu list stays at its fixed query count no matter how
1224+many menus or dishes the page holds.
1225+
1226+**Money is minor units** (kuruş) as an integer, at every layer: `4550` is
1227+45,50 β‚Ί. This API never speaks decimals or floats about money, so no rounding
1228+is ever introduced by transport or by a client's JSON number parser.
1229+
1230+Reads are open to every authenticated user β€” a student has to see what is
1231+being served β€” and every write is manager+. Deleting a menu takes its dishes
1232+with it: a dish has no meaning apart from the menu it was published on.
1233+
1234+**Bookings** are seats on a published menu (`POST
1235+/meals/menus/{id}/bookings`). One row per (menu, student), keyed by a
1236+deterministic composite id, so booking twice is the same seat and never a
1237+second one. A **student books only for themselves**; a **parent books for a
1238+student they hold a link to** β€” the one write a `parent_link` authorises, since
1239+paying for lunch is a parent's job. Nobody else books through this route: a
1240+teacher or manager ordering a child's lunch is a `403`.
1241+
1242+- **Cancelling is a status flip, not a delete** (`DELETE
1243+ /meals/bookings/{bid}` answers `200` with the flipped row): the row survives
1244+ as `cancelled` with a `cancelled_at` stamp, so a freed seat stays auditable
1245+ against the money it moved. Only `booked` rows count against `capacity`,
1246+ which is what genuinely frees the seat β€” and re-booking is the same row
1247+ flipped back. The call is **idempotent**: cancelling an already-cancelled
1248+ seat answers `200` with the row as it stands *and replays the refund*, so a
1249+ cancel cut short between the flip and the reversal (the tab closed, a proxy
1250+ timed out) is recovered by sending it again. Refusing it as a `409` β€” as it
1251+ once did β€” made that state permanent: no route could append the missing
1252+ reversal, and the student stayed billed for a seat they no longer held.
1253+- **The capacity check is serialized in-process.** Counting rows and then
1254+ writing one is write-skew: SurrealDB does not conflict-check a cross-record
1255+ count against a concurrent insert, so 24 students racing for 3 seats would
1256+ otherwise all pass the count. The whole check-then-write runs under the same
1257+ lock a menu publish takes, and the cap is re-read inside it.
1258+- **One cutoff closes both ends.** Within the school's
1259+ `meal_cancel_cutoff_minutes` of the meal's day, neither a new booking nor a
1260+ cancellation lands (`409`) β€” the kitchen's headcount has to settle at some
1261+ point. `null` (the default) means no cutoff at all. The cutoff is measured
1262+ back from **midnight UTC starting the meal's day**: `date` carries no
1263+ timezone and the backend stores no school timezone, so that is the only
1264+ instant derivable from it.
1265+- A menu somebody still holds a seat on **cannot be unpublished** (`409`) β€”
1266+ cancel the bookings first, so nothing is left pointing at a deleted meal.
1267+
1268+`GET /meals/bookings/me` is the caller's own list: the seats held *for* them
1269+plus, for a parent, the seats held for every student they **currently** hold a
1270+link to β€” so a parent's list is their children's meals. The links are re-read
1271+on every call rather than trusted from the booking's `booked_by` stamp: an
1272+unlinked parent stops seeing the child's seats at once, including the ones
1273+they booked and paid for themselves, exactly like every other parent read. `GET /meals/menus/{id}/bookings` is the kitchen's list for
1274+one menu (manager+), cancelled rows included so the changes are visible.
1275+
1276+### Meal attendance
1277+
1278+Whoever stands at the canteen door records who actually ate:
1279+`POST /meals/menus/{id}/attendance` with `{student_id, status}`, teacher+ (a
1280+student never marks, not even themselves). The status is the fixed pair
1281+`served` / `missed` β€” deliberately **not** the school's editable
1282+`attendance_statuses`, since a canteen line has no "late" or "excused", and one
1283+list meaning two things would let a school change one by editing the other.
1284+One row per (menu, student) keyed by a composite id, so a correction re-marks
1285+the same row instead of stacking a second one.
1286+
1287+**Attendance has zero billing effect.** Booking is the sole charge trigger, so
1288+a student who booked and did not eat still pays β€” the kitchen bought the food.
1289+There is no no-show penalty, no refund-on-missed, and no auto-reversal:
1290+nothing under `meal_attendance` writes to the ledger. A walk-in with no live
1291+booking *can* be marked `served` (the record is operationally true) and is
1292+likewise not charged for it β€” charging there would be a ledger write. The
1293+target only has to *exist*: a canteen also feeds staff, so any user may be
1294+marked, not only a student. A mark is a record of what happened, not a check
1295+of who was entitled, and since it moves no money it costs nobody anything.
1296+
1297+`GET /meals/menus/{id}/attendance` is the per-menu list (teacher+), and
1298+`GET /meals/attendance/{user}` is one student's history, narrowable with
1299+`?from=&to=` β€” inclusive `YYYY-MM-DD` bounds compared against the *menu's*
1300+day, a lexical compare that is chronological for that format. Same gate as the
1301+balance and the ledger: the caller's own id always passes, anyone else's needs
1302+teacher+ or a `parent_link` to that student.
1303+
1304+### The ledger
1305+
1306+The money is an **append-only ledger** (`meal_ledger`): one line per `charge`,
1307+`credit`, or `reversal`, every field `READONLY`, and **no code path anywhere
1308+that updates or deletes one**. A ledger line that can be edited or dropped
1309+silently rewrites a student's financial history with no trace of the rewrite β€”
1310+this is the one genuinely irreversible part of the food program, so a mistake
1311+is corrected by appending the opposing line, which leaves both the mistake and
1312+the correction visible.
1313+
1314+**No balance is stored, anywhere.** It is always derived:
1315+
1316+```text
1317+balance = SUM(credit) + SUM(reversal) - SUM(charge)
1318+```
1319+
1320+in **minor units** (kuruş) as an `i64` β€” no float, no decimal, at any layer.
1321+A *negative* balance means the student owes the school; a positive one is
1322+money on account. Amounts are stored positive; the sign lives in the `kind`.
1323+
1324+- **Booking is what charges, at a price snapshot.** The menu's dishes are
1325+ summed the moment the seat is taken and that number is frozen onto the
1326+ charge. Editing a dish's price afterwards moves no existing charge β€” what a
1327+ student owes is what the menu cost the day they booked. The price is
1328+ snapshotted *before* the seat is given, so a menu that cannot be charged
1329+ refuses the booking rather than leaving a booked-but-unbilled row (`400`,
1330+ when the dishes sum past 10 000 000). A free menu writes no line at all β€”
1331+ but the booking row records that it *was* free, so "free when taken" is
1332+ never confused with "not billed yet": pricing the menu afterwards leaves
1333+ every seat already taken on it free.
1334+- **Charge and reversal are keyed by `(booking, attempt)`.** The seat and its
1335+ money move together under one in-process lock, and the ledger id is derived
1336+ from the seat plus how many times it has been taken β€” so eight simultaneous
1337+ `POST`s of one seat write one charge, a retried cancel refunds once, and a
1338+ write that failed halfway heals when the request is repeated. Booking the
1339+ same seat twice bills once because the *identity* is the same, never
1340+ because a scan happened to see the first charge in time.
1341+- **Cancelling appends a `reversal`** for the charge's exact amount, with
1342+ `source` pointing at the charge it undoes. The charge row itself stays. A
1343+ cancel past the cutoff is already a `409`, so a reversal only ever follows a
1344+ legal cancel β€” and repeating a cancel replays the reversal, which is what
1345+ makes the refund recoverable rather than a one-shot the network can lose.
1346+ Re-booking afterwards is a **fresh** charge at the then-current price.
1347+- **The price snapshot is taken under the booking lock**, and dish
1348+ create/edit/delete take that same lock. Taken outside it, a dish added
1349+ between the sum and the seat would be frozen onto the row as "the menu was
1350+ free then" β€” and nothing heals it, since a seat already held is returned
1351+ as-is, never re-priced.
1352+- **A no-show still pays.** Meal attendance has zero billing effect β€” nothing
1353+ in the ledger reads or writes it. The seat was reserved and the food was
1354+ cooked; there is no no-show penalty and no no-show refund.
1355+- **`POST /meals/credits` is admin-only**, not manager: writing down cash
1356+ received is the highest-trust action in the app. It appends a `credit` for a
1357+ student with a positive `amount_minor` (≀ 10 000 000), an optional `method`
1358+ ("cash", "havale", …) and `note`, and records the admin as `recorded_by`.
1359+ There is no payment gateway and no card data, ever. An over-credit is
1360+ corrected with a compensating line, never a fix-up.
1361+
1362+`GET /meals/balance/me` is the caller's own balance. `GET
1363+/meals/balance/{user}` and `GET /meals/ledger/{user}` (paged, newest line
1364+first) read a student's: your own id always passes, anyone else's needs
1365+teacher+ or a `parent_link` to that student. A charge's `source` is the
1366+booking id it came from, a reversal's is the charge line it reverses, and a
1367+credit has none.
1368+
1135 ## Exam modes, attempts, retakes, rejoin & live monitoring1369 ## Exam modes, attempts, retakes, rejoin & live monitoring
1136 1370
1137 Preparing an exam is slow work, so an exam can be created as a **draft**1371 Preparing an exam is slow work, so an exam can be created as a **draft**
@@ -2058,6 +2292,21 @@ src/
2058 registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)2292 registration.rs RegistrationId Β· Registration (a seat on a registration event's signup list)
2059 subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)2293 subject.rs SubjectId Β· SubjectName Β· SubjectDescription Β· Subject (course curriculum)
2060 term.rs TermId Β· TermName Β· Term (school term window)2294 term.rs TermId Β· TermName Β· Term (school term window)
2295+ menu.rs MenuId Β· MenuDate Β· MenuSlot Β· Menu (one published menu per
2296+ calendar day + meal slot; slot snapshotted as text)
2297+ menu_dish.rs MenuDishId Β· DishName Β· DishDescription Β· DishPrice Β·
2298+ DishTags Β· MenuDish (a dish on a menu; price in minor units)
2299+ dietary_profile.rs DietaryProfileId Β· DietaryTags Β· DietaryNote Β·
2300+ DietaryProfile (what one student may not eat; keyed by the
2301+ student, tagged from the same `dietary_tags` list a dish is)
2302+ meal_booking.rs MealBookingId Β· MealBookingStatus Β· MealBooking (one seat
2303+ per (menu, student); a cancel flips the status, never deletes)
2304+ meal_attendance.rs MealAttendanceId Β· MealAttendanceStatus Β· MealAttendance
2305+ (who actually ate; one row per (menu, student), reporting
2306+ only β€” it never touches the ledger)
2307+ meal_ledger.rs MealLedgerId Β· MealLedgerKind Β· LedgerAmount Β· LedgerMethod Β·
2308+ LedgerNote Β· MealLedger (append-only money; the balance is
2309+ always the fold, never a stored field)
2061 settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)2310 settings.rs ExamKindDef Β· GradeBand Β· Settings (per-school policy)
2062 chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one2311 chatbot_thread.rs ChatbotThreadId Β· ChatbotThreadTitle Β· ChatbotThread (one
2063 chatbot thread, private to its owner)2312 chatbot thread, private to its owner)
@@ -2098,7 +2347,7 @@ src/
2098 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs2347 auth.rs users.rs notes.rs messages.rs events.rs appointments.rs
2099 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs2348 courses.rs subjects.rs sessions.rs exams.rs homework.rs questions.rs
2100 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs2349 bank_questions.rs marks.rs work.rs pomodoro.rs attendance.rs
2101- settings.rs terms.rs ai.rs chatbot.rs2350+ settings.rs terms.rs meals.rs ai.rs chatbot.rs
2102 limits.rs GET /limits: every constant.rs bound served as JSON2351 limits.rs GET /limits: every constant.rs bound served as JSON
2103 ```2352 ```
2104 2353
src/constant.rsmodified+160 -0
@@ -149,6 +149,52 @@ pub const MAX_APPOINTMENT_REASON_LEN: usize = 1_000;
149 /// (a decade out) is refused instead of writing thousands of rows.149 /// (a decade out) is refused instead of writing thousands of rows.
150 pub const MAX_SLOT_OCCURRENCES: usize = 52;150 pub const MAX_SLOT_OCCURRENCES: usize = 52;
151 151
152+/// The default meal slots; schools replace the list via `PATCH /settings`, and
153+/// a published menu snapshots the slot it was written for, so retiring a slot
154+/// never rewrites history.
155+pub const DEFAULT_MEAL_SLOTS: [&str; 3] = ["breakfast", "lunch", "snack"];
156+
157+/// The default dietary tags. A student's profile and a dish both carry tags
158+/// from this school-editable list, which is how "this dish is safe for them"
159+/// is answered without the backend knowing any nutrition.
160+pub const DEFAULT_DIETARY_TAGS: [&str; 5] = [
161+ "vegetarian",
162+ "vegan",
163+ "gluten_free",
164+ "lactose_free",
165+ "nut_allergy",
166+];
167+
168+/// Bounds on one menu and the dishes hanging off it.
169+pub const MAX_DISH_NAME_LEN: usize = 100;
170+pub const MAX_DISH_DESCRIPTION_LEN: usize = 500;
171+pub const MAX_DISHES_PER_MENU: usize = 50;
172+pub const MAX_DISH_TAGS: usize = 10;
173+
174+/// How many students one menu may seat. Absent capacity means uncapped, the
175+/// same shape a course's `capacity` uses.
176+pub const MAX_MENU_CAPACITY: i64 = 10_000;
177+
178+/// Bounds on a student's dietary profile: one row per student, so the tag list
179+/// is the whole payload plus a free-text note for the kitchen.
180+pub const MAX_DIETARY_TAGS: usize = 10;
181+pub const MAX_DIETARY_NOTE_LEN: usize = 500;
182+
183+/// Money is **minor units** (kuruş) as `i64` everywhere β€” never a decimal and
184+/// never a float. `MAX_DISH_PRICE_MINOR` caps one dish (10 000 β‚Ί);
185+/// `MAX_LEDGER_AMOUNT_MINOR` caps one ledger line (100 000 β‚Ί), which is wide
186+/// enough for a term's prepayment.
187+pub const MAX_DISH_PRICE_MINOR: i64 = 1_000_000;
188+pub const MAX_LEDGER_AMOUNT_MINOR: i64 = 10_000_000;
189+
190+/// Bounds on the free-text a ledger line carries: how the money moved, and why.
191+pub const MAX_LEDGER_METHOD_LEN: usize = 50;
192+pub const MAX_LEDGER_NOTE_LEN: usize = 500;
193+
194+/// Ceiling on the settings knob that closes booking (and cancelling) ahead of
195+/// a meal β€” one week. The knob itself is optional: absent means no cutoff.
196+pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60;
197+
152 /// The only accepted course kinds. `course`: a regular class (ders). `study`:198 /// The only accepted course kinds. `course`: a regular class (ders). `study`:
153 /// a supervised study session (etΓΌt). Behaviorally identical β€” the kind is a199 /// a supervised study session (etΓΌt). Behaviorally identical β€” the kind is a
154 /// label for the UI, everything else (enrollment, exams, sessions, marks)200 /// label for the UI, everything else (enrollment, exams, sessions, marks)
@@ -169,6 +215,23 @@ pub const EXAM_MODES: [&str; 3] = ["sync", "async", "open"];
169 /// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`.215 /// set; the DDL carries no ASSERT (repo convention), exactly like `EXAM_MODES`.
170 pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"];216 pub const HOMEWORK_STATUSES: [&str; 3] = ["done", "incomplete", "missing"];
171 217
218+/// The only accepted meal-booking states. A cancel flips the status and stamps
219+/// `cancelled_at` instead of deleting the row, so a seat freed after the cutoff
220+/// is still auditable against the ledger line it charged.
221+pub const MEAL_BOOKING_STATUSES: [&str; 2] = ["booked", "cancelled"];
222+
223+/// The only accepted meal-attendance states β€” did the student actually eat.
224+/// Deliberately *not* the school's `attendance_statuses`: a canteen line has no
225+/// "late" or "excused", and mixing the two would let a school edit one meaning
226+/// while changing the other.
227+pub const MEAL_ATTENDANCE_STATUSES: [&str; 2] = ["served", "missed"];
228+
229+/// The only accepted ledger kinds. `charge`: a booking billed the student.
230+/// `credit`: money in (a payment, or an opening balance). `reversal`: a charge
231+/// undone β€” the ledger is append-only, so a cancelled booking writes a new
232+/// opposing line rather than editing or deleting the charge.
233+pub const MEAL_LEDGER_KINDS: [&str; 3] = ["charge", "credit", "reversal"];
234+
172 /// Inclusive bounds for an exam's per-attempt duration, milliseconds235 /// Inclusive bounds for an exam's per-attempt duration, milliseconds
173 /// (1 minute to 24 hours). Required for `async`, optional for `open`.236 /// (1 minute to 24 hours). Required for `async`, optional for `open`.
174 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;237 pub const MIN_EXAM_DURATION_MS: i64 = 60 * 1000;
@@ -502,6 +565,12 @@ pub const CHATBOT_THREAD_TABLE: &str = "chatbot_thread";
502 pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";565 pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message";
503 pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";566 pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot";
504 pub const APPOINTMENT_TABLE: &str = "appointment";567 pub const APPOINTMENT_TABLE: &str = "appointment";
568+pub const MENU_TABLE: &str = "menu";
569+pub const MENU_DISH_TABLE: &str = "menu_dish";
570+pub const DIETARY_PROFILE_TABLE: &str = "dietary_profile";
571+pub const MEAL_BOOKING_TABLE: &str = "meal_booking";
572+pub const MEAL_ATTENDANCE_TABLE: &str = "meal_attendance";
573+pub const MEAL_LEDGER_TABLE: &str = "meal_ledger";
505 574
506 // --- schema migration SQL ----------------------------------------------575 // --- schema migration SQL ----------------------------------------------
507 576
@@ -884,6 +953,20 @@ pub const MIGRATION: &str = "
884 DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;953 DEFINE FIELD IF NOT EXISTS chatbot_history_turns ON settings TYPE option<int>;
885 DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;954 DEFINE FIELD IF NOT EXISTS max_chatbot_threads ON settings TYPE option<int>;
886 DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;955 DEFINE FIELD IF NOT EXISTS max_chatbot_message_len ON settings TYPE option<int>;
956+ -- Food program (2026-07-26). `meal_slots` mirrors the `exam_kinds` shape β€”
957+ -- a named list a menu snapshots from β€” and `dietary_tags` mirrors
958+ -- `attendance_statuses`. `meal_cancel_cutoff_minutes` is ONE knob for both
959+ -- the booking and the cancel deadline; absent means no cutoff at all. All
960+ -- three are `option<>`, exactly like `max_file_bytes`: NOT `DEFAULT []`.
961+ -- `DEFAULT` fires on create only, and `PATCH /settings` writes the whole
962+ -- row with `UPDATE ... CONTENT`, so a required-with-default field a writer
963+ -- omits coerces to NONE and fails every settings write until the domain
964+ -- struct carries it. `option<>` also means the existing singleton reads
965+ -- fine, which is why the food program needs no BACKFILL anywhere.
966+ DEFINE FIELD IF NOT EXISTS meal_slots ON settings TYPE option<array<object>>;
967+ DEFINE FIELD IF NOT EXISTS meal_slots.*.name ON settings TYPE string;
968+ DEFINE FIELD IF NOT EXISTS dietary_tags ON settings TYPE option<array<string>>;
969+ DEFINE FIELD IF NOT EXISTS meal_cancel_cutoff_minutes ON settings TYPE option<int>;
887 970
888 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students971 -- Homework (greenfield, 2026-07-22): a teacher assigns per course, students
889 -- submit files + optional text, a teacher grades a status + optional mark.972 -- submit files + optional text, a teacher grades a status + optional mark.
@@ -963,6 +1046,83 @@ pub const MIGRATION: &str = "
963 DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;1046 DEFINE INDEX IF NOT EXISTS appointment_slot_ref ON appointment FIELDS slot;
964 DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;1047 DEFINE INDEX IF NOT EXISTS appointment_requester ON appointment FIELDS requester;
965 DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;1048 DEFINE INDEX IF NOT EXISTS appointment_status ON appointment FIELDS status;
1049+
1050+ -- Food program (greenfield, 2026-07-26): a published menu per day+slot,
1051+ -- dishes on it, a dietary profile per student, bookings against a menu's
1052+ -- capacity, who actually ate, and the money that moved. `date` is a
1053+ -- calendar day as `YYYY-MM-DD` text, not a timestamp: the unique index is
1054+ -- an equality test and a midnight-in-millis day is only unique for one
1055+ -- timezone. `slot` is snapshotted text, not a link, so retiring a slot in
1056+ -- settings never rewrites a past menu. Stamps stay `int` millis like the
1057+ -- rest of the schema. No BACKFILL: all six tables are new.
1058+ DEFINE TABLE IF NOT EXISTS menu SCHEMAFULL;
1059+ DEFINE FIELD IF NOT EXISTS date ON menu TYPE string READONLY;
1060+ DEFINE FIELD IF NOT EXISTS slot ON menu TYPE string READONLY;
1061+ DEFINE FIELD IF NOT EXISTS capacity ON menu TYPE option<int>;
1062+ DEFINE FIELD IF NOT EXISTS created_by ON menu TYPE record<user> READONLY;
1063+ DEFINE FIELD IF NOT EXISTS created_at ON menu TYPE int READONLY;
1064+ DEFINE INDEX IF NOT EXISTS menu_date_slot ON menu FIELDS date, slot UNIQUE;
1065+
1066+ DEFINE TABLE IF NOT EXISTS menu_dish SCHEMAFULL;
1067+ DEFINE FIELD IF NOT EXISTS menu ON menu_dish TYPE record<menu> READONLY;
1068+ DEFINE FIELD IF NOT EXISTS name ON menu_dish TYPE string;
1069+ DEFINE FIELD IF NOT EXISTS description ON menu_dish TYPE option<string>;
1070+ -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
1071+ DEFINE FIELD IF NOT EXISTS price_minor ON menu_dish TYPE int;
1072+ DEFINE FIELD IF NOT EXISTS tags ON menu_dish TYPE array<string> DEFAULT [];
1073+ DEFINE FIELD IF NOT EXISTS tags[*] ON menu_dish TYPE string;
1074+ DEFINE FIELD IF NOT EXISTS created_at ON menu_dish TYPE int READONLY;
1075+ DEFINE INDEX IF NOT EXISTS menu_dish_menu ON menu_dish FIELDS menu;
1076+
1077+ DEFINE TABLE IF NOT EXISTS dietary_profile SCHEMAFULL;
1078+ DEFINE FIELD IF NOT EXISTS student ON dietary_profile TYPE record<user> READONLY;
1079+ DEFINE FIELD IF NOT EXISTS tags ON dietary_profile TYPE array<string> DEFAULT [];
1080+ DEFINE FIELD IF NOT EXISTS tags[*] ON dietary_profile TYPE string;
1081+ DEFINE FIELD IF NOT EXISTS note ON dietary_profile TYPE option<string>;
1082+ DEFINE FIELD IF NOT EXISTS updated_by ON dietary_profile TYPE record<user>;
1083+ DEFINE FIELD IF NOT EXISTS updated_at ON dietary_profile TYPE int;
1084+ DEFINE INDEX IF NOT EXISTS dietary_profile_student ON dietary_profile FIELDS student UNIQUE;
1085+
1086+ -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
1087+ -- freed seat is still auditable against the ledger line it charged.
1088+ DEFINE TABLE IF NOT EXISTS meal_booking SCHEMAFULL;
1089+ DEFINE FIELD IF NOT EXISTS menu ON meal_booking TYPE record<menu> READONLY;
1090+ DEFINE FIELD IF NOT EXISTS student ON meal_booking TYPE record<user> READONLY;
1091+ DEFINE FIELD IF NOT EXISTS booked_by ON meal_booking TYPE record<user> READONLY;
1092+ DEFINE FIELD IF NOT EXISTS status ON meal_booking TYPE string DEFAULT 'booked';
1093+ -- How many times this seat has been taken, and what it cost when the
1094+ -- *current* attempt took it (NONE = the menu was free then). Together they
1095+ -- key the attempt's ledger lines, which is what makes billing idempotent
1096+ -- by identity rather than by scanning for an outstanding charge.
1097+ DEFINE FIELD IF NOT EXISTS attempt ON meal_booking TYPE int DEFAULT 1;
1098+ DEFINE FIELD IF NOT EXISTS price_minor ON meal_booking TYPE option<int>;
1099+ DEFINE FIELD IF NOT EXISTS cancelled_at ON meal_booking TYPE option<int>;
1100+ DEFINE FIELD IF NOT EXISTS created_at ON meal_booking TYPE int READONLY;
1101+ DEFINE INDEX IF NOT EXISTS meal_booking_menu ON meal_booking FIELDS menu;
1102+ DEFINE INDEX IF NOT EXISTS meal_booking_student ON meal_booking FIELDS student;
1103+
1104+ DEFINE TABLE IF NOT EXISTS meal_attendance SCHEMAFULL;
1105+ DEFINE FIELD IF NOT EXISTS menu ON meal_attendance TYPE record<menu> READONLY;
1106+ DEFINE FIELD IF NOT EXISTS student ON meal_attendance TYPE record<user> READONLY;
1107+ DEFINE FIELD IF NOT EXISTS status ON meal_attendance TYPE string;
1108+ DEFINE FIELD IF NOT EXISTS marked_by ON meal_attendance TYPE record<user>;
1109+ DEFINE FIELD IF NOT EXISTS marked_at ON meal_attendance TYPE int;
1110+ DEFINE INDEX IF NOT EXISTS meal_attendance_menu_student ON meal_attendance FIELDS menu, student UNIQUE;
1111+
1112+ -- APPEND-ONLY by design: a mistake is corrected with an opposing
1113+ -- `reversal` line, never by editing or deleting one. Hence every field is
1114+ -- READONLY. `source` is untyped on purpose β€” a charge points at the
1115+ -- booking that caused it, a reversal at the line it undoes.
1116+ DEFINE TABLE IF NOT EXISTS meal_ledger SCHEMAFULL;
1117+ DEFINE FIELD IF NOT EXISTS student ON meal_ledger TYPE record<user> READONLY;
1118+ DEFINE FIELD IF NOT EXISTS kind ON meal_ledger TYPE string READONLY;
1119+ DEFINE FIELD IF NOT EXISTS amount_minor ON meal_ledger TYPE int READONLY;
1120+ DEFINE FIELD IF NOT EXISTS source ON meal_ledger TYPE option<record> READONLY;
1121+ DEFINE FIELD IF NOT EXISTS method ON meal_ledger TYPE option<string> READONLY;
1122+ DEFINE FIELD IF NOT EXISTS note ON meal_ledger TYPE option<string> READONLY;
1123+ DEFINE FIELD IF NOT EXISTS recorded_by ON meal_ledger TYPE record<user> READONLY;
1124+ DEFINE FIELD IF NOT EXISTS created_at ON meal_ledger TYPE int READONLY;
1125+ DEFINE INDEX IF NOT EXISTS meal_ledger_student ON meal_ledger FIELDS student;
966 ";1126 ";
967 1127
968 /// Data backfills for rows written by older binaries. Runs *after* (and apart1128 /// Data backfills for rows written by older binaries. Runs *after* (and apart
src/domain/dietary_profile.rsadded+211 -0
@@ -0,0 +1,211 @@
1+//! What one student may not eat: the school's record of their dietary tags
2+//! plus a free-text note for the kitchen.
3+//!
4+//! One row per student, so the record key **is** the student's key β€” no
5+//! generated id and no composite. Tags are validated against the same
6+//! `dietary_tags` vocabulary a dish's tags come from ([`Settings::get_dietary_tags`]);
7+//! that single shared list is what makes "this dish conflicts with this
8+//! student" answerable as a set intersection, without the backend knowing any
9+//! nutrition.
10+//!
11+//! [`Settings::get_dietary_tags`]: crate::domain::settings::Settings::get_dietary_tags
12+
13+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
14+
15+use crate::constant::{DIETARY_PROFILE_TABLE, MAX_DIETARY_NOTE_LEN, MAX_DIETARY_TAGS};
16+use crate::database::Database;
17+use crate::domain::field_update::FieldUpdate;
18+use crate::domain::timestamp::Timestamp;
19+use crate::domain::user::UserId;
20+use crate::error::{AppError, ValidationError};
21+use crate::validate::validate_optional;
22+
23+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
24+pub struct DietaryProfileId(RecordId);
25+
26+impl DietaryProfileId {
27+ /// The profile of one student β€” deterministic, so "read the caller's
28+ /// profile" is a single `SELECT` by id and never a scan.
29+ pub fn of(student: &UserId) -> Self {
30+ Self(RecordId::new(DIETARY_PROFILE_TABLE, student.key()))
31+ }
32+
33+ pub fn record(&self) -> RecordId {
34+ self.0.clone()
35+ }
36+
37+ pub fn key(&self) -> &str {
38+ match &self.0.key {
39+ RecordIdKey::String(key) => key,
40+ _ => "",
41+ }
42+ }
43+}
44+
45+/// The tags a student's diet carries, drawn from the school's `dietary_tags`
46+/// list β€” the same vocabulary a dish is tagged from, deduplicated and in the
47+/// order given.
48+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
49+pub struct DietaryTags(Vec<String>);
50+
51+impl DietaryTags {
52+ pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> {
53+ let mut tags: Vec<String> = Vec::new();
54+ for value in values {
55+ let value = value.trim();
56+ if !allowed.iter().any(|tag| tag == value) {
57+ return Err(ValidationError::Invalid {
58+ field: "tags",
59+ reason: "not one of the school's dietary tags (see GET /settings)",
60+ });
61+ }
62+ if !tags.iter().any(|tag| tag == value) {
63+ tags.push(value.to_string());
64+ }
65+ }
66+ if tags.len() > MAX_DIETARY_TAGS {
67+ return Err(ValidationError::Invalid {
68+ field: "tags",
69+ reason: "at most 10 tags per student",
70+ });
71+ }
72+ Ok(Self(tags))
73+ }
74+
75+ pub fn as_slice(&self) -> &[String] {
76+ &self.0
77+ }
78+}
79+
80+/// Anything the tag list cannot say β€” "carries an EpiPen", "no pork".
81+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
82+pub struct DietaryNote(String);
83+
84+impl DietaryNote {
85+ /// Blank (or whitespace-only) means "no note" β€” `None`, not an empty
86+ /// string, so the column is absent rather than falsely present.
87+ pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> {
88+ validate_optional("note", value, MAX_DIETARY_NOTE_LEN)?;
89+ let value = value.trim();
90+ Ok((!value.is_empty()).then(|| Self(value.to_string())))
91+ }
92+
93+ pub fn as_str(&self) -> &str {
94+ &self.0
95+ }
96+}
97+
98+#[derive(Debug, Clone, SurrealValue)]
99+pub struct DietaryProfile {
100+ id: DietaryProfileId,
101+ student: UserId,
102+ tags: DietaryTags,
103+ note: Option<DietaryNote>,
104+ updated_by: UserId,
105+ updated_at: Timestamp,
106+}
107+
108+impl DietaryProfile {
109+ pub fn get_student(&self) -> &UserId {
110+ &self.student
111+ }
112+
113+ pub fn get_tags(&self) -> &DietaryTags {
114+ &self.tags
115+ }
116+
117+ pub fn get_note(&self) -> Option<&DietaryNote> {
118+ self.note.as_ref()
119+ }
120+
121+ pub fn get_updated_by(&self) -> &UserId {
122+ &self.updated_by
123+ }
124+
125+ pub fn get_updated_at(&self) -> Timestamp {
126+ self.updated_at
127+ }
128+
129+ /// One student's profile, or `None` while the school never recorded one.
130+ /// A single `SELECT` by record id β€” this is what a menu read joins on.
131+ pub async fn read(student: &UserId, db: &Database) -> Result<Option<Self>, AppError> {
132+ Ok(db.select(DietaryProfileId::of(student).record()).await?)
133+ }
134+
135+ /// The tags a menu read matches its dishes against: the caller's, or an
136+ /// empty list when they have no profile (every manager, every teacher).
137+ pub async fn tags_of(student: &UserId, db: &Database) -> Result<Vec<String>, AppError> {
138+ Ok(Self::read(student, db)
139+ .await?
140+ .map(|profile| profile.tags.as_slice().to_vec())
141+ .unwrap_or_default())
142+ }
143+
144+ /// Write the fields the PATCH carried. Creates the row on first write;
145+ /// afterwards only the named fields move, because `student` is `READONLY`
146+ /// and a whole-row save would also revert a concurrent edit of the other
147+ /// field (see [`FieldUpdate`]).
148+ pub async fn save(
149+ student: &UserId,
150+ tags: Option<DietaryTags>,
151+ note: Option<Option<DietaryNote>>,
152+ by: &UserId,
153+ db: &Database,
154+ ) -> Result<Self, AppError> {
155+ if Self::read(student, db).await?.is_none() {
156+ let profile = Self {
157+ id: DietaryProfileId::of(student),
158+ student: student.clone(),
159+ tags: tags.unwrap_or(DietaryTags(Vec::new())),
160+ note: note.flatten(),
161+ updated_by: by.clone(),
162+ updated_at: Timestamp::now(),
163+ };
164+ let created: Option<Self> = db.create(profile.id.record()).content(profile).await?;
165+ return created.ok_or_else(|| AppError::Internal("failed to save the profile".into()));
166+ }
167+ FieldUpdate::new(DietaryProfileId::of(student).record())
168+ .set("tags", tags)
169+ .set("note", note)
170+ .set("updated_by", Some(by.clone()))
171+ .set("updated_at", Some(Timestamp::now()))
172+ .run::<Self>(db)
173+ .await
174+ }
175+}
176+
177+/// Which of a dish's tags the reader's own profile flags. Empty when there is
178+/// no overlap, and empty for every reader without a profile.
179+pub fn conflicts(dish_tags: &[String], profile_tags: &[String]) -> Vec<String> {
180+ dish_tags
181+ .iter()
182+ .filter(|tag| profile_tags.iter().any(|held| held == *tag))
183+ .cloned()
184+ .collect()
185+}
186+
187+#[cfg(test)]
188+mod tests {
189+ use super::*;
190+
191+ #[test]
192+ fn tags_must_come_from_the_school_list_and_dedupe() {
193+ let allowed = vec!["vegan".to_string(), "nut_allergy".to_string()];
194+ let tags =
195+ DietaryTags::try_new(&["vegan".to_string(), "vegan".to_string()], &allowed).unwrap();
196+ assert_eq!(tags.as_slice(), ["vegan"]);
197+ assert!(DietaryTags::try_new(&["halal".to_string()], &allowed).is_err());
198+ }
199+
200+ #[test]
201+ fn conflicts_are_the_intersection_in_dish_order() {
202+ let held = vec!["nut_allergy".to_string(), "vegan".to_string()];
203+ assert_eq!(
204+ conflicts(&["vegan".to_string(), "nut_allergy".to_string()], &held),
205+ ["vegan", "nut_allergy"]
206+ );
207+ assert!(conflicts(&["gluten_free".to_string()], &held).is_empty());
208+ // No profile is no conflict, never "everything conflicts".
209+ assert!(conflicts(&["vegan".to_string()], &[]).is_empty());
210+ }
211+}
src/domain/meal_attendance.rsadded+191 -0
@@ -0,0 +1,191 @@
1+//! Who actually ate. One row per (menu, student), keyed by a deterministic
2+//! composite id β€” the same pair always maps to the same record, so marking is a
3+//! single atomic UPSERT with no find-then-insert race, and re-marking flips the
4+//! status instead of stacking a second row.
5+//!
6+//! **Attendance is reporting only β€” it has zero billing effect.** Booking is
7+//! the sole charge trigger: a student who booked and did not eat still pays,
8+//! because the kitchen bought the food. Nothing here ever writes to
9+//! [`MealLedger`](crate::domain::meal_ledger::MealLedger) β€” no no-show penalty,
10+//! no refund-on-missed, no auto-reversal. A walk-in with no booking can still
11+//! be marked `served` (the record is operationally true) and is likewise never
12+//! charged for it.
13+//!
14+//! The statuses are the fixed [`MEAL_ATTENDANCE_STATUSES`] pair, deliberately
15+//! *not* the school's editable `attendance_statuses`: a canteen line has no
16+//! "late" or "excused".
17+
18+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
19+
20+use crate::constant::{MEAL_ATTENDANCE_STATUSES, MEAL_ATTENDANCE_TABLE};
21+use crate::database::Database;
22+use crate::domain::menu::{MenuDate, MenuId};
23+use crate::domain::timestamp::Timestamp;
24+use crate::domain::user::UserId;
25+use crate::error::{AppError, ValidationError};
26+
27+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
28+pub struct MealAttendanceId(RecordId);
29+
30+impl MealAttendanceId {
31+ /// A deterministic id for the (menu, student) pair β€” same trick as
32+ /// [`MealBookingId`](crate::domain::meal_booking::MealBookingId). ULID keys
33+ /// are alphanumeric, so `_` is an unambiguous joiner.
34+ pub fn composite(menu: &MenuId, student: &UserId) -> Self {
35+ Self(RecordId::new(
36+ MEAL_ATTENDANCE_TABLE,
37+ format!("{}_{}", menu.key(), student.key()),
38+ ))
39+ }
40+
41+ pub fn record(&self) -> RecordId {
42+ self.0.clone()
43+ }
44+
45+ pub fn key(&self) -> &str {
46+ match &self.0.key {
47+ RecordIdKey::String(key) => key,
48+ _ => "",
49+ }
50+ }
51+}
52+
53+/// `served` or `missed`, and nothing else β€” see the module header.
54+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
55+pub struct MealAttendanceStatus(String);
56+
57+impl MealAttendanceStatus {
58+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
59+ let value = value.trim();
60+ if !MEAL_ATTENDANCE_STATUSES.contains(&value) {
61+ return Err(ValidationError::Invalid {
62+ field: "status",
63+ reason: "must be 'served' or 'missed'",
64+ });
65+ }
66+ Ok(Self(value.to_string()))
67+ }
68+
69+ pub fn as_str(&self) -> &str {
70+ &self.0
71+ }
72+}
73+
74+#[derive(Debug, Clone, SurrealValue)]
75+pub struct MealAttendance {
76+ id: MealAttendanceId,
77+ menu: MenuId,
78+ student: UserId,
79+ status: MealAttendanceStatus,
80+ marked_by: UserId,
81+ marked_at: Timestamp,
82+}
83+
84+impl MealAttendance {
85+ pub fn get_id(&self) -> &MealAttendanceId {
86+ &self.id
87+ }
88+
89+ pub fn get_menu(&self) -> &MenuId {
90+ &self.menu
91+ }
92+
93+ pub fn get_student(&self) -> &UserId {
94+ &self.student
95+ }
96+
97+ pub fn get_status(&self) -> &MealAttendanceStatus {
98+ &self.status
99+ }
100+
101+ pub fn get_marked_by(&self) -> &UserId {
102+ &self.marked_by
103+ }
104+
105+ pub fn get_marked_at(&self) -> Timestamp {
106+ self.marked_at
107+ }
108+
109+ /// Record (or overwrite) whether `student` ate off `menu`. One row per
110+ /// pair by construction, so a correction is the same UPSERT flipping the
111+ /// status. No ledger line, ever β€” see the module header.
112+ pub async fn mark(
113+ menu: &MenuId,
114+ student: &UserId,
115+ status: MealAttendanceStatus,
116+ marked_by: &UserId,
117+ db: &Database,
118+ ) -> Result<MealAttendance, AppError> {
119+ let row = MealAttendance {
120+ id: MealAttendanceId::composite(menu, student),
121+ menu: menu.clone(),
122+ student: student.clone(),
123+ status,
124+ marked_by: marked_by.clone(),
125+ marked_at: Timestamp::now(),
126+ };
127+ let saved: Option<MealAttendance> = db.upsert(row.id.record()).content(row).await?;
128+ saved.ok_or_else(|| AppError::Internal("failed to mark meal attendance".into()))
129+ }
130+
131+ /// The kitchen's list for one menu.
132+ pub async fn list_for_menu(
133+ menu: &MenuId,
134+ db: &Database,
135+ ) -> Result<Vec<MealAttendance>, AppError> {
136+ let mut result = db
137+ .query(
138+ "SELECT * FROM meal_attendance WHERE menu = $menu \
139+ ORDER BY marked_at DESC, id DESC",
140+ )
141+ .bind(("menu", menu.record()))
142+ .await?
143+ .check()?;
144+ Ok(result.take::<Vec<MealAttendance>>(0)?)
145+ }
146+
147+ /// One student's marks, newest first. `from`/`to` are inclusive
148+ /// `YYYY-MM-DD` bounds on the *menu's* day β€” the comparison is lexical,
149+ /// which is chronological for that format (see [`MenuDate`]), and the link
150+ /// is followed rather than denormalized so a row can never disagree with
151+ /// the menu it belongs to.
152+ pub async fn list_for_student(
153+ student: &UserId,
154+ from: Option<&MenuDate>,
155+ to: Option<&MenuDate>,
156+ db: &Database,
157+ ) -> Result<Vec<MealAttendance>, AppError> {
158+ let mut result = db
159+ .query(
160+ "SELECT * FROM meal_attendance WHERE student = $usr \
161+ AND ($from = NONE OR menu.date >= $from) \
162+ AND ($to = NONE OR menu.date <= $to) \
163+ ORDER BY marked_at DESC, id DESC",
164+ )
165+ .bind(("usr", student.record()))
166+ .bind(("from", from.map(|date| date.as_str().to_string())))
167+ .bind(("to", to.map(|date| date.as_str().to_string())))
168+ .await?
169+ .check()?;
170+ Ok(result.take::<Vec<MealAttendance>>(0)?)
171+ }
172+}
173+
174+#[cfg(test)]
175+mod tests {
176+ use super::*;
177+
178+ #[test]
179+ fn status_is_the_fixed_canteen_pair() {
180+ for status in MEAL_ATTENDANCE_STATUSES {
181+ assert_eq!(
182+ MealAttendanceStatus::try_new(status).unwrap().as_str(),
183+ status
184+ );
185+ }
186+ // The school's roll-call vocabulary is not this vocabulary.
187+ assert!(MealAttendanceStatus::try_new("present").is_err());
188+ assert!(MealAttendanceStatus::try_new("excused").is_err());
189+ assert!(MealAttendanceStatus::try_new("").is_err());
190+ }
191+}
src/domain/meal_booking.rsadded+401 -0
@@ -0,0 +1,401 @@
1+//! A student's seat on a published [`Menu`]. One row per (menu, student),
2+//! keyed by a deterministic composite id β€” the same pair always maps to the
3+//! same record, so booking is a single atomic UPSERT with no find-then-insert
4+//! race and one-row-per-pair by construction.
5+//!
6+//! Two things are deliberate:
7+//!
8+//! - **A cancel is a status transition, not a delete.** The row stays, flipped
9+//! to `cancelled` with a `cancelled_at` stamp, so the freed seat is still
10+//! auditable against the money it moved. Only `booked` rows count against
11+//! the menu's capacity, which is what makes the seat genuinely free again β€”
12+//! and re-booking is the same UPSERT flipping it back.
13+//! - **The capacity check runs under [`MENU_LOCK`]**, the lock that already
14+//! serializes everything counting rows against one menu. Count-then-write is
15+//! write-skew: SurrealDB's transactions do not conflict-check a cross-record
16+//! count against a concurrent insert, so an unlocked check over-admits.
17+//! - **The seat and its money move together, inside that lock.** Booking
18+//! charges and cancelling reverses right here, not in the web layer after the
19+//! lock was dropped β€” a seam between the two let concurrent `POST`s bill one
20+//! seat twice. The lock stays a *leaf*: nothing below it takes another.
21+
22+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
23+
24+use crate::constant::MEAL_BOOKING_TABLE;
25+use crate::database::Database;
26+use crate::domain::meal_ledger::{LedgerAmount, MealLedger};
27+use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId};
28+use crate::domain::timestamp::Timestamp;
29+use crate::domain::user::UserId;
30+use crate::error::AppError;
31+
32+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
33+pub struct MealBookingId(RecordId);
34+
35+impl MealBookingId {
36+ /// A deterministic id for the (menu, student) pair β€” same trick as
37+ /// `EnrollmentId`. ULID keys are alphanumeric, so `_` is an unambiguous
38+ /// joiner.
39+ pub fn composite(menu: &MenuId, student: &UserId) -> Self {
40+ Self(RecordId::new(
41+ MEAL_BOOKING_TABLE,
42+ format!("{}_{}", menu.key(), student.key()),
43+ ))
44+ }
45+
46+ pub fn from_key(key: &str) -> Self {
47+ Self(RecordId::new(MEAL_BOOKING_TABLE, key))
48+ }
49+
50+ pub fn record(&self) -> RecordId {
51+ self.0.clone()
52+ }
53+
54+ pub fn key(&self) -> &str {
55+ match &self.0.key {
56+ RecordIdKey::String(key) => key,
57+ _ => "",
58+ }
59+ }
60+}
61+
62+/// Where a booking stands. `untagged` + `rename_all` store it as the bare
63+/// lowercase string the `status` column types as, exactly like
64+/// [`AppointmentStatus`](crate::domain::appointment::AppointmentStatus).
65+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
66+#[surreal(untagged, rename_all = "lowercase")]
67+pub enum MealBookingStatus {
68+ Booked,
69+ Cancelled,
70+}
71+
72+impl MealBookingStatus {
73+ /// The wire/storage form. Must stay in lockstep with `rename_all`.
74+ pub fn as_str(self) -> &'static str {
75+ match self {
76+ MealBookingStatus::Booked => "booked",
77+ MealBookingStatus::Cancelled => "cancelled",
78+ }
79+ }
80+}
81+
82+#[derive(Debug, Clone, SurrealValue)]
83+pub struct MealBooking {
84+ id: MealBookingId,
85+ menu: MenuId,
86+ student: UserId,
87+ booked_by: UserId,
88+ status: MealBookingStatus,
89+ /// How many times this seat has been taken: 1 on the first booking, +1 on
90+ /// every revival after a cancel. It is the *attempt* half of the ledger's
91+ /// idempotence key, so a re-book bills afresh while a repeat `POST` of a
92+ /// seat already held bills nothing.
93+ attempt: i64,
94+ /// What the menu cost when the current attempt took the seat; `None` means
95+ /// it was free *then*. Recorded rather than inferred: without it, "the menu
96+ /// was free" is indistinguishable from "not billed yet", and a dish added
97+ /// afterwards bills a seat that was free when taken.
98+ price_minor: Option<LedgerAmount>,
99+ cancelled_at: Option<Timestamp>,
100+ created_at: Timestamp,
101+}
102+
103+impl MealBooking {
104+ pub fn get_id(&self) -> &MealBookingId {
105+ &self.id
106+ }
107+
108+ pub fn get_menu(&self) -> &MenuId {
109+ &self.menu
110+ }
111+
112+ pub fn get_student(&self) -> &UserId {
113+ &self.student
114+ }
115+
116+ pub fn get_booked_by(&self) -> &UserId {
117+ &self.booked_by
118+ }
119+
120+ pub fn get_status(&self) -> MealBookingStatus {
121+ self.status
122+ }
123+
124+ pub fn get_attempt(&self) -> i64 {
125+ self.attempt
126+ }
127+
128+ pub fn get_price_minor(&self) -> Option<LedgerAmount> {
129+ self.price_minor
130+ }
131+
132+ pub fn get_cancelled_at(&self) -> Option<Timestamp> {
133+ self.cancelled_at
134+ }
135+
136+ pub fn get_created_at(&self) -> Timestamp {
137+ self.created_at
138+ }
139+
140+ /// Book (idempotently) `student` onto `menu` **and bill the seat**. Already
141+ /// booked is returned as-is; a cancelled row is revived by the same UPSERT,
142+ /// as a fresh attempt at the current `price`. When the menu carries a
143+ /// capacity, a full one refuses new seats (409) β€” the whole
144+ /// check-then-write runs under [`MENU_LOCK`], and the cap is re-derived
145+ /// from a fresh menu read inside it, since neither the transaction model
146+ /// nor a caller-supplied menu survives a concurrent capacity PATCH.
147+ ///
148+ /// The price is snapshotted **inside that same lock**, not handed in by the
149+ /// web layer: dish writes take the lock too, so the sum frozen onto the row
150+ /// is the menu as it stood the instant the seat was taken. Snapshotted
151+ /// outside it, a dish landing in the gap was stored as `None` = "was free
152+ /// then" β€” and no repeat `POST` ever heals that, since a held seat is
153+ /// returned as-is.
154+ ///
155+ /// The charge is appended inside the lock too, keyed by (seat, attempt):
156+ /// eight concurrent `POST`s of one seat hold one seat and write one charge
157+ /// line. The price is `None` when the menu is free, and that `None` is
158+ /// stored, so a dish added later never bills a seat retroactively.
159+ ///
160+ /// `cutoff_minutes` is the school's one meal cutoff (`None` = none): once
161+ /// the meal's day is that close, the seat is fixed either way.
162+ pub async fn book(
163+ menu: &MenuId,
164+ student: &UserId,
165+ booked_by: &UserId,
166+ cutoff_minutes: Option<i64>,
167+ db: &Database,
168+ ) -> Result<MealBooking, AppError> {
169+ let _guard = MENU_LOCK.lock().await;
170+ let fresh = Menu::read(menu, db).await?.ok_or(AppError::NotFound)?;
171+ check_cutoff(fresh.get_date(), cutoff_minutes)?;
172+ // Before the seat: an unchargeable menu (dishes summing past the cap)
173+ // must refuse the booking outright, never leave a booked-but-unbilled
174+ // row behind.
175+ let price = MealLedger::price_snapshot(menu, db).await?;
176+ let id = MealBookingId::composite(menu, student);
177+ let existing: Option<MealBooking> = db.select(id.record()).await?;
178+ let booking = match existing {
179+ // The seat is already held: same attempt, same price it was taken
180+ // at. Today's menu price bills nobody who booked yesterday's.
181+ Some(held) if held.status == MealBookingStatus::Booked => held,
182+ existing => {
183+ if let Some(capacity) = fresh.get_capacity()
184+ && Self::list_live_for_menu(menu, db).await?.len() as i64 >= capacity
185+ {
186+ return Err(AppError::Conflict("the menu is fully booked"));
187+ }
188+ let booking = MealBooking {
189+ id,
190+ menu: menu.clone(),
191+ student: student.clone(),
192+ // `booked_by` and `created_at` are READONLY columns: a
193+ // revived row keeps whoever opened the seat, and when.
194+ booked_by: existing
195+ .as_ref()
196+ .map_or_else(|| booked_by.clone(), |row| row.booked_by.clone()),
197+ status: MealBookingStatus::Booked,
198+ attempt: existing.as_ref().map_or(1, |row| row.attempt + 1),
199+ price_minor: price,
200+ cancelled_at: None,
201+ created_at: existing
202+ .as_ref()
203+ .map_or_else(Timestamp::now, |row| row.created_at),
204+ };
205+ let saved: Option<MealBooking> =
206+ db.upsert(booking.id.record()).content(booking).await?;
207+ saved.ok_or_else(|| AppError::Internal("failed to book the meal".into()))?
208+ }
209+ };
210+ // Writes nothing when this attempt is already billed, so the repeat
211+ // POST above costs nothing and a charge that failed once self-heals.
212+ MealLedger::charge_booking(&booking, booked_by, db).await?;
213+ Ok(booking)
214+ }
215+
216+ /// Free the seat: flip to `cancelled`, stamp the moment, **and give the
217+ /// money back**. Refused (409) only once the cutoff has passed.
218+ ///
219+ /// Under [`MENU_LOCK`] like [`Self::book`], and the row is re-read inside
220+ /// it: the caller's copy may predate a concurrent re-book, and cancelling a
221+ /// stale attempt would strand that attempt's charge forever. The reversal
222+ /// is keyed to the attempt, so a retried cancel refunds exactly once.
223+ ///
224+ /// **Idempotent, and that is what makes the refund recoverable.** The flip
225+ /// and the reversal are two writes; a handler future dropped between them
226+ /// (the client closed the tab, a proxy timed out) or a `create` that errors
227+ /// leaves the seat free and the charge standing. Refusing an
228+ /// already-cancelled row β€” as this used to β€” made that state permanent:
229+ /// no route on the API could ever append the missing reversal. So a
230+ /// cancelled row replays the reversal instead, which either heals the gap
231+ /// or writes nothing at all. The cutoff is not re-checked on that path: the
232+ /// seat is already given back, and refusing to finish the refund because
233+ /// the meal has since closed would strand the money exactly as before.
234+ pub async fn cancel(
235+ self,
236+ cutoff_minutes: Option<i64>,
237+ recorded_by: &UserId,
238+ db: &Database,
239+ ) -> Result<MealBooking, AppError> {
240+ let _guard = MENU_LOCK.lock().await;
241+ let fresh = Self::read(&self.id, db).await?.ok_or(AppError::NotFound)?;
242+ if fresh.status == MealBookingStatus::Cancelled {
243+ MealLedger::reverse_booking(&fresh, recorded_by, db).await?;
244+ return Ok(fresh);
245+ }
246+ let menu = Menu::read(&fresh.menu, db)
247+ .await?
248+ .ok_or(AppError::NotFound)?;
249+ check_cutoff(menu.get_date(), cutoff_minutes)?;
250+ let cancelled = MealBooking {
251+ status: MealBookingStatus::Cancelled,
252+ cancelled_at: Some(Timestamp::now()),
253+ ..fresh
254+ };
255+ let saved: Option<MealBooking> =
256+ db.upsert(cancelled.id.record()).content(cancelled).await?;
257+ let saved =
258+ saved.ok_or_else(|| AppError::Internal("failed to cancel the booking".into()))?;
259+ MealLedger::reverse_booking(&saved, recorded_by, db).await?;
260+ Ok(saved)
261+ }
262+
263+ pub async fn read(id: &MealBookingId, db: &Database) -> Result<Option<MealBooking>, AppError> {
264+ Ok(db.select(id.record()).await?)
265+ }
266+
267+ /// Every booking on a menu, cancelled ones included β€” the kitchen's list.
268+ pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result<Vec<MealBooking>, AppError> {
269+ let mut result = db
270+ .query(
271+ "SELECT * FROM meal_booking WHERE menu = $menu \
272+ ORDER BY created_at DESC, id DESC",
273+ )
274+ .bind(("menu", menu.record()))
275+ .await?
276+ .check()?;
277+ Ok(result.take::<Vec<MealBooking>>(0)?)
278+ }
279+
280+ /// The seats actually held β€” the capacity count.
281+ pub async fn list_live_for_menu(
282+ menu: &MenuId,
283+ db: &Database,
284+ ) -> Result<Vec<MealBooking>, AppError> {
285+ let mut result = db
286+ .query("SELECT * FROM meal_booking WHERE menu = $menu AND status = 'booked'")
287+ .bind(("menu", menu.record()))
288+ .await?
289+ .check()?;
290+ Ok(result.take::<Vec<MealBooking>>(0)?)
291+ }
292+
293+ /// True iff a seat on the menu is still held β€” the menu delete guard.
294+ /// Callers hold [`MENU_LOCK`] so a booking cannot slip in behind it.
295+ pub async fn any_live_for_menu(menu: &MenuId, db: &Database) -> Result<bool, AppError> {
296+ let mut result = db
297+ .query(
298+ "SELECT VALUE id FROM meal_booking \
299+ WHERE menu = $menu AND status = 'booked' LIMIT 1",
300+ )
301+ .bind(("menu", menu.record()))
302+ .await?
303+ .check()?;
304+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
305+ }
306+
307+ /// Every seat held for one of `students`, newest first β€” a caller's own
308+ /// list is themselves plus whoever they hold a *live* parent link to.
309+ ///
310+ /// Deliberately **not** `booked_by = $usr`: who placed a booking is history
311+ /// written onto a READONLY column, and history is not a read grant. A
312+ /// parent whose link was revoked (by an unlink or by the student-side role
313+ /// sweep) would otherwise keep a live view of the child's seat, watching
314+ /// cancellations made long after the link died β€” exactly what
315+ /// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The
316+ /// caller re-derives the list from the links on every read, so the view
317+ /// dies with the link.
318+ pub async fn list_for_students(
319+ students: &[UserId],
320+ db: &Database,
321+ ) -> Result<Vec<MealBooking>, AppError> {
322+ let mut result = db
323+ .query(
324+ "SELECT * FROM meal_booking WHERE student IN $students \
325+ ORDER BY created_at DESC, id DESC",
326+ )
327+ .bind((
328+ "students",
329+ students.iter().map(UserId::record).collect::<Vec<_>>(),
330+ ))
331+ .await?
332+ .check()?;
333+ Ok(result.take::<Vec<MealBooking>>(0)?)
334+ }
335+}
336+
337+/// The meal's day as an instant: **midnight UTC starting that day**. `date` is
338+/// text with no timezone (see [`MenuDate`]), and the backend stores no school
339+/// timezone, so the start of the UTC day is the only instant derivable from it.
340+/// A school wanting "two hours before lunch" sets the cutoff relative to that.
341+// ponytail: exact β€” needs a school timezone + a per-slot serving time, neither
342+// of which the settings singleton carries yet.
343+fn day_starts_at(date: &MenuDate) -> Option<Timestamp> {
344+ let day = chrono::NaiveDate::parse_from_str(date.as_str(), "%Y-%m-%d").ok()?;
345+ Some(Timestamp::from_millis(
346+ day.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis(),
347+ ))
348+}
349+
350+/// Booking and cancelling both close `cutoff_minutes` before the meal's day
351+/// starts. `None` = the school set no cutoff, so neither ever closes.
352+fn check_cutoff(date: &MenuDate, cutoff_minutes: Option<i64>) -> Result<(), AppError> {
353+ let (Some(cutoff), Some(start)) = (cutoff_minutes, day_starts_at(date)) else {
354+ return Ok(());
355+ };
356+ let deadline = start
357+ .as_millis()
358+ .saturating_sub(cutoff.saturating_mul(60_000));
359+ if Timestamp::now().as_millis() >= deadline {
360+ return Err(AppError::Conflict("the menu's booking cutoff has passed"));
361+ }
362+ Ok(())
363+}
364+
365+#[cfg(test)]
366+mod tests {
367+ use surrealdb::types::SurrealValue as _;
368+ use surrealdb::types::Value;
369+
370+ use super::*;
371+
372+ /// The `status` column is `TYPE string`: an object-wrapped enum would be
373+ /// rejected on write, and the `status = 'booked'` capacity count would
374+ /// silently match nothing.
375+ #[test]
376+ fn status_stores_as_a_bare_string() {
377+ for status in [MealBookingStatus::Booked, MealBookingStatus::Cancelled] {
378+ let value = status.into_value();
379+ assert_eq!(value, Value::String(status.as_str().to_string()));
380+ assert_eq!(MealBookingStatus::from_value(value).unwrap(), status);
381+ }
382+ }
383+
384+ #[test]
385+ fn cutoff_closes_only_within_the_window() {
386+ let far = MenuDate::try_new("2999-01-01").unwrap();
387+ let past = MenuDate::try_new("2000-01-01").unwrap();
388+ // No cutoff configured: nothing ever closes, not even a past day.
389+ assert!(check_cutoff(&past, None).is_ok());
390+ // A day far ahead is open; one long gone is shut.
391+ assert!(check_cutoff(&far, Some(60)).is_ok());
392+ assert!(check_cutoff(&past, Some(60)).is_err());
393+ // The cutoff is measured back from midnight UTC of the meal's day.
394+ assert_eq!(
395+ day_starts_at(&MenuDate::try_new("1970-01-02").unwrap())
396+ .unwrap()
397+ .as_millis(),
398+ 86_400_000
399+ );
400+ }
401+}
src/domain/meal_ledger.rsadded+496 -0
@@ -0,0 +1,496 @@
1+//! The food program's money: an **append-only** ledger of what a student was
2+//! charged and what they paid.
3+//!
4+//! Nothing here ever `UPDATE`s or `DELETE`s a row, and no such path exists β€”
5+//! every field is `READONLY` in the schema as well. A ledger line that can be
6+//! edited or dropped silently rewrites a student's financial history with no
7+//! trace of the rewrite; a mistake is corrected by appending the opposing
8+//! line, which leaves both the mistake and the correction visible.
9+//!
10+//! **The balance is never stored.** It is always the fold
11+//!
12+//! ```text
13+//! balance = SUM(credit) + SUM(reversal) - SUM(charge)
14+//! ```
15+//!
16+//! so a *negative* balance means the student owes the school, and a positive
17+//! one is money on account. Every amount on a row is stored positive; the sign
18+//! lives in the `kind`, so a line's meaning never depends on how it was read.
19+//!
20+//! Three more rules the code depends on:
21+//!
22+//! - **Booking is the charge trigger, at a price snapshot.** The menu's dishes
23+//! are summed when the seat is taken and that number is frozen onto the
24+//! *booking row*. Editing a dish's price afterwards moves no existing charge
25+//! β€” what a student owes is what the menu cost the day they booked β€” and a
26+//! seat taken while the menu was free stays free, because "free" is recorded
27+//! on the row rather than inferred from the absence of a charge.
28+//! - **A cancel appends a `reversal`**, for the charge's exact amount, with
29+//! `source` pointing at the charge it undoes. The charge row stays. Booking
30+//! again after a cancel is a *fresh* charge at the then-current price.
31+//! - **Every booking line is keyed by `(booking, attempt)`.** Both the charge
32+//! and its reversal derive their record id from the seat and the attempt
33+//! number, so replaying either writes nothing at all. Money must never
34+//! depend on a "has this been billed yet?" scan: two concurrent `POST`s of
35+//! one seat can both read "no charge yet" and both append, which is how a
36+//! double-click used to bill a seat twice.
37+//! - **A no-show still pays.** Meal attendance has zero billing effect β€”
38+//! nothing in this file reads or writes it. Do not add a no-show penalty
39+//! here: the seat was reserved and the food was cooked.
40+//!
41+//! Money is `i64` minor units (kuruş) end to end. No float, no decimal, ever.
42+
43+use std::sync::LazyLock;
44+
45+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
46+use ulid::Generator;
47+
48+use crate::constant::{
49+ MAX_LEDGER_AMOUNT_MINOR, MAX_LEDGER_METHOD_LEN, MAX_LEDGER_NOTE_LEN, MEAL_LEDGER_TABLE,
50+};
51+use crate::database::Database;
52+use crate::domain::meal_booking::{MealBooking, MealBookingId};
53+use crate::domain::menu::MenuId;
54+use crate::domain::menu_dish::MenuDish;
55+use crate::domain::timestamp::Timestamp;
56+use crate::domain::user::UserId;
57+use crate::error::{AppError, ValidationError};
58+use crate::validate::validate_optional;
59+
60+/// Mints ledger ids in write order β€” `Ulid::new()`'s random low bits sort
61+/// arbitrarily within one millisecond, which would scramble the `id` tie-break
62+/// of the newest-first statement below.
63+static IDS: LazyLock<std::sync::Mutex<Generator>> =
64+ LazyLock::new(|| std::sync::Mutex::new(Generator::new()));
65+
66+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
67+pub struct MealLedgerId(RecordId);
68+
69+impl MealLedgerId {
70+ pub fn generate() -> Self {
71+ let mut ids = IDS.lock().expect("meal ledger id generator poisoned");
72+ // The only error is exhausting the random bits within one millisecond
73+ // (2^80 ids deep); it clears itself as the clock ticks, so retry.
74+ let ulid = loop {
75+ if let Ok(ulid) = ids.generate() {
76+ break ulid;
77+ }
78+ };
79+ Self(RecordId::new(MEAL_LEDGER_TABLE, ulid.to_string()))
80+ }
81+
82+ /// The one line a booking attempt may ever write of this `kind` β€” a
83+ /// deterministic id, exactly like [`MealBookingId::composite`]. Two racing
84+ /// `POST`s of one seat derive the *same* id and so cannot become two
85+ /// charges: idempotence rests on identity, never on a scan that a
86+ /// concurrent writer can slip past. The `attempt` counter is what keeps a
87+ /// re-book after a cancel a genuinely fresh charge. Booking keys are
88+ /// `<ulid>_<ulid>`, so the `c`/`r` marker keeps the two kinds apart.
89+ pub fn for_attempt(booking: &MealBookingId, attempt: i64, kind: MealLedgerKind) -> Self {
90+ let marker = match kind {
91+ MealLedgerKind::Charge => 'c',
92+ MealLedgerKind::Reversal => 'r',
93+ // A credit is money arriving out of the blue, tied to no booking.
94+ MealLedgerKind::Credit => 'k',
95+ };
96+ Self(RecordId::new(
97+ MEAL_LEDGER_TABLE,
98+ format!("{}_{marker}{attempt}", booking.key()),
99+ ))
100+ }
101+
102+ pub fn record(&self) -> RecordId {
103+ self.0.clone()
104+ }
105+
106+ pub fn key(&self) -> &str {
107+ key_of(&self.0)
108+ }
109+}
110+
111+/// The bare key of a record id β€” how every id leaves this API.
112+fn key_of(record: &RecordId) -> &str {
113+ match &record.key {
114+ RecordIdKey::String(key) => key,
115+ _ => "",
116+ }
117+}
118+
119+/// What a line means. `untagged` + `rename_all` store it as the bare lowercase
120+/// string the `kind` column types as, in lockstep with `MEAL_LEDGER_KINDS`.
121+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
122+#[surreal(untagged, rename_all = "lowercase")]
123+pub enum MealLedgerKind {
124+ Charge,
125+ Credit,
126+ Reversal,
127+}
128+
129+impl MealLedgerKind {
130+ /// The wire/storage form. Must stay in lockstep with `rename_all`.
131+ pub fn as_str(self) -> &'static str {
132+ match self {
133+ MealLedgerKind::Charge => "charge",
134+ MealLedgerKind::Credit => "credit",
135+ MealLedgerKind::Reversal => "reversal",
136+ }
137+ }
138+
139+ /// How the line folds into the balance: a charge is the only thing that
140+ /// takes money away. This is the *single* place the sign convention lives.
141+ fn sign(self) -> i64 {
142+ match self {
143+ MealLedgerKind::Charge => -1,
144+ MealLedgerKind::Credit | MealLedgerKind::Reversal => 1,
145+ }
146+ }
147+}
148+
149+/// One line's amount, always positive β€” the sign is the [`MealLedgerKind`]'s
150+/// business. Capped so a slipped keystroke cannot book a fortune.
151+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
152+pub struct LedgerAmount(i64);
153+
154+impl LedgerAmount {
155+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
156+ if !(1..=MAX_LEDGER_AMOUNT_MINOR).contains(&value) {
157+ return Err(ValidationError::Invalid {
158+ field: "amount_minor",
159+ reason: "must be between 1 and 10000000 minor units",
160+ });
161+ }
162+ Ok(Self(value))
163+ }
164+
165+ pub fn as_minor(self) -> i64 {
166+ self.0
167+ }
168+}
169+
170+/// How the money arrived ("cash", "havale", …). Free text: the backend never
171+/// speaks to a payment gateway and stores no card data, ever.
172+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
173+pub struct LedgerMethod(String);
174+
175+impl LedgerMethod {
176+ pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> {
177+ let value = value.trim();
178+ validate_optional("method", value, MAX_LEDGER_METHOD_LEN)?;
179+ Ok((!value.is_empty()).then(|| Self(value.to_string())))
180+ }
181+
182+ pub fn as_str(&self) -> &str {
183+ &self.0
184+ }
185+}
186+
187+/// The bookkeeper's own words about a line β€” a receipt number, whose envelope
188+/// it came in.
189+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
190+pub struct LedgerNote(String);
191+
192+impl LedgerNote {
193+ pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> {
194+ let value = value.trim();
195+ validate_optional("note", value, MAX_LEDGER_NOTE_LEN)?;
196+ Ok((!value.is_empty()).then(|| Self(value.to_string())))
197+ }
198+
199+ pub fn as_str(&self) -> &str {
200+ &self.0
201+ }
202+}
203+
204+#[derive(Debug, Clone, SurrealValue)]
205+pub struct MealLedger {
206+ id: MealLedgerId,
207+ student: UserId,
208+ kind: MealLedgerKind,
209+ amount_minor: LedgerAmount,
210+ /// What caused the line: a charge points at its `meal_booking`, a reversal
211+ /// at the `meal_ledger` charge it undoes. Untyped, hence a bare `RecordId`.
212+ source: Option<RecordId>,
213+ method: Option<LedgerMethod>,
214+ note: Option<LedgerNote>,
215+ recorded_by: UserId,
216+ created_at: Timestamp,
217+}
218+
219+impl MealLedger {
220+ pub fn get_id(&self) -> &MealLedgerId {
221+ &self.id
222+ }
223+
224+ pub fn get_student(&self) -> &UserId {
225+ &self.student
226+ }
227+
228+ pub fn get_kind(&self) -> MealLedgerKind {
229+ self.kind
230+ }
231+
232+ pub fn get_amount_minor(&self) -> LedgerAmount {
233+ self.amount_minor
234+ }
235+
236+ /// The cause's bare key; which table it lives in follows from the kind.
237+ pub fn get_source_key(&self) -> Option<&str> {
238+ self.source.as_ref().map(key_of)
239+ }
240+
241+ pub fn get_method(&self) -> Option<&LedgerMethod> {
242+ self.method.as_ref()
243+ }
244+
245+ pub fn get_note(&self) -> Option<&LedgerNote> {
246+ self.note.as_ref()
247+ }
248+
249+ pub fn get_recorded_by(&self) -> &UserId {
250+ &self.recorded_by
251+ }
252+
253+ pub fn get_created_at(&self) -> Timestamp {
254+ self.created_at
255+ }
256+
257+ /// The only writer: one `CREATE`, no update path anywhere in this module.
258+ ///
259+ /// A line whose id already exists is left exactly as it is β€” the row wins,
260+ /// the write is dropped. That is what makes a deterministic id (see
261+ /// [`MealLedgerId::for_attempt`]) an idempotence key: replaying the same
262+ /// append is a no-op, never a second line and never an edit of the first.
263+ /// The point read is on the id itself, so unlike a scan it cannot miss a
264+ /// row a concurrent writer just made.
265+ async fn append(row: MealLedger, db: &Database) -> Result<MealLedger, AppError> {
266+ if let Some(existing) = Self::read(&row.id, db).await? {
267+ return Ok(existing);
268+ }
269+ let created: Option<MealLedger> = db.create(row.id.record()).content(row).await?;
270+ created.ok_or_else(|| AppError::Internal("failed to write the ledger line".into()))
271+ }
272+
273+ pub async fn read(id: &MealLedgerId, db: &Database) -> Result<Option<MealLedger>, AppError> {
274+ Ok(db.select(id.record()).await?)
275+ }
276+
277+ /// What a seat on `menu` costs *right now*: the sum of its dishes. `None`
278+ /// when the menu is free (or empty) β€” a zero line is noise, not history.
279+ ///
280+ /// Called before the seat is taken so an unchargeable menu (one summing
281+ /// past `MAX_LEDGER_AMOUNT_MINOR`) refuses the booking outright instead of
282+ /// leaving a booked-but-unbilled row behind.
283+ pub async fn price_snapshot(
284+ menu: &MenuId,
285+ db: &Database,
286+ ) -> Result<Option<LedgerAmount>, AppError> {
287+ let total = MenuDish::list_for_menu(menu, db)
288+ .await?
289+ .iter()
290+ .fold(0i64, |sum, dish| {
291+ sum.saturating_add(dish.get_price_minor().as_minor())
292+ });
293+ if total == 0 {
294+ return Ok(None);
295+ }
296+ Ok(Some(LedgerAmount::try_new(total)?))
297+ }
298+
299+ /// Bill `booking`'s current attempt at the price frozen onto it when that
300+ /// attempt took the seat.
301+ ///
302+ /// The price comes off the *booking row*, never off the menu as it stands
303+ /// now: a seat taken while the menu was free carries `None` forever, so
304+ /// "was free" is a recorded fact and a later dish never bills a seat
305+ /// retroactively. Called under
306+ /// [`MENU_LOCK`](crate::domain::menu::MENU_LOCK), from
307+ /// [`MealBooking::book`] alone, so the seat and its money move together.
308+ ///
309+ /// Replaying it is free: the id is `(booking, attempt)`, so a duplicate
310+ /// `POST` writes nothing, and an attempt whose charge failed the first time
311+ /// self-heals on the next `POST` of the same seat.
312+ pub async fn charge_booking(
313+ booking: &MealBooking,
314+ recorded_by: &UserId,
315+ db: &Database,
316+ ) -> Result<(), AppError> {
317+ let Some(amount) = booking.get_price_minor() else {
318+ return Ok(());
319+ };
320+ Self::append(
321+ MealLedger {
322+ id: MealLedgerId::for_attempt(
323+ booking.get_id(),
324+ booking.get_attempt(),
325+ MealLedgerKind::Charge,
326+ ),
327+ student: booking.get_student().clone(),
328+ kind: MealLedgerKind::Charge,
329+ amount_minor: amount,
330+ source: Some(booking.get_id().record()),
331+ method: None,
332+ note: None,
333+ recorded_by: recorded_by.clone(),
334+ created_at: Timestamp::now(),
335+ },
336+ db,
337+ )
338+ .await?;
339+ Ok(())
340+ }
341+
342+ /// Give the money back for a cancelled `booking`: a new `reversal` line for
343+ /// the charge's exact amount, pointing at it. The charge is never touched.
344+ /// A booking that was never billed (a free menu) reverses nothing, and
345+ /// neither does one whose charge never landed β€” the reversal is keyed to
346+ /// the very charge it undoes, so it can only exist alongside it.
347+ ///
348+ /// Keyed by `(booking, attempt)` like the charge, so a retried cancel
349+ /// refunds once. A cancel cut short between the status flip and this
350+ /// reversal is recovered by repeating the cancel β€” which is precisely why
351+ /// [`MealBooking::cancel`] replays this on an already-cancelled row instead
352+ /// of refusing it. Nothing else on the API can append the missing line.
353+ pub async fn reverse_booking(
354+ booking: &MealBooking,
355+ recorded_by: &UserId,
356+ db: &Database,
357+ ) -> Result<(), AppError> {
358+ let Some(amount) = booking.get_price_minor() else {
359+ return Ok(());
360+ };
361+ let charge = MealLedgerId::for_attempt(
362+ booking.get_id(),
363+ booking.get_attempt(),
364+ MealLedgerKind::Charge,
365+ );
366+ if Self::read(&charge, db).await?.is_none() {
367+ return Ok(());
368+ }
369+ Self::append(
370+ MealLedger {
371+ id: MealLedgerId::for_attempt(
372+ booking.get_id(),
373+ booking.get_attempt(),
374+ MealLedgerKind::Reversal,
375+ ),
376+ student: booking.get_student().clone(),
377+ kind: MealLedgerKind::Reversal,
378+ amount_minor: amount,
379+ source: Some(charge.record()),
380+ method: None,
381+ note: None,
382+ recorded_by: recorded_by.clone(),
383+ created_at: Timestamp::now(),
384+ },
385+ db,
386+ )
387+ .await?;
388+ Ok(())
389+ }
390+
391+ /// Money in: a payment received, or an opening balance.
392+ pub async fn credit(
393+ student: &UserId,
394+ amount_minor: LedgerAmount,
395+ method: Option<LedgerMethod>,
396+ note: Option<LedgerNote>,
397+ recorded_by: &UserId,
398+ db: &Database,
399+ ) -> Result<MealLedger, AppError> {
400+ Self::append(
401+ MealLedger {
402+ id: MealLedgerId::generate(),
403+ student: student.clone(),
404+ kind: MealLedgerKind::Credit,
405+ amount_minor,
406+ source: None,
407+ method,
408+ note,
409+ recorded_by: recorded_by.clone(),
410+ created_at: Timestamp::now(),
411+ },
412+ db,
413+ )
414+ .await
415+ }
416+
417+ /// A student's whole statement, newest first.
418+ pub async fn list_for_student(
419+ student: &UserId,
420+ db: &Database,
421+ ) -> Result<Vec<MealLedger>, AppError> {
422+ let mut result = db
423+ .query(
424+ "SELECT * FROM meal_ledger WHERE student = $student \
425+ ORDER BY created_at DESC, id DESC",
426+ )
427+ .bind(("student", student.record()))
428+ .await?
429+ .check()?;
430+ Ok(result.take::<Vec<MealLedger>>(0)?)
431+ }
432+
433+ /// The derived balance: `credits + reversals - charges`, in minor units.
434+ /// Negative means the student owes the school. Never stored anywhere.
435+ // ponytail: folds the student's lines in-process (a few hundred a year);
436+ // push it into a `math::sum` aggregate if a statement ever gets long.
437+ pub async fn balance_of(student: &UserId, db: &Database) -> Result<i64, AppError> {
438+ Ok(Self::list_for_student(student, db)
439+ .await?
440+ .iter()
441+ .fold(0i64, |sum, line| {
442+ sum + line.kind.sign() * line.amount_minor.as_minor()
443+ }))
444+ }
445+}
446+
447+#[cfg(test)]
448+mod tests {
449+ use surrealdb::types::SurrealValue as _;
450+ use surrealdb::types::Value;
451+
452+ use super::*;
453+
454+ /// The `kind` column is `TYPE string`: an object-wrapped enum would be
455+ /// rejected on write, and the `kind = 'charge'` lookup would silently
456+ /// match nothing β€” which would double-charge every re-booking.
457+ #[test]
458+ fn kind_stores_as_a_bare_string() {
459+ for kind in [
460+ MealLedgerKind::Charge,
461+ MealLedgerKind::Credit,
462+ MealLedgerKind::Reversal,
463+ ] {
464+ let value = kind.into_value();
465+ assert_eq!(value, Value::String(kind.as_str().to_string()));
466+ assert_eq!(MealLedgerKind::from_value(value).unwrap(), kind);
467+ }
468+ }
469+
470+ /// The one fold: a charge subtracts, a credit and a reversal add. A booked
471+ /// meal that was cancelled nets to exactly zero, never to a rounding scrap.
472+ #[test]
473+ fn the_balance_fold_is_credit_plus_reversal_minus_charge() {
474+ assert_eq!(MealLedgerKind::Charge.sign(), -1);
475+ assert_eq!(MealLedgerKind::Credit.sign(), 1);
476+ assert_eq!(MealLedgerKind::Reversal.sign(), 1);
477+ let lines = [
478+ (MealLedgerKind::Credit, 10_000),
479+ (MealLedgerKind::Charge, 4_500),
480+ (MealLedgerKind::Reversal, 4_500),
481+ ];
482+ let balance: i64 = lines
483+ .iter()
484+ .map(|(kind, amount)| kind.sign() * amount)
485+ .sum();
486+ assert_eq!(balance, 10_000);
487+ }
488+
489+ #[test]
490+ fn an_amount_is_positive_and_capped() {
491+ assert!(LedgerAmount::try_new(0).is_err());
492+ assert!(LedgerAmount::try_new(-1).is_err());
493+ assert!(LedgerAmount::try_new(MAX_LEDGER_AMOUNT_MINOR + 1).is_err());
494+ assert_eq!(LedgerAmount::try_new(1).unwrap().as_minor(), 1);
495+ }
496+}
src/domain/menu.rsadded+330 -0
@@ -0,0 +1,330 @@
1+//! A published menu: what the kitchen serves on one calendar day in one meal
2+//! slot. Dishes hang off it ([`MenuDish`](crate::domain::menu_dish::MenuDish)),
3+//! and bookings will hang off its `capacity`.
4+//!
5+//! Two things are deliberate:
6+//!
7+//! - **`date` is text** (`YYYY-MM-DD`), not a timestamp. The uniqueness rule is
8+//! "one menu per day and slot", an equality test β€” and a midnight-in-millis
9+//! day is only one school's day.
10+//! - **`slot` is a snapshot**, not a link into settings. Retiring a slot must
11+//! never rewrite a menu already published under it.
12+
13+use std::sync::LazyLock;
14+
15+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16+use tokio::sync::Mutex;
17+use ulid::Generator;
18+
19+use crate::constant::{MAX_MENU_CAPACITY, MENU_TABLE};
20+use crate::database::Database;
21+use crate::domain::field_update::FieldUpdate;
22+use crate::domain::menu_dish::MenuDish;
23+use crate::domain::settings::MealSlotDef;
24+use crate::domain::timestamp::Timestamp;
25+use crate::domain::user::UserId;
26+use crate::error::{AppError, ValidationError};
27+
28+/// Serializes "is there already a menu for this day and slot?" against the
29+/// publish it authorizes β€” a count-then-write pair SurrealDB does not
30+/// conflict-check, so the UNIQUE index would otherwise be the only thing
31+/// standing between two racing publishes and a 500. Also held by the settings
32+/// slot-removal guard, whose check ("was any menu published for this slot?")
33+/// is the mirror image.
34+///
35+/// Lock order: `EXAM_LOCK` (taken by the same settings write) is always taken
36+/// *before* this one; nothing here ever takes `EXAM_LOCK`, so the two cannot
37+/// deadlock.
38+pub(crate) static MENU_LOCK: Mutex<()> = Mutex::const_new(());
39+
40+/// Mints menu ids in write order β€” `Ulid::new()`'s random low bits sort
41+/// arbitrarily within one millisecond, which would scramble the `id` tie-break
42+/// of the listings below.
43+static IDS: LazyLock<std::sync::Mutex<Generator>> =
44+ LazyLock::new(|| std::sync::Mutex::new(Generator::new()));
45+
46+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
47+pub struct MenuId(RecordId);
48+
49+impl MenuId {
50+ pub fn generate() -> Self {
51+ let mut ids = IDS.lock().expect("menu id generator poisoned");
52+ // The only error is exhausting the random bits within one millisecond
53+ // (2^80 ids deep); it clears itself as the clock ticks, so retry.
54+ let ulid = loop {
55+ if let Ok(ulid) = ids.generate() {
56+ break ulid;
57+ }
58+ };
59+ Self(RecordId::new(MENU_TABLE, ulid.to_string()))
60+ }
61+
62+ pub fn from_key(key: &str) -> Self {
63+ Self(RecordId::new(MENU_TABLE, key))
64+ }
65+
66+ pub fn record(&self) -> RecordId {
67+ self.0.clone()
68+ }
69+
70+ pub fn key(&self) -> &str {
71+ match &self.0.key {
72+ RecordIdKey::String(key) => key,
73+ _ => "",
74+ }
75+ }
76+}
77+
78+/// A calendar day as `YYYY-MM-DD`. Zero-padded and fixed-width on purpose:
79+/// that makes the text sort chronologically, so the `?from=&to=` range filter
80+/// and the newest-first ordering are plain string comparisons.
81+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, SurrealValue)]
82+pub struct MenuDate(String);
83+
84+impl MenuDate {
85+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
86+ let invalid = ValidationError::Invalid {
87+ field: "date",
88+ reason: "must be a calendar day as YYYY-MM-DD",
89+ };
90+ let value = value.trim();
91+ let bytes = value.as_bytes();
92+ if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
93+ return Err(invalid);
94+ }
95+ let digits =
96+ |from: usize, to: usize| -> Option<u32> { value.get(from..to)?.parse::<u32>().ok() };
97+ let (Some(_year), Some(month), Some(day)) = (digits(0, 4), digits(5, 7), digits(8, 10))
98+ else {
99+ return Err(invalid);
100+ };
101+ // Day count per month is not checked: the calendar rules (leap years)
102+ // would be the only thing this file knows about time, and a 31st of
103+ // February menu is a typo nobody can act on, not a data hazard.
104+ if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
105+ return Err(invalid);
106+ }
107+ Ok(Self(value.to_string()))
108+ }
109+
110+ pub fn as_str(&self) -> &str {
111+ &self.0
112+ }
113+}
114+
115+/// The meal slot a menu was published for, snapshotted as text. Validated
116+/// against the school's *current* list at write time β€” that list is the only
117+/// place slot names are defined, and this is the sole funnel into the column.
118+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
119+pub struct MenuSlot(String);
120+
121+impl MenuSlot {
122+ pub fn try_new(value: &str, allowed: &[MealSlotDef]) -> Result<Self, ValidationError> {
123+ let value = value.trim();
124+ if !allowed.iter().any(|slot| slot.get_name() == value) {
125+ return Err(ValidationError::Invalid {
126+ field: "slot",
127+ reason: "not one of the school's meal slots (see GET /settings)",
128+ });
129+ }
130+ Ok(Self(value.to_string()))
131+ }
132+
133+ pub fn as_str(&self) -> &str {
134+ &self.0
135+ }
136+}
137+
138+/// How many students the menu may seat. `None` = uncapped, the shape a
139+/// course's `capacity` already uses.
140+pub fn validate_capacity(value: Option<i64>) -> Result<(), ValidationError> {
141+ match value {
142+ Some(capacity) if !(0..=MAX_MENU_CAPACITY).contains(&capacity) => {
143+ Err(ValidationError::Invalid {
144+ field: "capacity",
145+ reason: "must be between 0 and 10000",
146+ })
147+ }
148+ _ => Ok(()),
149+ }
150+}
151+
152+#[derive(Debug, Clone, SurrealValue)]
153+pub struct Menu {
154+ id: MenuId,
155+ date: MenuDate,
156+ slot: MenuSlot,
157+ capacity: Option<i64>,
158+ created_by: UserId,
159+ created_at: Timestamp,
160+}
161+
162+impl Menu {
163+ pub fn get_id(&self) -> &MenuId {
164+ &self.id
165+ }
166+
167+ pub fn get_date(&self) -> &MenuDate {
168+ &self.date
169+ }
170+
171+ pub fn get_slot(&self) -> &MenuSlot {
172+ &self.slot
173+ }
174+
175+ pub fn get_capacity(&self) -> Option<i64> {
176+ self.capacity
177+ }
178+
179+ pub fn get_created_by(&self) -> &UserId {
180+ &self.created_by
181+ }
182+
183+ pub fn get_created_at(&self) -> Timestamp {
184+ self.created_at
185+ }
186+
187+ /// Publish a menu. Refused (409) when the day+slot already carries one β€”
188+ /// re-checked under [`MENU_LOCK`], so two racing publishes cannot both find
189+ /// the day free and trip the UNIQUE index into a 500.
190+ pub async fn create(
191+ date: MenuDate,
192+ slot: MenuSlot,
193+ capacity: Option<i64>,
194+ created_by: &UserId,
195+ db: &Database,
196+ ) -> Result<Menu, AppError> {
197+ let _guard = MENU_LOCK.lock().await;
198+ if Self::find(&date, &slot, db).await?.is_some() {
199+ return Err(AppError::Conflict(
200+ "a menu is already published for that date and slot",
201+ ));
202+ }
203+ let menu = Menu {
204+ id: MenuId::generate(),
205+ date,
206+ slot,
207+ capacity,
208+ created_by: created_by.clone(),
209+ created_at: Timestamp::now(),
210+ };
211+ let created: Option<Menu> = db.create(menu.id.record()).content(menu).await?;
212+ created.ok_or_else(|| AppError::Internal("failed to publish the menu".into()))
213+ }
214+
215+ pub async fn read(id: &MenuId, db: &Database) -> Result<Option<Menu>, AppError> {
216+ Ok(db.select(id.record()).await?)
217+ }
218+
219+ /// The menu for one day and slot, if any β€” the uniqueness check.
220+ pub async fn find(
221+ date: &MenuDate,
222+ slot: &MenuSlot,
223+ db: &Database,
224+ ) -> Result<Option<Menu>, AppError> {
225+ let mut result = db
226+ .query("SELECT * FROM menu WHERE date = $date AND slot = $slot LIMIT 1")
227+ .bind(("date", date.as_str().to_string()))
228+ .bind(("slot", slot.as_str().to_string()))
229+ .await?
230+ .check()?;
231+ Ok(result.take::<Vec<Menu>>(0)?.into_iter().next())
232+ }
233+
234+ /// Menus, newest day first. `from`/`to` are inclusive `YYYY-MM-DD` bounds;
235+ /// either may be omitted. The comparison is lexical, which is chronological
236+ /// for this format.
237+ pub async fn list(
238+ from: Option<&MenuDate>,
239+ to: Option<&MenuDate>,
240+ db: &Database,
241+ ) -> Result<Vec<Menu>, AppError> {
242+ let mut result = db
243+ .query(
244+ "SELECT * FROM menu \
245+ WHERE ($from = NONE OR date >= $from) AND ($to = NONE OR date <= $to) \
246+ ORDER BY date DESC, slot ASC, id DESC",
247+ )
248+ .bind(("from", from.map(|date| date.as_str().to_string())))
249+ .bind(("to", to.map(|date| date.as_str().to_string())))
250+ .await?
251+ .check()?;
252+ Ok(result.take::<Vec<Menu>>(0)?)
253+ }
254+
255+ /// Only `capacity` is writable: `date` and `slot` are `READONLY` columns,
256+ /// because moving a published menu to another day is a different menu.
257+ /// `None` keeps the stored cap, `Some(None)` clears it back to uncapped.
258+ pub async fn update(
259+ self,
260+ capacity: Option<Option<i64>>,
261+ db: &Database,
262+ ) -> Result<Menu, AppError> {
263+ FieldUpdate::new(self.id.record())
264+ .set("capacity", capacity)
265+ .run::<Menu>(db)
266+ .await
267+ }
268+
269+ /// Whether any menu was ever published for this slot name β€” the guard
270+ /// behind removing a slot from `meal_slots`, mirroring
271+ /// [`ExamResult::any_for_kind`](crate::domain::exam_result::ExamResult::any_for_kind).
272+ /// Menus snapshot the slot as text, so this is a plain string match.
273+ /// Callers hold [`MENU_LOCK`] so a publish cannot slip in behind the check.
274+ pub async fn any_for_slot(slot: &str, db: &Database) -> Result<bool, AppError> {
275+ let mut result = db
276+ .query("SELECT VALUE id FROM menu WHERE slot = $slot LIMIT 1")
277+ .bind(("slot", slot.to_string()))
278+ .await?
279+ .check()?;
280+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
281+ }
282+
283+ /// Delete the menu and the dishes on it β€” a dish has no meaning without
284+ /// its menu, and the `menu` link is `READONLY`, so it cannot be re-homed.
285+ pub async fn delete(self, db: &Database) -> Result<Menu, AppError> {
286+ MenuDish::delete_for_menu(&self.id, db).await?;
287+ let deleted: Option<Menu> = db.delete(self.id.record()).await?;
288+ deleted.ok_or(AppError::NotFound)
289+ }
290+}
291+
292+#[cfg(test)]
293+mod tests {
294+ use super::*;
295+
296+ #[test]
297+ fn date_accepts_only_padded_calendar_days() {
298+ assert!(MenuDate::try_new("2026-07-26").is_ok());
299+ assert!(MenuDate::try_new("2026-7-26").is_err());
300+ assert!(MenuDate::try_new("2026-13-01").is_err());
301+ assert!(MenuDate::try_new("2026-00-01").is_err());
302+ assert!(MenuDate::try_new("2026-01-32").is_err());
303+ assert!(MenuDate::try_new("26-01-02").is_err());
304+ assert!(MenuDate::try_new("").is_err());
305+ // Sorting the text must sort the calendar β€” the range filter relies on it.
306+ assert!(
307+ MenuDate::try_new("2026-01-09").unwrap() < MenuDate::try_new("2026-01-10").unwrap()
308+ );
309+ assert!(
310+ MenuDate::try_new("2026-09-01").unwrap() < MenuDate::try_new("2026-10-01").unwrap()
311+ );
312+ }
313+
314+ #[test]
315+ fn slot_must_be_one_the_school_serves() {
316+ let allowed = vec![MealSlotDef::try_new("lunch").unwrap()];
317+ assert!(MenuSlot::try_new("lunch", &allowed).is_ok());
318+ assert!(MenuSlot::try_new("brunch", &allowed).is_err());
319+ assert!(MenuSlot::try_new("lunch", &[]).is_err());
320+ }
321+
322+ #[test]
323+ fn capacity_is_bounded_but_optional() {
324+ assert!(validate_capacity(None).is_ok());
325+ assert!(validate_capacity(Some(0)).is_ok());
326+ assert!(validate_capacity(Some(MAX_MENU_CAPACITY)).is_ok());
327+ assert!(validate_capacity(Some(-1)).is_err());
328+ assert!(validate_capacity(Some(MAX_MENU_CAPACITY + 1)).is_err());
329+ }
330+}
src/domain/menu_dish.rsadded+304 -0
@@ -0,0 +1,304 @@
1+//! One dish on a published [`Menu`](crate::domain::menu::Menu): what it is,
2+//! what it costs, and which dietary tags it carries.
3+//!
4+//! Money is **minor units** (kuruş) as `i64` β€” never a float, never a decimal,
5+//! at any layer. `tags` are validated against the school's `dietary_tags`
6+//! list, the same contract a menu's `slot` has with `meal_slots`.
7+
8+use std::sync::LazyLock;
9+
10+use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
11+use ulid::Generator;
12+
13+use crate::constant::{
14+ MAX_DISH_DESCRIPTION_LEN, MAX_DISH_NAME_LEN, MAX_DISH_PRICE_MINOR, MAX_DISH_TAGS,
15+ MENU_DISH_TABLE,
16+};
17+use crate::database::Database;
18+use crate::domain::field_update::FieldUpdate;
19+use crate::domain::menu::MenuId;
20+use crate::domain::timestamp::Timestamp;
21+use crate::error::{AppError, ValidationError};
22+use crate::validate::{validate_optional, validate_required};
23+
24+/// Mints dish ids in write order β€” see [`MenuId::generate`]; the listings below
25+/// order by `id` within a menu, which random low bits would scramble.
26+static IDS: LazyLock<std::sync::Mutex<Generator>> =
27+ LazyLock::new(|| std::sync::Mutex::new(Generator::new()));
28+
29+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
30+pub struct MenuDishId(RecordId);
31+
32+impl MenuDishId {
33+ pub fn generate() -> Self {
34+ let mut ids = IDS.lock().expect("menu dish id generator poisoned");
35+ // The only error is exhausting the random bits within one millisecond
36+ // (2^80 ids deep); it clears itself as the clock ticks, so retry.
37+ let ulid = loop {
38+ if let Ok(ulid) = ids.generate() {
39+ break ulid;
40+ }
41+ };
42+ Self(RecordId::new(MENU_DISH_TABLE, ulid.to_string()))
43+ }
44+
45+ pub fn from_key(key: &str) -> Self {
46+ Self(RecordId::new(MENU_DISH_TABLE, key))
47+ }
48+
49+ pub fn record(&self) -> RecordId {
50+ self.0.clone()
51+ }
52+
53+ pub fn key(&self) -> &str {
54+ match &self.0.key {
55+ RecordIdKey::String(key) => key,
56+ _ => "",
57+ }
58+ }
59+}
60+
61+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
62+pub struct DishName(String);
63+
64+impl DishName {
65+ pub fn try_new(value: &str) -> Result<Self, ValidationError> {
66+ validate_required("name", value, MAX_DISH_NAME_LEN)?;
67+ Ok(Self(value.to_string()))
68+ }
69+
70+ pub fn as_str(&self) -> &str {
71+ &self.0
72+ }
73+}
74+
75+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
76+pub struct DishDescription(String);
77+
78+impl DishDescription {
79+ /// Blank (or whitespace-only) means "no description" β€” `None`, not an
80+ /// empty string, so the column is absent rather than falsely present.
81+ pub fn try_new(value: &str) -> Result<Option<Self>, ValidationError> {
82+ validate_optional("description", value, MAX_DISH_DESCRIPTION_LEN)?;
83+ let value = value.trim();
84+ Ok((!value.is_empty()).then(|| Self(value.to_string())))
85+ }
86+
87+ pub fn as_str(&self) -> &str {
88+ &self.0
89+ }
90+}
91+
92+/// What one serving costs, in **minor units** (kuruş). Never negative β€” a
93+/// giveaway dish is `0`, and money that flows the other way is a ledger line.
94+#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
95+pub struct DishPrice(i64);
96+
97+impl DishPrice {
98+ pub fn try_new(value: i64) -> Result<Self, ValidationError> {
99+ if !(0..=MAX_DISH_PRICE_MINOR).contains(&value) {
100+ return Err(ValidationError::Invalid {
101+ field: "price_minor",
102+ reason: "must be between 0 and 1000000 minor units",
103+ });
104+ }
105+ Ok(Self(value))
106+ }
107+
108+ pub fn as_minor(self) -> i64 {
109+ self.0
110+ }
111+}
112+
113+/// The dietary tags a dish carries, drawn from the school's `dietary_tags`
114+/// list. Deduplicated, order preserved β€” the list is what a student's profile
115+/// is matched against, so a repeat carries no extra meaning.
116+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
117+pub struct DishTags(Vec<String>);
118+
119+impl DishTags {
120+ pub fn try_new(values: &[String], allowed: &[String]) -> Result<Self, ValidationError> {
121+ let mut tags: Vec<String> = Vec::new();
122+ for value in values {
123+ let value = value.trim();
124+ if !allowed.iter().any(|tag| tag == value) {
125+ return Err(ValidationError::Invalid {
126+ field: "tags",
127+ reason: "not one of the school's dietary tags (see GET /settings)",
128+ });
129+ }
130+ if !tags.iter().any(|tag| tag == value) {
131+ tags.push(value.to_string());
132+ }
133+ }
134+ if tags.len() > MAX_DISH_TAGS {
135+ return Err(ValidationError::Invalid {
136+ field: "tags",
137+ reason: "at most 10 tags per dish",
138+ });
139+ }
140+ Ok(Self(tags))
141+ }
142+
143+ pub fn as_slice(&self) -> &[String] {
144+ &self.0
145+ }
146+}
147+
148+#[derive(Debug, Clone, SurrealValue)]
149+pub struct MenuDish {
150+ id: MenuDishId,
151+ menu: MenuId,
152+ name: DishName,
153+ description: Option<DishDescription>,
154+ price_minor: DishPrice,
155+ tags: DishTags,
156+ created_at: Timestamp,
157+}
158+
159+impl MenuDish {
160+ pub fn get_id(&self) -> &MenuDishId {
161+ &self.id
162+ }
163+
164+ pub fn get_menu(&self) -> &MenuId {
165+ &self.menu
166+ }
167+
168+ pub fn get_name(&self) -> &DishName {
169+ &self.name
170+ }
171+
172+ pub fn get_description(&self) -> Option<&DishDescription> {
173+ self.description.as_ref()
174+ }
175+
176+ pub fn get_price_minor(&self) -> DishPrice {
177+ self.price_minor
178+ }
179+
180+ pub fn get_tags(&self) -> &DishTags {
181+ &self.tags
182+ }
183+
184+ pub fn get_created_at(&self) -> Timestamp {
185+ self.created_at
186+ }
187+
188+ pub async fn create(
189+ menu: &MenuId,
190+ name: DishName,
191+ description: Option<DishDescription>,
192+ price_minor: DishPrice,
193+ tags: DishTags,
194+ db: &Database,
195+ ) -> Result<MenuDish, AppError> {
196+ let dish = MenuDish {
197+ id: MenuDishId::generate(),
198+ menu: menu.clone(),
199+ name,
200+ description,
201+ price_minor,
202+ tags,
203+ created_at: Timestamp::now(),
204+ };
205+ let created: Option<MenuDish> = db.create(dish.id.record()).content(dish).await?;
206+ created.ok_or_else(|| AppError::Internal("failed to add the dish".into()))
207+ }
208+
209+ pub async fn read(id: &MenuDishId, db: &Database) -> Result<Option<MenuDish>, AppError> {
210+ Ok(db.select(id.record()).await?)
211+ }
212+
213+ /// Every dish on one menu, in the order they were added.
214+ pub async fn list_for_menu(menu: &MenuId, db: &Database) -> Result<Vec<MenuDish>, AppError> {
215+ Self::list_for_menus(std::slice::from_ref(menu), db).await
216+ }
217+
218+ /// Dishes for a whole page of menus in one round trip β€” the alternative is
219+ /// a query per menu, which is the N+1 the pagination slice exists to avoid.
220+ pub async fn list_for_menus(
221+ menus: &[MenuId],
222+ db: &Database,
223+ ) -> Result<Vec<MenuDish>, AppError> {
224+ if menus.is_empty() {
225+ return Ok(Vec::new());
226+ }
227+ let mut result = db
228+ .query("SELECT * FROM menu_dish WHERE menu IN $menus ORDER BY id ASC")
229+ .bind((
230+ "menus",
231+ menus.iter().map(MenuId::record).collect::<Vec<_>>(),
232+ ))
233+ .await?
234+ .check()?;
235+ Ok(result.take::<Vec<MenuDish>>(0)?)
236+ }
237+
238+ /// How many dishes the menu already carries β€” the `MAX_DISHES_PER_MENU` gate.
239+ pub async fn count_for_menu(menu: &MenuId, db: &Database) -> Result<usize, AppError> {
240+ Ok(Self::list_for_menu(menu, db).await?.len())
241+ }
242+
243+ /// Write only the fields the PATCH carried. `description` is nullable, so
244+ /// it takes the three-way shape: absent = keep, `Some(None)` = clear.
245+ pub async fn update(
246+ self,
247+ name: Option<DishName>,
248+ description: Option<Option<DishDescription>>,
249+ price_minor: Option<DishPrice>,
250+ tags: Option<DishTags>,
251+ db: &Database,
252+ ) -> Result<MenuDish, AppError> {
253+ FieldUpdate::new(self.id.record())
254+ .set("name", name)
255+ .set("description", description)
256+ .set("price_minor", price_minor)
257+ .set("tags", tags)
258+ .run::<MenuDish>(db)
259+ .await
260+ }
261+
262+ pub async fn delete(self, db: &Database) -> Result<MenuDish, AppError> {
263+ let deleted: Option<MenuDish> = db.delete(self.id.record()).await?;
264+ deleted.ok_or(AppError::NotFound)
265+ }
266+
267+ /// Drop every dish on a menu β€” the menu delete's cascade.
268+ pub async fn delete_for_menu(menu: &MenuId, db: &Database) -> Result<(), AppError> {
269+ db.query("DELETE menu_dish WHERE menu = $menu")
270+ .bind(("menu", menu.record()))
271+ .await?
272+ .check()?;
273+ Ok(())
274+ }
275+}
276+
277+#[cfg(test)]
278+mod tests {
279+ use super::*;
280+
281+ #[test]
282+ fn price_is_bounded_non_negative_minor_units() {
283+ assert_eq!(DishPrice::try_new(0).unwrap().as_minor(), 0);
284+ assert_eq!(DishPrice::try_new(4550).unwrap().as_minor(), 4550);
285+ assert!(DishPrice::try_new(-1).is_err());
286+ assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR).is_ok());
287+ assert!(DishPrice::try_new(MAX_DISH_PRICE_MINOR + 1).is_err());
288+ }
289+
290+ #[test]
291+ fn tags_must_come_from_the_school_list_and_dedupe() {
292+ let allowed = vec!["vegan".to_string(), "nut_allergy".to_string()];
293+ let tags =
294+ DishTags::try_new(&["vegan".to_string(), "vegan".to_string()], &allowed).unwrap();
295+ assert_eq!(tags.as_slice(), ["vegan"]);
296+ assert!(DishTags::try_new(&["halal".to_string()], &allowed).is_err());
297+ assert!(
298+ DishTags::try_new(&[], &allowed)
299+ .unwrap()
300+ .as_slice()
301+ .is_empty()
302+ );
303+ }
304+}
src/domain/mod.rsmodified+6 -0
@@ -12,6 +12,7 @@ pub mod chatbot_message;
12 pub mod chatbot_thread;12 pub mod chatbot_thread;
13 pub mod course;13 pub mod course;
14 pub mod course_session;14 pub mod course_session;
15+pub mod dietary_profile;
15 pub mod enrollment;16 pub mod enrollment;
16 pub mod event;17 pub mod event;
17 pub mod exam;18 pub mod exam;
@@ -24,6 +25,11 @@ pub mod homework;
24 pub mod homework_file;25 pub mod homework_file;
25 pub mod homework_result;26 pub mod homework_result;
26 pub mod homework_submission;27 pub mod homework_submission;
28+pub mod meal_attendance;
29+pub mod meal_booking;
30+pub mod meal_ledger;
31+pub mod menu;
32+pub mod menu_dish;
27 pub mod message;33 pub mod message;
28 pub mod monotonic_id;34 pub mod monotonic_id;
29 pub mod note;35 pub mod note;
src/domain/parent_link.rsmodified+5 -3
@@ -32,9 +32,11 @@ impl ParentLinkId {
32 }32 }
33 }33 }
34 34
35-/// A parent account's tie to one student it may observe. Purely a read grant:35+/// A parent account's tie to one student it may observe. Almost entirely a
36-/// it gates the parent's access to the student's reports (marks, attendance,36+/// read grant: it gates the parent's access to the student's reports (marks,
37-/// pomodoro) and nothing else β€” a parent never writes through it.37+/// attendance, pomodoro). The single write it authorizes is the food program β€”
38+/// a parent books and cancels a linked child's meals, since paying for lunch
39+/// is a parent's job and a small child cannot do it themselves.
38 #[derive(Debug, Clone, SurrealValue)]40 #[derive(Debug, Clone, SurrealValue)]
39 pub struct ParentLink {41 pub struct ParentLink {
40 id: ParentLinkId,42 id: ParentLinkId,
src/domain/settings.rsmodified+119 -5
@@ -14,10 +14,11 @@
14 use surrealdb::types::{RecordId, SurrealValue};14 use surrealdb::types::{RecordId, SurrealValue};
15 15
16 use crate::constant::{16 use crate::constant::{
17- DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_EXAM_KINDS,17+ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS,
18- DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES,18+ DEFAULT_EXAM_KINDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, DEFAULT_MAX_CHATBOT_THREADS,
19- MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN,19+ DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT,
20- MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES,20+ MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN,
21+ MAX_MAX_CHATBOT_THREADS, MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES,
21 MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,22 MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT,
22 MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES,23 MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES,
23 SETTINGS_KEY, SETTINGS_TABLE,24 SETTINGS_KEY, SETTINGS_TABLE,
@@ -66,6 +67,34 @@ impl ExamKindDef {
66 }67 }
67 }68 }
68 69
70+/// One meal slot the school serves (`"lunch"`, `"snack"`, …). A published menu
71+/// snapshots the slot's *name* as text, so retiring a slot never rewrites a
72+/// past menu β€” same contract exam kinds have with exams. An object, not a bare
73+/// string, so a slot can grow a serving window later without a migration.
74+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
75+pub struct MealSlotDef {
76+ name: String,
77+}
78+
79+impl MealSlotDef {
80+ pub fn try_new(name: &str) -> Result<Self, ValidationError> {
81+ let name = name.trim();
82+ if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {
83+ return Err(ValidationError::Invalid {
84+ field: "meal_slots",
85+ reason: "slot names must be 1 to 50 characters",
86+ });
87+ }
88+ Ok(Self {
89+ name: name.to_string(),
90+ })
91+ }
92+
93+ pub fn get_name(&self) -> &str {
94+ &self.name
95+ }
96+}
97+
69 /// One grade-display band: marks at or above `min` (and below the next band's98 /// One grade-display band: marks at or above `min` (and below the next band's
70 /// `min`) render as `label`. Display only β€” storage and averaging stay numeric.99 /// `min`) render as `label`. Display only β€” storage and averaging stay numeric.
71 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]100 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -120,6 +149,16 @@ pub struct Settings {
120 chatbot_history_turns: Option<i64>,149 chatbot_history_turns: Option<i64>,
121 max_chatbot_threads: Option<i64>,150 max_chatbot_threads: Option<i64>,
122 max_chatbot_message_len: Option<i64>,151 max_chatbot_message_len: Option<i64>,
152+ /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` β€”
153+ /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged`
154+ /// writes the whole row, so a field this struct did not carry would coerce
155+ /// to `NONE` and abort the transaction.
156+ meal_slots: Option<Vec<MealSlotDef>>,
157+ dietary_tags: Option<Vec<String>>,
158+ /// Minutes before a meal at which booking *and* cancelling close. One knob
159+ /// for both deadlines; `None` = no cutoff at all, which is also what an
160+ /// unset column reads as.
161+ meal_cancel_cutoff_minutes: Option<i64>,
123 }162 }
124 163
125 /// Everything [`Settings::try_new`] validates, in one struct β€” the knobs164 /// Everything [`Settings::try_new`] validates, in one struct β€” the knobs
@@ -134,6 +173,10 @@ pub struct SettingsParams {
134 pub chatbot_history_turns: i64,173 pub chatbot_history_turns: i64,
135 pub max_chatbot_threads: i64,174 pub max_chatbot_threads: i64,
136 pub max_chatbot_message_len: i64,175 pub max_chatbot_message_len: i64,
176+ pub meal_slots: Vec<MealSlotDef>,
177+ pub dietary_tags: Vec<String>,
178+ /// `None` = no booking/cancel cutoff.
179+ pub meal_cancel_cutoff_minutes: Option<i64>,
137 }180 }
138 181
139 impl Settings {182 impl Settings {
@@ -158,6 +201,9 @@ impl Settings {
158 chatbot_history_turns: None,201 chatbot_history_turns: None,
159 max_chatbot_threads: None,202 max_chatbot_threads: None,
160 max_chatbot_message_len: None,203 max_chatbot_message_len: None,
204+ meal_slots: None,
205+ dietary_tags: None,
206+ meal_cancel_cutoff_minutes: None,
161 }207 }
162 }208 }
163 209
@@ -172,6 +218,9 @@ impl Settings {
172 chatbot_history_turns: self.get_chatbot_history_turns(),218 chatbot_history_turns: self.get_chatbot_history_turns(),
173 max_chatbot_threads: self.get_max_chatbot_threads(),219 max_chatbot_threads: self.get_max_chatbot_threads(),
174 max_chatbot_message_len: self.get_max_chatbot_message_len(),220 max_chatbot_message_len: self.get_max_chatbot_message_len(),
221+ meal_slots: self.get_meal_slots(),
222+ dietary_tags: self.get_dietary_tags(),
223+ meal_cancel_cutoff_minutes: self.meal_cancel_cutoff_minutes,
175 }224 }
176 }225 }
177 226
@@ -192,6 +241,9 @@ impl Settings {
192 chatbot_history_turns,241 chatbot_history_turns,
193 max_chatbot_threads,242 max_chatbot_threads,
194 max_chatbot_message_len,243 max_chatbot_message_len,
244+ meal_slots,
245+ dietary_tags,
246+ meal_cancel_cutoff_minutes,
195 } = params;247 } = params;
196 in_range(248 in_range(
197 "max_file_bytes",249 "max_file_bytes",
@@ -260,6 +312,32 @@ impl Settings {
260 let mut grade_bands = grade_bands;312 let mut grade_bands = grade_bands;
261 grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min()));313 grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min()));
262 314
315+ // The food lists follow the same list rules as the kinds and statuses
316+ // above, with one difference: empty is legal on both. A school that
317+ // runs no canteen has no slots and no dietary tags, and refusing that
318+ // would force it to keep a list it never uses.
319+ let slot_names: Vec<String> = meal_slots
320+ .iter()
321+ .map(|slot| slot.get_name().to_string())
322+ .collect();
323+ if !slot_names.is_empty() {
324+ validate_list("meal_slots", slot_names)?;
325+ }
326+ let dietary_tags = if dietary_tags.is_empty() {
327+ dietary_tags
328+ } else {
329+ validate_list("dietary_tags", dietary_tags)?
330+ };
331+ // One knob for both deadlines: 0 = closes exactly at serving time.
332+ if let Some(minutes) = meal_cancel_cutoff_minutes {
333+ in_range(
334+ "meal_cancel_cutoff_minutes",
335+ minutes,
336+ 0..=MAX_MEAL_CANCEL_CUTOFF_MINUTES,
337+ "must be between 0 and 10080 (one week) minutes",
338+ )?;
339+ }
340+
263 Ok(Self {341 Ok(Self {
264 id: Self::record_id(),342 id: Self::record_id(),
265 exam_kinds,343 exam_kinds,
@@ -269,6 +347,9 @@ impl Settings {
269 chatbot_history_turns: Some(chatbot_history_turns),347 chatbot_history_turns: Some(chatbot_history_turns),
270 max_chatbot_threads: Some(max_chatbot_threads),348 max_chatbot_threads: Some(max_chatbot_threads),
271 max_chatbot_message_len: Some(max_chatbot_message_len),349 max_chatbot_message_len: Some(max_chatbot_message_len),
350+ meal_slots: Some(meal_slots),
351+ dietary_tags: Some(dietary_tags),
352+ meal_cancel_cutoff_minutes,
272 })353 })
273 }354 }
274 355
@@ -322,6 +403,33 @@ impl Settings {
322 .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN)403 .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN)
323 }404 }
324 405
406+ /// The meal slots the school serves; the built-in list while it never set
407+ /// one (including rows saved before the field existed). An explicitly
408+ /// stored empty list stays empty β€” that is "no meal program", not "unset".
409+ pub fn get_meal_slots(&self) -> Vec<MealSlotDef> {
410+ self.meal_slots.clone().unwrap_or_else(|| {
411+ DEFAULT_MEAL_SLOTS
412+ .map(|name| MealSlotDef {
413+ name: name.to_string(),
414+ })
415+ .to_vec()
416+ })
417+ }
418+
419+ /// The dietary tags a dish and a student's profile may carry; the built-in
420+ /// list while the school never set one.
421+ pub fn get_dietary_tags(&self) -> Vec<String> {
422+ self.dietary_tags
423+ .clone()
424+ .unwrap_or_else(|| DEFAULT_DIETARY_TAGS.map(String::from).to_vec())
425+ }
426+
427+ /// Minutes before a meal at which booking and cancelling close; `None` =
428+ /// no cutoff, the default while the school never set one.
429+ pub fn get_meal_cancel_cutoff_minutes(&self) -> Option<i64> {
430+ self.meal_cancel_cutoff_minutes
431+ }
432+
325 /// The label of the band `mark` falls into: the band with the greatest433 /// The label of the band `mark` falls into: the band with the greatest
326 /// `min` at or below it. `None` when no bands are configured. Takes an434 /// `min` at or below it. `None` when no bands are configured. Takes an
327 /// `f64` so course averages label the same way plain marks do.435 /// `f64` so course averages label the same way plain marks do.
@@ -376,7 +484,10 @@ impl Settings {
376 AND max_file_bytes = $mf484 AND max_file_bytes = $mf
377 AND chatbot_history_turns = $ct485 AND chatbot_history_turns = $ct
378 AND max_chatbot_threads = $cc486 AND max_chatbot_threads = $cc
379- AND max_chatbot_message_len = $cl;487+ AND max_chatbot_message_len = $cl
488+ AND meal_slots = $ms
489+ AND dietary_tags = $dt
490+ AND meal_cancel_cutoff_minutes = $mc;
380 COMMIT TRANSACTION;",491 COMMIT TRANSACTION;",
381 )492 )
382 .bind(("expected", expected.clone()))493 .bind(("expected", expected.clone()))
@@ -389,6 +500,9 @@ impl Settings {
389 .bind(("ct", expected.chatbot_history_turns))500 .bind(("ct", expected.chatbot_history_turns))
390 .bind(("cc", expected.max_chatbot_threads))501 .bind(("cc", expected.max_chatbot_threads))
391 .bind(("cl", expected.max_chatbot_message_len))502 .bind(("cl", expected.max_chatbot_message_len))
503+ .bind(("ms", expected.meal_slots.clone()))
504+ .bind(("dt", expected.dietary_tags.clone()))
505+ .bind(("mc", expected.meal_cancel_cutoff_minutes))
392 .await?506 .await?
393 .check()?;507 .check()?;
394 // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An508 // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An
src/lib.rsmodified+3 -1
@@ -56,8 +56,9 @@ use crate::state::AppState;
56 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),56 (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it β€” saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` β€” the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template β€” text, points, `choice`/`text` spec, illustration, and option pictures β€” into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only β€” the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin β€” 403 otherwise); as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≀ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),
57 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),57 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
58 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),58 (name = "exams", description = "Exams (per course, weighted by their kind β€” see `settings`): results, sync/async/open scheduling, attempts (students only β€” staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind β€” the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≀ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side β€” one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` β€” a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped β€” never another student's, and only once an `ExamResult` proves they were marked). A modeless exam is offline-graded β€” attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` β€” JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams β€” no `mode`, or `open` β€” drop out); without it the list stays newest-first"),
59+ (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` β€” `date` is text, `YYYY-MM-DD`, and `slot` must be one of the school's `meal_slots` from `GET /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` β€” edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer β€” this API never speaks decimals or floats about money. Deleting a menu takes its dishes with it. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` β€” own always, otherwise teacher+ or a parent link β€” and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list β€” the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served); every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) β€” staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is serialized in-process, since a cross-record count is not conflict-checked against a concurrent insert. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** β€” cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The school's `meal_cancel_cutoff_minutes` closes both ends at once β€” inside that window neither booking nor cancelling lands (`409`) β€” measured back from midnight UTC starting the meal's day, the only instant a timezone-free `date` yields. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to β€” the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** β€” no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row, under the same in-process lock every dish write takes, so no dish can land between the sum and the seat), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once β€” the charge and its reversal are keyed by (booking, attempt) and written under the same in-process lock as the seat, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge β€” the charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` β€” `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked β€” no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?}`) and is **admin-only**, not manager β€” the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as teacher+ or as a parent linked to them"),
59 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),60 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
60- (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+"),61+ (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` β€” note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) β€” those marks would silently re-weight. Also the food program: the meal slots menus are published for, the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` β€” one knob closing both booking and cancelling ahead of a meal (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. Read: any authenticated user; edit: manager+"),
61 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),62 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) β€” re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
62 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),63 (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course β€” whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files β€” any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored β€” the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark β€” grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report β€” statuses, late flags, marks β€” but never the submitted files"),
63 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),64 (name = "terms", description = "Academic terms (semester/trimester/quarter β€” whatever the school runs); courses may link to one. A term still linked by any course cannot be deleted (409) β€” unlink those courses first. Read: any authenticated user; edit: manager+"),
@@ -102,6 +103,7 @@ pub fn build_router(state: AppState) -> Router {
102 .nest("/sessions", web::sessions::routes())103 .nest("/sessions", web::sessions::routes())
103 .nest("/exams", web::exams::routes())104 .nest("/exams", web::exams::routes())
104 .nest("/marks", web::marks::routes())105 .nest("/marks", web::marks::routes())
106+ .nest("/meals", web::meals::routes())
105 .nest("/work", web::work::routes())107 .nest("/work", web::work::routes())
106 .nest("/pomodoro", web::pomodoro::routes())108 .nest("/pomodoro", web::pomodoro::routes())
107 .nest("/questions", web::questions::routes())109 .nest("/questions", web::questions::routes())
src/web/limits.rsmodified+57 -0
@@ -177,6 +177,45 @@ struct AppointmentLimits {
177 max_slot_occurrences: usize,177 max_slot_occurrences: usize,
178 }178 }
179 179
180+/// The food program: menus and their dishes, dietary profiles, bookings and
181+/// the meal ledger. The school's own lists (`meal_slots`, `dietary_tags`) and
182+/// its booking cutoff are on `GET /settings`; what stands here is the fixed
183+/// range those must stay inside.
184+#[derive(Serialize, ToSchema)]
185+struct MealLimits {
186+ max_dish_name_len: usize,
187+ max_dish_description_len: usize,
188+ /// How many dishes one menu may list.
189+ max_dishes_per_menu: usize,
190+ /// Dietary tags one dish may carry.
191+ max_dish_tags: usize,
192+ /// Upper bound for a menu's optional `capacity`; absent = uncapped.
193+ max_menu_capacity: i64,
194+ /// Dietary tags one student's profile may carry, and its kitchen note.
195+ max_dietary_tags: usize,
196+ max_dietary_note_len: usize,
197+ /// Money is **minor units** (kuruş) as an integer everywhere β€” never a
198+ /// decimal, never a float. These cap one dish and one ledger line.
199+ max_dish_price_minor: i64,
200+ max_ledger_amount_minor: i64,
201+ /// How the money moved, and why.
202+ max_ledger_method_len: usize,
203+ max_ledger_note_len: usize,
204+ /// Ceiling on the `/settings` knob that closes booking (and cancelling)
205+ /// ahead of a meal, minutes; the live value is on `GET /settings`.
206+ max_cancel_cutoff_minutes: i64,
207+ /// The only accepted booking `status` values.
208+ #[schema(example = json!(["booked", "cancelled"]))]
209+ booking_statuses: Vec<&'static str>,
210+ /// The only accepted meal-attendance `status` values β€” deliberately not
211+ /// the school's lesson attendance statuses.
212+ #[schema(example = json!(["served", "missed"]))]
213+ attendance_statuses: Vec<&'static str>,
214+ /// The only accepted ledger `kind` values.
215+ #[schema(example = json!(["charge", "credit", "reversal"]))]
216+ ledger_kinds: Vec<&'static str>,
217+}
218+
180 /// The AI chatbot. Each range bounds the matching `/settings` knob; the live219 /// The AI chatbot. Each range bounds the matching `/settings` knob; the live
181 /// values are on `GET /settings`.220 /// values are on `GET /settings`.
182 #[derive(Serialize, ToSchema)]221 #[derive(Serialize, ToSchema)]
@@ -260,6 +299,7 @@ struct LimitsResponse {
260 homework: HomeworkLimits,299 homework: HomeworkLimits,
261 question_pool: QuestionPoolLimits,300 question_pool: QuestionPoolLimits,
262 appointment: AppointmentLimits,301 appointment: AppointmentLimits,
302+ meal: MealLimits,
263 chatbot: ChatbotLimits,303 chatbot: ChatbotLimits,
264 settings: SettingsLimits,304 settings: SettingsLimits,
265 request: RequestLimits,305 request: RequestLimits,
@@ -355,6 +395,23 @@ impl LimitsResponse {
355 max_reason_len: MAX_APPOINTMENT_REASON_LEN,395 max_reason_len: MAX_APPOINTMENT_REASON_LEN,
356 max_slot_occurrences: MAX_SLOT_OCCURRENCES,396 max_slot_occurrences: MAX_SLOT_OCCURRENCES,
357 },397 },
398+ meal: MealLimits {
399+ max_dish_name_len: MAX_DISH_NAME_LEN,
400+ max_dish_description_len: MAX_DISH_DESCRIPTION_LEN,
401+ max_dishes_per_menu: MAX_DISHES_PER_MENU,
402+ max_dish_tags: MAX_DISH_TAGS,
403+ max_menu_capacity: MAX_MENU_CAPACITY,
404+ max_dietary_tags: MAX_DIETARY_TAGS,
405+ max_dietary_note_len: MAX_DIETARY_NOTE_LEN,
406+ max_dish_price_minor: MAX_DISH_PRICE_MINOR,
407+ max_ledger_amount_minor: MAX_LEDGER_AMOUNT_MINOR,
408+ max_ledger_method_len: MAX_LEDGER_METHOD_LEN,
409+ max_ledger_note_len: MAX_LEDGER_NOTE_LEN,
410+ max_cancel_cutoff_minutes: MAX_MEAL_CANCEL_CUTOFF_MINUTES,
411+ booking_statuses: MEAL_BOOKING_STATUSES.to_vec(),
412+ attendance_statuses: MEAL_ATTENDANCE_STATUSES.to_vec(),
413+ ledger_kinds: MEAL_LEDGER_KINDS.to_vec(),
414+ },
358 chatbot: ChatbotLimits {415 chatbot: ChatbotLimits {
359 max_message_len: MAX_CHATBOT_MESSAGE_LEN,416 max_message_len: MAX_CHATBOT_MESSAGE_LEN,
360 max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,417 max_thread_title_len: MAX_CHATBOT_THREAD_TITLE_LEN,
src/web/meals.rsadded+1376 -0
@@ -0,0 +1,1376 @@
1+//! The food program: menus and the dishes on them, the seats booked against
2+//! them, and the money that moved.
3+//!
4+//! Reads are open to every authenticated user (a student picks their lunch),
5+//! writes are manager+ β€” publishing what the school serves is kitchen
6+//! administration, not teaching.
7+//!
8+//! Money only ever *appends* here (see [`MealLedger`]): booking charges a price
9+//! snapshot, cancelling reverses it, and recording a payment is admin-only.
10+
11+use axum::Json;
12+use axum::extract::{Path, Query, State};
13+use axum::http::StatusCode;
14+use serde::{Deserialize, Serialize};
15+use utoipa::{IntoParams, ToSchema};
16+use utoipa_axum::router::OpenApiRouter;
17+use utoipa_axum::routes;
18+
19+use crate::constant::MAX_DISHES_PER_MENU;
20+use crate::database::Database;
21+use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags, conflicts};
22+use crate::domain::meal_attendance::{MealAttendance, MealAttendanceStatus};
23+use crate::domain::meal_booking::{MealBooking, MealBookingId};
24+use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger};
25+use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_capacity};
26+use crate::domain::menu_dish::{
27+ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
28+};
29+use crate::domain::parent_link::ParentLink;
30+use crate::domain::role::Role;
31+use crate::domain::settings::Settings;
32+use crate::domain::user::{User, UserId};
33+use crate::error::{AppError, ErrorResponse, ValidationError};
34+use crate::state::AppState;
35+
36+use super::{
37+ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,
38+ paginate, person_map, set_or_clear,
39+};
40+
41+pub fn routes() -> OpenApiRouter<AppState> {
42+ OpenApiRouter::new()
43+ .routes(routes!(create_menu, list_menus))
44+ .routes(routes!(get_menu, update_menu, delete_menu))
45+ .routes(routes!(add_dish))
46+ .routes(routes!(update_dish, delete_dish))
47+ .routes(routes!(book_meal, list_menu_bookings))
48+ .routes(routes!(my_bookings))
49+ .routes(routes!(cancel_booking))
50+ .routes(routes!(mark_attendance, list_menu_attendance))
51+ .routes(routes!(user_attendance))
52+ .routes(routes!(my_profile))
53+ .routes(routes!(user_profile, update_profile))
54+ .routes(routes!(my_balance))
55+ .routes(routes!(user_balance))
56+ .routes(routes!(user_ledger))
57+ .routes(routes!(record_credit))
58+}
59+
60+#[derive(Deserialize, ToSchema)]
61+struct CreateMenu {
62+ /// The calendar day, `YYYY-MM-DD`. Text, not a timestamp: "one menu per
63+ /// day and slot" is the school's own day, not UTC midnight.
64+ #[schema(example = "2026-09-14", min_length = 10, max_length = 10)]
65+ date: String,
66+ /// One of the school's `meal_slots` (see `GET /settings`).
67+ #[schema(example = "lunch")]
68+ slot: String,
69+ /// How many students may book it. Omit (or `null`) for uncapped.
70+ #[schema(minimum = 0, maximum = 10000, example = 120)]
71+ capacity: Option<i64>,
72+}
73+
74+#[derive(Deserialize, ToSchema)]
75+struct UpdateMenu {
76+ /// New seat cap; `null` clears it back to uncapped. `date` and `slot` are
77+ /// immutable β€” a menu on another day is another menu.
78+ #[serde(default, deserialize_with = "set_or_clear")]
79+ #[schema(value_type = Option<i64>, minimum = 0, maximum = 10000)]
80+ capacity: Option<Option<i64>>,
81+}
82+
83+/// Inclusive `YYYY-MM-DD` bounds on `GET /meals/menus`. Either may be omitted.
84+#[derive(Debug, Deserialize, IntoParams)]
85+struct MenuRange {
86+ /// Keep menus on or after this day.
87+ #[param(example = "2026-09-01")]
88+ from: Option<String>,
89+ /// Keep menus on or before this day.
90+ #[param(example = "2026-09-30")]
91+ to: Option<String>,
92+}
93+
94+#[derive(Deserialize, ToSchema)]
95+struct CreateDish {
96+ #[schema(example = "Mercimek Γ§orbasΔ±", max_length = 100)]
97+ name: String,
98+ #[schema(max_length = 500)]
99+ description: Option<String>,
100+ /// Price in **minor units** (kuruş) β€” `4550` is 45,50 β‚Ί. Integer only:
101+ /// this API never speaks decimals or floats about money.
102+ #[schema(minimum = 0, maximum = 1000000, example = 4550_i64)]
103+ price_minor: i64,
104+ /// Dietary tags, each one of the school's `dietary_tags` (`GET /settings`).
105+ #[schema(max_items = 10, example = json!(["vegetarian"]))]
106+ #[serde(default)]
107+ tags: Vec<String>,
108+}
109+
110+#[derive(Deserialize, ToSchema)]
111+struct UpdateDish {
112+ #[schema(max_length = 100)]
113+ name: Option<String>,
114+ /// `null` (or blank) clears the description.
115+ #[serde(default, deserialize_with = "set_or_clear")]
116+ #[schema(value_type = Option<String>, max_length = 500)]
117+ description: Option<Option<String>>,
118+ #[schema(minimum = 0, maximum = 1000000)]
119+ price_minor: Option<i64>,
120+ #[schema(max_items = 10)]
121+ tags: Option<Vec<String>>,
122+}
123+
124+#[derive(Serialize, ToSchema)]
125+struct DishResponse {
126+ id: String,
127+ #[schema(example = "Mercimek Γ§orbasΔ±")]
128+ name: String,
129+ description: Option<String>,
130+ /// Minor units (kuruş).
131+ price_minor: i64,
132+ tags: Vec<String>,
133+ /// Which of `tags` the **calling user's** own dietary profile flags β€” the
134+ /// set intersection of the two lists. Empty when they do not overlap, and
135+ /// empty for every reader without a profile (staff included).
136+ #[schema(example = json!(["nut_allergy"]))]
137+ conflicts: Vec<String>,
138+ created_at: i64,
139+}
140+
141+impl DishResponse {
142+ fn new(dish: &MenuDish, viewer_tags: &[String]) -> Self {
143+ Self {
144+ id: dish.get_id().key().to_string(),
145+ name: dish.get_name().as_str().to_string(),
146+ description: dish.get_description().map(|text| text.as_str().to_string()),
147+ price_minor: dish.get_price_minor().as_minor(),
148+ tags: dish.get_tags().as_slice().to_vec(),
149+ conflicts: conflicts(dish.get_tags().as_slice(), viewer_tags),
150+ created_at: dish.get_created_at().as_millis(),
151+ }
152+ }
153+}
154+
155+#[derive(Serialize, ToSchema)]
156+struct MenuResponse {
157+ id: String,
158+ /// The calendar day, `YYYY-MM-DD`.
159+ #[schema(example = "2026-09-14")]
160+ date: String,
161+ /// The meal slot, snapshotted when the menu was published β€” it stays as it
162+ /// was even if the school later retires the slot.
163+ #[schema(example = "lunch")]
164+ slot: String,
165+ /// Seat cap; `null` = uncapped.
166+ capacity: Option<i64>,
167+ /// Everything on offer, in the order it was added.
168+ dishes: Vec<DishResponse>,
169+ created_by: PersonRef,
170+ created_at: i64,
171+}
172+
173+impl MenuResponse {
174+ fn new(
175+ menu: &Menu,
176+ dishes: &[MenuDish],
177+ people: &std::collections::HashMap<String, PersonRef>,
178+ viewer_tags: &[String],
179+ ) -> Self {
180+ Self {
181+ id: menu.get_id().key().to_string(),
182+ date: menu.get_date().as_str().to_string(),
183+ slot: menu.get_slot().as_str().to_string(),
184+ capacity: menu.get_capacity(),
185+ dishes: dishes
186+ .iter()
187+ .filter(|dish| dish.get_menu() == menu.get_id())
188+ .map(|dish| DishResponse::new(dish, viewer_tags))
189+ .collect(),
190+ created_by: PersonRef::resolve(people, menu.get_created_by()),
191+ created_at: menu.get_created_at().as_millis(),
192+ }
193+ }
194+}
195+
196+/// Join dishes, publishers, and the reader's own dietary tags onto a page of
197+/// menus β€” three queries for the whole page, never one per row. The profile in
198+/// particular is read **once**, not per dish.
199+async fn menu_responses(
200+ menus: &[Menu],
201+ viewer: &UserId,
202+ db: &Database,
203+) -> Result<Vec<MenuResponse>, AppError> {
204+ let ids: Vec<MenuId> = menus.iter().map(|menu| menu.get_id().clone()).collect();
205+ let dishes = MenuDish::list_for_menus(&ids, db).await?;
206+ let people = person_map(menus.iter().map(|menu| menu.get_created_by().clone()), db).await?;
207+ let viewer_tags = DietaryProfile::tags_of(viewer, db).await?;
208+ Ok(menus
209+ .iter()
210+ .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags))
211+ .collect())
212+}
213+
214+/// One menu, with its dishes.
215+async fn one_menu(
216+ menu: &Menu,
217+ viewer: &UserId,
218+ db: &Database,
219+) -> Result<Json<MenuResponse>, AppError> {
220+ let dishes = MenuDish::list_for_menu(menu.get_id(), db).await?;
221+ let people = person_map([menu.get_created_by().clone()], db).await?;
222+ let viewer_tags = DietaryProfile::tags_of(viewer, db).await?;
223+ Ok(Json(MenuResponse::new(
224+ menu,
225+ &dishes,
226+ &people,
227+ &viewer_tags,
228+ )))
229+}
230+
231+/// Publish a menu for one day and meal slot. Requires manager+. The slot must
232+/// be one the school currently serves, and a day+slot already published is a
233+/// `409` β€” edit that menu instead of publishing a second one.
234+#[utoipa::path(
235+ post,
236+ path = "/menus",
237+ tag = "meals",
238+ security(("session_cookie" = [])),
239+ request_body = CreateMenu,
240+ responses(
241+ (status = 201, description = "Menu published", body = MenuResponse),
242+ (status = 400, description = "Malformed date, unknown slot, or out-of-range capacity", body = ErrorResponse),
243+ (status = 401, description = "Not authenticated", body = ErrorResponse),
244+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
245+ (status = 409, description = "A menu already exists for that date and slot", body = ErrorResponse),
246+ ),
247+)]
248+async fn create_menu(
249+ State(st): State<AppState>,
250+ RequireManager(user): RequireManager,
251+ Json(req): Json<CreateMenu>,
252+) -> Result<(StatusCode, Json<MenuResponse>), AppError> {
253+ let date = MenuDate::try_new(&req.date)?;
254+ let slot = MenuSlot::try_new(&req.slot, &Settings::load(&st.db).await?.get_meal_slots())?;
255+ validate_capacity(req.capacity)?;
256+ let menu = Menu::create(date, slot, req.capacity, user.get_id(), &st.db).await?;
257+ let body = one_menu(&menu, user.get_id(), &st.db).await?;
258+ Ok((StatusCode::CREATED, body))
259+}
260+
261+/// List published menus, newest day first, each with its dishes. Any
262+/// authenticated user. Narrow to a date range with `?from=&to=` (inclusive,
263+/// `YYYY-MM-DD`). Paged via `?limit=&offset=` (omit `limit` for the full list);
264+/// returns a `{items, total, limit, offset}` envelope.
265+#[utoipa::path(
266+ get,
267+ path = "/menus",
268+ tag = "meals",
269+ security(("session_cookie" = [])),
270+ params(MenuRange, PageParams),
271+ responses(
272+ (status = 200, description = "A page of menus (the full list when unpaged)", body = Page<MenuResponse>),
273+ (status = 400, description = "Malformed date bound, limit, or offset", body = ErrorResponse),
274+ (status = 401, description = "Not authenticated", body = ErrorResponse),
275+ ),
276+)]
277+async fn list_menus(
278+ State(st): State<AppState>,
279+ CurrentUser(user): CurrentUser,
280+ Query(range): Query<MenuRange>,
281+ Query(page): Query<PageParams>,
282+) -> Result<Json<Page<MenuResponse>>, AppError> {
283+ let (limit, offset) = page.resolve()?;
284+ let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
285+ let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
286+ let menus = Menu::list(from.as_ref(), to.as_ref(), &st.db).await?;
287+ let total = menus.len() as i64;
288+ // The dish/people join runs over the page alone, so it shrinks with it.
289+ let items = menu_responses(paginate(&menus, limit, offset), user.get_id(), &st.db).await?;
290+ Ok(Json(Page::new(items, total, limit, offset)))
291+}
292+
293+/// Fetch one menu with its dishes.
294+#[utoipa::path(
295+ get,
296+ path = "/menus/{id}",
297+ tag = "meals",
298+ security(("session_cookie" = [])),
299+ params(("id" = String, Path, description = "Menu id")),
300+ responses(
301+ (status = 200, description = "The menu", body = MenuResponse),
302+ (status = 401, description = "Not authenticated", body = ErrorResponse),
303+ (status = 404, description = "Not found", body = ErrorResponse),
304+ ),
305+)]
306+async fn get_menu(
307+ State(st): State<AppState>,
308+ CurrentUser(user): CurrentUser,
309+ Path(id): Path<String>,
310+) -> Result<Json<MenuResponse>, AppError> {
311+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
312+ .await?
313+ .ok_or(AppError::NotFound)?;
314+ one_menu(&menu, user.get_id(), &st.db).await
315+}
316+
317+/// Change a menu's seat cap. Requires manager+. `date` and `slot` are
318+/// immutable; `"capacity": null` goes back to uncapped.
319+#[utoipa::path(
320+ patch,
321+ path = "/menus/{id}",
322+ tag = "meals",
323+ security(("session_cookie" = [])),
324+ params(("id" = String, Path, description = "Menu id")),
325+ request_body = UpdateMenu,
326+ responses(
327+ (status = 200, description = "Updated menu", body = MenuResponse),
328+ (status = 400, description = "Capacity out of range", body = ErrorResponse),
329+ (status = 401, description = "Not authenticated", body = ErrorResponse),
330+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
331+ (status = 404, description = "Not found", body = ErrorResponse),
332+ ),
333+)]
334+async fn update_menu(
335+ State(st): State<AppState>,
336+ RequireManager(user): RequireManager,
337+ Path(id): Path<String>,
338+ Json(req): Json<UpdateMenu>,
339+) -> Result<Json<MenuResponse>, AppError> {
340+ if let Some(capacity) = req.capacity {
341+ validate_capacity(capacity)?;
342+ }
343+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
344+ .await?
345+ .ok_or(AppError::NotFound)?;
346+ let updated = menu.update(req.capacity, &st.db).await?;
347+ one_menu(&updated, user.get_id(), &st.db).await
348+}
349+
350+/// Unpublish a menu. Requires manager+. Its dishes go with it β€” a dish has no
351+/// meaning apart from the menu it was published on. A menu somebody still
352+/// holds a seat on is a `409`: cancel the bookings first.
353+#[utoipa::path(
354+ delete,
355+ path = "/menus/{id}",
356+ tag = "meals",
357+ security(("session_cookie" = [])),
358+ params(("id" = String, Path, description = "Menu id")),
359+ responses(
360+ (status = 204, description = "Deleted"),
361+ (status = 401, description = "Not authenticated", body = ErrorResponse),
362+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
363+ (status = 404, description = "Not found", body = ErrorResponse),
364+ (status = 409, description = "The menu still has live bookings", body = ErrorResponse),
365+ ),
366+)]
367+async fn delete_menu(
368+ State(st): State<AppState>,
369+ RequireManager(_user): RequireManager,
370+ Path(id): Path<String>,
371+) -> Result<StatusCode, AppError> {
372+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
373+ .await?
374+ .ok_or(AppError::NotFound)?;
375+ // [`MENU_LOCK`] holds the seat check and the delete together, so a booking
376+ // cannot land on a menu that is already on its way out.
377+ let _guard = MENU_LOCK.lock().await;
378+ if MealBooking::any_live_for_menu(menu.get_id(), &st.db).await? {
379+ return Err(AppError::Conflict(
380+ "the menu still has live bookings β€” cancel them first",
381+ ));
382+ }
383+ menu.delete(&st.db).await?;
384+ Ok(StatusCode::NO_CONTENT)
385+}
386+
387+/// Add a dish to a menu. Requires manager+. Tags must come from the school's
388+/// `dietary_tags`, and a menu holds at most 50 dishes (`409` at the cap).
389+#[utoipa::path(
390+ post,
391+ path = "/menus/{id}/dishes",
392+ tag = "meals",
393+ security(("session_cookie" = [])),
394+ params(("id" = String, Path, description = "Menu id")),
395+ request_body = CreateDish,
396+ responses(
397+ (status = 201, description = "Dish added", body = DishResponse),
398+ (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse),
399+ (status = 401, description = "Not authenticated", body = ErrorResponse),
400+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
401+ (status = 404, description = "No such menu", body = ErrorResponse),
402+ (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse),
403+ ),
404+)]
405+async fn add_dish(
406+ State(st): State<AppState>,
407+ RequireManager(user): RequireManager,
408+ Path(id): Path<String>,
409+ Json(req): Json<CreateDish>,
410+) -> Result<(StatusCode, Json<DishResponse>), AppError> {
411+ let name = DishName::try_new(&req.name)?;
412+ let description = req
413+ .description
414+ .as_deref()
415+ .map(DishDescription::try_new)
416+ .transpose()?
417+ .flatten();
418+ let price = DishPrice::try_new(req.price_minor)?;
419+ let tags = DishTags::try_new(&req.tags, &Settings::load(&st.db).await?.get_dietary_tags())?;
420+ // Dish writes take [`MENU_LOCK`] because a booking snapshots the menu's
421+ // price under it: a dish landing mid-booking would be stored on the seat as
422+ // "the menu was free", and a held seat is never re-priced. It also makes
423+ // the dish cap a real cap β€” count-then-write is write-skew otherwise. The
424+ // lock stays a leaf: nothing below here takes another.
425+ let _guard = MENU_LOCK.lock().await;
426+ // The menu is read *inside* the lock, like `MealBooking::book` does: read
427+ // before it, a `DELETE /menus/{id}` running in the gap takes its cascade
428+ // with it and this dish lands on a menu that no longer exists.
429+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
430+ .await?
431+ .ok_or(AppError::NotFound)?;
432+ if MenuDish::count_for_menu(menu.get_id(), &st.db).await? >= MAX_DISHES_PER_MENU {
433+ return Err(AppError::Conflict(
434+ "the menu already carries the maximum number of dishes",
435+ ));
436+ }
437+ let dish = MenuDish::create(menu.get_id(), name, description, price, tags, &st.db).await?;
438+ let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?;
439+ Ok((
440+ StatusCode::CREATED,
441+ Json(DishResponse::new(&dish, &viewer_tags)),
442+ ))
443+}
444+
445+/// Edit a dish. Requires manager+. Omitted fields keep their value;
446+/// `"description": null` clears it, and `tags` replaces the whole list.
447+#[utoipa::path(
448+ patch,
449+ path = "/dishes/{did}",
450+ tag = "meals",
451+ security(("session_cookie" = [])),
452+ params(("did" = String, Path, description = "Dish id")),
453+ request_body = UpdateDish,
454+ responses(
455+ (status = 200, description = "Updated dish", body = DishResponse),
456+ (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse),
457+ (status = 401, description = "Not authenticated", body = ErrorResponse),
458+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
459+ (status = 404, description = "Not found", body = ErrorResponse),
460+ ),
461+)]
462+async fn update_dish(
463+ State(st): State<AppState>,
464+ RequireManager(user): RequireManager,
465+ Path(did): Path<String>,
466+ Json(req): Json<UpdateDish>,
467+) -> Result<Json<DishResponse>, AppError> {
468+ let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db)
469+ .await?
470+ .ok_or(AppError::NotFound)?;
471+ let name = req.name.as_deref().map(DishName::try_new).transpose()?;
472+ // Absent keeps, `null` clears, and a blank string clears too β€” an empty
473+ // description is the absence of one, never a stored empty string.
474+ let description = match req.description {
475+ None => None,
476+ Some(None) => Some(None),
477+ Some(Some(text)) => Some(DishDescription::try_new(&text)?),
478+ };
479+ let price = req.price_minor.map(DishPrice::try_new).transpose()?;
480+ let tags = match &req.tags {
481+ Some(tags) => Some(DishTags::try_new(
482+ tags,
483+ &Settings::load(&st.db).await?.get_dietary_tags(),
484+ )?),
485+ None => None,
486+ };
487+ // Under [`MENU_LOCK`] like every dish write β€” see `add_dish`.
488+ let _guard = MENU_LOCK.lock().await;
489+ let updated = dish.update(name, description, price, tags, &st.db).await?;
490+ let viewer_tags = DietaryProfile::tags_of(user.get_id(), &st.db).await?;
491+ Ok(Json(DishResponse::new(&updated, &viewer_tags)))
492+}
493+
494+/// Remove a dish from its menu. Requires manager+.
495+#[utoipa::path(
496+ delete,
497+ path = "/dishes/{did}",
498+ tag = "meals",
499+ security(("session_cookie" = [])),
500+ params(("did" = String, Path, description = "Dish id")),
501+ responses(
502+ (status = 204, description = "Deleted"),
503+ (status = 401, description = "Not authenticated", body = ErrorResponse),
504+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
505+ (status = 404, description = "Not found", body = ErrorResponse),
506+ ),
507+)]
508+async fn delete_dish(
509+ State(st): State<AppState>,
510+ RequireManager(_user): RequireManager,
511+ Path(did): Path<String>,
512+) -> Result<StatusCode, AppError> {
513+ let dish = MenuDish::read(&MenuDishId::from_key(&did), &st.db)
514+ .await?
515+ .ok_or(AppError::NotFound)?;
516+ // Under [`MENU_LOCK`] like every dish write β€” see `add_dish`.
517+ let _guard = MENU_LOCK.lock().await;
518+ dish.delete(&st.db).await?;
519+ Ok(StatusCode::NO_CONTENT)
520+}
521+
522+// ---- dietary profiles -----------------------------------------------------
523+
524+#[derive(Deserialize, ToSchema)]
525+struct UpdateDietaryProfile {
526+ /// Replaces the whole tag list; each entry must be one of the school's
527+ /// `dietary_tags` (`GET /settings`) β€” the same vocabulary a dish is tagged
528+ /// from, which is what makes a menu's `conflicts` computable.
529+ #[schema(max_items = 10, example = json!(["nut_allergy"]))]
530+ tags: Option<Vec<String>>,
531+ /// Free text for the kitchen; `null` (or blank) clears it.
532+ #[serde(default, deserialize_with = "set_or_clear")]
533+ #[schema(value_type = Option<String>, max_length = 500, example = "carries an EpiPen")]
534+ note: Option<Option<String>>,
535+}
536+
537+#[derive(Serialize, ToSchema)]
538+struct DietaryProfileResponse {
539+ student: PersonRef,
540+ /// The tags the school recorded; empty while there is no profile.
541+ tags: Vec<String>,
542+ note: Option<String>,
543+ /// Who last wrote it, and when β€” both absent while no profile exists.
544+ updated_by: Option<PersonRef>,
545+ updated_at: Option<i64>,
546+}
547+
548+/// One student's profile, or the empty one. A student who was never recorded
549+/// has *no* restrictions, so that reads back as an empty profile rather than a
550+/// `404` β€” the caller asked "what may they not eat", and "nothing known" is an
551+/// answer.
552+async fn profile_response(
553+ student: &UserId,
554+ db: &Database,
555+) -> Result<Json<DietaryProfileResponse>, AppError> {
556+ let profile = DietaryProfile::read(student, db).await?;
557+ let people = person_map(
558+ std::iter::once(student.clone())
559+ .chain(profile.as_ref().map(|row| row.get_updated_by().clone())),
560+ db,
561+ )
562+ .await?;
563+ Ok(Json(DietaryProfileResponse {
564+ student: PersonRef::resolve(&people, student),
565+ tags: profile
566+ .as_ref()
567+ .map(|row| row.get_tags().as_slice().to_vec())
568+ .unwrap_or_default(),
569+ note: profile
570+ .as_ref()
571+ .and_then(|row| row.get_note())
572+ .map(|note| note.as_str().to_string()),
573+ updated_by: profile
574+ .as_ref()
575+ .map(|row| PersonRef::resolve(&people, row.get_updated_by())),
576+ updated_at: profile.as_ref().map(|row| row.get_updated_at().as_millis()),
577+ }))
578+}
579+
580+/// The caller's own dietary profile β€” what the school recorded about their
581+/// diet. Empty tags mean nothing was ever recorded.
582+#[utoipa::path(
583+ get,
584+ path = "/profiles/me",
585+ tag = "meals",
586+ security(("session_cookie" = [])),
587+ responses(
588+ (status = 200, description = "The caller's dietary profile", body = DietaryProfileResponse),
589+ (status = 401, description = "Not authenticated", body = ErrorResponse),
590+ ),
591+)]
592+async fn my_profile(
593+ State(st): State<AppState>,
594+ CurrentUser(user): CurrentUser,
595+) -> Result<Json<DietaryProfileResponse>, AppError> {
596+ profile_response(user.get_id(), &st.db).await
597+}
598+
599+/// One student's dietary profile. Requires teacher+, or a parent link to them
600+/// β€” the caller's own id always passes.
601+#[utoipa::path(
602+ get,
603+ path = "/profiles/{user}",
604+ tag = "meals",
605+ security(("session_cookie" = [])),
606+ params(("user" = String, Path, description = "Student id")),
607+ responses(
608+ (status = 200, description = "The student's dietary profile", body = DietaryProfileResponse),
609+ (status = 401, description = "Not authenticated", body = ErrorResponse),
610+ (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
611+ ),
612+)]
613+async fn user_profile(
614+ State(st): State<AppState>,
615+ CurrentUser(caller): CurrentUser,
616+ Path(user): Path<String>,
617+) -> Result<Json<DietaryProfileResponse>, AppError> {
618+ let target = UserId::from_key(&user);
619+ ensure_can_read_student(&caller, &target, &st.db).await?;
620+ profile_response(&target, &st.db).await
621+}
622+
623+/// Record what a student may not eat. **Manager+**, deliberately: an allergen
624+/// list is a safety record the school keeps on the student's behalf, not a
625+/// self-service preference β€” a student editing their own would let a mistyped
626+/// (or removed) allergy reach the kitchen with the school's authority behind
627+/// it. Omitted fields keep their value; `tags` replaces the whole list, and
628+/// `"note": null` clears the note. First write creates the row.
629+#[utoipa::path(
630+ patch,
631+ path = "/profiles/{user}",
632+ tag = "meals",
633+ security(("session_cookie" = [])),
634+ params(("user" = String, Path, description = "Student id")),
635+ request_body = UpdateDietaryProfile,
636+ responses(
637+ (status = 200, description = "The stored profile", body = DietaryProfileResponse),
638+ (status = 400, description = "Unknown dietary tag, too many tags, an over-long note, or a non-student target", body = ErrorResponse),
639+ (status = 401, description = "Not authenticated", body = ErrorResponse),
640+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
641+ (status = 404, description = "No such user", body = ErrorResponse),
642+ ),
643+)]
644+async fn update_profile(
645+ State(st): State<AppState>,
646+ RequireManager(manager): RequireManager,
647+ Path(user): Path<String>,
648+ Json(req): Json<UpdateDietaryProfile>,
649+) -> Result<Json<DietaryProfileResponse>, AppError> {
650+ let target = UserId::from_key(&user);
651+ // Only a student eats off the school's menus; a profile on anyone else is
652+ // a typo, and a typo here is an allergy filed against the wrong person.
653+ if User::read(&target, &st.db)
654+ .await?
655+ .ok_or(AppError::NotFound)?
656+ .get_role()
657+ != Role::Student
658+ {
659+ return Err(AppError::Validation(ValidationError::Invalid {
660+ field: "user",
661+ reason: "only a student carries a dietary profile",
662+ }));
663+ }
664+ let tags = match &req.tags {
665+ Some(tags) => Some(DietaryTags::try_new(
666+ tags,
667+ &Settings::load(&st.db).await?.get_dietary_tags(),
668+ )?),
669+ None => None,
670+ };
671+ // Absent keeps, `null` clears, and a blank string clears too β€” an empty
672+ // note is the absence of one, never a stored empty string.
673+ let note = match req.note {
674+ None => None,
675+ Some(None) => Some(None),
676+ Some(Some(text)) => Some(DietaryNote::try_new(&text)?),
677+ };
678+ DietaryProfile::save(&target, tags, note, manager.get_id(), &st.db).await?;
679+ profile_response(&target, &st.db).await
680+}
681+
682+// ---- bookings -------------------------------------------------------------
683+
684+#[derive(Deserialize, ToSchema)]
685+struct BookMeal {
686+ /// Who the seat is for. Omit to book for yourself (a student's own lunch);
687+ /// a parent must name one of their linked students.
688+ student_id: Option<String>,
689+}
690+
691+#[derive(Serialize, ToSchema)]
692+struct BookingResponse {
693+ id: String,
694+ /// The menu the seat is on.
695+ menu_id: String,
696+ student: PersonRef,
697+ /// Who placed it β€” the student themselves, or their parent.
698+ booked_by: PersonRef,
699+ /// `booked` or `cancelled`. A cancel keeps the row (audit), it only stops
700+ /// the seat counting against the menu's capacity.
701+ #[schema(example = "booked")]
702+ status: String,
703+ cancelled_at: Option<i64>,
704+ created_at: i64,
705+}
706+
707+impl BookingResponse {
708+ fn new(booking: &MealBooking, people: &std::collections::HashMap<String, PersonRef>) -> Self {
709+ Self {
710+ id: booking.get_id().key().to_string(),
711+ menu_id: booking.get_menu().key().to_string(),
712+ student: PersonRef::resolve(people, booking.get_student()),
713+ booked_by: PersonRef::resolve(people, booking.get_booked_by()),
714+ status: booking.get_status().as_str().to_string(),
715+ cancelled_at: booking.get_cancelled_at().map(|at| at.as_millis()),
716+ created_at: booking.get_created_at().as_millis(),
717+ }
718+ }
719+}
720+
721+/// Join the people onto a page of bookings β€” one query for the whole page.
722+async fn booking_responses(
723+ bookings: &[MealBooking],
724+ db: &Database,
725+) -> Result<Vec<BookingResponse>, AppError> {
726+ let people = person_map(
727+ bookings.iter().flat_map(|booking| {
728+ [
729+ booking.get_student().clone(),
730+ booking.get_booked_by().clone(),
731+ ]
732+ }),
733+ db,
734+ )
735+ .await?;
736+ Ok(bookings
737+ .iter()
738+ .map(|booking| BookingResponse::new(booking, &people))
739+ .collect())
740+}
741+
742+/// The school's one meal cutoff, applied to booking and cancelling alike.
743+async fn cutoff_minutes(db: &Database) -> Result<Option<i64>, AppError> {
744+ Ok(Settings::load(db).await?.get_meal_cancel_cutoff_minutes())
745+}
746+
747+/// Whose seat is this? A student books only for themselves; a parent only for
748+/// a student they hold a link to. Nobody else books through this route β€” a
749+/// teacher or manager arranging someone's lunch is not a thing this API does.
750+///
751+/// The link row alone is not the grant: like a stale enrollment, a link whose
752+/// student side changed role must be inert, so the target's live role is
753+/// re-read here. A missing or non-student target falls through to the same
754+/// 403 β€” a parent never gets an existence oracle.
755+async fn booking_target(
756+ caller: &User,
757+ student_id: Option<&str>,
758+ db: &Database,
759+) -> Result<UserId, AppError> {
760+ match caller.get_role() {
761+ Role::Student => match student_id {
762+ Some(id) if id != caller.get_id().key() => Err(AppError::Forbidden(
763+ "a student books meals only for themselves",
764+ )),
765+ _ => Ok(caller.get_id().clone()),
766+ },
767+ Role::Parent => {
768+ let target = UserId::from_key(student_id.ok_or(AppError::Validation(
769+ ValidationError::Invalid {
770+ field: "student_id",
771+ reason: "a parent must name the student the seat is for",
772+ },
773+ ))?);
774+ if ParentLink::exists(caller.get_id(), &target, db).await?
775+ && User::read(&target, db)
776+ .await?
777+ .is_some_and(|target| target.get_role() == Role::Student)
778+ {
779+ return Ok(target);
780+ }
781+ Err(AppError::Forbidden(
782+ "a parent books meals only for a linked student",
783+ ))
784+ }
785+ _ => Err(AppError::Forbidden(
786+ "only students and their parents book meals",
787+ )),
788+ }
789+}
790+
791+/// Take a seat on a published menu. A student books for themselves (omit
792+/// `student_id`); a parent books for a linked student by naming them. Booking
793+/// twice is the same seat, not a second one β€” and bills once, at the price the
794+/// menu carried when the seat was first taken. Refused (`409`) when the menu is
795+/// full or the school's `meal_cancel_cutoff_minutes` has closed the meal, and
796+/// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat
797+/// is never handed out unbilled.
798+#[utoipa::path(
799+ post,
800+ path = "/menus/{id}/bookings",
801+ tag = "meals",
802+ security(("session_cookie" = [])),
803+ params(("id" = String, Path, description = "Menu id")),
804+ request_body = BookMeal,
805+ responses(
806+ (status = 201, description = "Seat booked (or the seat already held)", body = BookingResponse),
807+ (status = 400, description = "A parent named no student, or the menu's dishes sum past the chargeable maximum", body = ErrorResponse),
808+ (status = 401, description = "Not authenticated", body = ErrorResponse),
809+ (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
810+ (status = 404, description = "No such menu", body = ErrorResponse),
811+ (status = 409, description = "The menu is full, or its cutoff has passed", body = ErrorResponse),
812+ ),
813+)]
814+async fn book_meal(
815+ State(st): State<AppState>,
816+ CurrentUser(user): CurrentUser,
817+ Path(id): Path<String>,
818+ Json(req): Json<BookMeal>,
819+) -> Result<(StatusCode, Json<BookingResponse>), AppError> {
820+ let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
821+ let cutoff = cutoff_minutes(&st.db).await?;
822+ let menu = MenuId::from_key(&id);
823+ // Price, seat and charge all land together under `MENU_LOCK`, keyed by
824+ // (seat, attempt) β€” a double-click books one seat and bills it once, and a
825+ // dish cannot slip in between the price snapshot and the row it is frozen
826+ // onto.
827+ let booking = MealBooking::book(&menu, &student, user.get_id(), cutoff, &st.db).await?;
828+ let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
829+ Ok((
830+ StatusCode::CREATED,
831+ Json(items.into_iter().next().expect("one booking in, one out")),
832+ ))
833+}
834+
835+/// The caller's own bookings, newest first: the seats held *for* them, plus β€”
836+/// for a parent β€” the seats held for every student they currently hold a link
837+/// to. The links are re-read on every call, so an unlinked parent stops seeing
838+/// the child's meals at once, even the ones they booked themselves. Cancelled
839+/// bookings stay in the list, flagged. Paged via `?limit=&offset=` (omit
840+/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope.
841+#[utoipa::path(
842+ get,
843+ path = "/bookings/me",
844+ tag = "meals",
845+ security(("session_cookie" = [])),
846+ params(PageParams),
847+ responses(
848+ (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<BookingResponse>),
849+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
850+ (status = 401, description = "Not authenticated", body = ErrorResponse),
851+ ),
852+)]
853+async fn my_bookings(
854+ State(st): State<AppState>,
855+ CurrentUser(user): CurrentUser,
856+ Query(page): Query<PageParams>,
857+) -> Result<Json<Page<BookingResponse>>, AppError> {
858+ let (limit, offset) = page.resolve()?;
859+ // Own seats always; a parent's children only while the link is live β€” the
860+ // booking row's `booked_by` is history, never a standing read grant.
861+ let mut students = vec![user.get_id().clone()];
862+ if user.get_role() == Role::Parent {
863+ students.extend(
864+ ParentLink::list_for_parent(user.get_id(), &st.db)
865+ .await?
866+ .iter()
867+ .map(|link| link.get_student().clone()),
868+ );
869+ }
870+ let rows = MealBooking::list_for_students(&students, &st.db).await?;
871+ let total = rows.len() as i64;
872+ let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?;
873+ Ok(Json(Page::new(items, total, limit, offset)))
874+}
875+
876+/// Who is eating: every booking on one menu, cancelled ones included so the
877+/// kitchen can see what changed. Requires manager+ β€” this is the whole school's
878+/// list, not one family's. Paged via `?limit=&offset=`.
879+#[utoipa::path(
880+ get,
881+ path = "/menus/{id}/bookings",
882+ tag = "meals",
883+ security(("session_cookie" = [])),
884+ params(("id" = String, Path, description = "Menu id"), PageParams),
885+ responses(
886+ (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<BookingResponse>),
887+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
888+ (status = 401, description = "Not authenticated", body = ErrorResponse),
889+ (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
890+ (status = 404, description = "No such menu", body = ErrorResponse),
891+ ),
892+)]
893+async fn list_menu_bookings(
894+ State(st): State<AppState>,
895+ RequireManager(_user): RequireManager,
896+ Path(id): Path<String>,
897+ Query(page): Query<PageParams>,
898+) -> Result<Json<Page<BookingResponse>>, AppError> {
899+ let (limit, offset) = page.resolve()?;
900+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
901+ .await?
902+ .ok_or(AppError::NotFound)?;
903+ let rows = MealBooking::list_for_menu(menu.get_id(), &st.db).await?;
904+ let total = rows.len() as i64;
905+ let items = booking_responses(paginate(&rows, limit, offset), &st.db).await?;
906+ Ok(Json(Page::new(items, total, limit, offset)))
907+}
908+
909+/// Give the seat back. The row survives, flipped to `cancelled` β€” the seat is
910+/// free for someone else, and the cancellation stays auditable. Only the
911+/// student it is for, or their parent, may cancel it. Refused (`409`) once the
912+/// school's `meal_cancel_cutoff_minutes` has closed the meal.
913+///
914+/// **Idempotent**: cancelling an already-cancelled booking is a `200` with the
915+/// row as it stands, not a `409`. Repeating it also replays the refund, so a
916+/// cancel that was cut short mid-flight (the tab closed, a proxy timed out) is
917+/// recovered by simply sending it again β€” the reversal is keyed to the seat's
918+/// attempt, so the money comes back exactly once however often it is retried.
919+#[utoipa::path(
920+ delete,
921+ path = "/bookings/{bid}",
922+ tag = "meals",
923+ security(("session_cookie" = [])),
924+ params(("bid" = String, Path, description = "Booking id")),
925+ responses(
926+ (status = 200, description = "Cancelled (also when it already was β€” the call is idempotent and replays the refund)", body = BookingResponse),
927+ (status = 401, description = "Not authenticated", body = ErrorResponse),
928+ (status = 403, description = "Not the booking's student, nor their parent", body = ErrorResponse),
929+ (status = 404, description = "Not found", body = ErrorResponse),
930+ (status = 409, description = "The cutoff has passed", body = ErrorResponse),
931+ ),
932+)]
933+async fn cancel_booking(
934+ State(st): State<AppState>,
935+ CurrentUser(user): CurrentUser,
936+ Path(bid): Path<String>,
937+) -> Result<Json<BookingResponse>, AppError> {
938+ let booking = MealBooking::read(&MealBookingId::from_key(&bid), &st.db)
939+ .await?
940+ .ok_or(AppError::NotFound)?;
941+ // Same door as booking: whoever may take the seat may give it back.
942+ let target = booking_target(&user, Some(booking.get_student().key()), &st.db).await?;
943+ if &target != booking.get_student() {
944+ return Err(AppError::Forbidden("not your booking"));
945+ }
946+ let cutoff = cutoff_minutes(&st.db).await?;
947+ // Flips the row and appends the reversal for that attempt's charge
948+ // together, under the same lock booking uses; the charge itself stays.
949+ let cancelled = booking.cancel(cutoff, user.get_id(), &st.db).await?;
950+ let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
951+ Ok(Json(
952+ items.into_iter().next().expect("one booking in, one out"),
953+ ))
954+}
955+
956+// ---- attendance -----------------------------------------------------------
957+//
958+// Reporting only: nothing in this section touches [`MealLedger`]. Booking is
959+// what charges, so a no-show still pays β€” the kitchen bought the food.
960+
961+#[derive(Deserialize, ToSchema)]
962+struct MarkMealAttendance {
963+ /// Who was (or was not) served β€” usually a student, but the canteen also
964+ /// feeds staff, so any existing user may be marked. The mark moves no money.
965+ student_id: String,
966+ /// `served` or `missed` β€” the canteen's own fixed pair, not the school's
967+ /// editable roll-call statuses.
968+ #[schema(example = "served")]
969+ status: String,
970+}
971+
972+#[derive(Serialize, ToSchema)]
973+struct MealAttendanceResponse {
974+ id: String,
975+ /// The menu the mark is against.
976+ menu_id: String,
977+ student: PersonRef,
978+ #[schema(example = "served")]
979+ status: String,
980+ marked_by: PersonRef,
981+ marked_at: i64,
982+}
983+
984+impl MealAttendanceResponse {
985+ fn new(row: &MealAttendance, people: &std::collections::HashMap<String, PersonRef>) -> Self {
986+ Self {
987+ id: row.get_id().key().to_string(),
988+ menu_id: row.get_menu().key().to_string(),
989+ student: PersonRef::resolve(people, row.get_student()),
990+ status: row.get_status().as_str().to_string(),
991+ marked_by: PersonRef::resolve(people, row.get_marked_by()),
992+ marked_at: row.get_marked_at().as_millis(),
993+ }
994+ }
995+}
996+
997+/// Join the people onto a page of marks β€” one query for the whole page.
998+async fn attendance_responses(
999+ rows: &[MealAttendance],
1000+ db: &Database,
1001+) -> Result<Vec<MealAttendanceResponse>, AppError> {
1002+ let people = person_map(
1003+ rows.iter()
1004+ .flat_map(|row| [row.get_student().clone(), row.get_marked_by().clone()]),
1005+ db,
1006+ )
1007+ .await?;
1008+ Ok(rows
1009+ .iter()
1010+ .map(|row| MealAttendanceResponse::new(row, &people))
1011+ .collect())
1012+}
1013+
1014+/// Record whether someone ate off a menu. Requires teacher+ β€” whoever stands
1015+/// at the canteen door marks, students never mark themselves. One row per
1016+/// (menu, person), so re-marking corrects the row rather than adding another.
1017+///
1018+/// The target need only *exist*: a canteen also serves staff, and a walk-in
1019+/// with no booking is still someone the kitchen fed. Marking is a record of
1020+/// what happened, not a check of who was entitled β€” and since it moves no
1021+/// money, a non-student mark costs nobody anything.
1022+///
1023+/// **This moves no money.** A booked student who did not show is still charged
1024+/// (the food was cooked), and a walk-in marked `served` without a booking is
1025+/// not charged either β€” booking is the only charge trigger.
1026+#[utoipa::path(
1027+ post,
1028+ path = "/menus/{id}/attendance",
1029+ tag = "meals",
1030+ security(("session_cookie" = [])),
1031+ params(("id" = String, Path, description = "Menu id")),
1032+ request_body = MarkMealAttendance,
1033+ responses(
1034+ (status = 200, description = "Attendance recorded", body = MealAttendanceResponse),
1035+ (status = 400, description = "Invalid status, or no such user", body = ErrorResponse),
1036+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1037+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1038+ (status = 404, description = "No such menu", body = ErrorResponse),
1039+ ),
1040+)]
1041+async fn mark_attendance(
1042+ State(st): State<AppState>,
1043+ RequireTeacher(marker): RequireTeacher,
1044+ Path(id): Path<String>,
1045+ Json(req): Json<MarkMealAttendance>,
1046+) -> Result<Json<MealAttendanceResponse>, AppError> {
1047+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
1048+ .await?
1049+ .ok_or(AppError::NotFound)?;
1050+ let status = MealAttendanceStatus::try_new(&req.status)?;
1051+ let student = UserId::from_key(&req.student_id);
1052+ // The target must exist; no booking is required, since a walk-in was still
1053+ // served and the record is operationally true.
1054+ if User::read(&student, &st.db).await?.is_none() {
1055+ return Err(AppError::Validation(ValidationError::Invalid {
1056+ field: "student_id",
1057+ reason: "target user does not exist",
1058+ }));
1059+ }
1060+ let row =
1061+ MealAttendance::mark(menu.get_id(), &student, status, marker.get_id(), &st.db).await?;
1062+ let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?;
1063+ Ok(Json(
1064+ items.into_iter().next().expect("one mark in, one out"),
1065+ ))
1066+}
1067+
1068+/// Who ate off one menu. Requires teacher+. Paged via `?limit=&offset=`.
1069+#[utoipa::path(
1070+ get,
1071+ path = "/menus/{id}/attendance",
1072+ tag = "meals",
1073+ security(("session_cookie" = [])),
1074+ params(("id" = String, Path, description = "Menu id"), PageParams),
1075+ responses(
1076+ (status = 200, description = "A page of marks (all of them when unpaged)", body = Page<MealAttendanceResponse>),
1077+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1078+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1079+ (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1080+ (status = 404, description = "No such menu", body = ErrorResponse),
1081+ ),
1082+)]
1083+async fn list_menu_attendance(
1084+ State(st): State<AppState>,
1085+ _teacher: RequireTeacher,
1086+ Path(id): Path<String>,
1087+ Query(page): Query<PageParams>,
1088+) -> Result<Json<Page<MealAttendanceResponse>>, AppError> {
1089+ let (limit, offset) = page.resolve()?;
1090+ // Menu must exist β€” a missing menu is a 404, not an empty list.
1091+ let menu = Menu::read(&MenuId::from_key(&id), &st.db)
1092+ .await?
1093+ .ok_or(AppError::NotFound)?;
1094+ let rows = MealAttendance::list_for_menu(menu.get_id(), &st.db).await?;
1095+ let total = rows.len() as i64;
1096+ let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?;
1097+ Ok(Json(Page::new(items, total, limit, offset)))
1098+}
1099+
1100+/// One student's meal-attendance history, newest mark first. Requires teacher+,
1101+/// or a parent linked to them β€” the caller's own id always passes, like the
1102+/// balance and ledger reads. Narrow to a date range with `?from=&to=`
1103+/// (inclusive `YYYY-MM-DD` bounds on the menu's day). Paged via `?limit=&offset=`.
1104+#[utoipa::path(
1105+ get,
1106+ path = "/attendance/{user}",
1107+ tag = "meals",
1108+ security(("session_cookie" = [])),
1109+ params(("user" = String, Path, description = "Student id"), MenuRange, PageParams),
1110+ responses(
1111+ (status = 200, description = "A page of marks (all of them when unpaged)", body = Page<MealAttendanceResponse>),
1112+ (status = 400, description = "Malformed date bound, limit, or offset", body = ErrorResponse),
1113+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1114+ (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
1115+ ),
1116+)]
1117+async fn user_attendance(
1118+ State(st): State<AppState>,
1119+ CurrentUser(caller): CurrentUser,
1120+ Path(user): Path<String>,
1121+ Query(range): Query<MenuRange>,
1122+ Query(page): Query<PageParams>,
1123+) -> Result<Json<Page<MealAttendanceResponse>>, AppError> {
1124+ let (limit, offset) = page.resolve()?;
1125+ let target = UserId::from_key(&user);
1126+ ensure_can_read_student(&caller, &target, &st.db).await?;
1127+ let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
1128+ let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
1129+ let rows =
1130+ MealAttendance::list_for_student(&target, from.as_ref(), to.as_ref(), &st.db).await?;
1131+ let total = rows.len() as i64;
1132+ let items = attendance_responses(paginate(&rows, limit, offset), &st.db).await?;
1133+ Ok(Json(Page::new(items, total, limit, offset)))
1134+}
1135+
1136+// ---- money ----------------------------------------------------------------
1137+
1138+#[derive(Serialize, ToSchema)]
1139+struct BalanceResponse {
1140+ student: PersonRef,
1141+ /// `credits + reversals - charges`, in **minor units** (kuruş). Negative
1142+ /// means the student owes the school. Derived on every read, never stored.
1143+ #[schema(example = -4500)]
1144+ balance_minor: i64,
1145+}
1146+
1147+#[derive(Serialize, ToSchema)]
1148+struct LedgerResponse {
1149+ id: String,
1150+ student: PersonRef,
1151+ /// `charge`, `credit`, or `reversal`.
1152+ #[schema(example = "charge")]
1153+ kind: String,
1154+ /// Always positive β€” the sign is the `kind`'s business.
1155+ #[schema(example = 4500)]
1156+ amount_minor: i64,
1157+ /// What caused the line: a booking id on a `charge`, the reversed charge's
1158+ /// own id on a `reversal`, absent on a `credit`.
1159+ source: Option<String>,
1160+ method: Option<String>,
1161+ note: Option<String>,
1162+ /// Who wrote it: the booker on a charge or reversal, the admin on a credit.
1163+ recorded_by: PersonRef,
1164+ created_at: i64,
1165+}
1166+
1167+impl LedgerResponse {
1168+ fn new(line: &MealLedger, people: &std::collections::HashMap<String, PersonRef>) -> Self {
1169+ Self {
1170+ id: line.get_id().key().to_string(),
1171+ student: PersonRef::resolve(people, line.get_student()),
1172+ kind: line.get_kind().as_str().to_string(),
1173+ amount_minor: line.get_amount_minor().as_minor(),
1174+ source: line.get_source_key().map(str::to_string),
1175+ method: line.get_method().map(|m| m.as_str().to_string()),
1176+ note: line.get_note().map(|n| n.as_str().to_string()),
1177+ recorded_by: PersonRef::resolve(people, line.get_recorded_by()),
1178+ created_at: line.get_created_at().as_millis(),
1179+ }
1180+ }
1181+}
1182+
1183+/// Join the people onto a page of ledger lines β€” one query for the whole page.
1184+async fn ledger_responses(
1185+ lines: &[MealLedger],
1186+ db: &Database,
1187+) -> Result<Vec<LedgerResponse>, AppError> {
1188+ let people = person_map(
1189+ lines
1190+ .iter()
1191+ .flat_map(|line| [line.get_student().clone(), line.get_recorded_by().clone()]),
1192+ db,
1193+ )
1194+ .await?;
1195+ Ok(lines
1196+ .iter()
1197+ .map(|line| LedgerResponse::new(line, &people))
1198+ .collect())
1199+}
1200+
1201+/// One student's balance, resolved to a response. Shared by both balance routes.
1202+async fn balance_response(
1203+ student: &UserId,
1204+ db: &Database,
1205+) -> Result<Json<BalanceResponse>, AppError> {
1206+ let people = person_map(std::iter::once(student.clone()), db).await?;
1207+ Ok(Json(BalanceResponse {
1208+ student: PersonRef::resolve(&people, student),
1209+ balance_minor: MealLedger::balance_of(student, db).await?,
1210+ }))
1211+}
1212+
1213+/// Reading someone else's meal record β€” money, attendance, dietary profile:
1214+/// teacher+, or a parent linked to the student. Reading your *own* is always
1215+/// allowed, since every `{user}` route here accepts the caller's own id; that
1216+/// is the one way this gate differs from [`super::ensure_can_observe`], which
1217+/// 403s a self-read because its subjects have their own `/me` routes.
1218+async fn ensure_can_read_student(
1219+ caller: &User,
1220+ target: &UserId,
1221+ db: &Database,
1222+) -> Result<(), AppError> {
1223+ if caller.get_id() == target {
1224+ return Ok(());
1225+ }
1226+ super::ensure_can_observe(caller, target, db).await
1227+}
1228+
1229+/// What the caller owes or has on account.
1230+#[utoipa::path(
1231+ get,
1232+ path = "/balance/me",
1233+ tag = "meals",
1234+ security(("session_cookie" = [])),
1235+ responses(
1236+ (status = 200, description = "The caller's meal balance", body = BalanceResponse),
1237+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1238+ ),
1239+)]
1240+async fn my_balance(
1241+ State(st): State<AppState>,
1242+ CurrentUser(user): CurrentUser,
1243+) -> Result<Json<BalanceResponse>, AppError> {
1244+ balance_response(user.get_id(), &st.db).await
1245+}
1246+
1247+/// One student's meal balance. Requires teacher+, or a parent link to them β€”
1248+/// the caller's own id always passes.
1249+#[utoipa::path(
1250+ get,
1251+ path = "/balance/{user}",
1252+ tag = "meals",
1253+ security(("session_cookie" = [])),
1254+ params(("user" = String, Path, description = "Student id")),
1255+ responses(
1256+ (status = 200, description = "The student's meal balance", body = BalanceResponse),
1257+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1258+ (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
1259+ ),
1260+)]
1261+async fn user_balance(
1262+ State(st): State<AppState>,
1263+ CurrentUser(caller): CurrentUser,
1264+ Path(user): Path<String>,
1265+) -> Result<Json<BalanceResponse>, AppError> {
1266+ let target = UserId::from_key(&user);
1267+ ensure_can_read_student(&caller, &target, &st.db).await?;
1268+ balance_response(&target, &st.db).await
1269+}
1270+
1271+/// One student's statement, newest line first: every charge, credit, and
1272+/// reversal. Nothing here is ever edited or deleted β€” a correction is another
1273+/// line. Same gate as the balance. Paged via `?limit=&offset=`.
1274+#[utoipa::path(
1275+ get,
1276+ path = "/ledger/{user}",
1277+ tag = "meals",
1278+ security(("session_cookie" = [])),
1279+ params(("user" = String, Path, description = "Student id"), PageParams),
1280+ responses(
1281+ (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page<LedgerResponse>),
1282+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1283+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1284+ (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
1285+ ),
1286+)]
1287+async fn user_ledger(
1288+ State(st): State<AppState>,
1289+ CurrentUser(caller): CurrentUser,
1290+ Path(user): Path<String>,
1291+ Query(page): Query<PageParams>,
1292+) -> Result<Json<Page<LedgerResponse>>, AppError> {
1293+ let (limit, offset) = page.resolve()?;
1294+ let target = UserId::from_key(&user);
1295+ ensure_can_read_student(&caller, &target, &st.db).await?;
1296+ let rows = MealLedger::list_for_student(&target, &st.db).await?;
1297+ let total = rows.len() as i64;
1298+ let items = ledger_responses(paginate(&rows, limit, offset), &st.db).await?;
1299+ Ok(Json(Page::new(items, total, limit, offset)))
1300+}
1301+
1302+#[derive(Deserialize, ToSchema)]
1303+struct RecordCredit {
1304+ /// The student the money is for.
1305+ student_id: String,
1306+ /// How much came in, **minor units** (kuruş), positive.
1307+ #[schema(minimum = 1, maximum = 10000000, example = 25000)]
1308+ amount_minor: i64,
1309+ /// How it arrived ("cash", "havale", …). Free text β€” the backend speaks to
1310+ /// no payment gateway and stores no card data.
1311+ #[schema(max_length = 50, example = "cash")]
1312+ method: Option<String>,
1313+ #[schema(max_length = 500, example = "receipt 2026-114")]
1314+ note: Option<String>,
1315+}
1316+
1317+/// Record money received from a student. **Admin only** β€” not manager: writing
1318+/// down cash is the highest-trust action in the app. Appends a `credit` line;
1319+/// nothing in the ledger is ever edited or removed, so an over-credit is
1320+/// corrected by a compensating line, not by a fix-up.
1321+#[utoipa::path(
1322+ post,
1323+ path = "/credits",
1324+ tag = "meals",
1325+ security(("session_cookie" = [])),
1326+ request_body = RecordCredit,
1327+ responses(
1328+ (status = 201, description = "Credit recorded", body = LedgerResponse),
1329+ (status = 400, description = "Invalid amount, method, note, or a non-student target", body = ErrorResponse),
1330+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1331+ (status = 403, description = "Requires the admin role", body = ErrorResponse),
1332+ (status = 404, description = "No such user", body = ErrorResponse),
1333+ ),
1334+)]
1335+async fn record_credit(
1336+ State(st): State<AppState>,
1337+ RequireAdmin(admin): RequireAdmin,
1338+ Json(req): Json<RecordCredit>,
1339+) -> Result<(StatusCode, Json<LedgerResponse>), AppError> {
1340+ let student = UserId::from_key(&req.student_id);
1341+ // Only a student carries a meal balance; crediting anyone else is a typo,
1342+ // and a typo here is money in the wrong ledger.
1343+ if User::read(&student, &st.db)
1344+ .await?
1345+ .ok_or(AppError::NotFound)?
1346+ .get_role()
1347+ != Role::Student
1348+ {
1349+ return Err(AppError::Validation(ValidationError::Invalid {
1350+ field: "student_id",
1351+ reason: "only a student carries a meal balance",
1352+ }));
1353+ }
1354+ let line = MealLedger::credit(
1355+ &student,
1356+ LedgerAmount::try_new(req.amount_minor)?,
1357+ req.method
1358+ .as_deref()
1359+ .map(LedgerMethod::try_new)
1360+ .transpose()?
1361+ .flatten(),
1362+ req.note
1363+ .as_deref()
1364+ .map(LedgerNote::try_new)
1365+ .transpose()?
1366+ .flatten(),
1367+ admin.get_id(),
1368+ &st.db,
1369+ )
1370+ .await?;
1371+ let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?;
1372+ Ok((
1373+ StatusCode::CREATED,
1374+ Json(items.into_iter().next().expect("one line in, one out")),
1375+ ))
1376+}
src/web/mod.rsmodified+1 -0
@@ -17,6 +17,7 @@ pub mod exams;
17 pub mod homework;17 pub mod homework;
18 pub mod limits;18 pub mod limits;
19 pub mod marks;19 pub mod marks;
20+pub mod meals;
20 pub mod messages;21 pub mod messages;
21 pub mod notes;22 pub mod notes;
22 pub mod pomodoro;23 pub mod pomodoro;
src/web/settings.rsmodified+91 -4
@@ -7,12 +7,13 @@ use utoipa_axum::routes;
7 7
8 use crate::constant::SETTINGS_UPDATE_RETRIES;8 use crate::constant::SETTINGS_UPDATE_RETRIES;
9 use crate::domain::exam_result::ExamResult;9 use crate::domain::exam_result::ExamResult;
10-use crate::domain::settings::{ExamKindDef, GradeBand, Settings};10+use crate::domain::menu::{MENU_LOCK, Menu};
11+use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
11 use crate::error::{AppError, ErrorResponse};12 use crate::error::{AppError, ErrorResponse};
12 use crate::state::AppState;13 use crate::state::AppState;
13 14
14 use super::exams::EXAM_LOCK;15 use super::exams::EXAM_LOCK;
15-use super::{CurrentUser, RequireManager};16+use super::{CurrentUser, RequireManager, set_or_clear};
16 17
17 pub fn routes() -> OpenApiRouter<AppState> {18 pub fn routes() -> OpenApiRouter<AppState> {
18 OpenApiRouter::new().routes(routes!(get_settings, update_settings))19 OpenApiRouter::new().routes(routes!(get_settings, update_settings))
@@ -31,6 +32,15 @@ struct ExamKindDto {
31 weight: i64,32 weight: i64,
32 }33 }
33 34
35+/// One meal slot the school serves. A published menu snapshots this name, so
36+/// renaming or retiring a slot never rewrites a past menu.
37+#[derive(Serialize, Deserialize, ToSchema)]
38+struct MealSlotDto {
39+ /// The `slot` value menus carry, 1–50 characters.
40+ #[schema(example = "lunch", max_length = 50)]
41+ name: String,
42+}
43+
34 /// One grade-display band: marks at or above `min` (and below the next band's44 /// One grade-display band: marks at or above `min` (and below the next band's
35 /// `min`) render as `label`.45 /// `min`) render as `label`.
36 #[derive(Serialize, Deserialize, ToSchema)]46 #[derive(Serialize, Deserialize, ToSchema)]
@@ -74,6 +84,17 @@ struct SettingsResponse {
74 /// Character limit on one chat message.84 /// Character limit on one chat message.
75 #[schema(example = 4000)]85 #[schema(example = 4000)]
76 max_chatbot_message_len: i64,86 max_chatbot_message_len: i64,
87+ /// Meal slots menus may be published for. Empty = the school runs no meal
88+ /// program.
89+ #[schema(example = json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}]))]
90+ meal_slots: Vec<MealSlotDto>,
91+ /// Dietary tags a dish and a student's profile may carry.
92+ #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))]
93+ dietary_tags: Vec<String>,
94+ /// How many minutes before a meal booking and cancelling close.
95+ /// `null` = no cutoff.
96+ #[schema(example = 120)]
97+ meal_cancel_cutoff_minutes: Option<i64>,
77 }98 }
78 99
79 impl SettingsResponse {100 impl SettingsResponse {
@@ -100,6 +121,15 @@ impl SettingsResponse {
100 chatbot_history_turns: settings.get_chatbot_history_turns(),121 chatbot_history_turns: settings.get_chatbot_history_turns(),
101 max_chatbot_threads: settings.get_max_chatbot_threads(),122 max_chatbot_threads: settings.get_max_chatbot_threads(),
102 max_chatbot_message_len: settings.get_max_chatbot_message_len(),123 max_chatbot_message_len: settings.get_max_chatbot_message_len(),
124+ meal_slots: settings
125+ .get_meal_slots()
126+ .iter()
127+ .map(|slot| MealSlotDto {
128+ name: slot.get_name().to_string(),
129+ })
130+ .collect(),
131+ dietary_tags: settings.get_dietary_tags(),
132+ meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(),
103 }133 }
104 }134 }
105 }135 }
@@ -135,6 +165,21 @@ struct UpdateSettings {
135 /// server hard cap.165 /// server hard cap.
136 #[schema(example = 4000, minimum = 100, maximum = 8_000)]166 #[schema(example = 4000, minimum = 100, maximum = 8_000)]
137 max_chatbot_message_len: Option<i64>,167 max_chatbot_message_len: Option<i64>,
168+ /// Replaces the whole list when present: at most 20 entries with unique
169+ /// names, each 1–50 characters. `[]` switches the meal program off. A slot
170+ /// a menu was already published for cannot be removed (409).
171+ #[schema(max_items = 20)]
172+ meal_slots: Option<Vec<MealSlotDto>>,
173+ /// Replaces the whole list when present: at most 20 unique entries, each
174+ /// 1–50 characters. `[]` means the school tracks no dietary tags.
175+ #[schema(max_items = 20)]
176+ dietary_tags: Option<Vec<String>>,
177+ /// Minutes before a meal at which booking *and* cancelling close,
178+ /// `0`–`10080` (one week). Omit to keep the current value; send `null` for
179+ /// no cutoff at all.
180+ #[serde(default, deserialize_with = "set_or_clear")]
181+ #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
182+ meal_cancel_cutoff_minutes: Option<Option<i64>>,
138 }183 }
139 184
140 /// The school's current policy. Any authenticated user β€” clients need it to185 /// The school's current policy. Any authenticated user β€” clients need it to
@@ -168,7 +213,9 @@ async fn get_settings(
168 /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is213 /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
169 /// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise214 /// gone counts with weight 1 until the kind returns. `max_file_bytes` likewise
170 /// applies at upload time only β€” already-stored files keep their size, and the215 /// applies at upload time only β€” already-stored files keep their size, and the
171-/// chatbot knobs apply to the next chat request only.216+/// chatbot knobs apply to the next chat request only. `meal_slots` follows the
217+/// exam-kind rule: a slot a menu was already published for cannot be dropped
218+/// (409), because the menu snapshotted its name.
172 #[utoipa::path(219 #[utoipa::path(
173 patch,220 patch,
174 path = "/",221 path = "/",
@@ -180,7 +227,7 @@ async fn get_settings(
180 (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse),227 (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse),
181 (status = 401, description = "Not authenticated", body = ErrorResponse),228 (status = 401, description = "Not authenticated", body = ErrorResponse),
182 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),229 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
183- (status = 409, description = "A removed exam kind still has graded exams, or concurrent edits kept changing the settings mid-save", body = ErrorResponse),230+ (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),
184 ),231 ),
185 )]232 )]
186 async fn update_settings(233 async fn update_settings(
@@ -199,6 +246,14 @@ async fn update_settings(
199 Some(_) => Some(EXAM_LOCK.write().await),246 Some(_) => Some(EXAM_LOCK.write().await),
200 None => None,247 None => None,
201 };248 };
249+ // Same shape for the slot list: the "was a menu ever published for it?"
250+ // check and the save are one unit, so a publish cannot land on a slot that
251+ // is being dropped mid-flight. Taken after EXAM_LOCK; nothing under
252+ // MENU_LOCK ever takes EXAM_LOCK, so the pair cannot deadlock.
253+ let _menu_guard = match req.meal_slots {
254+ Some(_) => Some(MENU_LOCK.lock().await),
255+ None => None,
256+ };
202 for _ in 0..SETTINGS_UPDATE_RETRIES {257 for _ in 0..SETTINGS_UPDATE_RETRIES {
203 let current = Settings::load(&st.db).await?;258 let current = Settings::load(&st.db).await?;
204 259
@@ -225,6 +280,29 @@ async fn update_settings(
225 )));280 )));
226 }281 }
227 }282 }
283+ // Same shape for meal slots: a slot a menu was already published for
284+ // cannot leave the list β€” the menu snapshotted the name as text, and a
285+ // slot no longer offered would leave that menu unreachable from the
286+ // school's own list.
287+ let meal_slots = match &req.meal_slots {
288+ Some(slots) => slots
289+ .iter()
290+ .map(|slot| MealSlotDef::try_new(&slot.name))
291+ .collect::<Result<Vec<_>, _>>()?,
292+ None => current.get_meal_slots(),
293+ };
294+ for gone in current.get_meal_slots().iter().filter(|slot| {
295+ !meal_slots
296+ .iter()
297+ .any(|new| new.get_name() == slot.get_name())
298+ }) {
299+ if Menu::any_for_slot(gone.get_name(), &st.db).await? {
300+ return Err(AppError::ConflictOwned(format!(
301+ "menus are already published for the '{}' slot β€” it cannot be removed",
302+ gone.get_name()
303+ )));
304+ }
305+ }
228 let attendance_statuses = req306 let attendance_statuses = req
229 .attendance_statuses307 .attendance_statuses
230 .clone()308 .clone()
@@ -252,6 +330,15 @@ async fn update_settings(
252 params.max_chatbot_message_len = req330 params.max_chatbot_message_len = req
253 .max_chatbot_message_len331 .max_chatbot_message_len
254 .unwrap_or(params.max_chatbot_message_len);332 .unwrap_or(params.max_chatbot_message_len);
333+ params.meal_slots = meal_slots;
334+ params.dietary_tags = req
335+ .dietary_tags
336+ .clone()
337+ .unwrap_or_else(|| current.get_dietary_tags());
338+ // Double option: absent keeps the knob, `null` clears it (no cutoff).
339+ params.meal_cancel_cutoff_minutes = req
340+ .meal_cancel_cutoff_minutes
341+ .unwrap_or(params.meal_cancel_cutoff_minutes);
255 342
256 let settings = Settings::try_new(params)?;343 let settings = Settings::try_new(params)?;
257 if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {344 if let Some(saved) = settings.save_if_unchanged(&current, &st.db).await? {
tests/integration.rsmodified+2125 -0

Diff too large; view file

@@ -10969,6 +10969,146 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() {
10969 );10969 );
10970 }10970 }
10971 10971
10972+/// The food-program knobs are `option<…>` columns, and every settings save
10973+/// rewrites the whole row β€” so a PATCH that never mentions them must still
10974+/// round-trip them. (A `DEFAULT []` column plus a struct that dropped the field
10975+/// aborts the transaction with a coercion error instead.)
10976+#[tokio::test]
10977+async fn settings_round_trip_the_food_program_knobs() {
10978+ let (app, db) = app_and_db().await;
10979+ let manager = login_as(&app, &db, "meal.manager", "manager").await;
10980+
10981+ // Unset columns read as the built-in seeds; an absent cutoff is no cutoff.
10982+ let res = send(&app, "GET", "/settings", Some(&manager), None).await;
10983+ assert_eq!(
10984+ res.body["meal_slots"],
10985+ json!([{"name": "breakfast"}, {"name": "lunch"}, {"name": "snack"}])
10986+ );
10987+ assert_eq!(
10988+ res.body["dietary_tags"],
10989+ json!([
10990+ "vegetarian",
10991+ "vegan",
10992+ "gluten_free",
10993+ "lactose_free",
10994+ "nut_allergy"
10995+ ])
10996+ );
10997+ assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null));
10998+
10999+ // A PATCH of an unrelated field still writes the whole row.
11000+ let res = send(
11001+ &app,
11002+ "PATCH",
11003+ "/settings",
11004+ Some(&manager),
11005+ Some(json!({ "max_file_bytes": 4096 })),
11006+ )
11007+ .await;
11008+ assert_eq!(res.status, StatusCode::OK);
11009+ assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 3);
11010+
11011+ // All three set at once; slot names arrive trimmed.
11012+ let res = send(
11013+ &app,
11014+ "PATCH",
11015+ "/settings",
11016+ Some(&manager),
11017+ Some(json!({
11018+ "meal_slots": [{"name": "lunch"}, {"name": " snack "}],
11019+ "dietary_tags": ["vegan"],
11020+ "meal_cancel_cutoff_minutes": 120,
11021+ })),
11022+ )
11023+ .await;
11024+ assert_eq!(res.status, StatusCode::OK);
11025+ assert_eq!(
11026+ res.body["meal_slots"],
11027+ json!([{"name": "lunch"}, {"name": "snack"}])
11028+ );
11029+ assert_eq!(res.body["dietary_tags"], json!(["vegan"]));
11030+ assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120);
11031+
11032+ // A later PATCH that omits them keeps them β€” now over a row that really
11033+ // carries the columns.
11034+ let res = send(
11035+ &app,
11036+ "PATCH",
11037+ "/settings",
11038+ Some(&manager),
11039+ Some(json!({ "chatbot_history_turns": 3 })),
11040+ )
11041+ .await;
11042+ assert_eq!(res.status, StatusCode::OK);
11043+ assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2);
11044+ assert_eq!(res.body["meal_cancel_cutoff_minutes"], 120);
11045+
11046+ // `null` clears the cutoff (no cutoff at all); the lists stay.
11047+ let res = send(
11048+ &app,
11049+ "PATCH",
11050+ "/settings",
11051+ Some(&manager),
11052+ Some(json!({ "meal_cancel_cutoff_minutes": null })),
11053+ )
11054+ .await;
11055+ assert_eq!(res.status, StatusCode::OK);
11056+ assert_eq!(res.body["meal_cancel_cutoff_minutes"], json!(null));
11057+ assert_eq!(res.body["meal_slots"].as_array().unwrap().len(), 2);
11058+
11059+ // Bounds hold on the way in.
11060+ for body in [
11061+ json!({ "meal_cancel_cutoff_minutes": 10_081 }),
11062+ json!({ "meal_cancel_cutoff_minutes": -1 }),
11063+ json!({ "meal_slots": [{"name": " "}] }),
11064+ json!({ "meal_slots": [{"name": "Lunch"}, {"name": "lunch"}] }),
11065+ json!({ "dietary_tags": ["vegan", "VEGAN"] }),
11066+ ] {
11067+ let res = send(
11068+ &app,
11069+ "PATCH",
11070+ "/settings",
11071+ Some(&manager),
11072+ Some(body.clone()),
11073+ )
11074+ .await;
11075+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "should reject {body}");
11076+ }
11077+
11078+ // A published menu pins the slot it snapshotted: dropping it is a 409.
11079+ db.query(
11080+ "CREATE menu SET date = '2026-07-27', slot = 'lunch',
11081+ created_by = (SELECT VALUE id FROM user LIMIT 1)[0], created_at = 0",
11082+ )
11083+ .await
11084+ .unwrap()
11085+ .check()
11086+ .unwrap();
11087+ let res = send(
11088+ &app,
11089+ "PATCH",
11090+ "/settings",
11091+ Some(&manager),
11092+ Some(json!({ "meal_slots": [{"name": "snack"}] })),
11093+ )
11094+ .await;
11095+ assert_eq!(res.status, StatusCode::CONFLICT);
11096+ // Keeping it is fine; an unused slot still leaves freely.
11097+ let res = send(
11098+ &app,
11099+ "PATCH",
11100+ "/settings",
11101+ Some(&manager),
11102+ Some(json!({ "meal_slots": [{"name": "lunch"}, {"name": "dinner"}] })),
11103+ )
11104+ .await;
11105+ assert_eq!(res.status, StatusCode::OK);
11106+ assert_eq!(
11107+ res.body["meal_slots"],
11108+ json!([{"name": "lunch"}, {"name": "dinner"}])
11109+ );
11110+}
11111+
10972 // --- question images ---------------------------------------------------------11112 // --- question images ---------------------------------------------------------
10973 11113
10974 /// POST `bytes` as a multipart image upload to `path`; returns (status, json).11114 /// 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() {
20022 let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await;20162 let res = send(&app, "GET", "/exams?starts_after=-1", Some(&ayse), None).await;
20023 assert_eq!(res.status, StatusCode::BAD_REQUEST);20163 assert_eq!(res.status, StatusCode::BAD_REQUEST);
20024 }20164 }
20165+
20166+// --- meals: menus and dishes ---------------------------------------------
20167+
20168+/// The whole published side, end to end: publish, list, patch the cap, add and
20169+/// edit and drop a dish, and the unique day+slot rule.
20170+#[tokio::test]
20171+async fn menus_and_dishes_round_trip() {
20172+ let (app, db) = app_and_db().await;
20173+ let mgr = login_as(&app, &db, "meal_mgr", "manager").await;
20174+
20175+ let res = send(
20176+ &app,
20177+ "POST",
20178+ "/meals/menus",
20179+ Some(&mgr),
20180+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 120 })),
20181+ )
20182+ .await;
20183+ assert_eq!(res.status, StatusCode::CREATED);
20184+ let menu = id_of(&res.body);
20185+ assert_eq!(res.body["slot"], "lunch");
20186+ assert_eq!(res.body["capacity"], 120);
20187+ assert_eq!(res.body["created_by"]["username"], "meal_mgr");
20188+
20189+ // A second menu for the same day and slot is the UNIQUE rule, as a 409 β€”
20190+ // never a 500 out of the index.
20191+ let res = send(
20192+ &app,
20193+ "POST",
20194+ "/meals/menus",
20195+ Some(&mgr),
20196+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
20197+ )
20198+ .await;
20199+ assert_eq!(res.status, StatusCode::CONFLICT);
20200+
20201+ // Same day, another slot is a different meal and lands fine.
20202+ let res = send(
20203+ &app,
20204+ "POST",
20205+ "/meals/menus",
20206+ Some(&mgr),
20207+ Some(json!({ "date": "2026-09-14", "slot": "breakfast" })),
20208+ )
20209+ .await;
20210+ assert_eq!(res.status, StatusCode::CREATED);
20211+
20212+ // Dishes: money is minor units, tags come from the school's list.
20213+ let res = send(
20214+ &app,
20215+ "POST",
20216+ &format!("/meals/menus/{menu}/dishes"),
20217+ Some(&mgr),
20218+ Some(json!({
20219+ "name": "Mercimek Γ§orbasΔ±",
20220+ "description": " ",
20221+ "price_minor": 4550,
20222+ "tags": ["vegetarian", "vegetarian"],
20223+ })),
20224+ )
20225+ .await;
20226+ assert_eq!(res.status, StatusCode::CREATED);
20227+ let dish = id_of(&res.body);
20228+ assert_eq!(res.body["price_minor"], 4550);
20229+ // A whitespace-only description is the absence of one, and repeated tags
20230+ // collapse.
20231+ assert_eq!(res.body["description"], json!(null));
20232+ assert_eq!(res.body["tags"], json!(["vegetarian"]));
20233+
20234+ let res = send(
20235+ &app,
20236+ "PATCH",
20237+ &format!("/meals/dishes/{dish}"),
20238+ Some(&mgr),
20239+ Some(json!({ "price_minor": 5000, "description": "gΓΌnlΓΌk" })),
20240+ )
20241+ .await;
20242+ assert_eq!(res.status, StatusCode::OK);
20243+ assert_eq!(res.body["price_minor"], 5000);
20244+ assert_eq!(res.body["description"], "gΓΌnlΓΌk");
20245+ assert_eq!(res.body["name"], "Mercimek Γ§orbasΔ±");
20246+
20247+ // The menu read carries its dishes, and `null` clears the cap.
20248+ let res = send(
20249+ &app,
20250+ "PATCH",
20251+ &format!("/meals/menus/{menu}"),
20252+ Some(&mgr),
20253+ Some(json!({ "capacity": null })),
20254+ )
20255+ .await;
20256+ assert_eq!(res.status, StatusCode::OK);
20257+ assert_eq!(res.body["capacity"], json!(null));
20258+ assert_eq!(res.body["dishes"].as_array().expect("dishes").len(), 1);
20259+
20260+ // Any authenticated user reads; the range filter is inclusive.
20261+ let student = login(&app, "meal_student").await;
20262+ let res = send(
20263+ &app,
20264+ "GET",
20265+ "/meals/menus?from=2026-09-14&to=2026-09-14",
20266+ Some(&student),
20267+ None,
20268+ )
20269+ .await;
20270+ assert_eq!(res.status, StatusCode::OK);
20271+ assert_eq!(common::total(&res.body), 2);
20272+ let res = send(
20273+ &app,
20274+ "GET",
20275+ "/meals/menus?from=2026-09-15",
20276+ Some(&student),
20277+ None,
20278+ )
20279+ .await;
20280+ assert_eq!(common::total(&res.body), 0);
20281+
20282+ let res = send(
20283+ &app,
20284+ "DELETE",
20285+ &format!("/meals/dishes/{dish}"),
20286+ Some(&mgr),
20287+ None,
20288+ )
20289+ .await;
20290+ assert_eq!(res.status, StatusCode::NO_CONTENT);
20291+ let res = send(
20292+ &app,
20293+ "GET",
20294+ &format!("/meals/menus/{menu}"),
20295+ Some(&mgr),
20296+ None,
20297+ )
20298+ .await;
20299+ assert_eq!(res.body["dishes"], json!([]));
20300+
20301+ let res = send(
20302+ &app,
20303+ "DELETE",
20304+ &format!("/meals/menus/{menu}"),
20305+ Some(&mgr),
20306+ None,
20307+ )
20308+ .await;
20309+ assert_eq!(res.status, StatusCode::NO_CONTENT);
20310+ let res = send(
20311+ &app,
20312+ "GET",
20313+ &format!("/meals/menus/{menu}"),
20314+ Some(&mgr),
20315+ None,
20316+ )
20317+ .await;
20318+ assert_eq!(res.status, StatusCode::NOT_FOUND);
20319+}
20320+
20321+/// Publishing is manager+, and both school-editable lists are enforced: a slot
20322+/// nobody serves and a tag nobody defined are 400s, not stored strings.
20323+#[tokio::test]
20324+async fn menu_writes_are_manager_only_and_validate_against_settings() {
20325+ let (app, db) = app_and_db().await;
20326+ let mgr = login_as(&app, &db, "meal_mgr2", "manager").await;
20327+ let teacher = login_as(&app, &db, "meal_teacher", "teacher").await;
20328+
20329+ let body = json!({ "date": "2026-09-15", "slot": "lunch" });
20330+ let res = send(
20331+ &app,
20332+ "POST",
20333+ "/meals/menus",
20334+ Some(&teacher),
20335+ Some(body.clone()),
20336+ )
20337+ .await;
20338+ assert_eq!(res.status, StatusCode::FORBIDDEN);
20339+
20340+ // A slot outside the school's `meal_slots` never reaches the column.
20341+ let res = send(
20342+ &app,
20343+ "POST",
20344+ "/meals/menus",
20345+ Some(&mgr),
20346+ Some(json!({ "date": "2026-09-15", "slot": "brunch" })),
20347+ )
20348+ .await;
20349+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
20350+
20351+ // Neither does a malformed day.
20352+ let res = send(
20353+ &app,
20354+ "POST",
20355+ "/meals/menus",
20356+ Some(&mgr),
20357+ Some(json!({ "date": "2026-9-15", "slot": "lunch" })),
20358+ )
20359+ .await;
20360+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
20361+
20362+ let res = send(&app, "POST", "/meals/menus", Some(&mgr), Some(body)).await;
20363+ assert_eq!(res.status, StatusCode::CREATED);
20364+ let menu = id_of(&res.body);
20365+
20366+ let res = send(
20367+ &app,
20368+ "POST",
20369+ &format!("/meals/menus/{menu}/dishes"),
20370+ Some(&teacher),
20371+ Some(json!({ "name": "Pilav", "price_minor": 1000 })),
20372+ )
20373+ .await;
20374+ assert_eq!(res.status, StatusCode::FORBIDDEN);
20375+
20376+ // A tag outside the school's `dietary_tags` is a 400, on create...
20377+ let res = send(
20378+ &app,
20379+ "POST",
20380+ &format!("/meals/menus/{menu}/dishes"),
20381+ Some(&mgr),
20382+ Some(json!({ "name": "Pilav", "price_minor": 1000, "tags": ["halal"] })),
20383+ )
20384+ .await;
20385+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
20386+
20387+ // ...and on patch, and negative money never lands either.
20388+ let res = send(
20389+ &app,
20390+ "POST",
20391+ &format!("/meals/menus/{menu}/dishes"),
20392+ Some(&mgr),
20393+ Some(json!({ "name": "Pilav", "price_minor": 1000 })),
20394+ )
20395+ .await;
20396+ assert_eq!(res.status, StatusCode::CREATED);
20397+ let dish = id_of(&res.body);
20398+ let res = send(
20399+ &app,
20400+ "PATCH",
20401+ &format!("/meals/dishes/{dish}"),
20402+ Some(&mgr),
20403+ Some(json!({ "tags": ["halal"] })),
20404+ )
20405+ .await;
20406+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
20407+ let res = send(
20408+ &app,
20409+ "PATCH",
20410+ &format!("/meals/dishes/{dish}"),
20411+ Some(&mgr),
20412+ Some(json!({ "price_minor": -1 })),
20413+ )
20414+ .await;
20415+ assert_eq!(res.status, StatusCode::BAD_REQUEST);
20416+}
20417+
20418+// --- meals: bookings ------------------------------------------------------
20419+
20420+/// A seat, end to end: book, see it on both listings, cancel it (the row stays,
20421+/// flipped), re-book the same seat, and the menu-delete guard in between.
20422+#[tokio::test]
20423+async fn meal_bookings_round_trip() {
20424+ let (app, db) = app_and_db().await;
20425+ let mgr = login_as(&app, &db, "booking_mgr", "manager").await;
20426+ let ali = login(&app, "booking_ali").await;
20427+
20428+ let res = send(
20429+ &app,
20430+ "POST",
20431+ "/meals/menus",
20432+ Some(&mgr),
20433+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),
20434+ )
20435+ .await;
20436+ let menu = id_of(&res.body);
20437+
20438+ let res = send(
20439+ &app,
20440+ "POST",
20441+ &format!("/meals/menus/{menu}/bookings"),
20442+ Some(&ali),
20443+ Some(json!({})),
20444+ )
20445+ .await;
20446+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20447+ let booking = id_of(&res.body);
20448+ assert_eq!(res.body["status"], "booked");
20449+ assert_eq!(res.body["student"]["username"], "booking_ali");
20450+ assert_eq!(res.body["booked_by"]["username"], "booking_ali");
20451+ assert_eq!(res.body["cancelled_at"], json!(null));
20452+
20453+ // Booking twice is the same seat, not a second one β€” the composite id.
20454+ let res = send(
20455+ &app,
20456+ "POST",
20457+ &format!("/meals/menus/{menu}/bookings"),
20458+ Some(&ali),
20459+ Some(json!({})),
20460+ )
20461+ .await;
20462+ assert_eq!(res.status, StatusCode::CREATED);
20463+ assert_eq!(id_of(&res.body), booking);
20464+
20465+ let res = send(&app, "GET", "/meals/bookings/me", Some(&ali), None).await;
20466+ assert_eq!(res.status, StatusCode::OK);
20467+ assert_eq!(common::total(&res.body), 1);
20468+ assert_eq!(res.body["items"][0]["id"], json!(booking));
20469+
20470+ // The kitchen's list is manager+; nobody else's `/me` shows the seat.
20471+ let res = send(
20472+ &app,
20473+ "GET",
20474+ &format!("/meals/menus/{menu}/bookings"),
20475+ Some(&mgr),
20476+ None,
20477+ )
20478+ .await;
20479+ assert_eq!(common::total(&res.body), 1);
20480+ let res = send(
20481+ &app,
20482+ "GET",
20483+ &format!("/meals/menus/{menu}/bookings"),
20484+ Some(&ali),
20485+ None,
20486+ )
20487+ .await;
20488+ assert_eq!(res.status, StatusCode::FORBIDDEN);
20489+ let res = send(&app, "GET", "/meals/bookings/me", Some(&mgr), None).await;
20490+ assert_eq!(common::total(&res.body), 0);
20491+
20492+ // A menu somebody still holds a seat on cannot be unpublished.
20493+ let res = send(
20494+ &app,
20495+ "DELETE",
20496+ &format!("/meals/menus/{menu}"),
20497+ Some(&mgr),
20498+ None,
20499+ )
20500+ .await;
20501+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
20502+
20503+ // Cancelling flips the row, it never deletes it.
20504+ let res = send(
20505+ &app,
20506+ "DELETE",
20507+ &format!("/meals/bookings/{booking}"),
20508+ Some(&ali),
20509+ None,
20510+ )
20511+ .await;
20512+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20513+ assert_eq!(res.body["status"], "cancelled");
20514+ let stamp = res.body["cancelled_at"].as_i64().expect("stamped");
20515+ assert!(stamp > 0);
20516+ // Cancelling again is idempotent β€” a `200` with the row as it stands, so a
20517+ // cancel interrupted before its refund can be recovered by repeating it.
20518+ // The stamp is not re-written: the seat was freed once.
20519+ let res = send(
20520+ &app,
20521+ "DELETE",
20522+ &format!("/meals/bookings/{booking}"),
20523+ Some(&ali),
20524+ None,
20525+ )
20526+ .await;
20527+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20528+ assert_eq!(res.body["status"], "cancelled");
20529+ assert_eq!(res.body["cancelled_at"], stamp);
20530+ let res = send(
20531+ &app,
20532+ "GET",
20533+ &format!("/meals/menus/{menu}/bookings"),
20534+ Some(&mgr),
20535+ None,
20536+ )
20537+ .await;
20538+ assert_eq!(common::total(&res.body), 1, "the cancelled row survives");
20539+
20540+ // Re-booking is the same row flipped back β€” one seat, never two.
20541+ let res = send(
20542+ &app,
20543+ "POST",
20544+ &format!("/meals/menus/{menu}/bookings"),
20545+ Some(&ali),
20546+ Some(json!({})),
20547+ )
20548+ .await;
20549+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20550+ assert_eq!(id_of(&res.body), booking);
20551+ assert_eq!(res.body["status"], "booked");
20552+ assert_eq!(res.body["cancelled_at"], json!(null));
20553+ let res = send(
20554+ &app,
20555+ "GET",
20556+ &format!("/meals/menus/{menu}/bookings"),
20557+ Some(&mgr),
20558+ None,
20559+ )
20560+ .await;
20561+ assert_eq!(common::total(&res.body), 1);
20562+
20563+ // Cancelled, the menu is free to go.
20564+ send(
20565+ &app,
20566+ "DELETE",
20567+ &format!("/meals/bookings/{booking}"),
20568+ Some(&ali),
20569+ None,
20570+ )
20571+ .await;
20572+ let res = send(
20573+ &app,
20574+ "DELETE",
20575+ &format!("/meals/menus/{menu}"),
20576+ Some(&mgr),
20577+ None,
20578+ )
20579+ .await;
20580+ assert_eq!(res.status, StatusCode::NO_CONTENT);
20581+}
20582+
20583+/// The cap refuses the seat that would overflow it, and a cancel genuinely
20584+/// gives that seat back.
20585+#[tokio::test]
20586+async fn meal_booking_capacity_caps_and_a_cancel_frees_a_seat() {
20587+ let (app, db) = app_and_db().await;
20588+ let mgr = login_as(&app, &db, "cap_mgr", "manager").await;
20589+ let res = send(
20590+ &app,
20591+ "POST",
20592+ "/meals/menus",
20593+ Some(&mgr),
20594+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 2 })),
20595+ )
20596+ .await;
20597+ let menu = id_of(&res.body);
20598+
20599+ let students: Vec<String> = {
20600+ let mut cookies = Vec::new();
20601+ for i in 0..3 {
20602+ cookies.push(login(&app, &format!("cap_student{i}")).await);
20603+ }
20604+ cookies
20605+ };
20606+ let book = |who: String| {
20607+ let app = app.clone();
20608+ let menu = menu.clone();
20609+ async move {
20610+ send(
20611+ &app,
20612+ "POST",
20613+ &format!("/meals/menus/{menu}/bookings"),
20614+ Some(&who),
20615+ Some(json!({})),
20616+ )
20617+ .await
20618+ }
20619+ };
20620+
20621+ let first = book(students[0].clone()).await;
20622+ assert_eq!(first.status, StatusCode::CREATED);
20623+ assert_eq!(book(students[1].clone()).await.status, StatusCode::CREATED);
20624+ assert_eq!(book(students[2].clone()).await.status, StatusCode::CONFLICT);
20625+
20626+ // Cancelling frees the seat β€” a cancelled row must not count.
20627+ let booking = id_of(&first.body);
20628+ send(
20629+ &app,
20630+ "DELETE",
20631+ &format!("/meals/bookings/{booking}"),
20632+ Some(&students[0]),
20633+ None,
20634+ )
20635+ .await;
20636+ assert_eq!(book(students[2].clone()).await.status, StatusCode::CREATED);
20637+ // …and the freed seat is gone again, so the first student cannot return.
20638+ assert_eq!(book(students[0].clone()).await.status, StatusCode::CONFLICT);
20639+}
20640+
20641+/// The cap is a count-then-write pair, which SurrealDB does not serialize:
20642+/// under a stampede it must still admit exactly `capacity` seats, and the
20643+/// losers must get a 409 rather than a 500. Mirrors
20644+/// `concurrent_duplicate_registrations_conflict_not_500`.
20645+#[tokio::test]
20646+async fn concurrent_meal_bookings_never_exceed_the_capacity() {
20647+ let (app, db) = app_and_db().await;
20648+ let mgr = login_as(&app, &db, "race_mgr", "manager").await;
20649+ let res = send(
20650+ &app,
20651+ "POST",
20652+ "/meals/menus",
20653+ Some(&mgr),
20654+ Some(json!({ "date": "2026-09-14", "slot": "lunch", "capacity": 3 })),
20655+ )
20656+ .await;
20657+ let menu = id_of(&res.body);
20658+
20659+ let mut students = Vec::new();
20660+ for i in 0..24 {
20661+ students.push(login(&app, &format!("race_student{i}")).await);
20662+ }
20663+
20664+ let mut handles = Vec::new();
20665+ for cookie in students {
20666+ let app = app.clone();
20667+ let menu = menu.clone();
20668+ handles.push(tokio::spawn(async move {
20669+ send(
20670+ &app,
20671+ "POST",
20672+ &format!("/meals/menus/{menu}/bookings"),
20673+ Some(&cookie),
20674+ Some(json!({})),
20675+ )
20676+ .await
20677+ .status
20678+ }));
20679+ }
20680+
20681+ let mut booked = 0;
20682+ for h in handles {
20683+ let status = h.await.unwrap();
20684+ assert!(
20685+ status == StatusCode::CREATED || status == StatusCode::CONFLICT,
20686+ "a lost race must be a 409, never a 500: {status}"
20687+ );
20688+ booked += i32::from(status == StatusCode::CREATED);
20689+ }
20690+ assert_eq!(booked, 3, "exactly the capacity was admitted");
20691+
20692+ let res = send(
20693+ &app,
20694+ "GET",
20695+ &format!("/meals/menus/{menu}/bookings"),
20696+ Some(&mgr),
20697+ None,
20698+ )
20699+ .await;
20700+ assert_eq!(common::total(&res.body), 3, "and only three rows exist");
20701+}
20702+
20703+/// One knob closes both ends: past the school's `meal_cancel_cutoff_minutes`
20704+/// neither a new booking nor a cancellation lands.
20705+#[tokio::test]
20706+async fn meal_cutoff_closes_booking_and_cancelling_alike() {
20707+ let (app, db) = app_and_db().await;
20708+ let mgr = login_as(&app, &db, "cutoff_mgr", "manager").await;
20709+ let ali = login(&app, "cutoff_ali").await;
20710+
20711+ // No cutoff configured yet, so a menu whose day is long gone still books.
20712+ let res = send(
20713+ &app,
20714+ "POST",
20715+ "/meals/menus",
20716+ Some(&mgr),
20717+ Some(json!({ "date": "2020-01-06", "slot": "lunch" })),
20718+ )
20719+ .await;
20720+ let menu = id_of(&res.body);
20721+ let res = send(
20722+ &app,
20723+ "POST",
20724+ &format!("/meals/menus/{menu}/bookings"),
20725+ Some(&ali),
20726+ Some(json!({})),
20727+ )
20728+ .await;
20729+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20730+ let booking = id_of(&res.body);
20731+
20732+ let res = send(
20733+ &app,
20734+ "PATCH",
20735+ "/settings",
20736+ Some(&mgr),
20737+ Some(json!({ "meal_cancel_cutoff_minutes": 60 })),
20738+ )
20739+ .await;
20740+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20741+
20742+ // Both ends now refuse: the meal is settled.
20743+ let res = send(
20744+ &app,
20745+ "DELETE",
20746+ &format!("/meals/bookings/{booking}"),
20747+ Some(&ali),
20748+ None,
20749+ )
20750+ .await;
20751+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
20752+ let veli = login(&app, "cutoff_veli").await;
20753+ let res = send(
20754+ &app,
20755+ "POST",
20756+ &format!("/meals/menus/{menu}/bookings"),
20757+ Some(&veli),
20758+ Some(json!({})),
20759+ )
20760+ .await;
20761+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
20762+
20763+ // A meal far enough ahead is untouched by the same cutoff.
20764+ let res = send(
20765+ &app,
20766+ "POST",
20767+ "/meals/menus",
20768+ Some(&mgr),
20769+ Some(json!({ "date": "2099-01-06", "slot": "lunch" })),
20770+ )
20771+ .await;
20772+ let later = id_of(&res.body);
20773+ let res = send(
20774+ &app,
20775+ "POST",
20776+ &format!("/meals/menus/{later}/bookings"),
20777+ Some(&ali),
20778+ Some(json!({})),
20779+ )
20780+ .await;
20781+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20782+}
20783+
20784+/// Who may take a seat: the student it is for, or a parent holding a link to
20785+/// them. Nobody else β€” a teacher does not order lunch for a child.
20786+#[tokio::test]
20787+async fn meal_bookings_are_student_or_linked_parent_only() {
20788+ let (app, db) = app_and_db().await;
20789+ let admin = login_as(&app, &db, "boss", "admin").await;
20790+ let mgr = login_as(&app, &db, "kin_mgr", "manager").await;
20791+ let teacher = login_as(&app, &db, "kin_teacher", "teacher").await;
20792+ let mom = login_as(&app, &db, "kin_mom", "parent").await;
20793+ let mom_id = me_id(&app, &mom).await;
20794+ let ali = login(&app, "kin_ali").await;
20795+ let ali_id = me_id(&app, &ali).await;
20796+ let veli = login(&app, "kin_veli").await;
20797+ let veli_id = me_id(&app, &veli).await;
20798+
20799+ let res = send(
20800+ &app,
20801+ "POST",
20802+ &format!("/users/{mom_id}/students"),
20803+ Some(&admin),
20804+ Some(json!({ "user_id": ali_id })),
20805+ )
20806+ .await;
20807+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20808+
20809+ let res = send(
20810+ &app,
20811+ "POST",
20812+ "/meals/menus",
20813+ Some(&mgr),
20814+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
20815+ )
20816+ .await;
20817+ let menu = id_of(&res.body);
20818+ let path = format!("/meals/menus/{menu}/bookings");
20819+
20820+ // The parent books for their own child.
20821+ let res = send(
20822+ &app,
20823+ "POST",
20824+ &path,
20825+ Some(&mom),
20826+ Some(json!({ "student_id": ali_id })),
20827+ )
20828+ .await;
20829+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20830+ assert_eq!(res.body["student"]["username"], "kin_ali");
20831+ assert_eq!(res.body["booked_by"]["username"], "kin_mom");
20832+ let booking = id_of(&res.body);
20833+ // …and sees it on their own list, though the seat is not theirs.
20834+ let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await;
20835+ assert_eq!(common::total(&res.body), 1);
20836+
20837+ // Never for someone else's child, and never without naming one.
20838+ let res = send(
20839+ &app,
20840+ "POST",
20841+ &path,
20842+ Some(&mom),
20843+ Some(json!({ "student_id": veli_id })),
20844+ )
20845+ .await;
20846+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
20847+ let res = send(&app, "POST", &path, Some(&mom), Some(json!({}))).await;
20848+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
20849+
20850+ // Staff do not order for children through this route.
20851+ let res = send(
20852+ &app,
20853+ "POST",
20854+ &path,
20855+ Some(&teacher),
20856+ Some(json!({ "student_id": ali_id })),
20857+ )
20858+ .await;
20859+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
20860+ let res = send(
20861+ &app,
20862+ "POST",
20863+ &path,
20864+ Some(&mgr),
20865+ Some(json!({ "student_id": ali_id })),
20866+ )
20867+ .await;
20868+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
20869+
20870+ // A student books only for themselves, and cancels only their own.
20871+ let res = send(
20872+ &app,
20873+ "POST",
20874+ &path,
20875+ Some(&veli),
20876+ Some(json!({ "student_id": ali_id })),
20877+ )
20878+ .await;
20879+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
20880+ let res = send(
20881+ &app,
20882+ "DELETE",
20883+ &format!("/meals/bookings/{booking}"),
20884+ Some(&veli),
20885+ None,
20886+ )
20887+ .await;
20888+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
20889+
20890+ // The linked parent may give the seat back.
20891+ let res = send(
20892+ &app,
20893+ "DELETE",
20894+ &format!("/meals/bookings/{booking}"),
20895+ Some(&mom),
20896+ None,
20897+ )
20898+ .await;
20899+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20900+ assert_eq!(res.body["status"], "cancelled");
20901+}
20902+
20903+// --- meals: the ledger ----------------------------------------------------
20904+
20905+/// The money, end to end: booking charges the menu's price *snapshot*, editing
20906+/// a dish afterwards never moves that charge, cancelling appends a reversal
20907+/// (leaving the charge standing β€” the append-only proof), and re-booking bills
20908+/// the new price.
20909+#[tokio::test]
20910+async fn meal_booking_charges_a_price_snapshot_and_a_cancel_reverses_it() {
20911+ let (app, db) = app_and_db().await;
20912+ let mgr = login_as(&app, &db, "money_mgr", "manager").await;
20913+ let ali = login(&app, "money_ali").await;
20914+ let ali_id = me_id(&app, &ali).await;
20915+
20916+ let res = send(
20917+ &app,
20918+ "POST",
20919+ "/meals/menus",
20920+ Some(&mgr),
20921+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
20922+ )
20923+ .await;
20924+ let menu = id_of(&res.body);
20925+ let res = send(
20926+ &app,
20927+ "POST",
20928+ &format!("/meals/menus/{menu}/dishes"),
20929+ Some(&mgr),
20930+ Some(json!({ "name": "Γ‡orba", "price_minor": 4_500 })),
20931+ )
20932+ .await;
20933+ let dish = id_of(&res.body);
20934+ send(
20935+ &app,
20936+ "POST",
20937+ &format!("/meals/menus/{menu}/dishes"),
20938+ Some(&mgr),
20939+ Some(json!({ "name": "Pilav", "price_minor": 2_000 })),
20940+ )
20941+ .await;
20942+
20943+ // A fresh student owes nothing.
20944+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
20945+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20946+ assert_eq!(res.body["balance_minor"], 0);
20947+
20948+ // Booking charges the sum of the dishes β€” negative means "owes".
20949+ let res = send(
20950+ &app,
20951+ "POST",
20952+ &format!("/meals/menus/{menu}/bookings"),
20953+ Some(&ali),
20954+ Some(json!({})),
20955+ )
20956+ .await;
20957+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
20958+ let booking = id_of(&res.body);
20959+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
20960+ assert_eq!(res.body["balance_minor"], -6_500);
20961+
20962+ // Booking again is the same seat, so it must not bill twice.
20963+ send(
20964+ &app,
20965+ "POST",
20966+ &format!("/meals/menus/{menu}/bookings"),
20967+ Some(&ali),
20968+ Some(json!({})),
20969+ )
20970+ .await;
20971+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
20972+ assert_eq!(res.body["balance_minor"], -6_500, "one seat, one charge");
20973+
20974+ // A price edit is not retroactive: what the student owes is what the menu
20975+ // cost the day they booked.
20976+ let res = send(
20977+ &app,
20978+ "PATCH",
20979+ &format!("/meals/dishes/{dish}"),
20980+ Some(&mgr),
20981+ Some(json!({ "price_minor": 9_900 })),
20982+ )
20983+ .await;
20984+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20985+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
20986+ assert_eq!(res.body["balance_minor"], -6_500, "the snapshot is frozen");
20987+
20988+ // Cancelling appends a reversal; the charge row stays right where it was.
20989+ let res = send(
20990+ &app,
20991+ "DELETE",
20992+ &format!("/meals/bookings/{booking}"),
20993+ Some(&ali),
20994+ None,
20995+ )
20996+ .await;
20997+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
20998+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
20999+ assert_eq!(res.body["balance_minor"], 0);
21000+
21001+ let res = send(
21002+ &app,
21003+ "GET",
21004+ &format!("/meals/ledger/{ali_id}"),
21005+ Some(&mgr),
21006+ None,
21007+ )
21008+ .await;
21009+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21010+ assert_eq!(common::total(&res.body), 2, "both lines survive the cancel");
21011+ let lines = res.body["items"].as_array().unwrap().clone();
21012+ // Newest first: the reversal, then the charge it points at.
21013+ assert_eq!(lines[0]["kind"], "reversal");
21014+ assert_eq!(lines[0]["amount_minor"], 6_500);
21015+ assert_eq!(lines[1]["kind"], "charge");
21016+ assert_eq!(lines[1]["amount_minor"], 6_500);
21017+ assert_eq!(lines[1]["source"], json!(booking));
21018+ assert_eq!(lines[0]["source"], lines[1]["id"]);
21019+
21020+ // Re-booking is a fresh charge, at the *new* price.
21021+ let res = send(
21022+ &app,
21023+ "POST",
21024+ &format!("/meals/menus/{menu}/bookings"),
21025+ Some(&ali),
21026+ Some(json!({})),
21027+ )
21028+ .await;
21029+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21030+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
21031+ assert_eq!(res.body["balance_minor"], -11_900);
21032+ let res = send(
21033+ &app,
21034+ "GET",
21035+ &format!("/meals/ledger/{ali_id}"),
21036+ Some(&mgr),
21037+ None,
21038+ )
21039+ .await;
21040+ assert_eq!(common::total(&res.body), 3);
21041+}
21042+
21043+/// Recording cash is admin-only β€” a manager runs the kitchen, not the till.
21044+#[tokio::test]
21045+async fn meal_credits_are_admin_only_and_raise_the_balance() {
21046+ let (app, db) = app_and_db().await;
21047+ let admin = login_as(&app, &db, "till_admin", "admin").await;
21048+ let mgr = login_as(&app, &db, "till_mgr", "manager").await;
21049+ let ali = login(&app, "till_ali").await;
21050+ let ali_id = me_id(&app, &ali).await;
21051+
21052+ let body = json!({ "student_id": ali_id, "amount_minor": 25_000, "method": "cash" });
21053+ let res = send(
21054+ &app,
21055+ "POST",
21056+ "/meals/credits",
21057+ Some(&mgr),
21058+ Some(body.clone()),
21059+ )
21060+ .await;
21061+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21062+ let res = send(
21063+ &app,
21064+ "POST",
21065+ "/meals/credits",
21066+ Some(&ali),
21067+ Some(body.clone()),
21068+ )
21069+ .await;
21070+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21071+
21072+ let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(body)).await;
21073+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21074+ assert_eq!(res.body["kind"], "credit");
21075+ assert_eq!(res.body["amount_minor"], 25_000);
21076+ assert_eq!(res.body["method"], "cash");
21077+ assert_eq!(res.body["note"], json!(null));
21078+ assert_eq!(res.body["source"], json!(null));
21079+ assert_eq!(res.body["recorded_by"]["username"], "till_admin");
21080+
21081+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
21082+ assert_eq!(res.body["balance_minor"], 25_000);
21083+
21084+ // The amount is bounded and positive; the target must be a student.
21085+ for bad in [
21086+ json!({ "student_id": ali_id, "amount_minor": 0 }),
21087+ json!({ "student_id": ali_id, "amount_minor": -100 }),
21088+ json!({ "student_id": ali_id, "amount_minor": 10_000_001 }),
21089+ ] {
21090+ let res = send(&app, "POST", "/meals/credits", Some(&admin), Some(bad)).await;
21091+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21092+ }
21093+ let mgr_id = me_id(&app, &mgr).await;
21094+ let res = send(
21095+ &app,
21096+ "POST",
21097+ "/meals/credits",
21098+ Some(&admin),
21099+ Some(json!({ "student_id": mgr_id, "amount_minor": 100 })),
21100+ )
21101+ .await;
21102+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21103+ // …and the failed writes left the balance exactly where it was.
21104+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
21105+ assert_eq!(res.body["balance_minor"], 25_000);
21106+}
21107+
21108+/// Whose money a caller may read: their own, their linked child's, or β€” as
21109+/// teacher+ β€” anyone's. Never another family's.
21110+#[tokio::test]
21111+async fn meal_balance_reads_follow_the_observer_gate() {
21112+ let (app, db) = app_and_db().await;
21113+ let admin = login_as(&app, &db, "wallet_boss", "admin").await;
21114+ let teacher = login_as(&app, &db, "wallet_teacher", "teacher").await;
21115+ let mom = login_as(&app, &db, "wallet_mom", "parent").await;
21116+ let mom_id = me_id(&app, &mom).await;
21117+ let ali = login(&app, "wallet_ali").await;
21118+ let ali_id = me_id(&app, &ali).await;
21119+ let veli = login(&app, "wallet_veli").await;
21120+ let veli_id = me_id(&app, &veli).await;
21121+
21122+ let res = send(
21123+ &app,
21124+ "POST",
21125+ &format!("/users/{mom_id}/students"),
21126+ Some(&admin),
21127+ Some(json!({ "user_id": ali_id })),
21128+ )
21129+ .await;
21130+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21131+
21132+ // The linked parent reads their child's balance and statement.
21133+ let res = send(
21134+ &app,
21135+ "GET",
21136+ &format!("/meals/balance/{ali_id}"),
21137+ Some(&mom),
21138+ None,
21139+ )
21140+ .await;
21141+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21142+ assert_eq!(res.body["student"]["username"], "wallet_ali");
21143+ let res = send(
21144+ &app,
21145+ "GET",
21146+ &format!("/meals/ledger/{ali_id}"),
21147+ Some(&mom),
21148+ None,
21149+ )
21150+ .await;
21151+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21152+
21153+ // Someone else's child is a 403, on both routes.
21154+ for path in [
21155+ format!("/meals/balance/{veli_id}"),
21156+ format!("/meals/ledger/{veli_id}"),
21157+ ] {
21158+ let res = send(&app, "GET", &path, Some(&mom), None).await;
21159+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21160+ }
21161+
21162+ // A student reads their own money, never a classmate's.
21163+ let res = send(
21164+ &app,
21165+ "GET",
21166+ &format!("/meals/balance/{ali_id}"),
21167+ Some(&ali),
21168+ None,
21169+ )
21170+ .await;
21171+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21172+ let res = send(
21173+ &app,
21174+ "GET",
21175+ &format!("/meals/balance/{ali_id}"),
21176+ Some(&veli),
21177+ None,
21178+ )
21179+ .await;
21180+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21181+
21182+ // Teacher+ reads any student's.
21183+ let res = send(
21184+ &app,
21185+ "GET",
21186+ &format!("/meals/balance/{ali_id}"),
21187+ Some(&teacher),
21188+ None,
21189+ )
21190+ .await;
21191+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21192+}
21193+
21194+// --- meals: attendance ----------------------------------------------------
21195+
21196+/// Marking who ate is reporting, never billing: a booked no-show still owes the
21197+/// full price, and a walk-in served without a booking owes nothing. Also covers
21198+/// the composite id (re-marking flips the row) and the teacher+ gate.
21199+#[tokio::test]
21200+async fn meal_attendance_never_moves_money() {
21201+ let (app, db) = app_and_db().await;
21202+ let mgr = login_as(&app, &db, "ate_mgr", "manager").await;
21203+ let teacher = login_as(&app, &db, "ate_teacher", "teacher").await;
21204+ let ali = login(&app, "ate_ali").await;
21205+ let ali_id = me_id(&app, &ali).await;
21206+ let veli = login(&app, "ate_veli").await;
21207+ let veli_id = me_id(&app, &veli).await;
21208+
21209+ let res = send(
21210+ &app,
21211+ "POST",
21212+ "/meals/menus",
21213+ Some(&mgr),
21214+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
21215+ )
21216+ .await;
21217+ let menu = id_of(&res.body);
21218+ send(
21219+ &app,
21220+ "POST",
21221+ &format!("/meals/menus/{menu}/dishes"),
21222+ Some(&mgr),
21223+ Some(json!({ "name": "Γ‡orba", "price_minor": 4_500 })),
21224+ )
21225+ .await;
21226+
21227+ // Ali books (and is charged); Veli never books.
21228+ let res = send(
21229+ &app,
21230+ "POST",
21231+ &format!("/meals/menus/{menu}/bookings"),
21232+ Some(&ali),
21233+ Some(json!({})),
21234+ )
21235+ .await;
21236+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21237+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
21238+ assert_eq!(res.body["balance_minor"], -4_500);
21239+
21240+ let path = format!("/meals/menus/{menu}/attendance");
21241+
21242+ // Served shows up on the menu's list.
21243+ let res = send(
21244+ &app,
21245+ "POST",
21246+ &path,
21247+ Some(&teacher),
21248+ Some(json!({ "student_id": ali_id, "status": "served" })),
21249+ )
21250+ .await;
21251+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21252+ let mark = id_of(&res.body);
21253+ assert_eq!(res.body["status"], "served");
21254+ assert_eq!(res.body["student"]["username"], "ate_ali");
21255+ assert_eq!(res.body["marked_by"]["username"], "ate_teacher");
21256+ assert_eq!(res.body["menu_id"], json!(menu));
21257+ let res = send(&app, "GET", &path, Some(&teacher), None).await;
21258+ assert_eq!(common::total(&res.body), 1);
21259+ assert_eq!(res.body["items"][0]["id"], json!(mark));
21260+
21261+ // Re-marking the same student flips the row β€” one row per (menu, student).
21262+ let res = send(
21263+ &app,
21264+ "POST",
21265+ &path,
21266+ Some(&teacher),
21267+ Some(json!({ "student_id": ali_id, "status": "missed" })),
21268+ )
21269+ .await;
21270+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21271+ assert_eq!(id_of(&res.body), mark);
21272+ assert_eq!(res.body["status"], "missed");
21273+ let res = send(&app, "GET", &path, Some(&teacher), None).await;
21274+ assert_eq!(
21275+ common::total(&res.body),
21276+ 1,
21277+ "the mark was flipped, not doubled"
21278+ );
21279+
21280+ // THE BILLING-ISOLATION PROOF: the no-show still owes the whole price, and
21281+ // his statement grew no reversal line. The kitchen bought the food.
21282+ let res = send(&app, "GET", "/meals/balance/me", Some(&ali), None).await;
21283+ assert_eq!(
21284+ res.body["balance_minor"], -4_500,
21285+ "attendance must never move money"
21286+ );
21287+ let res = send(
21288+ &app,
21289+ "GET",
21290+ &format!("/meals/ledger/{ali_id}"),
21291+ Some(&mgr),
21292+ None,
21293+ )
21294+ .await;
21295+ assert_eq!(common::total(&res.body), 1, "only the booking's charge");
21296+ assert_eq!(res.body["items"][0]["kind"], "charge");
21297+
21298+ // A walk-in with no booking is recordable β€” and still not charged.
21299+ let res = send(
21300+ &app,
21301+ "POST",
21302+ &path,
21303+ Some(&teacher),
21304+ Some(json!({ "student_id": veli_id, "status": "served" })),
21305+ )
21306+ .await;
21307+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21308+ let res = send(&app, "GET", "/meals/balance/me", Some(&veli), None).await;
21309+ assert_eq!(res.body["balance_minor"], 0, "a walk-in is never billed");
21310+
21311+ // Students never mark, not even themselves, and never read the list.
21312+ let res = send(
21313+ &app,
21314+ "POST",
21315+ &path,
21316+ Some(&ali),
21317+ Some(json!({ "student_id": ali_id, "status": "served" })),
21318+ )
21319+ .await;
21320+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21321+ let res = send(&app, "GET", &path, Some(&ali), None).await;
21322+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21323+
21324+ // Bad inputs: a roll-call status is not a canteen status, and the menu and
21325+ // the student both have to exist.
21326+ let res = send(
21327+ &app,
21328+ "POST",
21329+ &path,
21330+ Some(&teacher),
21331+ Some(json!({ "student_id": ali_id, "status": "excused" })),
21332+ )
21333+ .await;
21334+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21335+ let res = send(
21336+ &app,
21337+ "POST",
21338+ &path,
21339+ Some(&teacher),
21340+ Some(json!({ "student_id": "nobody", "status": "served" })),
21341+ )
21342+ .await;
21343+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21344+ let res = send(
21345+ &app,
21346+ "POST",
21347+ "/meals/menus/missing/attendance",
21348+ Some(&teacher),
21349+ Some(json!({ "student_id": ali_id, "status": "served" })),
21350+ )
21351+ .await;
21352+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{}", res.body);
21353+}
21354+
21355+/// The per-student report: a lexical `?from=&to=` window over the menu's day,
21356+/// readable by teacher+ or a linked parent and by nobody else.
21357+#[tokio::test]
21358+async fn meal_attendance_report_is_ranged_and_gated() {
21359+ let (app, db) = app_and_db().await;
21360+ let admin = login_as(&app, &db, "ate_boss", "admin").await;
21361+ let mgr = login_as(&app, &db, "range_mgr", "manager").await;
21362+ let teacher = login_as(&app, &db, "range_teacher", "teacher").await;
21363+ let mom = login_as(&app, &db, "range_mom", "parent").await;
21364+ let mom_id = me_id(&app, &mom).await;
21365+ let ali = login(&app, "range_ali").await;
21366+ let ali_id = me_id(&app, &ali).await;
21367+ let veli = login(&app, "range_veli").await;
21368+ let veli_id = me_id(&app, &veli).await;
21369+
21370+ let res = send(
21371+ &app,
21372+ "POST",
21373+ &format!("/users/{mom_id}/students"),
21374+ Some(&admin),
21375+ Some(json!({ "user_id": ali_id })),
21376+ )
21377+ .await;
21378+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21379+
21380+ // Three days, one mark each for Ali.
21381+ for date in ["2026-09-01", "2026-09-15", "2026-09-30"] {
21382+ let res = send(
21383+ &app,
21384+ "POST",
21385+ "/meals/menus",
21386+ Some(&mgr),
21387+ Some(json!({ "date": date, "slot": "lunch" })),
21388+ )
21389+ .await;
21390+ let menu = id_of(&res.body);
21391+ let res = send(
21392+ &app,
21393+ "POST",
21394+ &format!("/meals/menus/{menu}/attendance"),
21395+ Some(&teacher),
21396+ Some(json!({ "student_id": ali_id, "status": "served" })),
21397+ )
21398+ .await;
21399+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21400+ }
21401+
21402+ // Unbounded, then each bound, then both β€” the window is the menu's day.
21403+ for (query, expected) in [
21404+ ("", 3),
21405+ ("?from=2026-09-15", 2),
21406+ ("?to=2026-09-15", 2),
21407+ ("?from=2026-09-10&to=2026-09-20", 1),
21408+ ("?from=2026-10-01", 0),
21409+ ] {
21410+ let res = send(
21411+ &app,
21412+ "GET",
21413+ &format!("/meals/attendance/{ali_id}{query}"),
21414+ Some(&teacher),
21415+ None,
21416+ )
21417+ .await;
21418+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21419+ assert_eq!(common::total(&res.body), expected, "range {query}");
21420+ }
21421+
21422+ // A malformed bound is a 400, never a silently ignored filter.
21423+ let res = send(
21424+ &app,
21425+ "GET",
21426+ &format!("/meals/attendance/{ali_id}?from=2026-9-1"),
21427+ Some(&teacher),
21428+ None,
21429+ )
21430+ .await;
21431+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21432+
21433+ // The linked parent reads her child's report; another child's is a 403,
21434+ // and a classmate never reads it at all.
21435+ let res = send(
21436+ &app,
21437+ "GET",
21438+ &format!("/meals/attendance/{ali_id}"),
21439+ Some(&mom),
21440+ None,
21441+ )
21442+ .await;
21443+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21444+ assert_eq!(common::total(&res.body), 3);
21445+ let res = send(
21446+ &app,
21447+ "GET",
21448+ &format!("/meals/attendance/{veli_id}"),
21449+ Some(&mom),
21450+ None,
21451+ )
21452+ .await;
21453+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21454+ let res = send(
21455+ &app,
21456+ "GET",
21457+ &format!("/meals/attendance/{ali_id}"),
21458+ Some(&veli),
21459+ None,
21460+ )
21461+ .await;
21462+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21463+}
21464+
21465+/// The dietary profile and the `conflicts` it produces on a menu read: the
21466+/// school writes it, everyone in the reading gate sees it, and the overlap is
21467+/// computed against the *caller's* own tags.
21468+#[tokio::test]
21469+async fn dietary_profile_drives_menu_conflicts() {
21470+ let (app, db) = app_and_db().await;
21471+ let admin = login_as(&app, &db, "diet_boss", "admin").await;
21472+ let mgr = login_as(&app, &db, "diet_mgr", "manager").await;
21473+ let teacher = login_as(&app, &db, "diet_teacher", "teacher").await;
21474+ let mom = login_as(&app, &db, "diet_mom", "parent").await;
21475+ let mom_id = me_id(&app, &mom).await;
21476+ let other_mom = login_as(&app, &db, "diet_aunt", "parent").await;
21477+ let ali = login(&app, "diet_ali").await;
21478+ let ali_id = me_id(&app, &ali).await;
21479+ let veli = login(&app, "diet_veli").await;
21480+ let veli_id = me_id(&app, &veli).await;
21481+
21482+ let res = send(
21483+ &app,
21484+ "POST",
21485+ &format!("/users/{mom_id}/students"),
21486+ Some(&admin),
21487+ Some(json!({ "user_id": ali_id })),
21488+ )
21489+ .await;
21490+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21491+
21492+ // No profile yet: empty, never a 404.
21493+ let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await;
21494+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21495+ assert_eq!(res.body["tags"], json!([]));
21496+ assert_eq!(res.body["note"], json!(null));
21497+ assert_eq!(res.body["updated_at"], json!(null));
21498+
21499+ // A student does not write their own allergen list, and neither does a
21500+ // teacher β€” this is a manager+ safety record.
21501+ for actor in [&ali, &teacher] {
21502+ let res = send(
21503+ &app,
21504+ "PATCH",
21505+ &format!("/meals/profiles/{ali_id}"),
21506+ Some(actor),
21507+ Some(json!({ "tags": ["nut_allergy"] })),
21508+ )
21509+ .await;
21510+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21511+ }
21512+
21513+ // A tag outside the school's list is a 400, never a stored string.
21514+ let res = send(
21515+ &app,
21516+ "PATCH",
21517+ &format!("/meals/profiles/{ali_id}"),
21518+ Some(&mgr),
21519+ Some(json!({ "tags": ["halal"] })),
21520+ )
21521+ .await;
21522+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21523+
21524+ let res = send(
21525+ &app,
21526+ "PATCH",
21527+ &format!("/meals/profiles/{ali_id}"),
21528+ Some(&mgr),
21529+ Some(json!({ "tags": ["nut_allergy", "nut_allergy"], "note": " EpiPen " })),
21530+ )
21531+ .await;
21532+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21533+ assert_eq!(res.body["tags"], json!(["nut_allergy"]));
21534+ assert_eq!(res.body["note"], "EpiPen");
21535+ assert_eq!(res.body["updated_by"]["username"], "diet_mgr");
21536+
21537+ // The student reads it back at `/me`; a second PATCH edits the same row.
21538+ let res = send(&app, "GET", "/meals/profiles/me", Some(&ali), None).await;
21539+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21540+ assert_eq!(res.body["tags"], json!(["nut_allergy"]));
21541+ assert_eq!(res.body["student"]["username"], "diet_ali");
21542+
21543+ let res = send(
21544+ &app,
21545+ "PATCH",
21546+ &format!("/meals/profiles/{ali_id}"),
21547+ Some(&mgr),
21548+ Some(json!({ "note": null })),
21549+ )
21550+ .await;
21551+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21552+ assert_eq!(res.body["note"], json!(null));
21553+ assert_eq!(res.body["tags"], json!(["nut_allergy"]), "tags kept");
21554+
21555+ // The linked parent reads her child's; an unlinked one does not.
21556+ let res = send(
21557+ &app,
21558+ "GET",
21559+ &format!("/meals/profiles/{ali_id}"),
21560+ Some(&mom),
21561+ None,
21562+ )
21563+ .await;
21564+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21565+ assert_eq!(res.body["tags"], json!(["nut_allergy"]));
21566+ let res = send(
21567+ &app,
21568+ "GET",
21569+ &format!("/meals/profiles/{ali_id}"),
21570+ Some(&other_mom),
21571+ None,
21572+ )
21573+ .await;
21574+ assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body);
21575+
21576+ // A profile is a student's thing β€” a teacher never carries one.
21577+ let teacher_id = me_id(&app, &teacher).await;
21578+ let res = send(
21579+ &app,
21580+ "PATCH",
21581+ &format!("/meals/profiles/{teacher_id}"),
21582+ Some(&mgr),
21583+ Some(json!({ "tags": ["vegan"] })),
21584+ )
21585+ .await;
21586+ assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body);
21587+
21588+ // One menu, two dishes: one Ali must avoid, one he must not.
21589+ let res = send(
21590+ &app,
21591+ "POST",
21592+ "/meals/menus",
21593+ Some(&mgr),
21594+ Some(json!({ "date": "2026-10-05", "slot": "lunch" })),
21595+ )
21596+ .await;
21597+ let menu = id_of(&res.body);
21598+ for (name, tags) in [
21599+ ("FΔ±stΔ±klΔ± baklava", json!(["nut_allergy", "vegetarian"])),
21600+ ("Pilav", json!(["vegan"])),
21601+ ] {
21602+ let res = send(
21603+ &app,
21604+ "POST",
21605+ &format!("/meals/menus/{menu}/dishes"),
21606+ Some(&mgr),
21607+ Some(json!({ "name": name, "price_minor": 1000, "tags": tags })),
21608+ )
21609+ .await;
21610+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21611+ }
21612+
21613+ // Ali sees his own conflict on the one dish, and nothing on the other.
21614+ for path in [format!("/meals/menus/{menu}"), "/meals/menus".to_string()] {
21615+ let res = send(&app, "GET", &path, Some(&ali), None).await;
21616+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21617+ let menu_body = if path == "/meals/menus" {
21618+ res.body["items"][0].clone()
21619+ } else {
21620+ res.body.clone()
21621+ };
21622+ assert_eq!(
21623+ menu_body["dishes"][0]["conflicts"],
21624+ json!(["nut_allergy"]),
21625+ "{path}: the tag Ali holds, and only it"
21626+ );
21627+ assert_eq!(menu_body["dishes"][1]["conflicts"], json!([]), "{path}");
21628+ }
21629+
21630+ // A student with no profile, and a manager (who never has one), both read
21631+ // empty conflicts β€” that is correct, not a bug.
21632+ for actor in [&veli, &mgr] {
21633+ let res = send(
21634+ &app,
21635+ "GET",
21636+ &format!("/meals/menus/{menu}"),
21637+ Some(actor),
21638+ None,
21639+ )
21640+ .await;
21641+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21642+ assert_eq!(res.body["dishes"][0]["conflicts"], json!([]));
21643+ assert_eq!(res.body["dishes"][1]["conflicts"], json!([]));
21644+ }
21645+
21646+ // Cleanup 1: a student reads their OWN meal-attendance history, like they
21647+ // already read their own balance and statement.
21648+ let res = send(
21649+ &app,
21650+ "POST",
21651+ &format!("/meals/menus/{menu}/attendance"),
21652+ Some(&teacher),
21653+ Some(json!({ "student_id": veli_id, "status": "served" })),
21654+ )
21655+ .await;
21656+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21657+ let res = send(
21658+ &app,
21659+ "GET",
21660+ &format!("/meals/attendance/{veli_id}"),
21661+ Some(&veli),
21662+ None,
21663+ )
21664+ .await;
21665+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21666+ assert_eq!(common::total(&res.body), 1);
21667+}
21668+
21669+// --- meals: money under concurrency and stale grants ----------------------
21670+
21671+/// Publish a lunch menu carrying one dish at `price`; returns (menu id,
21672+/// student cookie). Every money-race test below needs the same three rows.
21673+async fn priced_menu(tag: &str, price: i64) -> (axum::Router, String, String) {
21674+ let (app, db) = app_and_db().await;
21675+ let mgr = login_as(&app, &db, &format!("{tag}_mgr"), "manager").await;
21676+ let stu = login(&app, &format!("{tag}_stu")).await;
21677+ let res = send(
21678+ &app,
21679+ "POST",
21680+ "/meals/menus",
21681+ Some(&mgr),
21682+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
21683+ )
21684+ .await;
21685+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21686+ let menu = id_of(&res.body);
21687+ let res = send(
21688+ &app,
21689+ "POST",
21690+ &format!("/meals/menus/{menu}/dishes"),
21691+ Some(&mgr),
21692+ Some(json!({ "name": "Pilav", "price_minor": price })),
21693+ )
21694+ .await;
21695+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21696+ (app, menu, stu)
21697+}
21698+
21699+/// The sequential "booking twice bills once" test cannot see this: idempotence
21700+/// that rests on a "is there already a charge?" scan is no idempotence at all,
21701+/// since eight simultaneous POSTs of one seat all read "not yet" and all
21702+/// append. One seat must mean one charge, so the ledger line is keyed by
21703+/// (booking, attempt) and written under the same lock as the seat.
21704+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
21705+async fn concurrent_bookings_of_one_seat_bill_it_once() {
21706+ let (app, menu, stu) = priced_menu("race", 5_000).await;
21707+
21708+ let mut tasks = Vec::new();
21709+ for _ in 0..8 {
21710+ let app = app.clone();
21711+ let stu = stu.clone();
21712+ let menu = menu.clone();
21713+ tasks.push(tokio::spawn(async move {
21714+ send(
21715+ &app,
21716+ "POST",
21717+ &format!("/meals/menus/{menu}/bookings"),
21718+ Some(&stu),
21719+ Some(json!({})),
21720+ )
21721+ .await
21722+ }));
21723+ }
21724+ for task in tasks {
21725+ let res = task.await.unwrap();
21726+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21727+ }
21728+
21729+ let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await;
21730+ assert_eq!(common::total(&res.body), 1, "one seat: {}", res.body);
21731+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21732+ assert_eq!(
21733+ res.body["balance_minor"], -5_000,
21734+ "one seat, one charge: {}",
21735+ res.body
21736+ );
21737+}
21738+
21739+/// A repeat POST racing the cancel. A cancel that reverses whatever charge it
21740+/// can find, off a booking row read before the lock, can flip the seat to
21741+/// `cancelled` while the charge of a newer attempt stands β€” the student owes
21742+/// for a seat they do not hold. Keying the reversal to the attempt, and
21743+/// re-reading the row inside the lock, is what closes it.
21744+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
21745+async fn a_cancelled_seat_never_keeps_its_charge() {
21746+ let (app, menu, stu) = priced_menu("race2", 3_000).await;
21747+ let res = send(
21748+ &app,
21749+ "POST",
21750+ &format!("/meals/menus/{menu}/bookings"),
21751+ Some(&stu),
21752+ Some(json!({})),
21753+ )
21754+ .await;
21755+ let booking = id_of(&res.body);
21756+
21757+ for round in 0..20 {
21758+ let book = {
21759+ let (app, stu, menu) = (app.clone(), stu.clone(), menu.clone());
21760+ tokio::spawn(async move {
21761+ send(
21762+ &app,
21763+ "POST",
21764+ &format!("/meals/menus/{menu}/bookings"),
21765+ Some(&stu),
21766+ Some(json!({})),
21767+ )
21768+ .await
21769+ })
21770+ };
21771+ let cancel = {
21772+ let (app, stu, booking) = (app.clone(), stu.clone(), booking.clone());
21773+ tokio::spawn(async move {
21774+ send(
21775+ &app,
21776+ "DELETE",
21777+ &format!("/meals/bookings/{booking}"),
21778+ Some(&stu),
21779+ None,
21780+ )
21781+ .await
21782+ })
21783+ };
21784+ book.await.unwrap();
21785+ cancel.await.unwrap();
21786+ // Settle the seat into `cancelled`, then the money must be back.
21787+ send(
21788+ &app,
21789+ "DELETE",
21790+ &format!("/meals/bookings/{booking}"),
21791+ Some(&stu),
21792+ None,
21793+ )
21794+ .await;
21795+ let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await;
21796+ assert_eq!(
21797+ common::items(&res.body)[0]["status"],
21798+ "cancelled",
21799+ "round {round}: {}",
21800+ res.body
21801+ );
21802+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21803+ assert_eq!(
21804+ res.body["balance_minor"], 0,
21805+ "round {round}: a cancelled seat still owes: {}",
21806+ res.body
21807+ );
21808+ }
21809+}
21810+
21811+/// "Was free" is a recorded fact, not the absence of a charge. A seat taken
21812+/// off a dishless menu writes no ledger line; if that were all the code knew,
21813+/// a dish added afterwards would make the next POST of the *same held seat*
21814+/// look unbilled and charge it β€” a price the student never agreed to.
21815+#[tokio::test]
21816+async fn a_repeat_post_never_bills_a_seat_that_was_free_when_taken() {
21817+ let (app, db) = app_and_db().await;
21818+ let mgr = login_as(&app, &db, "free_mgr", "manager").await;
21819+ let stu = login(&app, "free_stu").await;
21820+ let res = send(
21821+ &app,
21822+ "POST",
21823+ "/meals/menus",
21824+ Some(&mgr),
21825+ Some(json!({ "date": "2026-09-14", "slot": "lunch" })),
21826+ )
21827+ .await;
21828+ let menu = id_of(&res.body);
21829+
21830+ // The seat is taken while the menu carries no dishes at all.
21831+ let res = send(
21832+ &app,
21833+ "POST",
21834+ &format!("/meals/menus/{menu}/bookings"),
21835+ Some(&stu),
21836+ Some(json!({})),
21837+ )
21838+ .await;
21839+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21840+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21841+ assert_eq!(res.body["balance_minor"], 0, "a free menu bills nothing");
21842+
21843+ // The kitchen prices the menu afterwards.
21844+ let res = send(
21845+ &app,
21846+ "POST",
21847+ &format!("/meals/menus/{menu}/dishes"),
21848+ Some(&mgr),
21849+ Some(json!({ "name": "Pilav", "price_minor": 9_000 })),
21850+ )
21851+ .await;
21852+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21853+
21854+ // A refresh re-POSTs the seat the student already holds.
21855+ let res = send(
21856+ &app,
21857+ "POST",
21858+ &format!("/meals/menus/{menu}/bookings"),
21859+ Some(&stu),
21860+ Some(json!({})),
21861+ )
21862+ .await;
21863+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21864+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21865+ assert_eq!(
21866+ res.body["balance_minor"], 0,
21867+ "a repeat POST on a held seat moves no money: {}",
21868+ res.body
21869+ );
21870+
21871+ // Cancelling and taking the seat again *is* a fresh attempt, at the price
21872+ // the menu carries now β€” that is the same rule, not an exception to it.
21873+ let res = send(&app, "GET", "/meals/bookings/me", Some(&stu), None).await;
21874+ let booking = common::items(&res.body)[0]["id"]
21875+ .as_str()
21876+ .unwrap()
21877+ .to_string();
21878+ send(
21879+ &app,
21880+ "DELETE",
21881+ &format!("/meals/bookings/{booking}"),
21882+ Some(&stu),
21883+ None,
21884+ )
21885+ .await;
21886+ send(
21887+ &app,
21888+ "POST",
21889+ &format!("/meals/menus/{menu}/bookings"),
21890+ Some(&stu),
21891+ Some(json!({})),
21892+ )
21893+ .await;
21894+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21895+ assert_eq!(res.body["balance_minor"], -9_000, "{}", res.body);
21896+}
21897+
21898+/// A revoked parent link must go inert everywhere, `booked_by` included: the
21899+/// seats a parent paid for stay visible while the link lives, and vanish with
21900+/// it. The leak this catches was a *live* one β€” the unlinked parent kept
21901+/// watching the child's row, seeing a cancellation made after the unlink.
21902+#[tokio::test]
21903+async fn an_unlinked_parent_loses_the_live_view_of_a_childs_bookings() {
21904+ let (app, db) = app_and_db().await;
21905+ let admin = login_as(&app, &db, "lv_boss", "admin").await;
21906+ let mgr = login_as(&app, &db, "lv_mgr", "manager").await;
21907+ let mom = login_as(&app, &db, "lv_mom", "parent").await;
21908+ let mom_id = me_id(&app, &mom).await;
21909+ let kid = login(&app, "lv_kid").await;
21910+ let kid_id = me_id(&app, &kid).await;
21911+ let res = send(
21912+ &app,
21913+ "POST",
21914+ &format!("/users/{mom_id}/students"),
21915+ Some(&admin),
21916+ Some(json!({ "user_id": kid_id })),
21917+ )
21918+ .await;
21919+ assert!(res.status.is_success(), "link: {}", res.body);
21920+ let res = send(
21921+ &app,
21922+ "POST",
21923+ "/meals/menus",
21924+ Some(&mgr),
21925+ Some(json!({ "date": "2027-08-01", "slot": "lunch" })),
21926+ )
21927+ .await;
21928+ let menu = id_of(&res.body);
21929+ let res = send(
21930+ &app,
21931+ "POST",
21932+ &format!("/meals/menus/{menu}/bookings"),
21933+ Some(&mom),
21934+ Some(json!({ "student_id": kid_id })),
21935+ )
21936+ .await;
21937+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21938+ let booking = id_of(&res.body);
21939+
21940+ // While the link lives, mom sees the seat she booked.
21941+ let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await;
21942+ assert_eq!(common::total(&res.body), 1, "{}", res.body);
21943+
21944+ let res = send(
21945+ &app,
21946+ "DELETE",
21947+ &format!("/users/{mom_id}/students/{kid_id}"),
21948+ Some(&admin),
21949+ None,
21950+ )
21951+ .await;
21952+ assert!(res.status.is_success(), "unlink: {}", res.body);
21953+
21954+ // The kid cancels *after* the link is gone β€” mom must not see that.
21955+ let res = send(
21956+ &app,
21957+ "DELETE",
21958+ &format!("/meals/bookings/{booking}"),
21959+ Some(&kid),
21960+ None,
21961+ )
21962+ .await;
21963+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
21964+ let res = send(&app, "GET", "/meals/bookings/me", Some(&mom), None).await;
21965+ assert_eq!(
21966+ common::total(&res.body),
21967+ 0,
21968+ "an unlinked parent still reads the child's seat: {}",
21969+ res.body
21970+ );
21971+ // The child's own view is untouched.
21972+ let res = send(&app, "GET", "/meals/bookings/me", Some(&kid), None).await;
21973+ assert_eq!(common::total(&res.body), 1, "{}", res.body);
21974+}
21975+
21976+/// A cancel is two writes β€” the status flip, then the reversal β€” and axum drops
21977+/// the handler future when the client goes away (tab closed, proxy timeout). A
21978+/// drop landing between them freed the seat and left the charge standing, and
21979+/// while an already-cancelled row was a `409` **no route on the API could ever
21980+/// append the missing reversal**: the student stayed billed for a meal they had
21981+/// given back, and re-booking billed them a second time. So the cancel is
21982+/// idempotent β€” repeating it replays the reversal, keyed by (seat, attempt), so
21983+/// it heals the gap exactly once.
21984+#[tokio::test]
21985+async fn a_cancel_cut_short_mid_flight_is_healed_by_repeating_it() {
21986+ let (app, menu, stu) = priced_menu("cutshort", 3_000).await;
21987+ let res = send(
21988+ &app,
21989+ "POST",
21990+ &format!("/meals/menus/{menu}/bookings"),
21991+ Some(&stu),
21992+ Some(json!({})),
21993+ )
21994+ .await;
21995+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
21996+ let booking = id_of(&res.body);
21997+ let res = send(&app, "GET", "/meals/balance/me", Some(&stu), None).await;
21998+ assert_eq!(res.body["balance_minor"], -3_000, "{}", res.body);
21999+
22000+ // The DELETE, polled just far enough to flip the row, then dropped.
22001+ let req = Request::builder()
22002+ .method("DELETE")
22003+ .uri(format!("/meals/bookings/{booking}"))
22004+ .header("cookie", &stu)
22005+ .body(Body::empty())
22006+ .unwrap();
22007+ let mut fut = Box::pin(app.clone().oneshot(req));
22008+ for _ in 0..7 {
22009+ assert!(
22010+ futures_util::poll!(fut.as_mut()).is_pending(),
22011+ "the cancel finished before it could be interrupted"
22012+ );
22013+ tokio::task::yield_now().await;
22014+ }
22015+ drop(fut);
tests/limits_completeness.rsmodified+8 -0
@@ -78,6 +78,14 @@ const EXCLUDED: &[(&str, &str)] = &[
78 "DEFAULT_EXAM_KINDS",78 "DEFAULT_EXAM_KINDS",
79 "settings seed; the live list is on GET /settings",79 "settings seed; the live list is on GET /settings",
80 ),80 ),
81+ (
82+ "DEFAULT_MEAL_SLOTS",
83+ "settings seed; the live list is on GET /settings",
84+ ),
85+ (
86+ "DEFAULT_DIETARY_TAGS",
87+ "settings seed; the live list is on GET /settings",
88+ ),
81 // Schema and query text. `constant.rs` is the single home for every89 // Schema and query text. `constant.rs` is the single home for every
82 // constant, so the migration batches live there too β€” a client never sees90 // constant, so the migration batches live there too β€” a client never sees
83 // a byte of SurrealQL.91 // a byte of SurrealQL.
tests/spec_bounds.rsmodified+86 -0
@@ -571,6 +571,92 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
571 "maximum",571 "maximum",
572 MAX_MAX_CHATBOT_MESSAGE_LEN,572 MAX_MAX_CHATBOT_MESSAGE_LEN,
573 ),573 ),
574+ // --- food program (the school-editable lists live in /settings) ---
575+ (
576+ "MealSlotDto",
577+ "name",
578+ "maxLength",
579+ MAX_SETTINGS_ITEM_LEN as i64,
580+ ),
581+ (
582+ "UpdateSettings",
583+ "meal_slots",
584+ "maxItems",
585+ MAX_SETTINGS_LIST_LEN as i64,
586+ ),
587+ (
588+ "UpdateSettings",
589+ "dietary_tags",
590+ "maxItems",
591+ MAX_SETTINGS_LIST_LEN as i64,
592+ ),
593+ ("UpdateSettings", "meal_cancel_cutoff_minutes", "minimum", 0),
594+ (
595+ "UpdateSettings",
596+ "meal_cancel_cutoff_minutes",
597+ "maximum",
598+ MAX_MEAL_CANCEL_CUTOFF_MINUTES,
599+ ),
600+ // --- menus and dishes ---
601+ // `date` is a fixed-width `YYYY-MM-DD`, so both length bounds are 10 β€”
602+ // the shape itself, not a constant anyone could tune.
603+ ("CreateMenu", "date", "minLength", 10),
604+ ("CreateMenu", "date", "maxLength", 10),
605+ ("CreateMenu", "capacity", "minimum", 0),
606+ ("CreateMenu", "capacity", "maximum", MAX_MENU_CAPACITY),
607+ ("UpdateMenu", "capacity", "minimum", 0),
608+ ("UpdateMenu", "capacity", "maximum", MAX_MENU_CAPACITY),
609+ ("CreateDish", "price_minor", "minimum", 0),
610+ ("UpdateDish", "price_minor", "minimum", 0),
611+ ("CreateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64),
612+ ("UpdateDish", "name", "maxLength", MAX_DISH_NAME_LEN as i64),
613+ (
614+ "CreateDish",
615+ "description",
616+ "maxLength",
617+ MAX_DISH_DESCRIPTION_LEN as i64,
618+ ),
619+ (
620+ "UpdateDish",
621+ "description",
622+ "maxLength",
623+ MAX_DISH_DESCRIPTION_LEN as i64,
624+ ),
625+ ("CreateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR),
626+ ("UpdateDish", "price_minor", "maximum", MAX_DISH_PRICE_MINOR),
627+ ("CreateDish", "tags", "maxItems", MAX_DISH_TAGS as i64),
628+ ("UpdateDish", "tags", "maxItems", MAX_DISH_TAGS as i64),
629+ (
630+ "UpdateDietaryProfile",
631+ "tags",
632+ "maxItems",
633+ MAX_DIETARY_TAGS as i64,
634+ ),
635+ (
636+ "UpdateDietaryProfile",
637+ "note",
638+ "maxLength",
639+ MAX_DIETARY_NOTE_LEN as i64,
640+ ),
641+ ("RecordCredit", "amount_minor", "minimum", 1),
642+ (
643+ "RecordCredit",
644+ "amount_minor",
645+ "maximum",
646+ MAX_LEDGER_AMOUNT_MINOR,
647+ ),
648+ (
649+ "RecordCredit",
650+ "method",
651+ "maxLength",
652+ MAX_LEDGER_METHOD_LEN as i64,
653+ ),
654+ (
655+ "RecordCredit",
656+ "note",
657+ "maxLength",
658+ MAX_LEDGER_NOTE_LEN as i64,
659+ ),
574 ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),660 ("CreateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
575 ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),661 ("UpdateTerm", "name", "maxLength", MAX_TERM_NAME_LEN as i64),
576 (662 (