| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | use crate::web::tenant_state::State; |
| 13 | use axum::Json; |
| 14 | use axum::extract::{Path, Query}; |
| 15 | use axum::http::StatusCode; |
| 16 | use serde::{Deserialize, Serialize}; |
| 17 | use utoipa::{IntoParams, ToSchema}; |
| 18 | use utoipa_axum::router::OpenApiRouter; |
| 19 | use utoipa_axum::routes; |
| 20 | |
| 21 | use crate::database::Database; |
| 22 | use crate::domain::dietary_profile::{DietaryNote, DietaryTags, conflicts}; |
| 23 | use crate::domain::meal_attendance::{MealAttendance, MealAttendanceId, MealAttendanceStatus}; |
| 24 | use crate::domain::meal_booking::{MealBooking, MealBookingId, MealCutoff}; |
| 25 | use crate::domain::meal_ledger::{LedgerAmount, LedgerMethod, LedgerNote, MealLedger}; |
| 26 | use crate::domain::menu::{Menu, MenuDate, MenuId, MenuSlot, validate_capacity}; |
| 27 | use crate::domain::menu_dish::{ |
| 28 | DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId, |
| 29 | }; |
| 30 | |
| 31 | use crate::domain::payment_ledger::PaymentRequestKey; |
| 32 | use crate::domain::role::Role; |
| 33 | use crate::domain::user::{User, UserId}; |
| 34 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 35 | use crate::service; |
| 36 | use crate::state::AppState; |
| 37 | |
| 38 | use super::{ |
| 39 | CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireManager, RequireTeacher, |
| 40 | check_not_past, person_map, set_or_clear, |
| 41 | }; |
| 42 | |
| 43 | pub 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)] |
| 63 | struct CreateMenu { |
| 64 | |
| 65 | |
| 66 | #[schema(example = "2026-09-14", min_length = 10, max_length = 10)] |
| 67 | date: String, |
| 68 | |
| 69 | #[schema(example = "lunch")] |
| 70 | slot: String, |
| 71 | |
| 72 | #[schema(minimum = 0, maximum = 10000, example = 120)] |
| 73 | capacity: Option<i64>, |
| 74 | } |
| 75 | |
| 76 | #[derive(Deserialize, ToSchema)] |
| 77 | struct UpdateMenu { |
| 78 | |
| 79 | |
| 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 | |
| 86 | #[derive(Debug, Deserialize, IntoParams)] |
| 87 | struct MenuRange { |
| 88 | |
| 89 | #[param(example = "2026-09-01")] |
| 90 | from: Option<String>, |
| 91 | |
| 92 | #[param(example = "2026-09-30")] |
| 93 | to: Option<String>, |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | #[derive(Debug, Deserialize, IntoParams)] |
| 100 | struct MenuSlotFilter { |
| 101 | |
| 102 | |
| 103 | #[param(example = "lunch")] |
| 104 | slot: Option<String>, |
| 105 | } |
| 106 | |
| 107 | impl MenuSlotFilter { |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 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)] |
| 131 | struct CreateDish { |
| 132 | #[schema(example = "Mercimek çorbası", max_length = 100)] |
| 133 | name: String, |
| 134 | #[schema(max_length = 500)] |
| 135 | description: Option<String>, |
| 136 | |
| 137 | |
| 138 | #[schema(minimum = 0, maximum = 1000000, example = 4550_i64)] |
| 139 | price_minor: i64, |
| 140 | |
| 141 | #[schema(max_items = 10, example = json!(["vegetarian"]))] |
| 142 | #[serde(default)] |
| 143 | tags: Vec<String>, |
| 144 | } |
| 145 | |
| 146 | #[derive(Deserialize, ToSchema)] |
| 147 | struct UpdateDish { |
| 148 | #[schema(max_length = 100)] |
| 149 | name: Option<String>, |
| 150 | |
| 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)] |
| 161 | struct DishResponse { |
| 162 | id: String, |
| 163 | #[schema(example = "Mercimek çorbası")] |
| 164 | name: String, |
| 165 | description: Option<String>, |
| 166 | |
| 167 | price_minor: i64, |
| 168 | tags: Vec<String>, |
| 169 | |
| 170 | |
| 171 | |
| 172 | #[schema(example = json!(["nut_allergy"]))] |
| 173 | conflicts: Vec<String>, |
| 174 | created_at: i64, |
| 175 | } |
| 176 | |
| 177 | impl 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)] |
| 192 | struct MenuResponse { |
| 193 | id: String, |
| 194 | |
| 195 | #[schema(example = "2026-09-14")] |
| 196 | date: String, |
| 197 | |
| 198 | |
| 199 | #[schema(example = "lunch")] |
| 200 | slot: String, |
| 201 | |
| 202 | capacity: Option<i64>, |
| 203 | |
| 204 | dishes: Vec<DishResponse>, |
| 205 | created_by: PersonRef, |
| 206 | created_at: i64, |
| 207 | } |
| 208 | |
| 209 | impl 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 | |
| 233 | |
| 234 | |
| 235 | async 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 | |
| 251 | async 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 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 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 | )] |
| 293 | async 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 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 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 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 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 | )] |
| 339 | async 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 | |
| 360 | let items = menu_responses(&menus, user.get_id(), &st.db).await?; |
| 361 | Ok(Json(Page::new(items, total, limit, offset))) |
| 362 | } |
| 363 | |
| 364 | |
| 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 | )] |
| 377 | async 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 | |
| 389 | |
| 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 | )] |
| 406 | async 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 | |
| 423 | |
| 424 | |
| 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 | )] |
| 439 | async 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 | |
| 448 | |
| 449 | |
| 450 | service::menu::delete(&st.db, menu).await?; |
| 451 | Ok(StatusCode::NO_CONTENT) |
| 452 | } |
| 453 | |
| 454 | |
| 455 | |
| 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 | )] |
| 473 | async 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 | |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 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 | |
| 513 | |
| 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 | )] |
| 530 | async 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 | |
| 541 | |
| 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 | |
| 556 | |
| 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 | |
| 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 | )] |
| 576 | async 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 | |
| 585 | |
| 586 | service::menu::delete_dish(&st.db, dish).await?; |
| 587 | Ok(StatusCode::NO_CONTENT) |
| 588 | } |
| 589 | |
| 590 | |
| 591 | |
| 592 | #[derive(Deserialize, ToSchema)] |
| 593 | struct UpdateDietaryProfile { |
| 594 | |
| 595 | |
| 596 | |
| 597 | #[schema(max_items = 10, example = json!(["nut_allergy"]))] |
| 598 | tags: Option<Vec<String>>, |
| 599 | |
| 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)] |
| 606 | struct DietaryProfileResponse { |
| 607 | student: PersonRef, |
| 608 | |
| 609 | tags: Vec<String>, |
| 610 | note: Option<String>, |
| 611 | |
| 612 | updated_by: Option<PersonRef>, |
| 613 | updated_at: Option<i64>, |
| 614 | } |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | async 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 | |
| 648 | |
| 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 | )] |
| 659 | async 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 | |
| 667 | |
| 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 | )] |
| 680 | async 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 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 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 | )] |
| 712 | async 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 | |
| 720 | |
| 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 | |
| 740 | |
| 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 | |
| 751 | |
| 752 | #[derive(Deserialize, ToSchema)] |
| 753 | struct BookMeal { |
| 754 | |
| 755 | |
| 756 | student_id: Option<String>, |
| 757 | } |
| 758 | |
| 759 | #[derive(Serialize, ToSchema)] |
| 760 | struct BookingResponse { |
| 761 | id: String, |
| 762 | |
| 763 | menu_id: String, |
| 764 | student: PersonRef, |
| 765 | |
| 766 | booked_by: PersonRef, |
| 767 | |
| 768 | |
| 769 | #[schema(example = "booked")] |
| 770 | status: String, |
| 771 | cancelled_at: Option<i64>, |
| 772 | created_at: i64, |
| 773 | } |
| 774 | |
| 775 | impl 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 | |
| 790 | async 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 | |
| 808 | |
| 809 | |
| 810 | |
| 811 | async fn meal_cutoff(db: &Database) -> Result<MealCutoff, AppError> { |
| 812 | Ok(MealCutoff::from_settings( |
| 813 | &service::settings::load(db).await?, |
| 814 | )) |
| 815 | } |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | |
| 822 | |
| 823 | |
| 824 | |
| 825 | async 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 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | |
| 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 | )] |
| 890 | async 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 | |
| 900 | |
| 901 | |
| 902 | |
| 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 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 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 | )] |
| 930 | async 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 | |
| 937 | |
| 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 | |
| 954 | |
| 955 | |
| 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 | )] |
| 970 | async 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 | |
| 987 | |
| 988 | |
| 989 | |
| 990 | |
| 991 | |
| 992 | |
| 993 | |
| 994 | |
| 995 | |
| 996 | |
| 997 | |
| 998 | |
| 999 | |
| 1000 | |
| 1001 | |
| 1002 | |
| 1003 | |
| 1004 | |
| 1005 | |
| 1006 | |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | |
| 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 | )] |
| 1030 | async 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 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | let staff = user.get_role().at_least(Role::Manager); |
| 1044 | if !staff { |
| 1045 | |
| 1046 | |
| 1047 | |
| 1048 | |
| 1049 | |
| 1050 | |
| 1051 | |
| 1052 | |
| 1053 | |
| 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 | |
| 1061 | |
| 1062 | |
| 1063 | |
| 1064 | |
| 1065 | |
| 1066 | let cutoff = if staff { |
| 1067 | MealCutoff::default() |
| 1068 | } else { |
| 1069 | meal_cutoff(&st.db).await? |
| 1070 | }; |
| 1071 | |
| 1072 | |
| 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 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | |
| 1088 | #[derive(Deserialize, ToSchema)] |
| 1089 | struct MarkMealAttendance { |
| 1090 | |
| 1091 | |
| 1092 | student_id: String, |
| 1093 | |
| 1094 | |
| 1095 | #[schema(example = "served")] |
| 1096 | status: String, |
| 1097 | } |
| 1098 | |
| 1099 | #[derive(Serialize, ToSchema)] |
| 1100 | struct MealAttendanceResponse { |
| 1101 | id: String, |
| 1102 | |
| 1103 | menu_id: String, |
| 1104 | student: PersonRef, |
| 1105 | #[schema(example = "served")] |
| 1106 | status: String, |
| 1107 | marked_by: PersonRef, |
| 1108 | marked_at: i64, |
| 1109 | } |
| 1110 | |
| 1111 | impl 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 | |
| 1125 | async 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 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 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 | )] |
| 1169 | async 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 | |
| 1181 | |
| 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 | |
| 1192 | |
| 1193 | |
| 1194 | |
| 1195 | |
| 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 | |
| 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 | )] |
| 1220 | async 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 | |
| 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 | |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | |
| 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 | )] |
| 1255 | async 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 | |
| 1281 | |
| 1282 | #[derive(Serialize, ToSchema)] |
| 1283 | struct BalanceResponse { |
| 1284 | student: PersonRef, |
| 1285 | |
| 1286 | |
| 1287 | #[schema(example = -4500)] |
| 1288 | balance_minor: i64, |
| 1289 | } |
| 1290 | |
| 1291 | #[derive(Serialize, ToSchema)] |
| 1292 | struct LedgerResponse { |
| 1293 | id: String, |
| 1294 | student: PersonRef, |
| 1295 | |
| 1296 | #[schema(example = "charge")] |
| 1297 | kind: String, |
| 1298 | |
| 1299 | #[schema(example = 4500)] |
| 1300 | amount_minor: i64, |
| 1301 | |
| 1302 | |
| 1303 | source: Option<String>, |
| 1304 | method: Option<String>, |
| 1305 | note: Option<String>, |
| 1306 | |
| 1307 | recorded_by: PersonRef, |
| 1308 | created_at: i64, |
| 1309 | } |
| 1310 | |
| 1311 | impl 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 | |
| 1328 | async 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 | |
| 1346 | async 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 | |
| 1358 | |
| 1359 | |
| 1360 | |
| 1361 | |
| 1362 | |
| 1363 | async 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 | |
| 1375 | |
| 1376 | |
| 1377 | |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | |
| 1382 | async 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 | |
| 1391 | |
| 1392 | |
| 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 | |
| 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 | )] |
| 1414 | async 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 | |
| 1422 | |
| 1423 | |
| 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 | )] |
| 1436 | async 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 | |
| 1447 | |
| 1448 | |
| 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 | )] |
| 1462 | async 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)] |
| 1478 | struct RecordCredit { |
| 1479 | |
| 1480 | student_id: String, |
| 1481 | |
| 1482 | #[schema(minimum = 1, maximum = 10000000, example = 25000)] |
| 1483 | amount_minor: i64, |
| 1484 | |
| 1485 | |
| 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 | |
| 1491 | |
| 1492 | |
| 1493 | |
| 1494 | |
| 1495 | #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] |
| 1496 | request_key: Option<String>, |
| 1497 | } |
| 1498 | |
| 1499 | |
| 1500 | |
| 1501 | |
| 1502 | |
| 1503 | |
| 1504 | |
| 1505 | |
| 1506 | |
| 1507 | |
| 1508 | |
| 1509 | |
| 1510 | |
| 1511 | |
| 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 | )] |
| 1528 | async 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 | |
| 1535 | |
| 1536 | |
| 1537 | |
| 1538 | |
| 1539 | |
| 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 | } |