use crate::web::tenant_state::State; use axum::Json; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::domain::settings::Settings; use crate::error::{AppError, ErrorResponse}; use crate::service; use crate::state::AppState; use super::{CurrentUser, RequireManager, set_or_clear}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new().routes(routes!(get_settings, update_settings)) } /// One exam kind the school runs, with its weight in course averages. An exam /// of this kind counts `weight` times into `Σ(mark×weight) / Σ(weight)`. #[derive(Serialize, Deserialize, ToSchema)] struct ExamKindDto { /// The `kind` value exams carry, 1–50 characters. #[schema(example = "yazili", max_length = 50)] name: String, /// The kind's weight in the course average, `1`–`100`. Editing it /// re-weights every exam of this kind at once. #[schema(example = 2, minimum = 1, maximum = 100)] weight: i64, } /// One meal slot the school serves. A published menu snapshots this name, so /// renaming or retiring a slot never rewrites a past menu. #[derive(Serialize, Deserialize, ToSchema)] struct MealSlotDto { /// The `slot` value menus carry, 1–50 characters. #[schema(example = "lunch", max_length = 50)] name: String, /// When the slot is served, as minutes past midnight **UTC** on the menu's /// date (`0`–`1439`; `720` = 12:00 UTC). `meal_cancel_cutoff_minutes` /// counts back from this instant. /// /// **The clock is UTC, not local time** — this API stores no school /// timezone, so a UTC+3 school enters `540` (09:00 UTC) for a meal served /// at noon locally. `null` = unset, and then the cutoff counts back from /// midnight UTC of the menu's date, the pre-serving-time behaviour. #[schema(example = 720, minimum = 0, maximum = 1_439)] serving_minute: Option, } /// One grade-display band: marks at or above `min` (and below the next band's /// `min`) render as `label`. #[derive(Serialize, Deserialize, ToSchema)] struct GradeBandDto { /// Lowest mark of the band, `0`–`100`. One band must start at `0`. #[schema(example = 85, minimum = 0, maximum = 100)] min: i64, /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`). #[schema(example = "AA", max_length = 20)] label: String, } /// The school's policy: which exam kinds exist (and their weights in course /// averages), which attendance statuses the roll call accepts, and how /// numeric marks display as grades. #[derive(Serialize, ToSchema)] struct SettingsResponse { /// Accepted `kind` values for new exams, each with its weight in the /// course average. #[schema(example = json!([ {"name": "yazili", "weight": 3}, {"name": "sozlu", "weight": 1}, {"name": "uygulama", "weight": 1}, ]))] exam_kinds: Vec, /// Accepted `status` values for attendance marking. Always contains the /// core four (`present`, `absent`, `late`, `excused`). #[schema(example = json!(["present", "absent", "late", "excused"]))] attendance_statuses: Vec, /// Grade-display bands, highest first. Empty = marks display numeric-only. grade_bands: Vec, /// Per-file size limit for note uploads, in bytes. #[schema(example = 5_242_880)] max_file_bytes: i64, /// How many prior turns of a thread the chatbot is given as context. #[schema(example = 10)] chatbot_history_turns: i64, /// How many chatbot threads one user may keep. #[schema(example = 50)] max_chatbot_threads: i64, /// Character limit on one chat message. #[schema(example = 4000)] max_chatbot_message_len: i64, /// Meal slots menus may be published for, each with the UTC minute it is /// served at (`null` = unset → the cutoff counts back from midnight UTC). /// Empty = the school runs no meal program. #[schema(example = json!([ {"name": "breakfast", "serving_minute": 300}, {"name": "lunch", "serving_minute": 720}, {"name": "snack", "serving_minute": null}, ]))] meal_slots: Vec, /// Dietary tags a dish and a student's profile may carry. #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))] dietary_tags: Vec, /// How many minutes before a slot's `serving_minute` booking and /// cancelling close. `null` = no cutoff. #[schema(example = 120)] meal_cancel_cutoff_minutes: Option, /// The subject-specialisation vocabulary a profile's `branch` may name. /// Empty = the school keeps no list, and no profile may carry one. #[schema(max_items = 20, example = json!(["Matematik", "Fizik"]))] branches: Vec, /// What an absence may be excused as ("raporlu", "izinli", …). Empty = the /// school names no kinds. #[schema(max_items = 20, example = json!(["raporlu", "izinli"]))] excuse_kinds: Vec, /// Per-term excused-absence day limit; `null` = no limit configured. #[schema(example = 10)] max_excused_absent_days: Option, /// Per-term unexcused-absence day limit; `null` = no limit configured. #[schema(example = 20)] max_unexcused_absent_days: Option, /// The school's IANA timezone; `null` = the deployment default /// (`Europe/Istanbul`), which is what an unset setting reads as. It is the /// zone the absence days are bucketed in. #[schema(example = "Europe/Istanbul")] timezone: Option, } impl SettingsResponse { fn new(settings: &Settings) -> Self { Self { exam_kinds: settings .get_exam_kinds() .iter() .map(|kind| ExamKindDto { name: kind.get_name().to_string(), weight: kind.get_weight(), }) .collect(), attendance_statuses: settings.get_attendance_statuses().to_vec(), grade_bands: settings .get_grade_bands() .iter() .map(|band| GradeBandDto { min: band.get_min(), label: band.get_label().to_string(), }) .collect(), max_file_bytes: settings.get_max_file_bytes(), chatbot_history_turns: settings.get_chatbot_history_turns(), max_chatbot_threads: settings.get_max_chatbot_threads(), max_chatbot_message_len: settings.get_max_chatbot_message_len(), meal_slots: settings .get_meal_slots() .iter() .map(|slot| MealSlotDto { name: slot.get_name().to_string(), serving_minute: slot.get_serving_minute(), }) .collect(), dietary_tags: settings.get_dietary_tags(), meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(), branches: settings.get_branches(), excuse_kinds: settings.get_excuse_kinds(), max_excused_absent_days: settings.get_max_excused_absent_days(), max_unexcused_absent_days: settings.get_max_unexcused_absent_days(), timezone: settings.timezone.clone(), } } } #[derive(Deserialize, ToSchema)] struct UpdateSettings { /// Replaces the whole list when present: 1–20 entries with unique names, /// each name 1–50 characters, each weight `1`–`100`. #[schema(max_items = 20)] exam_kinds: Option>, /// Replaces the whole list when present; must keep `present`, `absent`, /// `late`, `excused` (the attendance rate is defined over them). Each entry /// is 1–50 characters. #[schema(max_items = 20)] attendance_statuses: Option>, /// Replaces the whole set when present. `[]` clears the bands (numeric-only /// marks); otherwise mins are unique and one band must start at `0`. #[schema(max_items = 20)] grade_bands: Option>, /// Per-file size limit for note uploads, in bytes: /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap. #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)] max_file_bytes: Option, /// How many prior turns of a thread the chatbot is given as context, /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens. #[schema(example = 10, minimum = 1, maximum = 50)] chatbot_history_turns: Option, /// How many chatbot threads one user may keep, `1`–`500`. At the cap /// the user deletes an old thread before starting a new one. #[schema(example = 50, minimum = 1, maximum = 500)] max_chatbot_threads: Option, /// Character limit on one chat message, `100`–`8000`. The ceiling is a /// server hard cap. #[schema(example = 4000, minimum = 100, maximum = 8_000)] max_chatbot_message_len: Option, /// Replaces the whole list when present: at most 20 entries with unique /// names, each 1–50 characters, each with an optional `serving_minute` /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts /// back from. `[]` switches the meal program off. A slot a menu was already /// published for cannot be removed (409); its serving time may be edited /// freely and applies live, to menus already published for it too. Names /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) — /// except a name the school already stores, which stays submittable so a /// list written before that rule can still be edited. #[schema(max_items = 20)] meal_slots: Option>, /// Replaces the whole list when present: at most 20 unique entries, each /// 1–50 characters. `[]` means the school tracks no dietary tags. #[schema(max_items = 20)] dietary_tags: Option>, /// Minutes before a slot's `serving_minute` at which booking *and* /// cancelling close, `0`–`10080` (one week). It binds only the slots that /// carry a `serving_minute`: with no serving hour there is no instant to /// count back from, so that slot's menus close at no deadline until the /// hour is set. Omit to keep the current value; send `null` for /// no cutoff at all. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = 120, minimum = 0, maximum = 10_080)] meal_cancel_cutoff_minutes: Option>, /// Replaces the whole subject list when present: at most 20 entries, each /// 1–50 characters, unique. `[]` means the school keeps no list — and a /// profile's `branch` may then only be cleared, never set. #[schema(max_items = 20, example = json!(["Matematik", "Fizik"]))] branches: Option>, /// Replaces the whole excuse-kind list when present: at most 20 entries, /// each 1–50 characters, unique. `[]` clears it. #[schema(max_items = 20, example = json!(["raporlu", "izinli"]))] excuse_kinds: Option>, /// Per-term excused-absence day limit, `0`–`365`. Omit to keep the /// current value; send `null` for no limit at all. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = 10, minimum = 0, maximum = 365)] max_excused_absent_days: Option>, /// Per-term unexcused-absence day limit, `0`–`365`. Omit to keep the /// current value; send `null` for no limit at all. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = 20, minimum = 0, maximum = 365)] max_unexcused_absent_days: Option>, /// The school's IANA timezone — one of the deployment's allow-list /// (`Europe/Istanbul`, `UTC`), by name. It is the zone the absence /// days are bucketed in and the one a menu's serving minute is *not* /// (that clock is UTC on purpose). Omit to keep the current value; send /// `null` to fall back to the deployment default. #[serde(default, deserialize_with = "set_or_clear")] #[schema(value_type = Option, example = "Europe/Istanbul")] timezone: Option>, } /// The school's current policy. Any authenticated user — clients need it to /// render pickers and grades. Falls back to the built-in defaults until a /// manager edits it. #[utoipa::path( get, path = "/", tag = "settings", security(("session_cookie" = [])), responses( (status = 200, description = "The school's policy", body = SettingsResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), ), )] async fn get_settings( State(st): State, CurrentUser(_user): CurrentUser, ) -> Result, AppError> { let settings = service::settings::load(&st.db).await?; Ok(Json(SettingsResponse::new(&settings))) } /// Update the school's policy. Requires manager+. Omitted fields keep their /// value; a present field replaces its list wholesale. Existing rows are /// untouched — a removed exam kind or status lives on in old records; only /// new writes are held to the new lists. Kind weights, though, apply live: /// mark reports read them at request time, so editing a weight re-weights /// every exam of that kind. For that reason a kind whose exams already carry /// marks cannot be dropped from the list (409) — those marks would silently /// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is /// gone counts with weight 1 but cannot be graded (409) until the kind /// returns — the other end of the same rule. `max_file_bytes` likewise /// applies at upload time only — already-stored files keep their size, and the /// chatbot knobs apply to the next chat request only. `meal_slots` follows the /// exam-kind rule: a slot a menu was already published for cannot be dropped /// (409), because the menu snapshotted its name. Slot names must not contain /// `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name /// already on the school's stored list is exempt, so a list written before that /// rule can still be edited around it. #[utoipa::path( patch, path = "/", tag = "settings", security(("session_cookie" = [])), request_body = UpdateSettings, responses( (status = 200, description = "Updated policy", body = SettingsResponse), (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 409, description = "A removed exam kind still has graded exams, a removed meal slot still has published menus, or concurrent edits kept changing the settings mid-save", 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_settings( State(st): State, RequireManager(_user): RequireManager, Json(req): Json, ) -> Result, AppError> { // Wire → workflow mapping, nothing more. The lists are deliberately not // validated here: that happens inside the service, in the workflow's own // order, and a stored meal-slot name skips the URL-charset rule — a // decision only the locked edit can make (`MealSlotDef::try_kept`). let patch = service::settings::SettingsPatch { exam_kinds: req.exam_kinds.as_ref().map(|kinds| { kinds .iter() .map(|kind| service::settings::ExamKindInput { name: kind.name.clone(), weight: kind.weight, }) .collect() }), attendance_statuses: req.attendance_statuses.clone(), grade_bands: req.grade_bands.as_ref().map(|bands| { bands .iter() .map(|band| service::settings::GradeBandInput { min: band.min, label: band.label.clone(), }) .collect() }), max_file_bytes: req.max_file_bytes, chatbot_history_turns: req.chatbot_history_turns, max_chatbot_threads: req.max_chatbot_threads, max_chatbot_message_len: req.max_chatbot_message_len, meal_slots: req.meal_slots.as_ref().map(|slots| { slots .iter() .map(|slot| service::settings::MealSlotInput { name: slot.name.clone(), serving_minute: slot.serving_minute, }) .collect() }), dietary_tags: req.dietary_tags.clone(), meal_cancel_cutoff_minutes: req.meal_cancel_cutoff_minutes, branches: req.branches.clone(), excuse_kinds: req.excuse_kinds.clone(), max_excused_absent_days: req.max_excused_absent_days, max_unexcused_absent_days: req.max_unexcused_absent_days, timezone: req.timezone.clone(), }; Ok(Json(SettingsResponse::new( &service::settings::apply(&st.db, &patch).await?, ))) }