forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

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

settings.rs364 lines, 17.1 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 = "yazili", 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": "yazili", "weight": 3},
72 {"name": "sozlu", "weight": 1},
73 {"name": "uygulama", "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 /// The subject-specialisation vocabulary a profile's `branch` may name.
111 /// Empty = the school keeps no list, and no profile may carry one.
112 #[schema(max_items = 20, example = json!(["Matematik", "Fizik"]))]
113 branches: Vec<String>,
114 /// What an absence may be excused as ("raporlu", "izinli", …). Empty = the
115 /// school names no kinds.
116 #[schema(max_items = 20, example = json!(["raporlu", "izinli"]))]
117 excuse_kinds: Vec<String>,
118 /// Per-term excused-absence day limit; `null` = no limit configured.
119 #[schema(example = 10)]
120 max_excused_absent_days: Option<i64>,
121 /// Per-term unexcused-absence day limit; `null` = no limit configured.
122 #[schema(example = 20)]
123 max_unexcused_absent_days: Option<i64>,
124 /// The school's IANA timezone; `null` = the deployment default
125 /// (`Europe/Istanbul`), which is what an unset setting reads as. It is the
126 /// zone the absence days are bucketed in.
127 #[schema(example = "Europe/Istanbul")]
128 timezone: Option<String>,
129}
130
131impl SettingsResponse {
132 fn new(settings: &Settings) -> Self {
133 Self {
134 exam_kinds: settings
135 .get_exam_kinds()
136 .iter()
137 .map(|kind| ExamKindDto {
138 name: kind.get_name().to_string(),
139 weight: kind.get_weight(),
140 })
141 .collect(),
142 attendance_statuses: settings.get_attendance_statuses().to_vec(),
143 grade_bands: settings
144 .get_grade_bands()
145 .iter()
146 .map(|band| GradeBandDto {
147 min: band.get_min(),
148 label: band.get_label().to_string(),
149 })
150 .collect(),
151 max_file_bytes: settings.get_max_file_bytes(),
152 chatbot_history_turns: settings.get_chatbot_history_turns(),
153 max_chatbot_threads: settings.get_max_chatbot_threads(),
154 max_chatbot_message_len: settings.get_max_chatbot_message_len(),
155 meal_slots: settings
156 .get_meal_slots()
157 .iter()
158 .map(|slot| MealSlotDto {
159 name: slot.get_name().to_string(),
160 serving_minute: slot.get_serving_minute(),
161 })
162 .collect(),
163 dietary_tags: settings.get_dietary_tags(),
164 meal_cancel_cutoff_minutes: settings.get_meal_cancel_cutoff_minutes(),
165 branches: settings.get_branches(),
166 excuse_kinds: settings.get_excuse_kinds(),
167 max_excused_absent_days: settings.get_max_excused_absent_days(),
168 max_unexcused_absent_days: settings.get_max_unexcused_absent_days(),
169 timezone: settings.timezone.clone(),
170 }
171 }
172}
173
174#[derive(Deserialize, ToSchema)]
175struct UpdateSettings {
176 /// Replaces the whole list when present: 1–20 entries with unique names,
177 /// each name 1–50 characters, each weight `1`–`100`.
178 #[schema(max_items = 20)]
179 exam_kinds: Option<Vec<ExamKindDto>>,
180 /// Replaces the whole list when present; must keep `present`, `absent`,
181 /// `late`, `excused` (the attendance rate is defined over them). Each entry
182 /// is 1–50 characters.
183 #[schema(max_items = 20)]
184 attendance_statuses: Option<Vec<String>>,
185 /// Replaces the whole set when present. `[]` clears the bands (numeric-only
186 /// marks); otherwise mins are unique and one band must start at `0`.
187 #[schema(max_items = 20)]
188 grade_bands: Option<Vec<GradeBandDto>>,
189 /// Per-file size limit for note uploads, in bytes:
190 /// `1024` (1 KiB) – `26214400` (25 MiB). The ceiling is a server hard cap.
191 #[schema(example = 5_242_880, minimum = 1_024, maximum = 26_214_400)]
192 max_file_bytes: Option<i64>,
193 /// How many prior turns of a thread the chatbot is given as context,
194 /// `1`–`50`. Every turn is re-sent on every reply, so this costs tokens.
195 #[schema(example = 10, minimum = 1, maximum = 50)]
196 chatbot_history_turns: Option<i64>,
197 /// How many chatbot threads one user may keep, `1`–`500`. At the cap
198 /// the user deletes an old thread before starting a new one.
199 #[schema(example = 50, minimum = 1, maximum = 500)]
200 max_chatbot_threads: Option<i64>,
201 /// Character limit on one chat message, `100`–`8000`. The ceiling is a
202 /// server hard cap.
203 #[schema(example = 4000, minimum = 100, maximum = 8_000)]
204 max_chatbot_message_len: Option<i64>,
205 /// Replaces the whole list when present: at most 20 entries with unique
206 /// names, each 1–50 characters, each with an optional `serving_minute`
207 /// (minutes past midnight **UTC**, `0`–`1439`) the booking cutoff counts
208 /// back from. `[]` switches the meal program off. A slot a menu was already
209 /// published for cannot be removed (409); its serving time may be edited
210 /// freely and applies live, to menus already published for it too. Names
211 /// must not contain `/ \ ? # %` (a menu's id carries the name into a URL) —
212 /// except a name the school already stores, which stays submittable so a
213 /// list written before that rule can still be edited.
214 #[schema(max_items = 20)]
215 meal_slots: Option<Vec<MealSlotDto>>,
216 /// Replaces the whole list when present: at most 20 unique entries, each
217 /// 1–50 characters. `[]` means the school tracks no dietary tags.
218 #[schema(max_items = 20)]
219 dietary_tags: Option<Vec<String>>,
220 /// Minutes before a slot's `serving_minute` at which booking *and*
221 /// cancelling close, `0`–`10080` (one week). It binds only the slots that
222 /// carry a `serving_minute`: with no serving hour there is no instant to
223 /// count back from, so that slot's menus close at no deadline until the
224 /// hour is set. Omit to keep the current value; send `null` for
225 /// no cutoff at all.
226 #[serde(default, deserialize_with = "set_or_clear")]
227 #[schema(value_type = Option<i64>, example = 120, minimum = 0, maximum = 10_080)]
228 meal_cancel_cutoff_minutes: Option<Option<i64>>,
229 /// Replaces the whole subject list when present: at most 20 entries, each
230 /// 1–50 characters, unique. `[]` means the school keeps no list — and a
231 /// profile's `branch` may then only be cleared, never set.
232 #[schema(max_items = 20, example = json!(["Matematik", "Fizik"]))]
233 branches: Option<Vec<String>>,
234 /// Replaces the whole excuse-kind list when present: at most 20 entries,
235 /// each 1–50 characters, unique. `[]` clears it.
236 #[schema(max_items = 20, example = json!(["raporlu", "izinli"]))]
237 excuse_kinds: Option<Vec<String>>,
238 /// Per-term excused-absence day limit, `0`–`365`. Omit to keep the
239 /// current value; send `null` for no limit at all.
240 #[serde(default, deserialize_with = "set_or_clear")]
241 #[schema(value_type = Option<i64>, example = 10, minimum = 0, maximum = 365)]
242 max_excused_absent_days: Option<Option<i64>>,
243 /// Per-term unexcused-absence day limit, `0`–`365`. Omit to keep the
244 /// current value; send `null` for no limit at all.
245 #[serde(default, deserialize_with = "set_or_clear")]
246 #[schema(value_type = Option<i64>, example = 20, minimum = 0, maximum = 365)]
247 max_unexcused_absent_days: Option<Option<i64>>,
248 /// The school's IANA timezone — one of the deployment's allow-list
249 /// (`Europe/Istanbul`, `UTC`), by name. It is the zone the absence
250 /// days are bucketed in and the one a menu's serving minute is *not*
251 /// (that clock is UTC on purpose). Omit to keep the current value; send
252 /// `null` to fall back to the deployment default.
253 #[serde(default, deserialize_with = "set_or_clear")]
254 #[schema(value_type = Option<String>, example = "Europe/Istanbul")]
255 timezone: Option<Option<String>>,
256}
257
258/// The school's current policy. Any authenticated user — clients need it to
259/// render pickers and grades. Falls back to the built-in defaults until a
260/// manager edits it.
261#[utoipa::path(
262 get,
263 path = "/",
264 tag = "settings",
265 security(("session_cookie" = [])),
266 responses(
267 (status = 200, description = "The school's policy", body = SettingsResponse),
268 (status = 401, description = "Not authenticated", body = ErrorResponse),
269 ),
270)]
271async fn get_settings(
272 State(st): State<AppState>,
273 CurrentUser(_user): CurrentUser,
274) -> Result<Json<SettingsResponse>, AppError> {
275 let settings = service::settings::load(&st.db).await?;
276 Ok(Json(SettingsResponse::new(&settings)))
277}
278
279/// Update the school's policy. Requires manager+. Omitted fields keep their
280/// value; a present field replaces its list wholesale. Existing rows are
281/// untouched — a removed exam kind or status lives on in old records; only
282/// new writes are held to the new lists. Kind weights, though, apply live:
283/// mark reports read them at request time, so editing a weight re-weights
284/// every exam of that kind. For that reason a kind whose exams already carry
285/// marks cannot be dropped from the list (409) — those marks would silently
286/// re-weight to 1; an unmarked kind leaves freely, and an exam whose kind is
287/// gone counts with weight 1 but cannot be graded (409) until the kind
288/// returns — the other end of the same rule. `max_file_bytes` likewise
289/// applies at upload time only — already-stored files keep their size, and the
290/// chatbot knobs apply to the next chat request only. `meal_slots` follows the
291/// exam-kind rule: a slot a menu was already published for cannot be dropped
292/// (409), because the menu snapshotted its name. Slot names must not contain
293/// `/ \ ? # %` (400) — a menu's id carries the name into a URL — but a name
294/// already on the school's stored list is exempt, so a list written before that
295/// rule can still be edited around it.
296#[utoipa::path(
297 patch,
298 path = "/",
299 tag = "settings",
300 security(("session_cookie" = [])),
301 request_body = UpdateSettings,
302 responses(
303 (status = 200, description = "Updated policy", body = SettingsResponse),
304 (status = 400, description = "Invalid lists, bands, file limit, or chat limits", body = ErrorResponse),
305 (status = 401, description = "Not authenticated", body = ErrorResponse),
306 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
307 (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),
308 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
309 ),
310)]
311async fn update_settings(
312 State(st): State<AppState>,
313 RequireManager(_user): RequireManager,
314 Json(req): Json<UpdateSettings>,
315) -> Result<Json<SettingsResponse>, AppError> {
316 // Wire → workflow mapping, nothing more. The lists are deliberately not
317 // validated here: that happens inside the service, in the workflow's own
318 // order, and a stored meal-slot name skips the URL-charset rule — a
319 // decision only the locked edit can make (`MealSlotDef::try_kept`).
320 let patch = service::settings::SettingsPatch {
321 exam_kinds: req.exam_kinds.as_ref().map(|kinds| {
322 kinds
323 .iter()
324 .map(|kind| service::settings::ExamKindInput {
325 name: kind.name.clone(),
326 weight: kind.weight,
327 })
328 .collect()
329 }),
330 attendance_statuses: req.attendance_statuses.clone(),
331 grade_bands: req.grade_bands.as_ref().map(|bands| {
332 bands
333 .iter()
334 .map(|band| service::settings::GradeBandInput {
335 min: band.min,
336 label: band.label.clone(),
337 })
338 .collect()
339 }),
340 max_file_bytes: req.max_file_bytes,
341 chatbot_history_turns: req.chatbot_history_turns,
342 max_chatbot_threads: req.max_chatbot_threads,
343 max_chatbot_message_len: req.max_chatbot_message_len,
344 meal_slots: req.meal_slots.as_ref().map(|slots| {
345 slots
346 .iter()
347 .map(|slot| service::settings::MealSlotInput {
348 name: slot.name.clone(),
349 serving_minute: slot.serving_minute,
350 })
351 .collect()
352 }),
353 dietary_tags: req.dietary_tags.clone(),
354 meal_cancel_cutoff_minutes: req.meal_cancel_cutoff_minutes,
355 branches: req.branches.clone(),
356 excuse_kinds: req.excuse_kinds.clone(),
357 max_excused_absent_days: req.max_excused_absent_days,
358 max_unexcused_absent_days: req.max_unexcused_absent_days,
359 timezone: req.timezone.clone(),
360 };
361 Ok(Json(SettingsResponse::new(
362 &service::settings::apply(&st.db, &patch).await?,
363 )))
364}