forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

settings.rs308 lines, 13.9 KiBHistoryRawDownload
1use crate::web::tenant_state::State;
2use axum::Json;
3use serde::{Deserialize, Serialize};
4use utoipa::ToSchema;
5use utoipa_axum::router::OpenApiRouter;
6use utoipa_axum::routes;
7
8use crate::domain::settings::Settings;
9use crate::error::{AppError, ErrorResponse};
10use crate::service;
11use crate::state::AppState;
12
13use super::{CurrentUser, RequireManager, set_or_clear};
14
15pub fn routes() -> OpenApiRouter<AppState> {
16 OpenApiRouter::new().routes(routes!(get_settings, update_settings))
17}
18
19/// One exam kind the school runs, with its weight in course averages. An exam
20/// of this kind counts `weight` times into `Σ(mark×weight) / Σ(weight)`.
21#[derive(Serialize, Deserialize, ToSchema)]
22struct ExamKindDto {
23 /// The `kind` value exams carry, 1–50 characters.
24 #[schema(example = "midterm", max_length = 50)]
25 name: String,
26 /// The kind's weight in the course average, `1`–`100`. Editing it
27 /// re-weights every exam of this kind at once.
28 #[schema(example = 2, minimum = 1, maximum = 100)]
29 weight: i64,
30}
31
32/// One meal slot the school serves. A published menu snapshots this name, so
33/// renaming or retiring a slot never rewrites a past menu.
34#[derive(Serialize, Deserialize, ToSchema)]
35struct MealSlotDto {
36 /// The `slot` value menus carry, 1–50 characters.
37 #[schema(example = "lunch", max_length = 50)]
38 name: String,
39 /// When the slot is served, as minutes past midnight **UTC** on the menu's
40 /// date (`0`–`1439`; `720` = 12:00 UTC). `meal_cancel_cutoff_minutes`
41 /// counts back from this instant.
42 ///
43 /// **The clock is UTC, not local time** — this API stores no school
44 /// timezone, so a UTC+3 school enters `540` (09:00 UTC) for a meal served
45 /// at noon locally. `null` = unset, and then the cutoff counts back from
46 /// midnight UTC of the menu's date, the pre-serving-time behaviour.
47 #[schema(example = 720, minimum = 0, maximum = 1_439)]
48 serving_minute: Option<i64>,
49}
50
51/// One grade-display band: marks at or above `min` (and below the next band's
52/// `min`) render as `label`.
53#[derive(Serialize, Deserialize, ToSchema)]
54struct GradeBandDto {
55 /// Lowest mark of the band, `0`–`100`. One band must start at `0`.
56 #[schema(example = 85, minimum = 0, maximum = 100)]
57 min: i64,
58 /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`).
59 #[schema(example = "AA", max_length = 20)]
60 label: String,
61}
62
63/// The school's policy: which exam kinds exist (and their weights in course
64/// averages), which attendance statuses the roll call accepts, and how
65/// numeric marks display as grades.
66#[derive(Serialize, ToSchema)]
67struct SettingsResponse {
68 /// Accepted `kind` values for new exams, each with its weight in the
69 /// course average.
70 #[schema(example = json!([
71 {"name": "midterm", "weight": 2},
72 {"name": "final", "weight": 3},
73 {"name": "oral", "weight": 1},
74 ]))]
75 exam_kinds: Vec<ExamKindDto>,
76 /// Accepted `status` values for attendance marking. Always contains the
77 /// core four (`present`, `absent`, `late`, `excused`).
78 #[schema(example = json!(["present", "absent", "late", "excused"]))]
79 attendance_statuses: Vec<String>,
80 /// Grade-display bands, highest first. Empty = marks display numeric-only.
81 grade_bands: Vec<GradeBandDto>,
82 /// Per-file size limit for note uploads, in bytes.
83 #[schema(example = 5_242_880)]
84 max_file_bytes: i64,
85 /// How many prior turns of a thread the chatbot is given as context.
86 #[schema(example = 10)]
87 chatbot_history_turns: i64,
88 /// How many chatbot threads one user may keep.
89 #[schema(example = 50)]
90 max_chatbot_threads: i64,
91 /// Character limit on one chat message.
92 #[schema(example = 4000)]
93 max_chatbot_message_len: i64,
94 /// Meal slots menus may be published for, each with the UTC minute it is
95 /// served at (`null` = unset → the cutoff counts back from midnight UTC).
96 /// Empty = the school runs no meal program.
97 #[schema(example = json!([
98 {"name": "breakfast", "serving_minute": 300},
99 {"name": "lunch", "serving_minute": 720},
100 {"name": "snack", "serving_minute": null},
101 ]))]
102 meal_slots: Vec<MealSlotDto>,
103 /// Dietary tags a dish and a student's profile may carry.
104 #[schema(example = json!(["vegetarian", "vegan", "gluten_free"]))]
105 dietary_tags: Vec<String>,
106 /// How many minutes before a slot's `serving_minute` booking and
107 /// cancelling close. `null` = no cutoff.
108 #[schema(example = 120)]
109 meal_cancel_cutoff_minutes: Option<i64>,
110}
111
112impl SettingsResponse {
113 fn new(settings: &Settings) -> Self {
114 Self {
115 exam_kinds: settings
116 .get_exam_kinds()
117 .iter()
118 .map(|kind| ExamKindDto {
119 name: kind.get_name().to_string(),
120 weight: kind.get_weight(),
121 })
122 .collect(),
123 attendance_statuses: settings.get_attendance_statuses().to_vec(),
124 grade_bands: settings
125 .get_grade_bands()
126 .iter()
127 .map(|band| GradeBandDto {
128 min: band.get_min(),
129 label: band.get_label().to_string(),
130 })
131 .collect(),
132 max_file_bytes: settings.get_max_file_bytes(),
133 chatbot_history_turns: settings.get_chatbot_history_turns(),
134 max_chatbot_threads: settings.get_max_chatbot_threads(),
135 max_chatbot_message_len: settings.get_max_chatbot_message_len(),
136 meal_slots: settings
137 .get_meal_slots()
138 .iter()
139 .map(|slot| MealSlotDto {
140 name: slot.get_name().to_string(),
141 serving_minute: slot.get_serving_minute(),
142 })
143 .collect(),
144 dietary_tags: settings.get_dietary_tags(),
145 meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(),
146 }
147 }
148}
149
150#[derive(Deserialize, ToSchema)]
151struct UpdateSettings {
152 /// Replaces the whole list when present: 1–20 entries with unique names,
153 /// each name 1–50 characters, each weight `1`–`100`.
154 #[schema(max_items = 20)]
155 exam_kinds: Option<Vec<ExamKindDto>>,
156 /// Replaces the whole list when present; must keep `present`, `absent`,
157 /// `late`, `excused` (the attendance rate is defined over them). Each entry
158 /// is 1–50 characters.
159 #[schema(max_items = 20)]
160 attendance_statuses: Option<Vec<String>>,
161 /// Replaces the whole set when present. `[]` clears the bands (numeric-only
162 /// marks); otherwise mins are unique and one band must start at `0`.
163 #[schema(max_items = 20)]
164 grade_bands: Option<Vec<GradeBandDto>>,
165 /// Per-file size limit for note uploads, in bytes:
166 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
167 #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)]
168 max_file_bytes: Option<i64>,
169 /// How many prior turns of a thread the chatbot is given as context,
170 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
171 #[schema(example = 10, minimum = 1, maximum = 50)]
172 chatbot_history_turns: Option<i64>,
173 /// How many chatbot threads one user may keep, `1`–`500`. At the cap
174 /// the user deletes an old thread before starting a new one.
175 #[schema(example = 50, minimum = 1, maximum = 500)]
176 max_chatbot_threads: Option<i64>,
177 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
178 /// server hard cap.
179 #[schema(example = 4000, minimum = 100, maximum = 8_000)]
180 max_chatbot_message_len: Option<i64>,
181 /// Replaces the whole list when present: at most 20 entries with unique
182 /// names, each 1–50 characters, each with an optional `serving_minute`
183 /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts
184 /// back from. `[]` switches the meal program off. A slot a menu was already
185 /// published for cannot be removed (409); its serving time may be edited
186 /// freely and applies live, to menus already published for it too. Names
187 /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) —
188 /// except a name the school already stores, which stays submittable so a
189 /// list written before that rule can still be edited.
190 #[schema(max_items = 20)]
191 meal_slots: Option<Vec<MealSlotDto>>,
192 /// Replaces the whole list when present: at most 20 unique entries, each
193 /// 1–50 characters. `[]` means the school tracks no dietary tags.
194 #[schema(max_items = 20)]
195 dietary_tags: Option<Vec<String>>,
196 /// Minutes before a slot's `serving_minute` at which booking *and*
197 /// cancelling close, `0`–`10080` (one week). It binds only the slots that
198 /// carry a `serving_minute`: with no serving hour there is no instant to
199 /// count back from, so that slot's menus close at no deadline until the
200 /// hour is set. Omit to keep the current value; send `null` for
201 /// no cutoff at all.
202 #[serde(default, deserialize_with = "set_or_clear")]
203 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
204 meal_cancel_cutoff_minutes: Option<Option<i64>>,
205}
206
207/// The school's current policy. Any authenticated user — clients need it to
208/// render pickers and grades. Falls back to the built-in defaults until a
209/// manager edits it.
210#[utoipa::path(
211 get,
212 path = "/",
213 tag = "settings",
214 security(("session_cookie" = [])),
215 responses(
216 (status = 200, description = "The school's policy", body = SettingsResponse),
217 (status = 401, description = "Not authenticated", body = ErrorResponse),
218 ),
219)]
220async fn get_settings(
221 State(st): State<AppState>,
222 CurrentUser(_user): CurrentUser,
223) -> Result<Json<SettingsResponse>, AppError> {
224 let settings = service::settings::load(&st.db).await?;
225 Ok(Json(SettingsResponse::new(&settings)))
226}
227
228/// Update the school's policy. Requires manager+. Omitted fields keep their
229/// value; a present field replaces its list wholesale. Existing rows are
230/// untouched — a removed exam kind or status lives on in old records; only
231/// new writes are held to the new lists. Kind weights, though, apply live:
232/// mark reports read them at request time, so editing a weight re-weights
233/// every exam of that kind. For that reason a kind whose exams already carry
234/// marks cannot be dropped from the list (409) — those marks would silently
235/// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
236/// gone counts with weight 1 but cannot be graded (409) until the kind
237/// returns — the other end of the same rule. `max_file_bytes` likewise
238/// applies at upload time only — already-stored files keep their size, and the
239/// chatbot knobs apply to the next chat request only. `meal_slots` follows the
240/// exam-kind rule: a slot a menu was already published for cannot be dropped
241/// (409), because the menu snapshotted its name. Slot names must not contain
242/// `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name
243/// already on the school's stored list is exempt, so a list written before that
244/// rule can still be edited around it.
245#[utoipa::path(
246 patch,
247 path = "/",
248 tag = "settings",
249 security(("session_cookie" = [])),
250 request_body = UpdateSettings,
251 responses(
252 (status = 200, description = "Updated policy", body = SettingsResponse),
253 (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse),
254 (status = 401, description = "Not authenticated", body = ErrorResponse),
255 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
256 (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),
257 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
258 ),
259)]
260async fn update_settings(
261 State(st): State<AppState>,
262 RequireManager(_user): RequireManager,
263 Json(req): Json<UpdateSettings>,
264) -> Result<Json<SettingsResponse>, AppError> {
265 // Wire → workflow mapping, nothing more. The lists are deliberately not
266 // validated here: that happens inside the service, in the workflow's own
267 // order, and a stored meal-slot name skips the URL-charset rule — a
268 // decision only the locked edit can make (`MealSlotDef::try_kept`).
269 let patch = service::settings::SettingsPatch {
270 exam_kinds: req.exam_kinds.as_ref().map(|kinds| {
271 kinds
272 .iter()
273 .map(|kind| service::settings::ExamKindInput {
274 name: kind.name.clone(),
275 weight: kind.weight,
276 })
277 .collect()
278 }),
279 attendance_statuses: req.attendance_statuses.clone(),
280 grade_bands: req.grade_bands.as_ref().map(|bands| {
281 bands
282 .iter()
283 .map(|band| service::settings::GradeBandInput {
284 min: band.min,
285 label: band.label.clone(),
286 })
287 .collect()
288 }),
289 max_file_bytes: req.max_file_bytes,
290 chatbot_history_turns: req.chatbot_history_turns,
291 max_chatbot_threads: req.max_chatbot_threads,
292 max_chatbot_message_len: req.max_chatbot_message_len,
293 meal_slots: req.meal_slots.as_ref().map(|slots| {
294 slots
295 .iter()
296 .map(|slot| service::settings::MealSlotInput {
297 name: slot.name.clone(),
298 serving_minute: slot.serving_minute,
299 })
300 .collect()
301 }),
302 dietary_tags: req.dietary_tags.clone(),
303 meal_cancel_cutoff_minutes: req.meal_cancel_cutoff_minutes,
304 };
305 Ok(Json(SettingsResponse::new(
306 &service::settings::apply(&st.db, &patch).await?,
307 )))
308}