//! The food program: menus and the dishes on them, the seats booked against //! them, and the money that moved. //! //! Reads are open to every authenticated user (a student picks their lunch), //! writes are manager+ — publishing what the school serves is kitchen //! administration, not teaching. The balance and the ledger are the exception: //! they are manager+ like `/payments`, since canteen debt is family debt. //! //! Money only ever *appends* here (see [`MealLedger`]): booking charges a price //! snapshot, cancelling reverses it, and recording a payment is admin-only. use crate::web::tenant_state::State; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; use crate::domain::menu_dish::{ DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, }; // The same idempotence key `/payments/credits` takes — one grammar, one type. use crate::domain::payment_ledger::PaymentRequestKey; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::service; use crate::state::AppState; use super::{ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher, check_not_past, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(create_menu, list_menus)) .routes(routes!(get_menu, update_menu, delete_menu)) .routes(routes!(add_dish)) .routes(routes!(update_dish, delete_dish)) .routes(routes!(book_meal, list_menu_bookings)) .routes(routes!(my_bookings)) .routes(routes!(cancel_booking)) .routes(routes!(mark_attendance, list_menu_attendance)) .routes(routes!(user_attendance)) .routes(routes!(my_profile)) .routes(routes!(user_profile, update_profile)) .routes(routes!(my_balance)) .routes(routes!(user_balance)) .routes(routes!(user_ledger)) .routes(routes!(record_credit)) } #[derive(Deserialize, ToSchema)] struct CreateMenu { /// The calendar day, `YYYY-MM-DD`. Text, not a timestamp: "one menu per /// day and slot" is the school's own day, not UTC midnight. #[schema(example = "2026-09-14", min_length = 10, max_length = 10)] date: String, /// One of the school's `meal_slots` (see `GET /settings`). #[schema(example = "lunch")] slot: String, /// How many students may book it. Omit (or `null`) for uncapped. #[schema(minimum = 0, maximum = 10000, example = 120)] capacity: Option, } #[derive(Deserialize, ToSchema)] struct UpdateMenu { /// New seat cap; `null` clears it back to uncapped. `date` and `slot` are /// immutable — a menu on another day is another menu. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, minimum = 0, maximum = 10000)] capacity: Option>, } /// Inclusive `YYYY-MM-DD` bounds on `GET /meals/menus`. Either may be omitted. #[derive(Debug, Deserialize, IntoParams)] struct MenuRange { /// Keep menus on or after this day. #[param(example = "2026-09-01")] from: Option, /// Keep menus on or before this day. #[param(example = "2026-09-30")] to: Option, } /// Optional slot filter on `GET /meals/menus`. Its own extractor, so /// `GET /meals/attendance/{user}` — which shares [`MenuRange`] for its date /// bounds — gains no dead `slot` param. #[derive(Debug, Deserialize, IntoParams)] struct MenuSlotFilter { /// Keep only menus published for this meal slot, named exactly as the /// menu snapshotted it. #[param(example = "lunch")] slot: Option, } impl MenuSlotFilter { /// The slot text to bind, trimmed. Deliberately *not* checked against /// the school's current `meal_slots`: a menu snapshots its slot's name /// at publish, so a slot retired since must still find the menus /// published under it — an unknown name simply matches nothing (an /// empty page, not a `400`). An empty value, though, filters nothing /// and says nothing: refused, naming the field. fn resolve(self) -> Result, AppError> { let Some(raw) = self.slot else { return Ok(None); }; let slot = raw.trim(); if slot.is_empty() { return Err(ValidationError::Invalid { field: "slot", reason: "must name a meal slot and may not be empty", } .into()); } Ok(Some(slot.to_string())) } } #[derive(Deserialize, ToSchema)] struct CreateDish { #[schema(example = "Mercimek çorbası", max_length = 100)] name: String, #[schema(max_length = 500)] description: Option, /// Price in **minor units** — `4550` is 45,50 ₺. Integer only: /// this API never speaks decimals or floats about money. #[schema(minimum = 0, maximum = 1000000, example = 4550_i64)] price_minor: i64, /// Dietary tags, each one of the school's `dietary_tags` (`GET /settings`). #[schema(max_items = 10, example = json!(["vegetarian"]))] #[serde(default)] tags: Vec, } #[derive(Deserialize, ToSchema)] struct UpdateDish { #[schema(max_length = 100)] name: Option, /// `null` (or blank) clears the description. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, max_length = 500)] description: Option>, #[schema(minimum = 0, maximum = 1000000)] price_minor: Option, #[schema(max_items = 10)] tags: Option>, } #[derive(Serialize, ToSchema)] struct DishResponse { id: String, #[schema(example = "Mercimek çorbası")] name: String, description: Option, /// Minor units. price_minor: i64, tags: Vec, /// Which of `tags` the **calling user's** own dietary profile flags — the /// set intersection of the two lists. Empty when they do not overlap, and /// empty for every reader without a profile (staff included). #[schema(example = json!(["nut_allergy"]))] conflicts: Vec, created_at: i64, } impl DishResponse { fn new(dish: &MenuDish, viewer_tags: &[String]) -> Self { Self { id: dish.get_id().key().to_string(), name: dish.get_name().as_str().to_string(), description: dish.get_description().map(|text| text.as_str().to_string()), price_minor: dish.get_price_minor().as_minor(), tags: dish.get_tags().as_slice().to_vec(), conflicts: conflicts(dish.get_tags().as_slice(), viewer_tags), created_at: dish.get_created_at().as_millis(), } } } #[derive(Serialize, ToSchema)] struct MenuResponse { id: String, /// The calendar day, `YYYY-MM-DD`. #[schema(example = "2026-09-14")] date: String, /// The meal slot, snapshotted when the menu was published — it stays as it /// was even if the school later retires the slot. #[schema(example = "lunch")] slot: String, /// Seat cap; `null` = uncapped. capacity: Option, /// Everything on offer, in the order it was added. dishes: Vec, created_by: PersonRef, created_at: i64, } impl MenuResponse { fn new( menu: &Menu, dishes: &[MenuDish], people: &std::collections::HashMap, viewer_tags: &[String], ) -> Self { Self { id: menu.get_id().key().to_string(), date: menu.get_date().as_str().to_string(), slot: menu.get_slot().as_str().to_string(), capacity: menu.get_capacity(), dishes: dishes .iter() .filter(|dish| dish.get_menu() == menu.get_id()) .map(|dish| DishResponse::new(dish, viewer_tags)) .collect(), created_by: PersonRef::resolve(people, menu.get_created_by()), created_at: menu.get_created_at().as_millis(), } } } /// Join dishes, publishers, and the reader's own dietary tags onto a page of /// menus — three queries for the whole page, never one per row. The profile in /// particular is read **once**, not per dish. async fn menu_responses( menus: &[Menu], viewer: &UserId, db: &Database, ) -> Result, AppError> { let ids: Vec = menus.iter().map(|menu| menu.get_id().clone()).collect(); let dishes = service::menu::list_dishes_for_menus(db, &ids).await?; let people = person_map(menus.iter().map(|menu| *menu.get_created_by()), db).await?; let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; Ok(menus .iter() .map(|menu| MenuResponse::new(menu, &dishes, &people, &viewer_tags)) .collect()) } /// One menu, with its dishes. async fn one_menu( menu: &Menu, viewer: &UserId, db: &Database, ) -> Result, AppError> { let dishes = service::menu::list_dishes(db, menu.get_id()).await?; let people = person_map([*menu.get_created_by()], db).await?; let viewer_tags = service::dietary_profile::tags_of(db, viewer).await?; Ok(Json(MenuResponse::new( menu, &dishes, &people, &viewer_tags, ))) } /// Publish a menu for one day and meal slot. Requires manager+. `date` is /// `YYYY-MM-DD` text and must be a real calendar day (`2026-02-29` is a `400`: /// a menu on a day that does not exist has no serving instant, so no booking /// cutoff). The slot must be one the school currently serves and may not /// contain `/ \ ? # %` (it becomes part of the menu's URL id). A day+slot /// already published is a `409` — edit that menu instead of publishing a /// second one. /// /// The day must not already be over (`400`): a published menu is a bookable /// one, and a booking is what charges the student. Today counts as ahead, all /// day long. #[utoipa::path( post, path = "/menus", tag = "meals", security(("session_cookie" = [])), request_body = CreateMenu, responses( (status = 201, description = "Menu published", body = MenuResponse), (status = 400, description = "Malformed date, a day that is already over, unknown slot, or out-of-range capacity", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 409, description = "A menu already exists for that date and slot, or the slot was removed from the settings mid-request", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn create_menu( State(st): State, RequireManager(user): RequireManager, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let date = MenuDate::try_new(&req.date)?; // The kitchen publishes ahead, never behind: a menu on a day already over // is bookable and therefore *billable* (booking is the charge trigger), so // this is the same door every other create path in the crate has. Measured // against the end of the day, so today's menu is publishable all day — the // meal's own deadline is `meal_cancel_cutoff_minutes`, not this. check_not_past("date", date.day_end())?; let slot = MenuSlot::try_new( &req.slot, &service::settings::load(&st.db).await?.get_meal_slots(), )?; validate_capacity(req.capacity)?; let menu = service::menu::create(&st.db, date, slot, req.capacity, user.get_id()).await?; let body = one_menu(&menu, user.get_id(), &st.db).await?; Ok((StatusCode::CREATED, body)) } /// List published menus, newest day first, each with its dishes. Any /// authenticated user. Narrow to a date range with `?from=&to=` (inclusive, /// `YYYY-MM-DD`, each bound held to the same real-calendar-day rule a menu's /// own date is). Paged via `?limit=&offset=` (omit `limit` for the full list); /// returns a `{items, total, limit, offset}` envelope. /// /// Narrow to one meal slot with `?slot=` — matched exactly against the slot /// text each menu snapshotted at publish, not against the school's current /// `meal_slots`, so a slot retired since still finds its menus and an /// unknown name is an empty page rather than an error. `?slot=` (empty) is a /// `400`. The filter runs in SQL: `total` counts the filtered rows, and /// `limit`/`offset` window inside them. #[utoipa::path( get, path = "/menus", tag = "meals", security(("session_cookie" = [])), params(MenuRange, MenuSlotFilter, PageParams), responses( (status = 200, description = "A page of menus (the full list when unpaged)", body = Page), (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), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn list_menus( State(st): State, CurrentUser(user): CurrentUser, Query(range): Query, Query(filter): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; let slot = filter.resolve()?; let (menus, total) = service::menu::list( &st.db, from.as_ref(), to.as_ref(), slot.as_deref(), limit, offset, ) .await?; // The dish/people join runs over the page alone, so it shrinks with it. let items = menu_responses(&menus, user.get_id(), &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } /// Fetch one menu with its dishes. #[utoipa::path( get, path = "/menus/{id}", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), responses( (status = 200, description = "The menu", body = MenuResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn get_menu( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, ) -> Result, AppError> { let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; one_menu(&menu, user.get_id(), &st.db).await } /// Change a menu's seat cap. Requires manager+. `date` and `slot` are /// immutable; `"capacity": null` goes back to uncapped. #[utoipa::path( patch, path = "/menus/{id}", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), request_body = UpdateMenu, responses( (status = 200, description = "Updated menu", body = MenuResponse), (status = 400, description = "Capacity out of range", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn update_menu( State(st): State, RequireManager(user): RequireManager, Path(id): Path, Json(req): Json, ) -> Result, AppError> { if let Some(capacity) = req.capacity { validate_capacity(capacity)?; } let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let updated = service::menu::update(&st.db, menu, req.capacity).await?; one_menu(&updated, user.get_id(), &st.db).await } /// Unpublish a menu. Requires manager+. Its dishes go with it — a dish has no /// meaning apart from the menu it was published on. A menu somebody still /// holds a seat on is a `409`: cancel the bookings first. #[utoipa::path( delete, path = "/menus/{id}", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 409, description = "The menu still has live bookings", body = ErrorResponse), ), )] async fn delete_menu( State(st): State, RequireManager(_user): RequireManager, Path(id): Path, ) -> Result { let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; // The seat check rides in the delete's own `WHERE` (the persistence // layer's `menu::delete`), so a concurrent booking cannot slip between // the read and the delete. service::menu::delete(&st.db, menu).await?; Ok(StatusCode::NO_CONTENT) } /// Add a dish to a menu. Requires manager+. Tags must come from the school's /// `dietary_tags`, and a menu holds at most 50 dishes (`409` at the cap). #[utoipa::path( post, path = "/menus/{id}/dishes", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), request_body = CreateDish, responses( (status = 201, description = "Dish added", body = DishResponse), (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), (status = 409, description = "The menu already carries the maximum number of dishes", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn add_dish( State(st): State, RequireManager(user): RequireManager, Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let name = DishName::try_new(&req.name)?; let description = req .description .as_deref() .map(DishDescription::try_new) .transpose()? .flatten(); let price = DishPrice::try_new(req.price_minor)?; let tags = DishTags::try_new( &req.tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?; // The dish-cap gate lives in the service: the cap is one guarded // statement now — the menu row is locked `FOR NO KEY UPDATE` inside the // dish write's own transaction and the insert carries the // `count(*) < cap` guard, so a dish can never land on a menu that no // longer exists, and two racing writers cannot overfill it either. let dish = service::menu::add_dish( &st.db, &MenuId::from_key(&id), name, description, price, tags, ) .await?; let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(( StatusCode::CREATED, Json(DishResponse::new(&dish, &viewer_tags)), )) } /// Edit a dish. Requires manager+. Omitted fields keep their value; /// `"description": null` clears it, and `tags` replaces the whole list. #[utoipa::path( patch, path = "/dishes/{did}", tag = "meals", security(("session_cookie" = [])), params(("did" = String, Path, description = "Dish id")), request_body = UpdateDish, responses( (status = 200, description = "Updated dish", body = DishResponse), (status = 400, description = "Invalid name, price, or unknown dietary tag", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn update_dish( State(st): State, RequireManager(user): RequireManager, Path(did): Path, Json(req): Json, ) -> Result, AppError> { let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; let name = req.name.as_deref().map(DishName::try_new).transpose()?; // Absent keeps, `null` clears, and a blank string clears too — an empty // description is the absence of one, never a stored empty string. let description = match req.description { None => None, Some(None) => Some(None), Some(Some(text)) => Some(DishDescription::try_new(&text)?), }; let price = req.price_minor.map(DishPrice::try_new).transpose()?; let tags = match &req.tags { Some(tags) => Some(DishTags::try_new( tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?), None => None, }; // The dish write locks the menu row inside its own transaction — see // `add_dish`. let updated = service::menu::update_dish(&st.db, dish, name, description, price, tags).await?; let viewer_tags = service::dietary_profile::tags_of(&st.db, user.get_id()).await?; Ok(Json(DishResponse::new(&updated, &viewer_tags))) } /// Remove a dish from its menu. Requires manager+. #[utoipa::path( delete, path = "/dishes/{did}", tag = "meals", security(("session_cookie" = [])), params(("did" = String, Path, description = "Dish id")), responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn delete_dish( State(st): State, RequireManager(_user): RequireManager, Path(did): Path, ) -> Result { let dish = service::menu::read_dish(&st.db, &MenuDishId::from_key(&did)) .await? .ok_or(AppError::NotFound)?; // The dish write locks the menu row inside its own transaction — see // `add_dish`. service::menu::delete_dish(&st.db, dish).await?; Ok(StatusCode::NO_CONTENT) } // ---- dietary profiles ----------------------------------------------------- #[derive(Deserialize, ToSchema)] struct UpdateDietaryProfile { /// Replaces the whole tag list; each entry must be one of the school's /// `dietary_tags` (`GET /settings`) — the same vocabulary a dish is tagged /// from, which is what makes a menu's `conflicts` computable. #[schema(max_items = 10, example = json!(["nut_allergy"]))] tags: Option>, /// Free text for the kitchen; `null` (or blank) clears it. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, max_length = 500, example = "carries an EpiPen")] note: Option>, } #[derive(Serialize, ToSchema)] struct DietaryProfileResponse { student: PersonRef, /// The tags the school recorded; empty while there is no profile. tags: Vec, note: Option, /// Who last wrote it, and when — both absent while no profile exists. updated_by: Option, updated_at: Option, } /// One student's profile, or the empty one. A student who was never recorded /// has *no* restrictions, so that reads back as an empty profile rather than a /// `404` — the caller asked "what may they not eat", and "nothing known" is an /// answer. async fn profile_response( student: &UserId, db: &Database, ) -> Result, AppError> { let profile = service::dietary_profile::read(db, student).await?; let people = person_map( std::iter::once(*student).chain(profile.as_ref().map(|row| *row.get_updated_by())), db, ) .await?; Ok(Json(DietaryProfileResponse { student: PersonRef::resolve(&people, student), tags: profile .as_ref() .map(|row| row.get_tags().as_slice().to_vec()) .unwrap_or_default(), note: profile .as_ref() .and_then(|row| row.get_note()) .map(|note| note.as_str().to_string()), updated_by: profile .as_ref() .map(|row| PersonRef::resolve(&people, row.get_updated_by())), updated_at: profile.as_ref().map(|row| row.get_updated_at().as_millis()), })) } /// The caller's own dietary profile — what the school recorded about their /// diet. Empty tags mean nothing was ever recorded. #[utoipa::path( get, path = "/profiles/me", tag = "meals", security(("session_cookie" = [])), responses( (status = 200, description = "The caller's dietary profile", body = DietaryProfileResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn my_profile( State(st): State, CurrentUser(user): CurrentUser, ) -> Result, AppError> { profile_response(user.get_id(), &st.db).await } /// One student's dietary profile. Requires teacher+, or a parent link to them /// — the caller's own id always passes. #[utoipa::path( get, path = "/profiles/{user}", tag = "meals", security(("session_cookie" = [])), params(("user" = String, Path, description = "Student id")), responses( (status = 200, description = "The student's dietary profile", body = DietaryProfileResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_profile( State(st): State, CurrentUser(caller): CurrentUser, Path(user): Path, ) -> Result, AppError> { let target = UserId::from_key(&user); ensure_can_read_student(&caller, &target, &st.db).await?; profile_response(&target, &st.db).await } /// Record what a student may not eat. **Manager+**, deliberately: an allergen /// list is a safety record the school keeps on the student's behalf, not a /// self-service preference — a student editing their own would let a mistyped /// (or removed) allergy reach the kitchen with the school's authority behind /// it. Omitted fields keep their value; `tags` replaces the whole list, and /// `"note": null` clears the note. First write creates the row. #[utoipa::path( patch, path = "/profiles/{user}", tag = "meals", security(("session_cookie" = [])), params(("user" = String, Path, description = "Student id")), request_body = UpdateDietaryProfile, responses( (status = 200, description = "The stored profile", body = DietaryProfileResponse), (status = 400, description = "Unknown dietary tag, too many tags, an over-long note, or a non-student target", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such user", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn update_profile( State(st): State, RequireManager(manager): RequireManager, Path(user): Path, Json(req): Json, ) -> Result, AppError> { let target = UserId::from_key(&user); // Only a student eats off the school's menus; a profile on anyone else is // a typo, and a typo here is an allergy filed against the wrong person. if crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)? .get_role() != Role::Student { return Err(AppError::Validation(ValidationError::Invalid { field: "user", reason: "only a student carries a dietary profile", })); } let tags = match &req.tags { Some(tags) => Some(DietaryTags::try_new( tags, &service::settings::load(&st.db).await?.get_dietary_tags(), )?), None => None, }; // Absent keeps, `null` clears, and a blank string clears too — an empty // note is the absence of one, never a stored empty string. let note = match req.note { None => None, Some(None) => Some(None), Some(Some(text)) => Some(DietaryNote::try_new(&text)?), }; service::dietary_profile::save(&st.db, &target, tags, note, manager.get_id()).await?; profile_response(&target, &st.db).await } // ---- bookings ------------------------------------------------------------- #[derive(Deserialize, ToSchema)] struct BookMeal { /// Who the seat is for. Omit to book for yourself (a student's own lunch); /// a parent must name one of their linked students. student_id: Option, } #[derive(Serialize, ToSchema)] struct BookingResponse { id: String, /// The menu the seat is on. menu_id: String, student: PersonRef, /// Who placed it — the student themselves, or their parent. booked_by: PersonRef, /// `booked` or `cancelled`. A cancel keeps the row (audit), it only stops /// the seat counting against the menu's capacity. #[schema(example = "booked")] status: String, cancelled_at: Option, created_at: i64, } impl BookingResponse { fn new(booking: &MealBooking, people: &std::collections::HashMap) -> Self { Self { id: booking.id().key(), menu_id: booking.get_menu().key().to_string(), student: PersonRef::resolve(people, booking.get_student()), booked_by: PersonRef::resolve(people, booking.get_booked_by()), status: booking.get_status().as_str().to_string(), cancelled_at: booking.get_cancelled_at().map(|at| at.as_millis()), created_at: booking.get_created_at().as_millis(), } } } /// Join the people onto a page of bookings — one query for the whole page. async fn booking_responses( bookings: &[MealBooking], db: &Database, ) -> Result, AppError> { let people = person_map( bookings .iter() .flat_map(|booking| [*booking.get_student(), *booking.get_booked_by()]), db, ) .await?; Ok(bookings .iter() .map(|booking| BookingResponse::new(booking, &people)) .collect()) } /// The school's one meal deadline, applied to booking and cancelling alike: /// the cutoff minutes plus the slot serving times they count back from. Read /// live on every call, so a serving time corrected today moves the deadline of /// menus already published for it. async fn meal_cutoff(db: &Database) -> Result { Ok(MealCutoff::from_settings( &service::settings::load(db).await?, )) } /// Whose seat is this? A student books only for themselves; a parent only for /// a student they hold a link to. Nobody else books through this route — a /// teacher or manager arranging someone's lunch is not a thing this API does. /// /// The link row alone is not the grant: like a stale enrollment, a link whose /// student side changed role must be inert, so the target's live role is /// re-read here. A missing or non-student target falls through to the same /// 403 — a parent never gets an existence oracle. async fn booking_target( caller: &User, student_id: Option<&str>, db: &Database, ) -> Result { match caller.get_role() { Role::Student => match student_id { Some(id) if id != caller.get_id().key() => Err(AppError::Forbidden( "a student books meals only for themselves", )), _ => Ok(*caller.get_id()), }, Role::Parent => { let target = UserId::from_key(student_id.ok_or(AppError::Validation( ValidationError::Invalid { field: "student_id", reason: "a parent must name the student the seat is for", }, ))?); if crate::service::parent_link::links_live(db, caller.get_id(), &target).await? { return Ok(target); } Err(AppError::Forbidden( "a parent books meals only for a linked student", )) } _ => Err(AppError::Forbidden( "only students and their parents book meals", )), } } /// Take a seat on a published menu. A student books for themselves (omit /// `student_id`); a parent books for a linked student by naming them. Booking /// twice is the same seat, not a second one — and bills once, at the price the /// menu carried when the seat was first taken. Refused (`409`) when the menu is /// full, when its **day has already passed** (a seat taken then would bill a /// meal nobody can be served — and no role bypasses that, since only students /// and their parents book at all), or when the school's /// `meal_cancel_cutoff_minutes` has closed the meal, and /// (`400`) when the menu's dishes sum past the chargeable maximum, since a seat /// is never handed out unbilled. /// /// One seat may be taken at most `meal.max_booking_attempts` times (`GET /// /limits`) — the first booking plus the re-bookings after a cancel. Past that /// it is a `409`: every cycle appends a charge and its reversal, permanently, so /// the ceiling bounds the student's statement rather than their mind changing. /// A seat that really must move again is the canteen's to cancel. #[utoipa::path( post, path = "/menus/{id}/bookings", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), request_body = BookMeal, responses( (status = 201, description = "Seat booked (or the seat already held)", body = BookingResponse), (status = 400, description = "A parent named no student, or the menu's dishes sum past the chargeable maximum", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student booking for themselves, nor a parent booking for a linked student", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), (status = 409, description = "The menu is full, 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), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn book_meal( State(st): State, CurrentUser(user): CurrentUser, Path(id): Path, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let student = booking_target(&user, req.student_id.as_deref(), &st.db).await?; let cutoff = meal_cutoff(&st.db).await?; let menu = MenuId::from_key(&id); // Price, seat and charge land as one decision (see // `service::meal_booking::book`), keyed by (seat, attempt) — a double-click // books one seat and bills it once, and a dish landing between the price // and the seat is refused by the claim rather than billed. let booking = service::meal_booking::book(&st.db, &menu, &student, user.get_id(), &cutoff).await?; let items = booking_responses(std::slice::from_ref(&booking), &st.db).await?; Ok(( StatusCode::CREATED, Json(items.into_iter().next().expect("one booking in, one out")), )) } /// The caller's own bookings, newest first: the seats held *for* them, plus — /// for a parent — the seats held for every student they currently hold a link /// to. The links are re-read on every call, so an unlinked parent stops seeing /// the child's meals at once, even the ones they booked themselves. Cancelled /// bookings stay in the list, flagged. Paged via `?limit=&offset=` (omit /// `limit` for all of them); returns a `{items, total, limit, offset}` envelope. #[utoipa::path( get, path = "/bookings/me", tag = "meals", security(("session_cookie" = [])), params(PageParams), responses( (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn my_bookings( State(st): State, CurrentUser(user): CurrentUser, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Own seats always; a parent's children only while the link is live — the // booking row's `booked_by` is history, never a standing read grant. let mut students = vec![*user.get_id()]; if user.get_role() == Role::Parent { students.extend( crate::service::parent_link::list_for_parent(&st.db, user.get_id()) .await? .iter() .map(|link| *link.get_student()), ); } let (rows, total) = service::meal_booking::list_for_students(&st.db, &students, limit, offset).await?; let items = booking_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } /// Who is eating: every booking on one menu, cancelled ones included so the /// kitchen can see what changed. Requires manager+ — this is the whole school's /// list, not one family's. Paged via `?limit=&offset=`. #[utoipa::path( get, path = "/menus/{id}/bookings", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id"), PageParams), responses( (status = 200, description = "A page of bookings (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), ), )] async fn list_menu_bookings( State(st): State, RequireManager(_user): RequireManager, Path(id): Path, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let (rows, total) = service::meal_booking::list_for_menu(&st.db, menu.get_id(), limit, offset).await?; let items = booking_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } /// Give the seat back. The row survives, flipped to `cancelled` — the seat is /// free for someone else, and the cancellation stays auditable. Only the /// student it is for, or their parent, **or any manager+**, may cancel it — and /// for the student and their parent it is refused (`409`) once the school's /// `meal_cancel_cutoff_minutes` has closed the meal, a cutoff a manager+ is not /// bound by. Idempotent: cancelling again is a `200` that replays the refund. /// `409` too when the menu's date is not a real calendar day, since no cutoff /// can be worked out from one, and when the seat was booked again while the /// call ran, since only the attempt it read is ever released. /// /// Manager+ may cancel anyone's booking, and is not bound by the cutoff — the /// seat and the money have to stay reachable when the student it was booked for /// is no longer a student, or when the meal has already closed. /// /// **Idempotent**: cancelling an already-cancelled booking is a `200` with the /// row as it stands, not a `409`. Repeating it also replays the refund, so a /// cancel that was cut short mid-flight (the tab closed, a proxy timed out) is /// recovered by simply sending it again — the reversal is keyed to the seat's /// attempt, so the money comes back exactly once however often it is retried. /// /// A seat **re-booked while this call was running** is a `409`: the flip only /// ever releases the attempt this call read, so the newer seat — one this API /// answered `201` for and nobody here asked to free — is left alone. Send the /// call again to cancel the seat as it now stands. /// /// **Who is asking is decided before the seat is looked up**, so an unauthorised /// caller gets the same `403` whether or not the booking exists. Booking ids are /// derivable (`{date}_{slot}_{student}`), and a `404` here would otherwise /// answer "did this student book this meal?" — the manager-only list at /// `GET /meals/menus/{id}/bookings`, one student at a time. #[utoipa::path( delete, path = "/bookings/{bid}", tag = "meals", security(("session_cookie" = [])), params(("bid" = String, Path, description = "Booking id")), responses( (status = 200, description = "Cancelled (also when it already was — the call is idempotent and replays the refund)", body = BookingResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the booking's student, 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), (status = 404, description = "Not found (only for a caller who may cancel it)", body = ErrorResponse), (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), ), )] async fn cancel_booking( State(st): State, CurrentUser(user): CurrentUser, Path(bid): Path, ) -> Result, AppError> { let id = MealBookingId::from_key(&bid); // Manager+ may give back *any* seat. Not a convenience: `booking_target` // grants only students and parents, so a student promoted to staff (or a // parent unlinked) left a live seat nobody on the API could cancel — the // menu 409s its own delete forever and the charge can never be reversed, // since cancelling is the only route that reverses one. Promotion itself // deliberately sweeps nothing: moving money is a decision, not a side // effect of a role change. let staff = user.get_role().at_least(Role::Manager); if !staff { // Decided off the *id*, before the row is read: the id is // `{date}_{slot}_{student}`, and a teacher may list both the menus and // the users, so authorising after the read answered 403 for a seat that // exists and 404 for one that does not — an existence oracle around the // deliberate manager+ gate on `GET /menus/{id}/bookings`, and one any // peer holding a user id could work too. An unauthorised caller now // gets the same 403 either way, and learns nothing. // // Same door as booking: whoever may take the seat may give it back. let student = id.student(); let target = booking_target(&user, Some(student.key().as_str()), &st.db).await?; if target != student { return Err(AppError::Forbidden("not your booking")); } } // …and the cutoff does not bind them either. It exists to stop students // gaming the kitchen's headcount, which is no reason to leave staff holding // a seat they cannot free: past the cutoff the seat was uncancellable, and // its menu — which refuses its own delete while a seat is held — was // undeletable with it, forever. A deadline that binds nobody is exactly the // one a school that set no `meal_cancel_cutoff_minutes` already runs under. let cutoff = if staff { MealCutoff::default() } else { meal_cutoff(&st.db).await? }; // Flips the row and appends the reversal for that attempt's charge in one // transaction; the charge itself stays. let booking = service::meal_booking::read(&st.db, &id) .await? .ok_or(AppError::NotFound)?; let cancelled = service::meal_booking::cancel(&st.db, booking, &cutoff, user.get_id()).await?; let items = booking_responses(std::slice::from_ref(&cancelled), &st.db).await?; Ok(Json( items.into_iter().next().expect("one booking in, one out"), )) } // ---- attendance ----------------------------------------------------------- // // Reporting only: nothing in this section touches [`MealLedger`]. Booking is // what charges, so a no-show still pays — the kitchen bought the food. #[derive(Deserialize, ToSchema)] struct MarkMealAttendance { /// Who was (or was not) served — usually a student, but the canteen also /// feeds staff, so any existing user may be marked. The mark moves no money. student_id: String, /// `served` or `missed` — the canteen's own fixed pair, not the school's /// editable roll-call statuses. #[schema(example = "served")] status: String, } #[derive(Serialize, ToSchema)] struct MealAttendanceResponse { id: String, /// The menu the mark is against. menu_id: String, student: PersonRef, #[schema(example = "served")] status: String, marked_by: PersonRef, marked_at: i64, } impl MealAttendanceResponse { fn new(row: &MealAttendance, people: &std::collections::HashMap) -> Self { Self { id: MealAttendanceId::composite(row.get_menu(), row.get_student()).key(), menu_id: row.get_menu().key().to_string(), student: PersonRef::resolve(people, row.get_student()), status: row.get_status().as_str().to_string(), marked_by: PersonRef::resolve(people, row.get_marked_by()), marked_at: row.get_marked_at().as_millis(), } } } /// Join the people onto a page of marks — one query for the whole page. async fn attendance_responses( rows: &[MealAttendance], db: &Database, ) -> Result, AppError> { let people = person_map( rows.iter() .flat_map(|row| [*row.get_student(), *row.get_marked_by()]), db, ) .await?; Ok(rows .iter() .map(|row| MealAttendanceResponse::new(row, &people)) .collect()) } /// Record whether someone ate off a menu. Requires teacher+ — whoever stands /// at the canteen door marks, students never mark themselves. One row per /// (menu, person), so re-marking corrects the row rather than adding another. /// /// The target need only *exist*: a canteen also serves staff, and a walk-in /// with no booking is still someone the kitchen fed. Marking is a record of /// what happened, not a check of who was entitled — and since it moves no /// money, a non-student mark costs nobody anything. /// /// **This moves no money.** A booked student who did not show is still charged /// (the food was cooked), and a walk-in marked `served` without a booking is /// not charged either — booking is the only charge trigger. #[utoipa::path( post, path = "/menus/{id}/attendance", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id")), request_body = MarkMealAttendance, responses( (status = 200, description = "Attendance recorded", body = MealAttendanceResponse), (status = 400, description = "Invalid status, or no such user", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn mark_attendance( State(st): State, RequireTeacher(marker): RequireTeacher, Path(id): Path, Json(req): Json, ) -> Result, AppError> { let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let status = MealAttendanceStatus::try_new(&req.status)?; let student = UserId::from_key(&req.student_id); // The target must exist; no booking is required, since a walk-in was still // served and the record is operationally true. if crate::service::user::read(&st.db, &student) .await? .is_none() { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", reason: "target user does not exist", })); } // The write moves the menu's own revision (see the persistence layer's // `meal_attendance::mark`), so // a delete landing between the read above and this write cannot commit // alongside it — one of the two loses its round, and this one then answers // 404 with no mark behind it, exactly as the read would have. let row = service::meal_attendance::mark(&st.db, menu.get_id(), &student, status, marker.get_id()) .await?; let items = attendance_responses(std::slice::from_ref(&row), &st.db).await?; Ok(Json( items.into_iter().next().expect("one mark in, one out"), )) } /// Who ate off one menu. Requires teacher+. Paged via `?limit=&offset=`. #[utoipa::path( get, path = "/menus/{id}/attendance", tag = "meals", security(("session_cookie" = [])), params(("id" = String, Path, description = "Menu id"), PageParams), responses( (status = 200, description = "A page of marks (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), (status = 404, description = "No such menu", body = ErrorResponse), ), )] async fn list_menu_attendance( State(st): State, _teacher: RequireTeacher, Path(id): Path, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; // Menu must exist — a missing menu is a 404, not an empty list. let menu = service::menu::read(&st.db, &MenuId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let (rows, total) = service::meal_attendance::list_for_menu(&st.db, menu.get_id(), limit, offset).await?; let items = attendance_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } /// One student's meal-attendance history, newest mark first. Requires teacher+, /// or a parent linked to them — the caller's own id always passes, like the /// balance and ledger reads. Narrow to a date range with `?from=&to=` /// (inclusive `YYYY-MM-DD` bounds on the menu's day, each held to the same /// real-calendar-day rule the menu's own date is). Paged via `?limit=&offset=`. #[utoipa::path( get, path = "/attendance/{user}", tag = "meals", security(("session_cookie" = [])), params(("user" = String, Path, description = "Student id"), MenuRange, PageParams), responses( (status = 200, description = "A page of marks (all of them when unpaged)", body = Page), (status = 400, description = "Date bound that is not a real YYYY-MM-DD calendar day, or a malformed limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_attendance( State(st): State, CurrentUser(caller): CurrentUser, Path(user): Path, Query(range): Query, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); ensure_can_read_student(&caller, &target, &st.db).await?; let from = range.from.as_deref().map(MenuDate::try_new).transpose()?; let to = range.to.as_deref().map(MenuDate::try_new).transpose()?; let (rows, total) = service::meal_attendance::list_for_student( &st.db, &target, from.as_ref(), to.as_ref(), limit, offset, ) .await?; let items = attendance_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } // ---- money ---------------------------------------------------------------- #[derive(Serialize, ToSchema)] struct BalanceResponse { student: PersonRef, /// `credits + reversals - charges`, in **minor units**. Negative /// means the student owes the school. Derived on every read, never stored. #[schema(example = -4500)] balance_minor: i64, } #[derive(Serialize, ToSchema)] struct LedgerResponse { id: String, student: PersonRef, /// `charge`, `credit`, or `reversal`. #[schema(example = "charge")] kind: String, /// Always positive — the sign is the `kind`'s business. #[schema(example = 4500)] amount_minor: i64, /// What caused the line: a booking id on a `charge`, the reversed charge's /// own id on a `reversal`, absent on a `credit`. source: Option, method: Option, note: Option, /// Who wrote it: the booker on a charge or reversal, the admin on a credit. recorded_by: PersonRef, created_at: i64, } impl LedgerResponse { fn new(line: &MealLedger, people: &std::collections::HashMap) -> Self { Self { id: line.get_id().key().to_string(), student: PersonRef::resolve(people, line.get_student()), kind: line.get_kind().as_str().to_string(), amount_minor: line.get_amount_minor().as_minor(), source: line.get_source_key().map(str::to_string), method: line.get_method().map(|m| m.as_str().to_string()), note: line.get_note().map(|n| n.as_str().to_string()), recorded_by: PersonRef::resolve(people, line.get_recorded_by()), created_at: line.get_created_at().as_millis(), } } } /// Join the people onto a page of ledger lines — one query for the whole page. async fn ledger_responses( lines: &[MealLedger], db: &Database, ) -> Result, AppError> { let people = person_map( lines .iter() .flat_map(|line| [*line.get_student(), *line.get_recorded_by()]), db, ) .await?; Ok(lines .iter() .map(|line| LedgerResponse::new(line, &people)) .collect()) } /// One student's balance, resolved to a response. Shared by both balance routes. async fn balance_response( student: &UserId, db: &Database, ) -> Result, AppError> { let people = person_map(std::iter::once(*student), db).await?; Ok(Json(BalanceResponse { student: PersonRef::resolve(&people, student), balance_minor: service::meal_ledger::balance_of(db, student).await?, })) } /// Reading someone else's meal record — money, attendance, dietary profile: /// teacher+, or a parent linked to the student. Reading your *own* is always /// allowed, since every `{user}` route here accepts the caller's own id; that /// is the one way this gate differs from /// [`crate::service::parent_link::ensure_can_observe`], which /// 403s a self-read because its subjects have their own `/me` routes. async fn ensure_can_read_student( caller: &User, target: &UserId, db: &Database, ) -> Result<(), AppError> { if caller.get_id() == target { return Ok(()); } crate::service::parent_link::ensure_can_observe(caller, target, db).await } /// May `caller` read `target`'s meal *money* — balance and ledger? Own always; /// a parent only for a student they hold a live link to; manager+ for anyone. /// /// Deliberately narrower than [`ensure_can_read_student`], which still gates /// the profile, booking and attendance reads at teacher+: **a teacher sees no /// money**. Canteen debt is family debt, so this is the same rule (and the same /// 403) `/payments` has always held — what a family owes the school is not /// classroom information, and neither is what it owes the canteen. async fn ensure_can_read_money( caller: &User, target: &UserId, db: &Database, ) -> Result<(), AppError> { if caller.get_id() == target || caller.get_role().at_least(Role::Manager) { return Ok(()); } // The link row alone is not the grant: a link whose student side changed // role must be inert, so the target's live role is re-read. A missing or // non-student target falls through to the same 403 — a parent never gets an if caller.get_role() == Role::Parent && crate::service::parent_link::links_live(db, caller.get_id(), target).await? { return Ok(()); } Err(AppError::Forbidden( "requires manager role or higher, or a parent link to this student", )) } /// What the caller owes or has on account, in minor units (negative = owes). #[utoipa::path( get, path = "/balance/me", tag = "meals", security(("session_cookie" = [])), responses( (status = 200, description = "The caller's meal balance", body = BalanceResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn my_balance( State(st): State, CurrentUser(user): CurrentUser, ) -> Result, AppError> { balance_response(user.get_id(), &st.db).await } /// One student's meal balance. Requires manager+, or a parent link to them — /// the caller's own id always passes. A teacher gets a `403`: canteen debt is /// family debt, gated exactly like `/payments`. #[utoipa::path( get, path = "/balance/{user}", tag = "meals", security(("session_cookie" = [])), params(("user" = String, Path, description = "Student id")), responses( (status = 200, description = "The student's meal balance", body = BalanceResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_balance( State(st): State, CurrentUser(caller): CurrentUser, Path(user): Path, ) -> Result, AppError> { let target = UserId::from_key(&user); ensure_can_read_money(&caller, &target, &st.db).await?; balance_response(&target, &st.db).await } /// One student's statement, newest line first: every charge, credit, and /// reversal. Nothing here is ever edited or deleted — a correction is another /// line. Same gate as the balance. Paged via `?limit=&offset=`. #[utoipa::path( get, path = "/ledger/{user}", tag = "meals", security(("session_cookie" = [])), params(("user" = String, Path, description = "Student id"), PageParams), responses( (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page), (status = 400, description = "Invalid limit or offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse), ), )] async fn user_ledger( State(st): State, CurrentUser(caller): CurrentUser, Path(user): Path, Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let target = UserId::from_key(&user); ensure_can_read_money(&caller, &target, &st.db).await?; let (rows, total) = service::meal_ledger::list_for_student(&st.db, &target, limit, offset).await?; let items = ledger_responses(&rows, &st.db).await?; Ok(Json(Page::new(items, total, limit, offset))) } #[derive(Deserialize, ToSchema)] struct RecordCredit { /// The student the money is for. student_id: String, /// How much came in, **minor units**, positive. #[schema(minimum = 1, maximum = 10000000, example = 25000)] amount_minor: i64, /// How it arrived ("cash", "havale", …). Free text — the backend speaks to /// no payment gateway and stores no card data. #[schema(max_length = 50, example = "cash")] method: Option, #[schema(max_length = 500, example = "receipt 2026-114")] note: Option, /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the /// separator inside a ledger line's id). Send one and a retry after a /// timeout returns the **same** line instead of recording the money twice; /// omit it and two identical calls are two credits. The same key sent with a /// different `amount_minor` is a `409`. #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] request_key: Option, } /// Record money received from a student. **Admin only** — not manager: writing /// down cash is the highest-trust action in the app. The target must be a /// student, or anyone who already carries meal-ledger lines — a debt survives /// its debtor's role change, and it has to stay settleable. Appends a `credit` line; /// nothing in the ledger is ever edited or removed, so an over-credit is /// corrected by a compensating line, not by a fix-up. /// /// **Retry-safe on request** — send a `request_key` and a repeat of the call (a /// client retry after a network timeout, which used to record the money a second /// time the moment the response was lost) returns the line the first attempt /// wrote. The same key with a different `amount_minor` is a `409`: that is a /// client bug, not a replay. Without a key two identical calls are two credits, /// as a desk taking the same amount twice really is. #[utoipa::path( post, path = "/credits", tag = "meals", security(("session_cookie" = [])), request_body = RecordCredit, responses( (status = 201, description = "Credit recorded", body = LedgerResponse), (status = 400, description = "Invalid amount, method, note, request_key, or a non-student target", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires the admin role", body = ErrorResponse), (status = 404, description = "No such user", body = ErrorResponse), (status = 409, description = "The request_key was already used for a different amount", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] async fn record_credit( State(st): State, RequireAdmin(admin): RequireAdmin, Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let student = UserId::from_key(&req.student_id); // Only a student carries a meal balance; crediting anyone else is a typo, // and a typo here is money in the wrong ledger. Unless they already carry // ledger lines: a debt outlives its debtor's role change (a student // promoted to staff keeps what they owed), and the student rule alone made // that debt permanently unsettleable — there is no other route that // appends a credit. A typo'd staff id has no lines, so it still 400s. if crate::service::user::read(&st.db, &student) .await? .ok_or(AppError::NotFound)? .get_role() != Role::Student && service::meal_ledger::list_for_student(&st.db, &student, Some(1), 0) .await? .0 .is_empty() { return Err(AppError::Validation(ValidationError::Invalid { field: "student_id", reason: "only a student carries a meal balance", })); } let request_key = req .request_key .as_deref() .map(PaymentRequestKey::try_new) .transpose()?; let line = service::meal_ledger::credit( &st.db, &student, LedgerAmount::try_new(req.amount_minor)?, req.method .as_deref() .map(LedgerMethod::try_new) .transpose()? .flatten(), req.note .as_deref() .map(LedgerNote::try_new) .transpose()? .flatten(), request_key.as_ref(), admin.get_id(), ) .await?; let items = ledger_responses(std::slice::from_ref(&line), &st.db).await?; Ok(( StatusCode::CREATED, Json(items.into_iter().next().expect("one line in, one out")), )) }