forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

meals.rs1583 lines, 66.2 KiBHistoryRawDownload
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. The balance and the ledger are the exception:
7//! they are manager+ like `/payments`, since canteen debt is family debt.
8//!
9//! Money only ever *appends* here (see [`MealLedger`]): booking charges a price
10//! snapshot, cancelling reverses it, and recording a payment is admin-only.
11
12use crate::web::tenant_state::State;
13use axum::Json;
14use axum::extract::{Path, Query};
15use axum::http::StatusCode;
16use serde::{Deserialize, Serialize};
17use utoipa::{IntoParams, ToSchema};
18use utoipa_axum::router::OpenApiRouter;
19use utoipa_axum::routes;
20
21use crate::database::Database;
22use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts};
23use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus};
24use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff};
25use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger};
26use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity};
27use crate::domain::menu_dish::{
28 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
29};
30// The same idempotence key `/payments/credits` takes — one grammar, one type.
31use crate::domain::payment_ledger::PaymentRequestKey;
32use crate::domain::role::Role;
33use crate::domain::user::{User, UserId};
34use crate::error::{AppError, ErrorResponse, ValidationError};
35use crate::service;
36use crate::state::AppState;
37
38use super::{
39 CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher,
40 check_not_past, person_map, set_or_clear,
41};
42
43pub fn routes() -> OpenApiRouter<AppState> {
44 OpenApiRouter::new()
45 .routes(routes!(create_menu, list_menus))
46 .routes(routes!(get_menu, update_menu, delete_menu))
47 .routes(routes!(add_dish))
48 .routes(routes!(update_dish, delete_dish))
49 .routes(routes!(book_meal, list_menu_bookings))
50 .routes(routes!(my_bookings))
51 .routes(routes!(cancel_booking))
52 .routes(routes!(mark_attendance, list_menu_attendance))
53 .routes(routes!(user_attendance))
54 .routes(routes!(my_profile))
55 .routes(routes!(user_profile, update_profile))
56 .routes(routes!(my_balance))
57 .routes(routes!(user_balance))
58 .routes(routes!(user_ledger))
59 .routes(routes!(record_credit))
60}
61
62#[derive(Deserialize, ToSchema)]
63struct CreateMenu {
64 /// The calendar day, `YYYY-MM-DD`. Text, not a timestamp: "one menu per
65 /// day and slot" is the school's own day, not UTC midnight.
66 #[schema(example = "2026-09-14", min_length = 10, max_length = 10)]
67 date: String,
68 /// One of the school's `meal_slots` (see `GET /settings`).
69 #[schema(example = "lunch")]
70 slot: String,
71 /// How many students may book it. Omit (or `null`) for uncapped.
72 #[schema(minimum = 0, maximum = 10000, example = 120)]
73 capacity: Option<i64>,
74}
75
76#[derive(Deserialize, ToSchema)]
77struct UpdateMenu {
78 /// New seat cap; `null` clears it back to uncapped. `date` and `slot` are
79 /// immutable — a menu on another day is another menu.
80 #[serde(default, deserialize_with = "set_or_clear")]
81 #[schema(value_type = Option<i64>, minimum = 0, maximum = 10000)]
82 capacity: Option<Option<i64>>,
83}
84
85/// Inclusive `YYYY-MM-DD` bounds on `GET /meals/menus`. Either may be omitted.
86#[derive(Debug, Deserialize, IntoParams)]
87struct MenuRange {
88 /// Keep menus on or after this day.
89 #[param(example = "2026-09-01")]
90 from: Option<String>,
91 /// Keep menus on or before this day.
92 #[param(example = "2026-09-30")]
93 to: Option<String>,
94}
95
96/// Optional slot filter on `GET /meals/menus`. Its own extractor, so
97/// `GET /meals/attendance/{user}` — which shares [`MenuRange`] for its date
98/// bounds — gains no dead `slot` param.
99#[derive(Debug, Deserialize, IntoParams)]
100struct MenuSlotFilter {
101 /// Keep only menus published for this meal slot, named exactly as the
102 /// menu snapshotted it.
103 #[param(example = "lunch")]
104 slot: Option<String>,
105}
106
107impl MenuSlotFilter {
108 /// The slot text to bind, trimmed. Deliberately *not* checked against
109 /// the school's current `meal_slots`: a menu snapshots its slot's name
110 /// at publish, so a slot retired since must still find the menus
111 /// published under it — an unknown name simply matches nothing (an
112 /// empty page, not a `400`). An empty value, though, filters nothing
113 /// and says nothing: refused, naming the field.
114 fn resolve(self) -> Result<Option<String>, AppError> {
115 let Some(raw) = self.slot else {
116 return Ok(None);
117 };
118 let slot = raw.trim();
119 if slot.is_empty() {
120 return Err(ValidationError::Invalid {
121 field: "slot",
122 reason: "must name a meal slot and may not be empty",
123 }
124 .into());
125 }
126 Ok(Some(slot.to_string()))
127 }
128}
129
130#[derive(Deserialize, ToSchema)]
131struct CreateDish {
132 #[schema(example = "Mercimek çorbası", max_length = 100)]
133 name: String,
134 #[schema(max_length = 500)]
135 description: Option<String>,
136 /// Price in **minor units** — `4550` is 45,50 ₺. Integer only:
137 /// this API never speaks decimals or floats about money.
138 #[schema(minimum = 0, maximum = 1000000, example = 4550_i64)]
139 price_minor: i64,
140 /// Dietary tags, each one of the school's `dietary_tags` (`GET /settings`).
141 #[schema(max_items = 10, example = json!(["vegetarian"]))]
142 #[serde(default)]
143 tags: Vec<String>,
144}
145
146#[derive(Deserialize, ToSchema)]
147struct UpdateDish {
148 #[schema(max_length = 100)]
149 name: Option<String>,
150 /// `null` (or blank) clears the description.
151 #[serde(default, deserialize_with = "set_or_clear")]
152 #[schema(value_type = Option<String>, max_length = 500)]
153 description: Option<Option<String>>,
154 #[schema(minimum = 0, maximum = 1000000)]
155 price_minor: Option<i64>,
156 #[schema(max_items = 10)]
157 tags: Option<Vec<String>>,
158}
159
160#[derive(Serialize, ToSchema)]
161struct DishResponse {
162 id: String,
163 #[schema(example = "Mercimek çorbası")]
164 name: String,
165 description: Option<String>,
166 /// Minor units.
167 price_minor: i64,
168 tags: Vec<String>,
169 /// Which of `tags` the **calling user's** own dietary profile flags — the
170 /// set intersection of the two lists. Empty when they do not overlap, and
171 /// empty for every reader without a profile (staff included).
172 #[schema(example = json!(["nut_allergy"]))]
173 conflicts: Vec<String>,
174 created_at: i64,
175}
176
177impl DishResponse {
178 fn new(dish: &MenuDish, viewer_tags: &[String]) -> Self {
179 Self {
180 id: dish.get_id().key().to_string(),
181 name: dish.get_name().as_str().to_string(),
182 description: dish.get_description().map(|text| text.as_str().to_string()),
183 price_minor: dish.get_price_minor().as_minor(),
184 tags: dish.get_tags().as_slice().to_vec(),
185 conflicts: conflicts(dish.get_tags().as_slice(), viewer_tags),
186 created_at: dish.get_created_at().as_millis(),
187 }
188 }
189}
190
191#[derive(Serialize, ToSchema)]
192struct MenuResponse {
193 id: String,
194 /// The calendar day, `YYYY-MM-DD`.
195 #[schema(example = "2026-09-14")]
196 date: String,
197 /// The meal slot, snapshotted when the menu was published — it stays as it
198 /// was even if the school later retires the slot.
199 #[schema(example = "lunch")]
200 slot: String,
201 /// Seat cap; `null` = uncapped.
202 capacity: Option<i64>,
203 /// Everything on offer, in the order it was added.
204 dishes: Vec<DishResponse>,
205 created_by: PersonRef,
206 created_at: i64,
207}
208
209impl MenuResponse {
210 fn new(
211 menu: &Menu,
212 dishes: &[MenuDish],
213 people: &std::collections::HashMap<String, PersonRef>,
214 viewer_tags: &[String],
215 ) -> Self {
216 Self {
217 id: menu.get_id().key().to_string(),
218 date: menu.get_date().as_str().to_string(),
219 slot: menu.get_slot().as_str().to_string(),
220 capacity: menu.get_capacity(),
221 dishes: dishes
222 .iter()
223 .filter(|dish| dish.get_menu() == menu.get_id())
224 .map(|dish| DishResponse::new(dish, viewer_tags))
225 .collect(),
226 created_by: PersonRef::resolve(people, menu.get_created_by()),
227 created_at: menu.get_created_at().as_millis(),
228 }
229 }
230}
231
232/// Join dishes, publishers, and the reader's own dietary tags onto a page of
233/// menus — three queries for the whole page, never one per row. The profile in
234/// particular is read **once**, not per dish.
235async fn menu_responses(
236 menus: &[Menu],
237 viewer: &UserId,
238 db: &Database,
239) -> Result<Vec<MenuResponse>, AppError> {
240 let ids: Vec<MenuId> = menus.iter().map(|menu| menu.get_id().clone()).collect();
241 let dishes = service::menu::list_dishes_for_menus(db, &ids).await?;
242 let people = person_map(menus.iter().map(|menu| *menu.get_created_by()), db).await?;
243 let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?;
244 Ok(menus
245 .iter()
246 .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags))
247 .collect())
248}
249
250/// One menu, with its dishes.
251async fn one_menu(
252 menu: &Menu,
253 viewer: &UserId,
254 db: &Database,
255) -> Result<Json<MenuResponse>, AppError> {
256 let dishes = service::menu::list_dishes(db, menu.get_id()).await?;
257 let people = person_map([*menu.get_created_by()], db).await?;
258 let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?;
259 Ok(Json(MenuResponse::new(
260 menu,
261 &dishes,
262 &people,
263 &viewer_tags,
264 )))
265}
266
267/// Publish a menu for one day and meal slot. Requires manager+. `date` is
268/// `YYYY-MM-DD` text and must be a real calendar day (`2026-02-29` is a `400`:
269/// a menu on a day that does not exist has no serving instant, so no booking
270/// cutoff). The slot must be one the school currently serves and may not
271/// contain `/ \ ? # %` (it becomes part of the menu's URL id). A day+slot
272/// already published is a `409` — edit that menu instead of publishing a
273/// second one.
274///
275/// The day must not already be over (`400`): a published menu is a bookable
276/// one, and a booking is what charges the student. Today counts as ahead, all
277/// day long.
278#[utoipa::path(
279 post,
280 path = "/menus",
281 tag = "meals",
282 security(("session_cookie" = [])),
283 request_body = CreateMenu,
284 responses(
285 (status = 201, description = "Menu published", body = MenuResponse),
286 (status = 400, description = "Malformed date, a day that is already over, unknown slot, or out-of-range capacity", body = ErrorResponse),
287 (status = 401, description = "Not authenticated", body = ErrorResponse),
288 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
289 (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse),
290 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
291 ),
292)]
293async fn create_menu(
294 State(st): State<AppState>,
295 RequireManager(user): RequireManager,
296 Json(req): Json<CreateMenu>,
297) -> Result<(StatusCode, Json<MenuResponse>), AppError> {
298 let date = MenuDate::try_new(&req.date)?;
299 // The kitchen publishes ahead, never behind: a menu on a day already over
300 // is bookable and therefore *billable* (booking is the charge trigger), so
301 // this is the same door every other create path in the crate has. Measured
302 // against the end of the day, so today's menu is publishable all day — the
303 // meal's own deadline is `meal_cancel_cutoff_minutes`, not this.
304 check_not_past("date", date.day_end())?;
305 let slot = MenuSlot::try_new(
306 &req.slot,
307 &service::settings::load(&st.db).await?.get_meal_slots(),
308 )?;
309 validate_capacity(req.capacity)?;
310 let menu = service::menu::create(&st.db, date, slot, req.capacity, user.get_id()).await?;
311 let body = one_menu(&menu, user.get_id(), &st.db).await?;
312 Ok((StatusCode::CREATED, body))
313}
314
315/// List published menus, newest day first, each with its dishes. Any
316/// authenticated user. Narrow to a date range with `?from=&to=` (inclusive,
317/// `YYYY-MM-DD`, each bound held to the same real-calendar-day rule a menu's
318/// own date is). Paged via `?limit=&offset=` (omit `limit` for the full list);
319/// returns a `{items, total, limit, offset}` envelope.
320///
321/// Narrow to one meal slot with `?slot=` — matched exactly against the slot
322/// text each menu snapshotted at publish, not against the school's current
323/// `meal_slots`, so a slot retired since still finds its menus and an
324/// unknown name is an empty page rather than an error. `?slot=` (empty) is a
325/// `400`. The filter runs in SQL: `total` counts the filtered rows, and
326/// `limit`/`offset` window inside them.
327#[utoipa::path(
328 get,
329 path = "/menus",
330 tag = "meals",
331 security(("session_cookie" = [])),
332 params(MenuRange, MenuSlotFilter, PageParams),
333 responses(
334 (status = 200, description = "A page of menus (the full list when unpaged)", body = Page<MenuResponse>),
335 (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, an empty slot, or a malformed limit or offset", body = ErrorResponse),
336 (status = 401, description = "Not authenticated", body = ErrorResponse),
337 ),
338)]
339async fn list_menus(
340 State(st): State<AppState>,
341 CurrentUser(user): CurrentUser,
342 Query(range): Query<MenuRange>,
343 Query(filter): Query<MenuSlotFilter>,
344 Query(page): Query<PageParams>,
345) -> Result<Json<Page<MenuResponse>>, AppError> {
346 let (limit, offset) = page.resolve()?;
347 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
348 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
349 let slot = filter.resolve()?;
350 let (menus, total) = service::menu::list(
351 &st.db,
352 from.as_ref(),
353 to.as_ref(),
354 slot.as_deref(),
355 limit,
356 offset,
357 )
358 .await?;
359 // The dish/people join runs over the page alone, so it shrinks with it.
360 let items = menu_responses(&menus, user.get_id(), &st.db).await?;
361 Ok(Json(Page::new(items, total, limit, offset)))
362}
363
364/// Fetch one menu with its dishes.
365#[utoipa::path(
366 get,
367 path = "/menus/{id}",
368 tag = "meals",
369 security(("session_cookie" = [])),
370 params(("id" = String, Path, description = "Menu id")),
371 responses(
372 (status = 200, description = "The menu", body = MenuResponse),
373 (status = 401, description = "Not authenticated", body = ErrorResponse),
374 (status = 404, description = "Not found", body = ErrorResponse),
375 ),
376)]
377async fn get_menu(
378 State(st): State<AppState>,
379 CurrentUser(user): CurrentUser,
380 Path(id): Path<String>,
381) -> Result<Json<MenuResponse>, AppError> {
382 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
383 .await?
384 .ok_or(AppError::NotFound)?;
385 one_menu(&menu, user.get_id(), &st.db).await
386}
387
388/// Change a menu's seat cap. Requires manager+. `date` and `slot` are
389/// immutable; `"capacity": null` goes back to uncapped.
390#[utoipa::path(
391 patch,
392 path = "/menus/{id}",
393 tag = "meals",
394 security(("session_cookie" = [])),
395 params(("id" = String, Path, description = "Menu id")),
396 request_body = UpdateMenu,
397 responses(
398 (status = 200, description = "Updated menu", body = MenuResponse),
399 (status = 400, description = "Capacity out of range", body = ErrorResponse),
400 (status = 401, description = "Not authenticated", body = ErrorResponse),
401 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
402 (status = 404, description = "Not found", body = ErrorResponse),
403 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
404 ),
405)]
406async fn update_menu(
407 State(st): State<AppState>,
408 RequireManager(user): RequireManager,
409 Path(id): Path<String>,
410 Json(req): Json<UpdateMenu>,
411) -> Result<Json<MenuResponse>, AppError> {
412 if let Some(capacity) = req.capacity {
413 validate_capacity(capacity)?;
414 }
415 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
416 .await?
417 .ok_or(AppError::NotFound)?;
418 let updated = service::menu::update(&st.db, menu, req.capacity).await?;
419 one_menu(&updated, user.get_id(), &st.db).await
420}
421
422/// Unpublish a menu. Requires manager+. Its dishes go with it — a dish has no
423/// meaning apart from the menu it was published on. A menu somebody still
424/// holds a seat on is a `409`: cancel the bookings first.
425#[utoipa::path(
426 delete,
427 path = "/menus/{id}",
428 tag = "meals",
429 security(("session_cookie" = [])),
430 params(("id" = String, Path, description = "Menu id")),
431 responses(
432 (status = 204, description = "Deleted"),
433 (status = 401, description = "Not authenticated", body = ErrorResponse),
434 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
435 (status = 404, description = "Not found", body = ErrorResponse),
436 (status = 409, description = "The menu still has live bookings", body = ErrorResponse),
437 ),
438)]
439async fn delete_menu(
440 State(st): State<AppState>,
441 RequireManager(_user): RequireManager,
442 Path(id): Path<String>,
443) -> Result<StatusCode, AppError> {
444 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
445 .await?
446 .ok_or(AppError::NotFound)?;
447 // The seat check rides in the delete's own `WHERE` (the persistence
448 // layer's `menu::delete`), so a concurrent booking cannot slip between
449 // the read and the delete.
450 service::menu::delete(&st.db, menu).await?;
451 Ok(StatusCode::NO_CONTENT)
452}
453
454/// Add a dish to a menu. Requires manager+. Tags must come from the school's
455/// `dietary_tags`, and a menu holds at most 50 dishes (`409` at the cap).
456#[utoipa::path(
457 post,
458 path = "/menus/{id}/dishes",
459 tag = "meals",
460 security(("session_cookie" = [])),
461 params(("id" = String, Path, description = "Menu id")),
462 request_body = CreateDish,
463 responses(
464 (status = 201, description = "Dish added", body = DishResponse),
465 (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse),
466 (status = 401, description = "Not authenticated", body = ErrorResponse),
467 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
468 (status = 404, description = "No such menu", body = ErrorResponse),
469 (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse),
470 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
471 ),
472)]
473async fn add_dish(
474 State(st): State<AppState>,
475 RequireManager(user): RequireManager,
476 Path(id): Path<String>,
477 Json(req): Json<CreateDish>,
478) -> Result<(StatusCode, Json<DishResponse>), AppError> {
479 let name = DishName::try_new(&req.name)?;
480 let description = req
481 .description
482 .as_deref()
483 .map(DishDescription::try_new)
484 .transpose()?
485 .flatten();
486 let price = DishPrice::try_new(req.price_minor)?;
487 let tags = DishTags::try_new(
488 &req.tags,
489 &service::settings::load(&st.db).await?.get_dietary_tags(),
490 )?;
491 // The dish-cap gate lives in the service: the cap is one guarded
492 // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the
493 // dish write's own transaction and the insert carries the
494 // `count(*) < cap` guard, so a dish can never land on a menu that no
495 // longer exists, and two racing writers cannot overfill it either.
496 let dish = service::menu::add_dish(
497 &st.db,
498 &MenuId::from_key(&id),
499 name,
500 description,
501 price,
502 tags,
503 )
504 .await?;
505 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;
506 Ok((
507 StatusCode::CREATED,
508 Json(DishResponse::new(&dish, &viewer_tags)),
509 ))
510}
511
512/// Edit a dish. Requires manager+. Omitted fields keep their value;
513/// `"description": null` clears it, and `tags` replaces the whole list.
514#[utoipa::path(
515 patch,
516 path = "/dishes/{did}",
517 tag = "meals",
518 security(("session_cookie" = [])),
519 params(("did" = String, Path, description = "Dish id")),
520 request_body = UpdateDish,
521 responses(
522 (status = 200, description = "Updated dish", body = DishResponse),
523 (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse),
524 (status = 401, description = "Not authenticated", body = ErrorResponse),
525 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
526 (status = 404, description = "Not found", body = ErrorResponse),
527 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
528 ),
529)]
530async fn update_dish(
531 State(st): State<AppState>,
532 RequireManager(user): RequireManager,
533 Path(did): Path<String>,
534 Json(req): Json<UpdateDish>,
535) -> Result<Json<DishResponse>, AppError> {
536 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))
537 .await?
538 .ok_or(AppError::NotFound)?;
539 let name = req.name.as_deref().map(DishName::try_new).transpose()?;
540 // Absent keeps, `null` clears, and a blank string clears too — an empty
541 // description is the absence of one, never a stored empty string.
542 let description = match req.description {
543 None => None,
544 Some(None) => Some(None),
545 Some(Some(text)) => Some(DishDescription::try_new(&text)?),
546 };
547 let price = req.price_minor.map(DishPrice::try_new).transpose()?;
548 let tags = match &req.tags {
549 Some(tags) => Some(DishTags::try_new(
550 tags,
551 &service::settings::load(&st.db).await?.get_dietary_tags(),
552 )?),
553 None => None,
554 };
555 // The dish write locks the menu row inside its own transaction — see
556 // `add_dish`.
557 let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?;
558 let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?;
559 Ok(Json(DishResponse::new(&updated, &viewer_tags)))
560}
561
562/// Remove a dish from its menu. Requires manager+.
563#[utoipa::path(
564 delete,
565 path = "/dishes/{did}",
566 tag = "meals",
567 security(("session_cookie" = [])),
568 params(("did" = String, Path, description = "Dish id")),
569 responses(
570 (status = 204, description = "Deleted"),
571 (status = 401, description = "Not authenticated", body = ErrorResponse),
572 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
573 (status = 404, description = "Not found", body = ErrorResponse),
574 ),
575)]
576async fn delete_dish(
577 State(st): State<AppState>,
578 RequireManager(_user): RequireManager,
579 Path(did): Path<String>,
580) -> Result<StatusCode, AppError> {
581 let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did))
582 .await?
583 .ok_or(AppError::NotFound)?;
584 // The dish write locks the menu row inside its own transaction — see
585 // `add_dish`.
586 service::menu::delete_dish(&st.db, dish).await?;
587 Ok(StatusCode::NO_CONTENT)
588}
589
590// ---- dietary profiles -----------------------------------------------------
591
592#[derive(Deserialize, ToSchema)]
593struct UpdateDietaryProfile {
594 /// Replaces the whole tag list; each entry must be one of the school's
595 /// `dietary_tags` (`GET /settings`) — the same vocabulary a dish is tagged
596 /// from, which is what makes a menu's `conflicts` computable.
597 #[schema(max_items = 10, example = json!(["nut_allergy"]))]
598 tags: Option<Vec<String>>,
599 /// Free text for the kitchen; `null` (or blank) clears it.
600 #[serde(default, deserialize_with = "set_or_clear")]
601 #[schema(value_type = Option<String>, max_length = 500, example = "carries an EpiPen")]
602 note: Option<Option<String>>,
603}
604
605#[derive(Serialize, ToSchema)]
606struct DietaryProfileResponse {
607 student: PersonRef,
608 /// The tags the school recorded; empty while there is no profile.
609 tags: Vec<String>,
610 note: Option<String>,
611 /// Who last wrote it, and when — both absent while no profile exists.
612 updated_by: Option<PersonRef>,
613 updated_at: Option<i64>,
614}
615
616/// One student's profile, or the empty one. A student who was never recorded
617/// has *no* restrictions, so that reads back as an empty profile rather than a
618/// `404` — the caller asked "what may they not eat", and "nothing known" is an
619/// answer.
620async fn profile_response(
621 student: &UserId,
622 db: &Database,
623) -> Result<Json<DietaryProfileResponse>, AppError> {
624 let profile = service::dietary_profile::read(db, student).await?;
625 let people = person_map(
626 std::iter::once(*student).chain(profile.as_ref().map(|row| *row.get_updated_by())),
627 db,
628 )
629 .await?;
630 Ok(Json(DietaryProfileResponse {
631 student: PersonRef::resolve(&people, student),
632 tags: profile
633 .as_ref()
634 .map(|row| row.get_tags().as_slice().to_vec())
635 .unwrap_or_default(),
636 note: profile
637 .as_ref()
638 .and_then(|row| row.get_note())
639 .map(|note| note.as_str().to_string()),
640 updated_by: profile
641 .as_ref()
642 .map(|row| PersonRef::resolve(&people, row.get_updated_by())),
643 updated_at: profile.as_ref().map(|row| row.get_updated_at().as_millis()),
644 }))
645}
646
647/// The caller's own dietary profile — what the school recorded about their
648/// diet. Empty tags mean nothing was ever recorded.
649#[utoipa::path(
650 get,
651 path = "/profiles/me",
652 tag = "meals",
653 security(("session_cookie" = [])),
654 responses(
655 (status = 200, description = "The caller's dietary profile", body = DietaryProfileResponse),
656 (status = 401, description = "Not authenticated", body = ErrorResponse),
657 ),
658)]
659async fn my_profile(
660 State(st): State<AppState>,
661 CurrentUser(user): CurrentUser,
662) -> Result<Json<DietaryProfileResponse>, AppError> {
663 profile_response(user.get_id(), &st.db).await
664}
665
666/// One student's dietary profile. Requires teacher+, or a parent link to them
667/// — the caller's own id always passes.
668#[utoipa::path(
669 get,
670 path = "/profiles/{user}",
671 tag = "meals",
672 security(("session_cookie" = [])),
673 params(("user" = String, Path, description = "Student id")),
674 responses(
675 (status = 200, description = "The student's dietary profile", body = DietaryProfileResponse),
676 (status = 401, description = "Not authenticated", body = ErrorResponse),
677 (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
678 ),
679)]
680async fn user_profile(
681 State(st): State<AppState>,
682 CurrentUser(caller): CurrentUser,
683 Path(user): Path<String>,
684) -> Result<Json<DietaryProfileResponse>, AppError> {
685 let target = UserId::from_key(&user);
686 ensure_can_read_student(&caller, &target, &st.db).await?;
687 profile_response(&target, &st.db).await
688}
689
690/// Record what a student may not eat. **Manager+**, deliberately: an allergen
691/// list is a safety record the school keeps on the student's behalf, not a
692/// self-service preference — a student editing their own would let a mistyped
693/// (or removed) allergy reach the kitchen with the school's authority behind
694/// it. Omitted fields keep their value; `tags` replaces the whole list, and
695/// `"note": null` clears the note. First write creates the row.
696#[utoipa::path(
697 patch,
698 path = "/profiles/{user}",
699 tag = "meals",
700 security(("session_cookie" = [])),
701 params(("user" = String, Path, description = "Student id")),
702 request_body = UpdateDietaryProfile,
703 responses(
704 (status = 200, description = "The stored profile", body = DietaryProfileResponse),
705 (status = 400, description = "Unknown dietary tag, too many tags, an over-long note, or a non-student target", body = ErrorResponse),
706 (status = 401, description = "Not authenticated", body = ErrorResponse),
707 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
708 (status = 404, description = "No such user", body = ErrorResponse),
709 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
710 ),
711)]
712async fn update_profile(
713 State(st): State<AppState>,
714 RequireManager(manager): RequireManager,
715 Path(user): Path<String>,
716 Json(req): Json<UpdateDietaryProfile>,
717) -> Result<Json<DietaryProfileResponse>, AppError> {
718 let target = UserId::from_key(&user);
719 // Only a student eats off the school's menus; a profile on anyone else is
720 // a typo, and a typo here is an allergy filed against the wrong person.
721 if crate::service::user::read(&st.db, &target)
722 .await?
723 .ok_or(AppError::NotFound)?
724 .get_role()
725 != Role::Student
726 {
727 return Err(AppError::Validation(ValidationError::Invalid {
728 field: "user",
729 reason: "only a student carries a dietary profile",
730 }));
731 }
732 let tags = match &req.tags {
733 Some(tags) => Some(DietaryTags::try_new(
734 tags,
735 &service::settings::load(&st.db).await?.get_dietary_tags(),
736 )?),
737 None => None,
738 };
739 // Absent keeps, `null` clears, and a blank string clears too — an empty
740 // note is the absence of one, never a stored empty string.
741 let note = match req.note {
742 None => None,
743 Some(None) => Some(None),
744 Some(Some(text)) => Some(DietaryNote::try_new(&text)?),
745 };
746 service::dietary_profile::save(&st.db, &target, tags, note, manager.get_id()).await?;
747 profile_response(&target, &st.db).await
748}
749
750// ---- bookings -------------------------------------------------------------
751
752#[derive(Deserialize, ToSchema)]
753struct BookMeal {
754 /// Who the seat is for. Omit to book for yourself (a student's own lunch);
755 /// a parent must name one of their linked students.
756 student_id: Option<String>,
757}
758
759#[derive(Serialize, ToSchema)]
760struct BookingResponse {
761 id: String,
762 /// The menu the seat is on.
763 menu_id: String,
764 student: PersonRef,
765 /// Who placed it — the student themselves, or their parent.
766 booked_by: PersonRef,
767 /// `booked` or `cancelled`. A cancel keeps the row (audit), it only stops
768 /// the seat counting against the menu's capacity.
769 #[schema(example = "booked")]
770 status: String,
771 cancelled_at: Option<i64>,
772 created_at: i64,
773}
774
775impl BookingResponse {
776 fn new(booking: &MealBooking, people: &std::collections::HashMap<String, PersonRef>) -> Self {
777 Self {
778 id: booking.id().key(),
779 menu_id: booking.get_menu().key().to_string(),
780 student: PersonRef::resolve(people, booking.get_student()),
781 booked_by: PersonRef::resolve(people, booking.get_booked_by()),
782 status: booking.get_status().as_str().to_string(),
783 cancelled_at: booking.get_cancelled_at().map(|at| at.as_millis()),
784 created_at: booking.get_created_at().as_millis(),
785 }
786 }
787}
788
789/// Join the people onto a page of bookings — one query for the whole page.
790async fn booking_responses(
791 bookings: &[MealBooking],
792 db: &Database,
793) -> Result<Vec<BookingResponse>, AppError> {
794 let people = person_map(
795 bookings
796 .iter()
797 .flat_map(|booking| [*booking.get_student(), *booking.get_booked_by()]),
798 db,
799 )
800 .await?;
801 Ok(bookings
802 .iter()
803 .map(|booking| BookingResponse::new(booking, &people))
804 .collect())
805}
806
807/// The school's one meal deadline, applied to booking and cancelling alike:
808/// the cutoff minutes plus the slot serving times they count back from. Read
809/// live on every call, so a serving time corrected today moves the deadline of
810/// menus already published for it.
811async fn meal_cutoff(db: &Database) -> Result<MealCutoff, AppError> {
812 Ok(MealCutoff::from_settings(
813 &service::settings::load(db).await?,
814 ))
815}
816
817/// Whose seat is this? A student books only for themselves; a parent only for
818/// a student they hold a link to. Nobody else books through this route — a
819/// teacher or manager arranging someone's lunch is not a thing this API does.
820///
821/// The link row alone is not the grant: like a stale enrollment, a link whose
822/// student side changed role must be inert, so the target's live role is
823/// re-read here. A missing or non-student target falls through to the same
824/// 403 — a parent never gets an existence oracle.
825async fn booking_target(
826 caller: &User,
827 student_id: Option<&str>,
828 db: &Database,
829) -> Result<UserId, AppError> {
830 match caller.get_role() {
831 Role::Student => match student_id {
832 Some(id) if id != caller.get_id().key() => Err(AppError::Forbidden(
833 "a student books meals only for themselves",
834 )),
835 _ => Ok(*caller.get_id()),
836 },
837 Role::Parent => {
838 let target = UserId::from_key(student_id.ok_or(AppError::Validation(
839 ValidationError::Invalid {
840 field: "student_id",
841 reason: "a parent must name the student the seat is for",
842 },
843 ))?);
844 if crate::service::parent_link::links_live(db, caller.get_id(), &target).await? {
845 return Ok(target);
846 }
847 Err(AppError::Forbidden(
848 "a parent books meals only for a linked student",
849 ))
850 }
851 _ => Err(AppError::Forbidden(
852 "only students and their parents book meals",
853 )),
854 }
855}
856
857/// Take a seat on a published menu. A student books for themselves (omit
858/// `student_id`); a parent books for a linked student by naming them. Booking
859/// twice is the same seat, not a second one — and bills once, at the price the
860/// menu carried when the seat was first taken. Refused (`409`) when the menu is
861/// full, when its **day has already passed** (a seat taken then would bill a
862/// meal nobody can be served — and no role bypasses that, since only students
863/// and their parents book at all), or when the school's
864/// `meal_cancel_cutoff_minutes` has closed the meal, and
865/// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat
866/// is never handed out unbilled.
867///
868/// One seat may be taken at most `meal.max_booking_attempts` times (`GET
869/// /limits`) — the first booking plus the re-bookings after a cancel. Past that
870/// it is a `409`: every cycle appends a charge and its reversal, permanently, so
871/// the ceiling bounds the student's statement rather than their mind changing.
872/// A seat that really must move again is the canteen's to cancel.
873#[utoipa::path(
874 post,
875 path = "/menus/{id}/bookings",
876 tag = "meals",
877 security(("session_cookie" = [])),
878 params(("id" = String, Path, description = "Menu id")),
879 request_body = BookMeal,
880 responses(
881 (status = 201, description = "Seat booked (or the seat already held)", body = BookingResponse),
882 (status = 400, description = "A parent named no student, or the menu's dishes sum past the chargeable maximum", body = ErrorResponse),
883 (status = 401, description = "Not authenticated", body = ErrorResponse),
884 (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse),
885 (status = 404, description = "No such menu", body = ErrorResponse),
886 (status = 409, description = "The menu is full, its day has already passed, its cutoff has passed, its date is not a real calendar day so no cutoff can be worked out, the seat has been booked and cancelled its maximum number of times, or the menu kept being edited while the seat was being taken", body = ErrorResponse),
887 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
888 ),
889)]
890async fn book_meal(
891 State(st): State<AppState>,
892 CurrentUser(user): CurrentUser,
893 Path(id): Path<String>,
894 Json(req): Json<BookMeal>,
895) -> Result<(StatusCode, Json<BookingResponse>), AppError> {
896 let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?;
897 let cutoff = meal_cutoff(&st.db).await?;
898 let menu = MenuId::from_key(&id);
899 // Price, seat and charge land as one decision (see
900 // `service::meal_booking::book`), keyed by (seat, attempt) — a double-click
901 // books one seat and bills it once, and a dish landing between the price
902 // and the seat is refused by the claim rather than billed.
903 let booking =
904 service::meal_booking::book(&st.db, &menu, &student, user.get_id(), &cutoff).await?;
905 let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?;
906 Ok((
907 StatusCode::CREATED,
908 Json(items.into_iter().next().expect("one booking in, one out")),
909 ))
910}
911
912/// The caller's own bookings, newest first: the seats held *for* them, plus —
913/// for a parent — the seats held for every student they currently hold a link
914/// to. The links are re-read on every call, so an unlinked parent stops seeing
915/// the child's meals at once, even the ones they booked themselves. Cancelled
916/// bookings stay in the list, flagged. Paged via `?limit=&offset=` (omit
917/// `limit` for all of them); returns a `{items, total, limit, offset}` envelope.
918#[utoipa::path(
919 get,
920 path = "/bookings/me",
921 tag = "meals",
922 security(("session_cookie" = [])),
923 params(PageParams),
924 responses(
925 (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<BookingResponse>),
926 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
927 (status = 401, description = "Not authenticated", body = ErrorResponse),
928 ),
929)]
930async fn my_bookings(
931 State(st): State<AppState>,
932 CurrentUser(user): CurrentUser,
933 Query(page): Query<PageParams>,
934) -> Result<Json<Page<BookingResponse>>, AppError> {
935 let (limit, offset) = page.resolve()?;
936 // Own seats always; a parent's children only while the link is live — the
937 // booking row's `booked_by` is history, never a standing read grant.
938 let mut students = vec![*user.get_id()];
939 if user.get_role() == Role::Parent {
940 students.extend(
941 crate::service::parent_link::list_for_parent(&st.db, user.get_id())
942 .await?
943 .iter()
944 .map(|link| *link.get_student()),
945 );
946 }
947 let (rows, total) =
948 service::meal_booking::list_for_students(&st.db, &students, limit, offset).await?;
949 let items = booking_responses(&rows, &st.db).await?;
950 Ok(Json(Page::new(items, total, limit, offset)))
951}
952
953/// Who is eating: every booking on one menu, cancelled ones included so the
954/// kitchen can see what changed. Requires manager+ — this is the whole school's
955/// list, not one family's. Paged via `?limit=&offset=`.
956#[utoipa::path(
957 get,
958 path = "/menus/{id}/bookings",
959 tag = "meals",
960 security(("session_cookie" = [])),
961 params(("id" = String, Path, description = "Menu id"), PageParams),
962 responses(
963 (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page<BookingResponse>),
964 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
965 (status = 401, description = "Not authenticated", body = ErrorResponse),
966 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
967 (status = 404, description = "No such menu", body = ErrorResponse),
968 ),
969)]
970async fn list_menu_bookings(
971 State(st): State<AppState>,
972 RequireManager(_user): RequireManager,
973 Path(id): Path<String>,
974 Query(page): Query<PageParams>,
975) -> Result<Json<Page<BookingResponse>>, AppError> {
976 let (limit, offset) = page.resolve()?;
977 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
978 .await?
979 .ok_or(AppError::NotFound)?;
980 let (rows, total) =
981 service::meal_booking::list_for_menu(&st.db, menu.get_id(), limit, offset).await?;
982 let items = booking_responses(&rows, &st.db).await?;
983 Ok(Json(Page::new(items, total, limit, offset)))
984}
985
986/// Give the seat back. The row survives, flipped to `cancelled` — the seat is
987/// free for someone else, and the cancellation stays auditable. Only the
988/// student it is for, or their parent, **or any manager+**, may cancel it — and
989/// for the student and their parent it is refused (`409`) once the school's
990/// `meal_cancel_cutoff_minutes` has closed the meal, a cutoff a manager+ is not
991/// bound by. Idempotent: cancelling again is a `200` that replays the refund.
992/// `409` too when the menu's date is not a real calendar day, since no cutoff
993/// can be worked out from one, and when the seat was booked again while the
994/// call ran, since only the attempt it read is ever released.
995///
996/// Manager+ may cancel anyone's booking, and is not bound by the cutoff — the
997/// seat and the money have to stay reachable when the student it was booked for
998/// is no longer a student, or when the meal has already closed.
999///
1000/// **Idempotent**: cancelling an already-cancelled booking is a `200` with the
1001/// row as it stands, not a `409`. Repeating it also replays the refund, so a
1002/// cancel that was cut short mid-flight (the tab closed, a proxy timed out) is
1003/// recovered by simply sending it again — the reversal is keyed to the seat's
1004/// attempt, so the money comes back exactly once however often it is retried.
1005///
1006/// A seat **re-booked while this call was running** is a `409`: the flip only
1007/// ever releases the attempt this call read, so the newer seat — one this API
1008/// answered `201` for and nobody here asked to free — is left alone. Send the
1009/// call again to cancel the seat as it now stands.
1010///
1011/// **Who is asking is decided before the seat is looked up**, so an unauthorised
1012/// caller gets the same `403` whether or not the booking exists. Booking ids are
1013/// derivable (`{date}_{slot}_{student}`), and a `404` here would otherwise
1014/// answer "did this student book this meal?" — the manager-only list at
1015/// `GET /meals/menus/{id}/bookings`, one student at a time.
1016#[utoipa::path(
1017 delete,
1018 path = "/bookings/{bid}",
1019 tag = "meals",
1020 security(("session_cookie" = [])),
1021 params(("bid" = String, Path, description = "Booking id")),
1022 responses(
1023 (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse),
1024 (status = 401, description = "Not authenticated", body = ErrorResponse),
1025 (status = 403, description = "Not the booking's student, their parent, nor a manager — answered before the booking is read, so it is also what an unauthorised caller gets for a booking that does not exist", body = ErrorResponse),
1026 (status = 404, description = "Not found (only for a caller who may cancel it)", body = ErrorResponse),
1027 (status = 409, description = "The cutoff has passed (students and parents only), the menu's date is not a real calendar day so no cutoff can be worked out, the seat was booked again while this call ran, or the menu was too contended to free the seat", body = ErrorResponse),
1028 ),
1029)]
1030async fn cancel_booking(
1031 State(st): State<AppState>,
1032 CurrentUser(user): CurrentUser,
1033 Path(bid): Path<String>,
1034) -> Result<Json<BookingResponse>, AppError> {
1035 let id = MealBookingId::from_key(&bid);
1036 // Manager+ may give back *any* seat. Not a convenience: `booking_target`
1037 // grants only students and parents, so a student promoted to staff (or a
1038 // parent unlinked) left a live seat nobody on the API could cancel — the
1039 // menu 409s its own delete forever and the charge can never be reversed,
1040 // since cancelling is the only route that reverses one. Promotion itself
1041 // deliberately sweeps nothing: moving money is a decision, not a side
1042 // effect of a role change.
1043 let staff = user.get_role().at_least(Role::Manager);
1044 if !staff {
1045 // Decided off the *id*, before the row is read: the id is
1046 // `{date}_{slot}_{student}`, and a teacher may list both the menus and
1047 // the users, so authorising after the read answered 403 for a seat that
1048 // exists and 404 for one that does not — an existence oracle around the
1049 // deliberate manager+ gate on `GET /menus/{id}/bookings`, and one any
1050 // peer holding a user id could work too. An unauthorised caller now
1051 // gets the same 403 either way, and learns nothing.
1052 //
1053 // Same door as booking: whoever may take the seat may give it back.
1054 let student = id.student();
1055 let target = booking_target(&user, Some(student.key().as_str()), &st.db).await?;
1056 if target != student {
1057 return Err(AppError::Forbidden("not your booking"));
1058 }
1059 }
1060 // …and the cutoff does not bind them either. It exists to stop students
1061 // gaming the kitchen's headcount, which is no reason to leave staff holding
1062 // a seat they cannot free: past the cutoff the seat was uncancellable, and
1063 // its menu — which refuses its own delete while a seat is held — was
1064 // undeletable with it, forever. A deadline that binds nobody is exactly the
1065 // one a school that set no `meal_cancel_cutoff_minutes` already runs under.
1066 let cutoff = if staff {
1067 MealCutoff::default()
1068 } else {
1069 meal_cutoff(&st.db).await?
1070 };
1071 // Flips the row and appends the reversal for that attempt's charge in one
1072 // transaction; the charge itself stays.
1073 let booking = service::meal_booking::read(&st.db, &id)
1074 .await?
1075 .ok_or(AppError::NotFound)?;
1076 let cancelled = service::meal_booking::cancel(&st.db, booking, &cutoff, user.get_id()).await?;
1077 let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?;
1078 Ok(Json(
1079 items.into_iter().next().expect("one booking in, one out"),
1080 ))
1081}
1082
1083// ---- attendance -----------------------------------------------------------
1084//
1085// Reporting only: nothing in this section touches [`MealLedger`]. Booking is
1086// what charges, so a no-show still pays — the kitchen bought the food.
1087
1088#[derive(Deserialize, ToSchema)]
1089struct MarkMealAttendance {
1090 /// Who was (or was not) served — usually a student, but the canteen also
1091 /// feeds staff, so any existing user may be marked. The mark moves no money.
1092 student_id: String,
1093 /// `served` or `missed` — the canteen's own fixed pair, not the school's
1094 /// editable roll-call statuses.
1095 #[schema(example = "served")]
1096 status: String,
1097}
1098
1099#[derive(Serialize, ToSchema)]
1100struct MealAttendanceResponse {
1101 id: String,
1102 /// The menu the mark is against.
1103 menu_id: String,
1104 student: PersonRef,
1105 #[schema(example = "served")]
1106 status: String,
1107 marked_by: PersonRef,
1108 marked_at: i64,
1109}
1110
1111impl MealAttendanceResponse {
1112 fn new(row: &MealAttendance, people: &std::collections::HashMap<String, PersonRef>) -> Self {
1113 Self {
1114 id: MealAttendanceId::composite(row.get_menu(), row.get_student()).key(),
1115 menu_id: row.get_menu().key().to_string(),
1116 student: PersonRef::resolve(people, row.get_student()),
1117 status: row.get_status().as_str().to_string(),
1118 marked_by: PersonRef::resolve(people, row.get_marked_by()),
1119 marked_at: row.get_marked_at().as_millis(),
1120 }
1121 }
1122}
1123
1124/// Join the people onto a page of marks — one query for the whole page.
1125async fn attendance_responses(
1126 rows: &[MealAttendance],
1127 db: &Database,
1128) -> Result<Vec<MealAttendanceResponse>, AppError> {
1129 let people = person_map(
1130 rows.iter()
1131 .flat_map(|row| [*row.get_student(), *row.get_marked_by()]),
1132 db,
1133 )
1134 .await?;
1135 Ok(rows
1136 .iter()
1137 .map(|row| MealAttendanceResponse::new(row, &people))
1138 .collect())
1139}
1140
1141/// Record whether someone ate off a menu. Requires teacher+ — whoever stands
1142/// at the canteen door marks, students never mark themselves. One row per
1143/// (menu, person), so re-marking corrects the row rather than adding another.
1144///
1145/// The target need only *exist*: a canteen also serves staff, and a walk-in
1146/// with no booking is still someone the kitchen fed. Marking is a record of
1147/// what happened, not a check of who was entitled — and since it moves no
1148/// money, a non-student mark costs nobody anything.
1149///
1150/// **This moves no money.** A booked student who did not show is still charged
1151/// (the food was cooked), and a walk-in marked `served` without a booking is
1152/// not charged either — booking is the only charge trigger.
1153#[utoipa::path(
1154 post,
1155 path = "/menus/{id}/attendance",
1156 tag = "meals",
1157 security(("session_cookie" = [])),
1158 params(("id" = String, Path, description = "Menu id")),
1159 request_body = MarkMealAttendance,
1160 responses(
1161 (status = 200, description = "Attendance recorded", body = MealAttendanceResponse),
1162 (status = 400, description = "Invalid status, or no such user", body = ErrorResponse),
1163 (status = 401, description = "Not authenticated", body = ErrorResponse),
1164 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1165 (status = 404, description = "No such menu", body = ErrorResponse),
1166 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1167 ),
1168)]
1169async fn mark_attendance(
1170 State(st): State<AppState>,
1171 RequireTeacher(marker): RequireTeacher,
1172 Path(id): Path<String>,
1173 Json(req): Json<MarkMealAttendance>,
1174) -> Result<Json<MealAttendanceResponse>, AppError> {
1175 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
1176 .await?
1177 .ok_or(AppError::NotFound)?;
1178 let status = MealAttendanceStatus::try_new(&req.status)?;
1179 let student = UserId::from_key(&req.student_id);
1180 // The target must exist; no booking is required, since a walk-in was still
1181 // served and the record is operationally true.
1182 if crate::service::user::read(&st.db, &student)
1183 .await?
1184 .is_none()
1185 {
1186 return Err(AppError::Validation(ValidationError::Invalid {
1187 field: "student_id",
1188 reason: "target user does not exist",
1189 }));
1190 }
1191 // The write moves the menu's own revision (see the persistence layer's
1192 // `meal_attendance::mark`), so
1193 // a delete landing between the read above and this write cannot commit
1194 // alongside it — one of the two loses its round, and this one then answers
1195 // 404 with no mark behind it, exactly as the read would have.
1196 let row =
1197 service::meal_attendance::mark(&st.db, menu.get_id(), &student, status, marker.get_id())
1198 .await?;
1199 let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?;
1200 Ok(Json(
1201 items.into_iter().next().expect("one mark in, one out"),
1202 ))
1203}
1204
1205/// Who ate off one menu. Requires teacher+. Paged via `?limit=&offset=`.
1206#[utoipa::path(
1207 get,
1208 path = "/menus/{id}/attendance",
1209 tag = "meals",
1210 security(("session_cookie" = [])),
1211 params(("id" = String, Path, description = "Menu id"), PageParams),
1212 responses(
1213 (status = 200, description = "A page of marks (all of them when unpaged)", body = Page<MealAttendanceResponse>),
1214 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1215 (status = 401, description = "Not authenticated", body = ErrorResponse),
1216 (status = 403, description = "Requires teacher role or higher", body = ErrorResponse),
1217 (status = 404, description = "No such menu", body = ErrorResponse),
1218 ),
1219)]
1220async fn list_menu_attendance(
1221 State(st): State<AppState>,
1222 _teacher: RequireTeacher,
1223 Path(id): Path<String>,
1224 Query(page): Query<PageParams>,
1225) -> Result<Json<Page<MealAttendanceResponse>>, AppError> {
1226 let (limit, offset) = page.resolve()?;
1227 // Menu must exist — a missing menu is a 404, not an empty list.
1228 let menu = service::menu::read(&st.db, &MenuId::from_key(&id))
1229 .await?
1230 .ok_or(AppError::NotFound)?;
1231 let (rows, total) =
1232 service::meal_attendance::list_for_menu(&st.db, menu.get_id(), limit, offset).await?;
1233 let items = attendance_responses(&rows, &st.db).await?;
1234 Ok(Json(Page::new(items, total, limit, offset)))
1235}
1236
1237/// One student's meal-attendance history, newest mark first. Requires teacher+,
1238/// or a parent linked to them — the caller's own id always passes, like the
1239/// balance and ledger reads. Narrow to a date range with `?from=&to=`
1240/// (inclusive `YYYY-MM-DD` bounds on the menu's day, each held to the same
1241/// real-calendar-day rule the menu's own date is). Paged via `?limit=&offset=`.
1242#[utoipa::path(
1243 get,
1244 path = "/attendance/{user}",
1245 tag = "meals",
1246 security(("session_cookie" = [])),
1247 params(("user" = String, Path, description = "Student id"), MenuRange, PageParams),
1248 responses(
1249 (status = 200, description = "A page of marks (all of them when unpaged)", body = Page<MealAttendanceResponse>),
1250 (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, or a malformed limit or offset", body = ErrorResponse),
1251 (status = 401, description = "Not authenticated", body = ErrorResponse),
1252 (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse),
1253 ),
1254)]
1255async fn user_attendance(
1256 State(st): State<AppState>,
1257 CurrentUser(caller): CurrentUser,
1258 Path(user): Path<String>,
1259 Query(range): Query<MenuRange>,
1260 Query(page): Query<PageParams>,
1261) -> Result<Json<Page<MealAttendanceResponse>>, AppError> {
1262 let (limit, offset) = page.resolve()?;
1263 let target = UserId::from_key(&user);
1264 ensure_can_read_student(&caller, &target, &st.db).await?;
1265 let from = range.from.as_deref().map(MenuDate::try_new).transpose()?;
1266 let to = range.to.as_deref().map(MenuDate::try_new).transpose()?;
1267 let (rows, total) = service::meal_attendance::list_for_student(
1268 &st.db,
1269 &target,
1270 from.as_ref(),
1271 to.as_ref(),
1272 limit,
1273 offset,
1274 )
1275 .await?;
1276 let items = attendance_responses(&rows, &st.db).await?;
1277 Ok(Json(Page::new(items, total, limit, offset)))
1278}
1279
1280// ---- money ----------------------------------------------------------------
1281
1282#[derive(Serialize, ToSchema)]
1283struct BalanceResponse {
1284 student: PersonRef,
1285 /// `credits + reversals - charges`, in **minor units**. Negative
1286 /// means the student owes the school. Derived on every read, never stored.
1287 #[schema(example = -4500)]
1288 balance_minor: i64,
1289}
1290
1291#[derive(Serialize, ToSchema)]
1292struct LedgerResponse {
1293 id: String,
1294 student: PersonRef,
1295 /// `charge`, `credit`, or `reversal`.
1296 #[schema(example = "charge")]
1297 kind: String,
1298 /// Always positive — the sign is the `kind`'s business.
1299 #[schema(example = 4500)]
1300 amount_minor: i64,
1301 /// What caused the line: a booking id on a `charge`, the reversed charge's
1302 /// own id on a `reversal`, absent on a `credit`.
1303 source: Option<String>,
1304 method: Option<String>,
1305 note: Option<String>,
1306 /// Who wrote it: the booker on a charge or reversal, the admin on a credit.
1307 recorded_by: PersonRef,
1308 created_at: i64,
1309}
1310
1311impl LedgerResponse {
1312 fn new(line: &MealLedger, people: &std::collections::HashMap<String, PersonRef>) -> Self {
1313 Self {
1314 id: line.get_id().key().to_string(),
1315 student: PersonRef::resolve(people, line.get_student()),
1316 kind: line.get_kind().as_str().to_string(),
1317 amount_minor: line.get_amount_minor().as_minor(),
1318 source: line.get_source_key().map(str::to_string),
1319 method: line.get_method().map(|m| m.as_str().to_string()),
1320 note: line.get_note().map(|n| n.as_str().to_string()),
1321 recorded_by: PersonRef::resolve(people, line.get_recorded_by()),
1322 created_at: line.get_created_at().as_millis(),
1323 }
1324 }
1325}
1326
1327/// Join the people onto a page of ledger lines — one query for the whole page.
1328async fn ledger_responses(
1329 lines: &[MealLedger],
1330 db: &Database,
1331) -> Result<Vec<LedgerResponse>, AppError> {
1332 let people = person_map(
1333 lines
1334 .iter()
1335 .flat_map(|line| [*line.get_student(), *line.get_recorded_by()]),
1336 db,
1337 )
1338 .await?;
1339 Ok(lines
1340 .iter()
1341 .map(|line| LedgerResponse::new(line, &people))
1342 .collect())
1343}
1344
1345/// One student's balance, resolved to a response. Shared by both balance routes.
1346async fn balance_response(
1347 student: &UserId,
1348 db: &Database,
1349) -> Result<Json<BalanceResponse>, AppError> {
1350 let people = person_map(std::iter::once(*student), db).await?;
1351 Ok(Json(BalanceResponse {
1352 student: PersonRef::resolve(&people, student),
1353 balance_minor: service::meal_ledger::balance_of(db, student).await?,
1354 }))
1355}
1356
1357/// Reading someone else's meal record — money, attendance, dietary profile:
1358/// teacher+, or a parent linked to the student. Reading your *own* is always
1359/// allowed, since every `{user}` route here accepts the caller's own id; that
1360/// is the one way this gate differs from
1361/// [`crate::service::parent_link::ensure_can_observe`], which
1362/// 403s a self-read because its subjects have their own `/me` routes.
1363async fn ensure_can_read_student(
1364 caller: &User,
1365 target: &UserId,
1366 db: &Database,
1367) -> Result<(), AppError> {
1368 if caller.get_id() == target {
1369 return Ok(());
1370 }
1371 crate::service::parent_link::ensure_can_observe(caller, target, db).await
1372}
1373
1374/// May `caller` read `target`'s meal *money* — balance and ledger? Own always;
1375/// a parent only for a student they hold a live link to; manager+ for anyone.
1376///
1377/// Deliberately narrower than [`ensure_can_read_student`], which still gates
1378/// the profile, booking and attendance reads at teacher+: **a teacher sees no
1379/// money**. Canteen debt is family debt, so this is the same rule (and the same
1380/// 403) `/payments` has always held — what a family owes the school is not
1381/// classroom information, and neither is what it owes the canteen.
1382async fn ensure_can_read_money(
1383 caller: &User,
1384 target: &UserId,
1385 db: &Database,
1386) -> Result<(), AppError> {
1387 if caller.get_id() == target || caller.get_role().at_least(Role::Manager) {
1388 return Ok(());
1389 }
1390 // The link row alone is not the grant: a link whose student side changed
1391 // role must be inert, so the target's live role is re-read. A missing or
1392 // non-student target falls through to the same 403 — a parent never gets an
1393 if caller.get_role() == Role::Parent
1394 && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
1395 {
1396 return Ok(());
1397 }
1398 Err(AppError::Forbidden(
1399 "requires manager role or higher, or a parent link to this student",
1400 ))
1401}
1402
1403/// What the caller owes or has on account, in minor units (negative = owes).
1404#[utoipa::path(
1405 get,
1406 path = "/balance/me",
1407 tag = "meals",
1408 security(("session_cookie" = [])),
1409 responses(
1410 (status = 200, description = "The caller's meal balance", body = BalanceResponse),
1411 (status = 401, description = "Not authenticated", body = ErrorResponse),
1412 ),
1413)]
1414async fn my_balance(
1415 State(st): State<AppState>,
1416 CurrentUser(user): CurrentUser,
1417) -> Result<Json<BalanceResponse>, AppError> {
1418 balance_response(user.get_id(), &st.db).await
1419}
1420
1421/// One student's meal balance. Requires manager+, or a parent link to them —
1422/// the caller's own id always passes. A teacher gets a `403`: canteen debt is
1423/// family debt, gated exactly like `/payments`.
1424#[utoipa::path(
1425 get,
1426 path = "/balance/{user}",
1427 tag = "meals",
1428 security(("session_cookie" = [])),
1429 params(("user" = String, Path, description = "Student id")),
1430 responses(
1431 (status = 200, description = "The student's meal balance", body = BalanceResponse),
1432 (status = 401, description = "Not authenticated", body = ErrorResponse),
1433 (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1434 ),
1435)]
1436async fn user_balance(
1437 State(st): State<AppState>,
1438 CurrentUser(caller): CurrentUser,
1439 Path(user): Path<String>,
1440) -> Result<Json<BalanceResponse>, AppError> {
1441 let target = UserId::from_key(&user);
1442 ensure_can_read_money(&caller, &target, &st.db).await?;
1443 balance_response(&target, &st.db).await
1444}
1445
1446/// One student's statement, newest line first: every charge, credit, and
1447/// reversal. Nothing here is ever edited or deleted — a correction is another
1448/// line. Same gate as the balance. Paged via `?limit=&offset=`.
1449#[utoipa::path(
1450 get,
1451 path = "/ledger/{user}",
1452 tag = "meals",
1453 security(("session_cookie" = [])),
1454 params(("user" = String, Path, description = "Student id"), PageParams),
1455 responses(
1456 (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page<LedgerResponse>),
1457 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1458 (status = 401, description = "Not authenticated", body = ErrorResponse),
1459 (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1460 ),
1461)]
1462async fn user_ledger(
1463 State(st): State<AppState>,
1464 CurrentUser(caller): CurrentUser,
1465 Path(user): Path<String>,
1466 Query(page): Query<PageParams>,
1467) -> Result<Json<Page<LedgerResponse>>, AppError> {
1468 let (limit, offset) = page.resolve()?;
1469 let target = UserId::from_key(&user);
1470 ensure_can_read_money(&caller, &target, &st.db).await?;
1471 let (rows, total) =
1472 service::meal_ledger::list_for_student(&st.db, &target, limit, offset).await?;
1473 let items = ledger_responses(&rows, &st.db).await?;
1474 Ok(Json(Page::new(items, total, limit, offset)))
1475}
1476
1477#[derive(Deserialize, ToSchema)]
1478struct RecordCredit {
1479 /// The student the money is for.
1480 student_id: String,
1481 /// How much came in, **minor units**, positive.
1482 #[schema(minimum = 1, maximum = 10000000, example = 25000)]
1483 amount_minor: i64,
1484 /// How it arrived ("cash", "havale", …). Free text — the backend speaks to
1485 /// no payment gateway and stores no card data.
1486 #[schema(max_length = 50, example = "cash")]
1487 method: Option<String>,
1488 #[schema(max_length = 500, example = "receipt 2026-114")]
1489 note: Option<String>,
1490 /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the
1491 /// separator inside a ledger line's id). Send one and a retry after a
1492 /// timeout returns the **same** line instead of recording the money twice;
1493 /// omit it and two identical calls are two credits. The same key sent with a
1494 /// different `amount_minor` is a `409`.
1495 #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")]
1496 request_key: Option<String>,
1497}
1498
1499/// Record money received from a student. **Admin only** — not manager: writing
1500/// down cash is the highest-trust action in the app. The target must be a
1501/// student, or anyone who already carries meal-ledger lines — a debt survives
1502/// its debtor's role change, and it has to stay settleable. Appends a `credit` line;
1503/// nothing in the ledger is ever edited or removed, so an over-credit is
1504/// corrected by a compensating line, not by a fix-up.
1505///
1506/// **Retry-safe on request** — send a `request_key` and a repeat of the call (a
1507/// client retry after a network timeout, which used to record the money a second
1508/// time the moment the response was lost) returns the line the first attempt
1509/// wrote. The same key with a different `amount_minor` is a `409`: that is a
1510/// client bug, not a replay. Without a key two identical calls are two credits,
1511/// as a desk taking the same amount twice really is.
1512#[utoipa::path(
1513 post,
1514 path = "/credits",
1515 tag = "meals",
1516 security(("session_cookie" = [])),
1517 request_body = RecordCredit,
1518 responses(
1519 (status = 201, description = "Credit recorded", body = LedgerResponse),
1520 (status = 400, description = "Invalid amount, method, note, request_key, or a non-student target", body = ErrorResponse),
1521 (status = 401, description = "Not authenticated", body = ErrorResponse),
1522 (status = 403, description = "Requires the admin role", body = ErrorResponse),
1523 (status = 404, description = "No such user", body = ErrorResponse),
1524 (status = 409, description = "The request_key was already used for a different amount", body = ErrorResponse),
1525 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
1526 ),
1527)]
1528async fn record_credit(
1529 State(st): State<AppState>,
1530 RequireAdmin(admin): RequireAdmin,
1531 Json(req): Json<RecordCredit>,
1532) -> Result<(StatusCode, Json<LedgerResponse>), AppError> {
1533 let student = UserId::from_key(&req.student_id);
1534 // Only a student carries a meal balance; crediting anyone else is a typo,
1535 // and a typo here is money in the wrong ledger. Unless they already carry
1536 // ledger lines: a debt outlives its debtor's role change (a student
1537 // promoted to staff keeps what they owed), and the student rule alone made
1538 // that debt permanently unsettleable — there is no other route that
1539 // appends a credit. A typo'd staff id has no lines, so it still 400s.
1540 if crate::service::user::read(&st.db, &student)
1541 .await?
1542 .ok_or(AppError::NotFound)?
1543 .get_role()
1544 != Role::Student
1545 && service::meal_ledger::list_for_student(&st.db, &student, Some(1), 0)
1546 .await?
1547 .0
1548 .is_empty()
1549 {
1550 return Err(AppError::Validation(ValidationError::Invalid {
1551 field: "student_id",
1552 reason: "only a student carries a meal balance",
1553 }));
1554 }
1555 let request_key = req
1556 .request_key
1557 .as_deref()
1558 .map(PaymentRequestKey::try_new)
1559 .transpose()?;
1560 let line = service::meal_ledger::credit(
1561 &st.db,
1562 &student,
1563 LedgerAmount::try_new(req.amount_minor)?,
1564 req.method
1565 .as_deref()
1566 .map(LedgerMethod::try_new)
1567 .transpose()?
1568 .flatten(),
1569 req.note
1570 .as_deref()
1571 .map(LedgerNote::try_new)
1572 .transpose()?
1573 .flatten(),
1574 request_key.as_ref(),
1575 admin.get_id(),
1576 )
1577 .await?;
1578 let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?;
1579 Ok((
1580 StatusCode::CREATED,
1581 Json(items.into_iter().next().expect("one line in, one out")),
1582 ))
1583}