hezarfen_backend
Clone
https://git.tahinli.com/archive/hezarfen_backend.git
0 watching·0 forks·Rust·8.3 MiB·6d68754·Ahmet Kaan Gümüş·2 months ago·566 commits
| 1 | //! School-adjustable policy: which exam kinds exist (and how much each |
| 2 | //! weighs in course averages), which attendance statuses the roll call |
| 3 | //! accepts, how numeric marks display as grades, and how large an uploaded |
| 4 | //! note file may be. |
| 5 | //! |
| 6 | //! One singleton record (`settings:school` — one school per deployment). An |
| 7 | //! absent record means "the defaults from `constant.rs`", so a fresh or |
| 8 | //! pre-existing database needs no seeding and behaves exactly as before. The |
| 9 | //! same holds per field: `max_file_bytes` is `option<int>` and reads as the |
| 10 | //! default while unset, so rows saved before the field existed keep working |
| 11 | //! without a backfill (backfills crash boots — `DEFAULT` never rescues |
| 12 | //! existing rows, and `UPDATE` re-validates whole records). |
| 13 | |
| 14 | use serde::{Deserialize, Serialize}; |
| 15 | use sqlx::types::Json; |
| 16 | |
| 17 | use crate::constant::{ |
| 18 | DEFAULT_ATTENDANCE_STATUSES, DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_DIETARY_TAGS, |
| 19 | DEFAULT_EXAM_KINDS, DEFAULT_GRADE_BANDS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, |
| 20 | DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, DEFAULT_MEAL_SLOTS, DEFAULT_TIMEZONE, |
| 21 | MAX_ABSENCE_DAYS, MAX_CHATBOT_HISTORY_TURNS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, |
| 22 | MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_MAX_CHATBOT_MESSAGE_LEN, MAX_MAX_CHATBOT_THREADS, |
| 23 | MAX_MAX_FILE_BYTES, MAX_MEAL_CANCEL_CUTOFF_MINUTES, MAX_MEAL_SERVING_MINUTE, |
| 24 | MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_CHATBOT_HISTORY_TURNS, MIN_EXAM_KIND_WEIGHT, |
| 25 | MIN_MARK, MIN_MAX_CHATBOT_MESSAGE_LEN, MIN_MAX_CHATBOT_THREADS, MIN_MAX_FILE_BYTES, TIMEZONES, |
| 26 | }; |
| 27 | use crate::domain::text_fold; |
| 28 | use crate::error::ValidationError; |
| 29 | |
| 30 | /// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight: |
| 31 | /// how many times an exam of that kind counts into its course's average. |
| 32 | /// Weight lives here, not on the exam — reweighting a kind reweights every |
| 33 | /// exam of that kind at once. |
| 34 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 35 | pub struct ExamKindDef { |
| 36 | name: String, |
| 37 | weight: i64, |
| 38 | } |
| 39 | |
| 40 | impl ExamKindDef { |
| 41 | pub fn try_new(name: &str, weight: i64) -> Result<Self, ValidationError> { |
| 42 | let name = name.trim(); |
| 43 | if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { |
| 44 | return Err(ValidationError::Invalid { |
| 45 | field: "exam_kinds", |
| 46 | reason: "kind names must be 1 to 50 characters", |
| 47 | }); |
| 48 | } |
| 49 | if !(MIN_EXAM_KIND_WEIGHT..=MAX_EXAM_KIND_WEIGHT).contains(&weight) { |
| 50 | return Err(ValidationError::Invalid { |
| 51 | field: "exam_kinds", |
| 52 | reason: "kind weights must be between 1 and 100", |
| 53 | }); |
| 54 | } |
| 55 | Ok(Self { |
| 56 | name: name.to_string(), |
| 57 | weight, |
| 58 | }) |
| 59 | } |
| 60 | |
| 61 | pub fn get_name(&self) -> &str { |
| 62 | &self.name |
| 63 | } |
| 64 | |
| 65 | pub fn get_weight(&self) -> i64 { |
| 66 | self.weight |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// One meal slot the school serves (`"lunch"`, `"snack"`, …). A published menu |
| 71 | /// snapshots the slot's *name* as text, so retiring a slot never rewrites a |
| 72 | /// past menu — same contract exam kinds have with exams. An object, not a bare |
| 73 | /// string, which is what let the serving time land here without a migration. |
| 74 | /// |
| 75 | /// `serving_minute` is minutes past midnight **UTC** on the menu's date, and |
| 76 | /// it is what the booking/cancel cutoff counts back from. The backend stores |
| 77 | /// no school timezone (deliberately), so staff enter UTC: a UTC+3 school sets |
| 78 | /// `540` (09:00) for a meal served at noon locally. `None` — every slot |
| 79 | /// written before the field existed — falls back to midnight UTC, the old |
| 80 | /// behaviour. |
| 81 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 82 | pub struct MealSlotDef { |
| 83 | name: String, |
| 84 | serving_minute: Option<i64>, |
| 85 | } |
| 86 | |
| 87 | impl MealSlotDef { |
| 88 | pub fn try_new(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> { |
| 89 | Self::build(name, serving_minute, false) |
| 90 | } |
| 91 | |
| 92 | /// [`Self::try_new`] for a name the stored list *already* carries. |
| 93 | /// |
| 94 | /// The URL-safety rule below is younger than the lists it validates, and |
| 95 | /// `PATCH /settings` re-validates the whole submitted list — so a school |
| 96 | /// that stored a slot named `a/b` before the rule existed could never edit |
| 97 | /// `meal_slots` again: re-sending the name is a 400, and dropping it is a |
| 98 | /// 409 the moment a menu was published under it. Grandfathering a name the |
| 99 | /// row already holds unwedges the rest of the list while leaving the rule |
| 100 | /// in full force for every *new* name — the stored one is exactly as |
| 101 | /// unusable as it already was, and dropping it stays the only way out. |
| 102 | pub fn try_kept(name: &str, serving_minute: Option<i64>) -> Result<Self, ValidationError> { |
| 103 | Self::build(name, serving_minute, true) |
| 104 | } |
| 105 | |
| 106 | fn build(name: &str, serving_minute: Option<i64>, kept: bool) -> Result<Self, ValidationError> { |
| 107 | let name = name.trim(); |
| 108 | if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { |
| 109 | return Err(ValidationError::Invalid { |
| 110 | field: "meal_slots", |
| 111 | reason: "slot names must be 1 to 50 characters", |
| 112 | }); |
| 113 | } |
| 114 | // The name goes verbatim into a menu's record id, and that id is a URL |
| 115 | // path segment: a slot named `a/b` would define a slot no menu can ever |
| 116 | // be published under (`MenuSlot::try_new` refuses the same characters, |
| 117 | // at the one place a name becomes an id). Refusing it here too is what |
| 118 | // keeps the settings from offering a slot the canteen cannot use. |
| 119 | if !kept |
| 120 | && name |
| 121 | .chars() |
| 122 | .any(|c| matches!(c, '/' | '\\' | '?' | '#' | '%')) |
| 123 | { |
| 124 | return Err(ValidationError::Invalid { |
| 125 | field: "meal_slots", |
| 126 | reason: "meal slot names used for menus must not contain / \\ ? # or %", |
| 127 | }); |
| 128 | } |
| 129 | if let Some(minute) = serving_minute { |
| 130 | in_range( |
| 131 | "meal_slots", |
| 132 | minute, |
| 133 | 0..=MAX_MEAL_SERVING_MINUTE, |
| 134 | "serving minutes must be between 0 (00:00 UTC) and 1439 (23:59 UTC)", |
| 135 | )?; |
| 136 | } |
| 137 | Ok(Self { |
| 138 | name: name.to_string(), |
| 139 | serving_minute, |
| 140 | }) |
| 141 | } |
| 142 | |
| 143 | pub fn get_name(&self) -> &str { |
| 144 | &self.name |
| 145 | } |
| 146 | |
| 147 | /// Minutes past midnight UTC at which this slot is served; `None` = unset, |
| 148 | /// so the cutoff counts back from midnight UTC instead. |
| 149 | pub fn get_serving_minute(&self) -> Option<i64> { |
| 150 | self.serving_minute |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// One grade-display band: marks at or above `min` (and below the next band's |
| 155 | /// `min`) render as `label`. Display only — storage and averaging stay numeric. |
| 156 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 157 | pub struct GradeBand { |
| 158 | min: i64, |
| 159 | label: String, |
| 160 | } |
| 161 | |
| 162 | impl GradeBand { |
| 163 | pub fn try_new(min: i64, label: &str) -> Result<Self, ValidationError> { |
| 164 | if !(MIN_MARK..=MAX_MARK).contains(&min) { |
| 165 | return Err(ValidationError::Invalid { |
| 166 | field: "grade_bands", |
| 167 | reason: "band mins must be between 0 and 100", |
| 168 | }); |
| 169 | } |
| 170 | let label = label.trim(); |
| 171 | if label.is_empty() || label.chars().count() > MAX_GRADE_LABEL_LEN { |
| 172 | return Err(ValidationError::Invalid { |
| 173 | field: "grade_bands", |
| 174 | reason: "band labels must be 1 to 20 characters", |
| 175 | }); |
| 176 | } |
| 177 | Ok(Self { |
| 178 | min, |
| 179 | label: label.to_string(), |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | pub fn get_min(&self) -> i64 { |
| 184 | self.min |
| 185 | } |
| 186 | |
| 187 | pub fn get_label(&self) -> &str { |
| 188 | &self.label |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// The school's policy knobs, validated as a whole (parse, don't validate — |
| 193 | /// like every other entity, an existing `Settings` is always internally |
| 194 | /// consistent). Fields are crate-visible because [`crate::db::settings`] |
| 195 | /// binds them directly in the compare-and-set guard. |
| 196 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 197 | pub struct Settings { |
| 198 | pub(crate) exam_kinds: Json<Vec<ExamKindDef>>, |
| 199 | pub(crate) attendance_statuses: Vec<String>, |
| 200 | pub(crate) grade_bands: Json<Vec<GradeBand>>, |
| 201 | /// Per-file byte cap for note uploads. `None` = the row predates the |
| 202 | /// field (or the defaults) — reads as `DEFAULT_MAX_FILE_BYTES`. |
| 203 | pub(crate) max_file_bytes: Option<i64>, |
| 204 | /// Chatbot knobs, `None`-while-unset exactly like `max_file_bytes`. |
| 205 | pub(crate) chatbot_history_turns: Option<i64>, |
| 206 | pub(crate) max_chatbot_threads: Option<i64>, |
| 207 | pub(crate) max_chatbot_message_len: Option<i64>, |
| 208 | /// Food-program knobs. `None`-while-unset exactly like `max_file_bytes` — |
| 209 | /// the columns are `option<…>`, never `DEFAULT []`: `save_if_unchanged` |
| 210 | /// writes the whole row, so a field this struct did not carry would coerce |
| 211 | /// to `NONE` and abort the transaction. |
| 212 | pub(crate) meal_slots: Option<Json<Vec<MealSlotDef>>>, |
| 213 | pub(crate) dietary_tags: Option<Vec<String>>, |
| 214 | /// Minutes before a meal at which booking *and* cancelling close. One knob |
| 215 | /// for both deadlines; `None` = no cutoff at all, which is also what an |
| 216 | /// unset column reads as. |
| 217 | pub(crate) meal_cancel_cutoff_minutes: Option<i64>, |
| 218 | /// Teacher branch lists (D6): the school's subject specialisations a |
| 219 | /// teacher profile may name. `None`-while-unset; an empty list is legal |
| 220 | /// (a school that never configured one). |
| 221 | pub(crate) branches: Option<Json<Vec<String>>>, |
| 222 | /// What an absence may be excused as (with a report / on leave / …): the |
| 223 | /// vocabulary pointed at by an excused roll-call row. `None`-while-unset, |
| 224 | /// like `branches`. |
| 225 | pub(crate) excuse_kinds: Option<Json<Vec<String>>>, |
| 226 | /// Absence policy (D7): the per-term excused/unexcused day limits a student |
| 227 | /// may exceed. `None` = no limit configured. |
| 228 | pub(crate) max_excused_absent_days: Option<i64>, |
| 229 | pub(crate) max_unexcused_absent_days: Option<i64>, |
| 230 | /// The school's IANA timezone, used to bucket attendance days. `None` |
| 231 | /// reads as [`crate::constant::DEFAULT_TIMEZONE`]. |
| 232 | pub(crate) timezone: Option<String>, |
| 233 | } |
| 234 | |
| 235 | /// Everything [`Settings::try_new`] validates, in one struct — the knobs |
| 236 | /// outgrew a readable argument list. Take a resolved snapshot with |
| 237 | /// [`Settings::params`] and overwrite only the fields being changed; that is |
| 238 | /// exactly what `PATCH /settings` merges. |
| 239 | pub struct SettingsParams { |
| 240 | pub exam_kinds: Vec<ExamKindDef>, |
| 241 | pub attendance_statuses: Vec<String>, |
| 242 | pub grade_bands: Vec<GradeBand>, |
| 243 | pub max_file_bytes: i64, |
| 244 | pub chatbot_history_turns: i64, |
| 245 | pub max_chatbot_threads: i64, |
| 246 | pub max_chatbot_message_len: i64, |
| 247 | pub meal_slots: Vec<MealSlotDef>, |
| 248 | pub dietary_tags: Vec<String>, |
| 249 | /// `None` = no booking/cancel cutoff. |
| 250 | pub meal_cancel_cutoff_minutes: Option<i64>, |
| 251 | pub branches: Vec<String>, |
| 252 | pub excuse_kinds: Vec<String>, |
| 253 | /// `None` = no limit configured. |
| 254 | pub max_excused_absent_days: Option<i64>, |
| 255 | pub max_unexcused_absent_days: Option<i64>, |
| 256 | /// `None` = the deployment default timezone. |
| 257 | pub timezone: Option<String>, |
| 258 | } |
| 259 | |
| 260 | impl Settings { |
| 261 | /// The out-of-the-box policy — mirrors the constants that were previously |
| 262 | /// hard-coded, so a school that never touches `/settings` sees no change. |
| 263 | pub fn defaults() -> Self { |
| 264 | Self { |
| 265 | exam_kinds: Json( |
| 266 | DEFAULT_EXAM_KINDS |
| 267 | .map(|(name, weight)| ExamKindDef { |
| 268 | name: name.to_string(), |
| 269 | weight, |
| 270 | }) |
| 271 | .to_vec(), |
| 272 | ), |
| 273 | attendance_statuses: { |
| 274 | let mut statuses = DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(); |
| 275 | statuses.sort(); |
| 276 | statuses |
| 277 | }, |
| 278 | grade_bands: Json( |
| 279 | DEFAULT_GRADE_BANDS |
| 280 | .map(|(min, label)| GradeBand { |
| 281 | min, |
| 282 | label: label.to_string(), |
| 283 | }) |
| 284 | .to_vec(), |
| 285 | ), |
| 286 | max_file_bytes: None, |
| 287 | chatbot_history_turns: None, |
| 288 | max_chatbot_threads: None, |
| 289 | max_chatbot_message_len: None, |
| 290 | meal_slots: None, |
| 291 | dietary_tags: None, |
| 292 | meal_cancel_cutoff_minutes: None, |
| 293 | branches: None, |
| 294 | excuse_kinds: None, |
| 295 | max_excused_absent_days: None, |
| 296 | max_unexcused_absent_days: None, |
| 297 | timezone: None, |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | /// This policy as editable parameters, every optional knob resolved to the |
| 302 | /// value it currently reads as. |
| 303 | pub fn params(&self) -> SettingsParams { |
| 304 | SettingsParams { |
| 305 | exam_kinds: self.exam_kinds.0.clone(), |
| 306 | attendance_statuses: self.attendance_statuses.clone(), |
| 307 | grade_bands: self.grade_bands.0.clone(), |
| 308 | max_file_bytes: self.get_max_file_bytes(), |
| 309 | chatbot_history_turns: self.get_chatbot_history_turns(), |
| 310 | max_chatbot_threads: self.get_max_chatbot_threads(), |
| 311 | max_chatbot_message_len: self.get_max_chatbot_message_len(), |
| 312 | meal_slots: self.get_meal_slots(), |
| 313 | dietary_tags: self.get_dietary_tags(), |
| 314 | meal_cancel_cutoff_minutes: self.meal_cancel_cutoff_minutes, |
| 315 | branches: self.get_branches(), |
| 316 | excuse_kinds: self.get_excuse_kinds(), |
| 317 | max_excused_absent_days: self.max_excused_absent_days, |
| 318 | max_unexcused_absent_days: self.max_unexcused_absent_days, |
| 319 | timezone: self.timezone.clone(), |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | /// Validate a full policy. List entries are trimmed; kinds and statuses |
| 324 | /// must be non-empty, unique (folded: case- and Turkish-insensitive), and bounded; the four |
| 325 | /// core attendance statuses can never be removed (the attendance rate's |
| 326 | /// semantics are defined over them). Bands may be empty (numeric-only |
| 327 | /// display), otherwise their mins are unique and one band must start at 0 |
| 328 | /// so every mark maps to a label. The upload cap must sit inside the |
| 329 | /// server's hard bounds — the ceiling protects memory and disk, whatever |
| 330 | /// the school would prefer, and the same holds for the chatbot knobs. |
| 331 | pub fn try_new(params: SettingsParams) -> Result<Self, ValidationError> { |
| 332 | let SettingsParams { |
| 333 | exam_kinds, |
| 334 | attendance_statuses, |
| 335 | grade_bands, |
| 336 | max_file_bytes, |
| 337 | chatbot_history_turns, |
| 338 | max_chatbot_threads, |
| 339 | max_chatbot_message_len, |
| 340 | meal_slots, |
| 341 | dietary_tags, |
| 342 | meal_cancel_cutoff_minutes, |
| 343 | branches, |
| 344 | excuse_kinds, |
| 345 | max_excused_absent_days, |
| 346 | max_unexcused_absent_days, |
| 347 | timezone, |
| 348 | } = params; |
| 349 | in_range( |
| 350 | "max_file_bytes", |
| 351 | max_file_bytes, |
| 352 | MIN_MAX_FILE_BYTES..=MAX_MAX_FILE_BYTES, |
| 353 | "must be between 1024 (1 KiB) and 26214400 (25 MiB)", |
| 354 | )?; |
| 355 | in_range( |
| 356 | "chatbot_history_turns", |
| 357 | chatbot_history_turns, |
| 358 | MIN_CHATBOT_HISTORY_TURNS..=MAX_CHATBOT_HISTORY_TURNS, |
| 359 | "must be between 1 and 50", |
| 360 | )?; |
| 361 | in_range( |
| 362 | "max_chatbot_threads", |
| 363 | max_chatbot_threads, |
| 364 | MIN_MAX_CHATBOT_THREADS..=MAX_MAX_CHATBOT_THREADS, |
| 365 | "must be between 1 and 500", |
| 366 | )?; |
| 367 | in_range( |
| 368 | "max_chatbot_message_len", |
| 369 | max_chatbot_message_len, |
| 370 | MIN_MAX_CHATBOT_MESSAGE_LEN..=MAX_MAX_CHATBOT_MESSAGE_LEN, |
| 371 | "must be between 100 and 8000 characters", |
| 372 | )?; |
| 373 | // Per-entry rules (name shape, weight range) hold structurally on any |
| 374 | // `ExamKindDef`; here only the list-level rules need checking. |
| 375 | let names: Vec<String> = exam_kinds |
| 376 | .iter() |
| 377 | .map(|kind| kind.get_name().to_string()) |
| 378 | .collect(); |
| 379 | validate_list("exam_kinds", names)?; |
| 380 | let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?; |
| 381 | if DEFAULT_ATTENDANCE_STATUSES |
| 382 | .iter() |
| 383 | .any(|core| !attendance_statuses.iter().any(|s| s == core)) |
| 384 | { |
| 385 | return Err(ValidationError::Invalid { |
| 386 | field: "attendance_statuses", |
| 387 | reason: "must keep the core statuses: present, absent, late, excused", |
| 388 | }); |
| 389 | } |
| 390 | |
| 391 | if grade_bands.len() > MAX_GRADE_BANDS { |
| 392 | return Err(ValidationError::Invalid { |
| 393 | field: "grade_bands", |
| 394 | reason: "must contain at most 20 bands", |
| 395 | }); |
| 396 | } |
| 397 | let mut mins: Vec<i64> = grade_bands.iter().map(GradeBand::get_min).collect(); |
| 398 | mins.sort_unstable(); |
| 399 | mins.dedup(); |
| 400 | if mins.len() != grade_bands.len() { |
| 401 | return Err(ValidationError::Invalid { |
| 402 | field: "grade_bands", |
| 403 | reason: "band mins must be unique", |
| 404 | }); |
| 405 | } |
| 406 | if !grade_bands.is_empty() && !mins.contains(&MIN_MARK) { |
| 407 | return Err(ValidationError::Invalid { |
| 408 | field: "grade_bands", |
| 409 | reason: "one band must start at 0 so every mark gets a label", |
| 410 | }); |
| 411 | } |
| 412 | // Canonical order: highest band first, matching lookup direction. |
| 413 | let mut grade_bands = grade_bands; |
| 414 | grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min())); |
| 415 | |
| 416 | // The food lists follow the same list rules as the kinds and statuses |
| 417 | // above, with one difference: empty is legal on both. A school that |
| 418 | // runs no canteen has no slots and no dietary tags, and refusing that |
| 419 | // would force it to keep a list it never uses. |
| 420 | let slot_names: Vec<String> = meal_slots |
| 421 | .iter() |
| 422 | .map(|slot| slot.get_name().to_string()) |
| 423 | .collect(); |
| 424 | if !slot_names.is_empty() { |
| 425 | validate_list("meal_slots", slot_names)?; |
| 426 | } |
| 427 | let dietary_tags = if dietary_tags.is_empty() { |
| 428 | dietary_tags |
| 429 | } else { |
| 430 | validate_list("dietary_tags", dietary_tags)? |
| 431 | }; |
| 432 | // One knob for both deadlines: 0 = closes exactly at serving time. |
| 433 | if let Some(minutes) = meal_cancel_cutoff_minutes { |
| 434 | in_range( |
| 435 | "meal_cancel_cutoff_minutes", |
| 436 | minutes, |
| 437 | 0..=MAX_MEAL_CANCEL_CUTOFF_MINUTES, |
| 438 | "must be between 0 and 10080 (one week) minutes", |
| 439 | )?; |
| 440 | } |
| 441 | |
| 442 | // Branch and excuse-kind lists follow the same rules as the kinds and |
| 443 | // statuses above, but empty is legal on both — a school that never |
| 444 | // configured either is not forced to invent one. |
| 445 | let branches = if branches.is_empty() { |
| 446 | branches |
| 447 | } else { |
| 448 | validate_list("branches", branches)? |
| 449 | }; |
| 450 | let excuse_kinds = if excuse_kinds.is_empty() { |
| 451 | excuse_kinds |
| 452 | } else { |
| 453 | validate_list("excuse_kinds", excuse_kinds)? |
| 454 | }; |
| 455 | for (field, value) in [ |
| 456 | ("max_excused_absent_days", max_excused_absent_days), |
| 457 | ("max_unexcused_absent_days", max_unexcused_absent_days), |
| 458 | ] { |
| 459 | if let Some(days) = value { |
| 460 | in_range( |
| 461 | field, |
| 462 | days, |
| 463 | 0..=MAX_ABSENCE_DAYS, |
| 464 | "must be between 0 and 365 days", |
| 465 | )?; |
| 466 | } |
| 467 | } |
| 468 | if let Some(tz) = timezone.as_deref() |
| 469 | && !TIMEZONES.contains(&tz) |
| 470 | { |
| 471 | return Err(ValidationError::Invalid { |
| 472 | field: "timezone", |
| 473 | reason: "is not a supported timezone (see GET /limits)", |
| 474 | }); |
| 475 | } |
| 476 | |
| 477 | Ok(Self { |
| 478 | exam_kinds: Json(exam_kinds), |
| 479 | attendance_statuses, |
| 480 | grade_bands: Json(grade_bands), |
| 481 | max_file_bytes: Some(max_file_bytes), |
| 482 | chatbot_history_turns: Some(chatbot_history_turns), |
| 483 | max_chatbot_threads: Some(max_chatbot_threads), |
| 484 | max_chatbot_message_len: Some(max_chatbot_message_len), |
| 485 | meal_slots: Some(Json(meal_slots)), |
| 486 | dietary_tags: Some(dietary_tags), |
| 487 | meal_cancel_cutoff_minutes, |
| 488 | branches: Some(Json(branches)), |
| 489 | excuse_kinds: Some(Json(excuse_kinds)), |
| 490 | max_excused_absent_days, |
| 491 | max_unexcused_absent_days, |
| 492 | timezone, |
| 493 | }) |
| 494 | } |
| 495 | |
| 496 | pub fn get_exam_kinds(&self) -> &[ExamKindDef] { |
| 497 | &self.exam_kinds.0 |
| 498 | } |
| 499 | |
| 500 | /// The weight of the kind named `kind` (exact match, like kind |
| 501 | /// validation), or `None` when the school no longer lists it. Callers |
| 502 | /// averaging marks fall back to weight 1 — an exam keeps its retired kind |
| 503 | /// (settings edits never rewrite history), so it must still count. |
| 504 | pub fn exam_kind_weight(&self, kind: &str) -> Option<i64> { |
| 505 | self.exam_kinds |
| 506 | .0 |
| 507 | .iter() |
| 508 | .find(|def| def.get_name() == kind) |
| 509 | .map(ExamKindDef::get_weight) |
| 510 | } |
| 511 | |
| 512 | pub fn get_attendance_statuses(&self) -> &[String] { |
| 513 | &self.attendance_statuses |
| 514 | } |
| 515 | |
| 516 | pub fn get_grade_bands(&self) -> &[GradeBand] { |
| 517 | &self.grade_bands.0 |
| 518 | } |
| 519 | |
| 520 | /// The per-file upload cap in bytes; the built-in default while the |
| 521 | /// school never set one (including rows saved before the field existed). |
| 522 | pub fn get_max_file_bytes(&self) -> i64 { |
| 523 | self.max_file_bytes.unwrap_or(DEFAULT_MAX_FILE_BYTES) |
| 524 | } |
| 525 | |
| 526 | /// How many prior thread turns ride along as context on an AI |
| 527 | /// request; the built-in default while the school never set one. |
| 528 | pub fn get_chatbot_history_turns(&self) -> i64 { |
| 529 | self.chatbot_history_turns |
| 530 | .unwrap_or(DEFAULT_CHATBOT_HISTORY_TURNS) |
| 531 | } |
| 532 | |
| 533 | /// How many threads one user may keep; the built-in default while |
| 534 | /// the school never set one. |
| 535 | pub fn get_max_chatbot_threads(&self) -> i64 { |
| 536 | self.max_chatbot_threads |
| 537 | .unwrap_or(DEFAULT_MAX_CHATBOT_THREADS) |
| 538 | } |
| 539 | |
| 540 | /// Character cap on one chat message; the built-in default while the |
| 541 | /// school never set one. |
| 542 | pub fn get_max_chatbot_message_len(&self) -> i64 { |
| 543 | self.max_chatbot_message_len |
| 544 | .unwrap_or(DEFAULT_MAX_CHATBOT_MESSAGE_LEN) |
| 545 | } |
| 546 | |
| 547 | /// The meal slots the school serves; the built-in list while it never set |
| 548 | /// one (including rows saved before the field existed). An explicitly |
| 549 | /// stored empty list stays empty — that is "no meal program", not "unset". |
| 550 | pub fn get_meal_slots(&self) -> Vec<MealSlotDef> { |
| 551 | self.meal_slots |
| 552 | .as_ref() |
| 553 | .map(|slots| slots.0.clone()) |
| 554 | .unwrap_or_else(|| { |
| 555 | DEFAULT_MEAL_SLOTS |
| 556 | .map(|name| MealSlotDef { |
| 557 | name: name.to_string(), |
| 558 | // No built-in serving time, and the backend will not guess |
| 559 | // one: a slot with no hour has no instant for the cutoff to |
| 560 | // count back from, so the school's `meal_cancel_cutoff_ |
| 561 | // minutes` binds none of these slots until it sets real |
| 562 | // hours (see `check_cutoff`). |
| 563 | serving_minute: None, |
| 564 | }) |
| 565 | .to_vec() |
| 566 | }) |
| 567 | } |
| 568 | |
| 569 | /// The dietary tags a dish and a student's profile may carry; the built-in |
| 570 | /// list while the school never set one. |
| 571 | pub fn get_dietary_tags(&self) -> Vec<String> { |
| 572 | self.dietary_tags |
| 573 | .clone() |
| 574 | .unwrap_or_else(|| DEFAULT_DIETARY_TAGS.map(String::from).to_vec()) |
| 575 | } |
| 576 | |
| 577 | /// Minutes before a meal at which booking and cancelling close; `None` = |
| 578 | /// no cutoff, the default while the school never set one. |
| 579 | pub fn get_meal_cancel_cutoff_minutes(&self) -> Option<i64> { |
| 580 | self.meal_cancel_cutoff_minutes |
| 581 | } |
| 582 | |
| 583 | /// The branch (subject specialisation) vocabulary a teacher profile may |
| 584 | /// name; empty while the school never configured one. |
| 585 | pub fn get_branches(&self) -> Vec<String> { |
| 586 | self.branches |
| 587 | .as_ref() |
| 588 | .map(|list| list.0.clone()) |
| 589 | .unwrap_or_default() |
| 590 | } |
| 591 | |
| 592 | /// The excuse-kind vocabulary an excused absence may name; empty while the |
| 593 | /// school never configured one. |
| 594 | pub fn get_excuse_kinds(&self) -> Vec<String> { |
| 595 | self.excuse_kinds |
| 596 | .as_ref() |
| 597 | .map(|list| list.0.clone()) |
| 598 | .unwrap_or_default() |
| 599 | } |
| 600 | |
| 601 | /// The per-term excused-absence day limit; `None` = no limit configured. |
| 602 | pub fn get_max_excused_absent_days(&self) -> Option<i64> { |
| 603 | self.max_excused_absent_days |
| 604 | } |
| 605 | |
| 606 | /// The per-term unexcused-absence day limit; `None` = no limit configured. |
| 607 | pub fn get_max_unexcused_absent_days(&self) -> Option<i64> { |
| 608 | self.max_unexcused_absent_days |
| 609 | } |
| 610 | |
| 611 | /// The school's IANA timezone; the deployment default while unset. |
| 612 | pub fn get_timezone(&self) -> &str { |
| 613 | self.timezone.as_deref().unwrap_or(DEFAULT_TIMEZONE) |
| 614 | } |
| 615 | |
| 616 | /// The label of the band `mark` falls into: the band with the greatest |
| 617 | /// `min` at or below it. `None` when no bands are configured. Takes an |
| 618 | /// `f64` so course averages label the same way plain marks do. |
| 619 | pub fn grade_label(&self, mark: f64) -> Option<&str> { |
| 620 | self.grade_bands |
| 621 | .0 |
| 622 | .iter() |
| 623 | .filter(|band| band.get_min() as f64 <= mark) |
| 624 | .max_by_key(|band| band.get_min()) |
| 625 | .map(GradeBand::get_label) |
| 626 | } |
| 627 | } |
| 628 | |
| 629 | /// Shared bounds check for the numeric knobs (upload cap, chatbot limits): |
| 630 | /// each is held to a server-defined inclusive range. |
| 631 | fn in_range( |
| 632 | field: &'static str, |
| 633 | value: i64, |
| 634 | range: std::ops::RangeInclusive<i64>, |
| 635 | reason: &'static str, |
| 636 | ) -> Result<(), ValidationError> { |
| 637 | if range.contains(&value) { |
| 638 | Ok(()) |
| 639 | } else { |
| 640 | Err(ValidationError::Invalid { field, reason }) |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | /// Shared rules for the editable string lists: 1–20 trimmed, non-empty, |
| 645 | /// ≤50-char entries with no case-insensitive duplicates. |
| 646 | fn validate_list(field: &'static str, values: Vec<String>) -> Result<Vec<String>, ValidationError> { |
| 647 | if values.is_empty() { |
| 648 | return Err(ValidationError::Empty(field)); |
| 649 | } |
| 650 | if values.len() > MAX_SETTINGS_LIST_LEN { |
| 651 | return Err(ValidationError::Invalid { |
| 652 | field, |
| 653 | reason: "must contain at most 20 entries", |
| 654 | }); |
| 655 | } |
| 656 | let mut trimmed = Vec::with_capacity(values.len()); |
| 657 | for value in &values { |
| 658 | let value = value.trim(); |
| 659 | if value.is_empty() || value.chars().count() > MAX_SETTINGS_ITEM_LEN { |
| 660 | return Err(ValidationError::Invalid { |
| 661 | field, |
| 662 | reason: "entries must be 1 to 50 characters", |
| 663 | }); |
| 664 | } |
| 665 | trimmed.push(value.to_string()); |
| 666 | } |
| 667 | // `to_lowercase` is locale-invariant — `İZİN` lowercases to `i̇zin` (with a |
| 668 | // leftover combining dot) and would slip past `izin` as a distinct entry. |
| 669 | // The *identity* fold, not search's: search deliberately collapses `ü`→`u`, |
| 670 | // which would make a school unable to have both `tur` and `tür`. |
| 671 | let mut folded: Vec<String> = trimmed.iter().map(|v| text_fold::case_fold_tr(v)).collect(); |
| 672 | folded.sort_unstable(); |
| 673 | folded.dedup(); |
| 674 | if folded.len() != trimmed.len() { |
| 675 | return Err(ValidationError::Invalid { |
| 676 | field, |
| 677 | reason: "two entries are the same word apart from upper/lower case \ |
| 678 | or Turkish letters — keep only one of them", |
| 679 | }); |
| 680 | } |
| 681 | Ok(trimmed) |
| 682 | } |
| 683 | |
| 684 | #[cfg(test)] |
| 685 | mod tests { |
| 686 | use super::*; |
| 687 | use crate::constant::MAX_CHATBOT_MESSAGE_LEN; |
| 688 | |
| 689 | fn kinds(list: &[&str]) -> Vec<ExamKindDef> { |
| 690 | list.iter() |
| 691 | .map(|s| ExamKindDef::try_new(s, 1).unwrap()) |
| 692 | .collect() |
| 693 | } |
| 694 | |
| 695 | fn names(settings: &Settings) -> Vec<&str> { |
| 696 | settings |
| 697 | .get_exam_kinds() |
| 698 | .iter() |
| 699 | .map(ExamKindDef::get_name) |
| 700 | .collect() |
| 701 | } |
| 702 | |
| 703 | /// The defaults as tweakable params — every site below overrides only the |
| 704 | /// fields it is testing (`..params()`). |
| 705 | fn params() -> SettingsParams { |
| 706 | Settings::defaults().params() |
| 707 | } |
| 708 | |
| 709 | fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> { |
| 710 | list.iter() |
| 711 | .map(|(min, label)| GradeBand::try_new(*min, label).unwrap()) |
| 712 | .collect() |
| 713 | } |
| 714 | |
| 715 | #[tokio::test] |
| 716 | async fn defaults_are_a_valid_policy() { |
| 717 | let defaults = Settings::defaults(); |
| 718 | let rebuilt = Settings::try_new(defaults.params()).unwrap(); |
| 719 | assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); |
| 720 | // The Turkish 5-point scale ships by default, so a mark always labels. |
| 721 | assert_eq!(defaults.get_grade_bands().len(), DEFAULT_GRADE_BANDS.len()); |
| 722 | assert_eq!(defaults.grade_label(90.0), Some("5")); |
| 723 | assert_eq!(defaults.grade_label(0.0), Some("1")); |
| 724 | } |
| 725 | |
| 726 | #[tokio::test] |
| 727 | async fn kind_defs_hold_name_and_weight_rules() { |
| 728 | // Names are trimmed; blank or over-long names die. |
| 729 | assert_eq!( |
| 730 | ExamKindDef::try_new(" lab ", 1).unwrap().get_name(), |
| 731 | "lab" |
| 732 | ); |
| 733 | assert!(ExamKindDef::try_new(" ", 1).is_err()); |
| 734 | assert!(ExamKindDef::try_new(&"x".repeat(51), 1).is_err()); |
| 735 | // Weights are held to 1–100 — 0 would erase the kind's exams from the |
| 736 | // average, and negatives would corrupt it. |
| 737 | for weight in [1, 50, 100] { |
| 738 | assert_eq!( |
| 739 | ExamKindDef::try_new("oral", weight).unwrap().get_weight(), |
| 740 | weight |
| 741 | ); |
| 742 | } |
| 743 | assert!(ExamKindDef::try_new("oral", 0).is_err()); |
| 744 | assert!(ExamKindDef::try_new("oral", -1).is_err()); |
| 745 | assert!(ExamKindDef::try_new("oral", 101).is_err()); |
| 746 | } |
| 747 | |
| 748 | #[tokio::test] |
| 749 | async fn lists_are_bounded_and_deduped() { |
| 750 | let with_kinds = |exam_kinds| { |
| 751 | Settings::try_new(SettingsParams { |
| 752 | exam_kinds, |
| 753 | ..params() |
| 754 | }) |
| 755 | }; |
| 756 | let s = with_kinds(kinds(&["lab", "quiz"])).unwrap(); |
| 757 | assert_eq!(names(&s), ["lab", "quiz"]); |
| 758 | // Empty list and case-insensitive duplicate names are rejected. |
| 759 | assert!(with_kinds(vec![]).is_err()); |
| 760 | assert!(with_kinds(kinds(&["Lab", "lab"])).is_err()); |
| 761 | let too_many: Vec<ExamKindDef> = (0..21) |
| 762 | .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap()) |
| 763 | .collect(); |
| 764 | assert!(with_kinds(too_many).is_err()); |
| 765 | } |
| 766 | |
| 767 | /// Rust's `to_lowercase` is locale-invariant: `İZİN` becomes `i̇zin` (with a |
| 768 | /// combining dot above), which never equals `izin`, so both spellings of |
| 769 | /// the same word used to land in one list. Teachers type these by hand in |
| 770 | /// Turkish, which is exactly when it happens. |
| 771 | #[tokio::test] |
| 772 | async fn turkish_casing_is_a_duplicate() { |
| 773 | let with_kinds = |exam_kinds| { |
| 774 | Settings::try_new(SettingsParams { |
| 775 | exam_kinds, |
| 776 | ..params() |
| 777 | }) |
| 778 | }; |
| 779 | assert!(with_kinds(kinds(&["İZİN", "izin"])).is_err()); |
| 780 | assert!(with_kinds(kinds(&["SINAV", "sınav"])).is_err()); |
| 781 | // Plain English duplicates still die, genuinely distinct entries live. |
| 782 | assert!(with_kinds(kinds(&["Lab", "LAB"])).is_err()); |
| 783 | assert!(with_kinds(kinds(&["izin", "sınav", "lab"])).is_ok()); |
| 784 | // Same rule on the other guarded list. |
| 785 | assert!( |
| 786 | Settings::try_new(SettingsParams { |
| 787 | attendance_statuses: statuses_with(&["İZİN", "izin"]), |
| 788 | ..params() |
| 789 | }) |
| 790 | .is_err() |
| 791 | ); |
| 792 | } |
| 793 | |
| 794 | /// Dedup folds *case*, not letters. The search fold collapses `ü`→`u`, so |
| 795 | /// using it here made genuinely distinct Turkish words un-listable: a |
| 796 | /// school could not have both a `tur` and a `tür`. |
| 797 | #[tokio::test] |
| 798 | async fn distinct_turkish_words_are_not_duplicates() { |
| 799 | let with_kinds = |exam_kinds| { |
| 800 | Settings::try_new(SettingsParams { |
| 801 | exam_kinds, |
| 802 | ..params() |
| 803 | }) |
| 804 | }; |
| 805 | assert!(with_kinds(kinds(&["tur", "tür"])).is_ok()); |
| 806 | assert!(with_kinds(kinds(&["kir", "kır"])).is_ok()); |
| 807 | // A true case variant of one of them is still a duplicate. |
| 808 | assert!(with_kinds(kinds(&["tür", "TÜR"])).is_err()); |
| 809 | assert!(with_kinds(kinds(&["kır", "KIR"])).is_err()); |
| 810 | // Same on the other guarded list. |
| 811 | assert!( |
| 812 | Settings::try_new(SettingsParams { |
| 813 | attendance_statuses: statuses_with(&["tur", "tür"]), |
| 814 | ..params() |
| 815 | }) |
| 816 | .is_ok() |
| 817 | ); |
| 818 | } |
| 819 | |
| 820 | #[tokio::test] |
| 821 | async fn kind_weights_resolve_by_exact_name() { |
| 822 | let s = Settings::try_new(SettingsParams { |
| 823 | exam_kinds: vec![ |
| 824 | ExamKindDef::try_new("midterm", 2).unwrap(), |
| 825 | ExamKindDef::try_new("final", 3).unwrap(), |
| 826 | ], |
| 827 | ..params() |
| 828 | }) |
| 829 | .unwrap(); |
| 830 | assert_eq!(s.exam_kind_weight("final"), Some(3)); |
| 831 | assert_eq!(s.exam_kind_weight("midterm"), Some(2)); |
| 832 | // Exact match, case included — same contract as kind validation. |
| 833 | assert_eq!(s.exam_kind_weight("Final"), None); |
| 834 | assert_eq!(s.exam_kind_weight("oral"), None); |
| 835 | } |
| 836 | |
| 837 | #[tokio::test] |
| 838 | async fn core_attendance_statuses_are_mandatory() { |
| 839 | let with_statuses = |attendance_statuses| { |
| 840 | Settings::try_new(SettingsParams { |
| 841 | attendance_statuses, |
| 842 | ..params() |
| 843 | }) |
| 844 | }; |
| 845 | // Extras on top of the core are fine. |
| 846 | assert!(with_statuses(statuses_with(&["online"])).is_ok()); |
| 847 | // Dropping any core status is not. |
| 848 | let missing: Vec<String> = statuses_with(&[]) |
| 849 | .into_iter() |
| 850 | .filter(|s| s != "late") |
| 851 | .collect(); |
| 852 | assert!(with_statuses(missing).is_err()); |
| 853 | } |
| 854 | |
| 855 | fn statuses_with(extra: &[&str]) -> Vec<String> { |
| 856 | DEFAULT_ATTENDANCE_STATUSES |
| 857 | .iter() |
| 858 | .map(|s| s.to_string()) |
| 859 | .chain(extra.iter().map(|s| s.to_string())) |
| 860 | .collect() |
| 861 | } |
| 862 | |
| 863 | #[tokio::test] |
| 864 | async fn band_rules() { |
| 865 | // Per-band validation: min range and label shape. |
| 866 | assert!(GradeBand::try_new(-1, "FF").is_err()); |
| 867 | assert!(GradeBand::try_new(101, "AA").is_err()); |
| 868 | assert!(GradeBand::try_new(50, " ").is_err()); |
| 869 | assert!(GradeBand::try_new(50, &"x".repeat(21)).is_err()); |
| 870 | assert_eq!(GradeBand::try_new(50, " CC ").unwrap().get_label(), "CC"); |
| 871 | |
| 872 | let ok = |grade_bands| { |
| 873 | Settings::try_new(SettingsParams { |
| 874 | grade_bands, |
| 875 | ..params() |
| 876 | }) |
| 877 | }; |
| 878 | // Empty = numeric-only display. |
| 879 | assert!(ok(vec![]).is_ok()); |
| 880 | // Duplicate mins die; a set without a 0-band dies (marks below the |
| 881 | // lowest band would have no label). |
| 882 | assert!(ok(bands(&[(0, "F"), (0, "E")])).is_err()); |
| 883 | assert!(ok(bands(&[(50, "CC"), (85, "AA")])).is_err()); |
| 884 | assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); |
| 885 | } |
| 886 | |
| 887 | #[tokio::test] |
| 888 | async fn max_file_bytes_is_bounded() { |
| 889 | let with_cap = |max_file_bytes| { |
| 890 | Settings::try_new(SettingsParams { |
| 891 | max_file_bytes, |
| 892 | ..params() |
| 893 | }) |
| 894 | }; |
| 895 | for cap in [ |
| 896 | MIN_MAX_FILE_BYTES, |
| 897 | DEFAULT_MAX_FILE_BYTES, |
| 898 | MAX_MAX_FILE_BYTES, |
| 899 | ] { |
| 900 | assert_eq!(with_cap(cap).unwrap().get_max_file_bytes(), cap); |
| 901 | } |
| 902 | assert!(with_cap(MIN_MAX_FILE_BYTES - 1).is_err()); |
| 903 | assert!(with_cap(MAX_MAX_FILE_BYTES + 1).is_err()); |
| 904 | assert!(with_cap(0).is_err()); |
| 905 | assert!(with_cap(-1).is_err()); |
| 906 | } |
| 907 | |
| 908 | #[tokio::test] |
| 909 | async fn chat_knobs_are_bounded() { |
| 910 | // Each knob is held to its own inclusive range; the edges are legal. |
| 911 | let turns = |chatbot_history_turns| { |
| 912 | Settings::try_new(SettingsParams { |
| 913 | chatbot_history_turns, |
| 914 | ..params() |
| 915 | }) |
| 916 | }; |
| 917 | assert_eq!( |
| 918 | turns(MAX_CHATBOT_HISTORY_TURNS) |
| 919 | .unwrap() |
| 920 | .get_chatbot_history_turns(), |
| 921 | MAX_CHATBOT_HISTORY_TURNS |
| 922 | ); |
| 923 | assert!(turns(MIN_CHATBOT_HISTORY_TURNS).is_ok()); |
| 924 | assert!(turns(0).is_err()); |
| 925 | assert!(turns(MAX_CHATBOT_HISTORY_TURNS + 1).is_err()); |
| 926 | |
| 927 | let convos = |max_chatbot_threads| { |
| 928 | Settings::try_new(SettingsParams { |
| 929 | max_chatbot_threads, |
| 930 | ..params() |
| 931 | }) |
| 932 | }; |
| 933 | assert_eq!( |
| 934 | convos(7).unwrap().get_max_chatbot_threads(), |
| 935 | 7, |
| 936 | "an in-range cap survives validation" |
| 937 | ); |
| 938 | assert!(convos(MIN_MAX_CHATBOT_THREADS).is_ok()); |
| 939 | assert!(convos(MAX_MAX_CHATBOT_THREADS).is_ok()); |
| 940 | assert!(convos(0).is_err()); |
| 941 | assert!(convos(MAX_MAX_CHATBOT_THREADS + 1).is_err()); |
| 942 | |
| 943 | let len = |max_chatbot_message_len| { |
| 944 | Settings::try_new(SettingsParams { |
| 945 | max_chatbot_message_len, |
| 946 | ..params() |
| 947 | }) |
| 948 | }; |
| 949 | assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN).is_ok()); |
| 950 | assert!(len(MAX_MAX_CHATBOT_MESSAGE_LEN).is_ok()); |
| 951 | assert!(len(MIN_MAX_CHATBOT_MESSAGE_LEN - 1).is_err()); |
| 952 | // The ceiling is the newtype's hard cap: no school can raise it. |
| 953 | assert!(len(MAX_CHATBOT_MESSAGE_LEN as i64 + 1).is_err()); |
| 954 | } |
| 955 | |
| 956 | #[tokio::test] |
| 957 | async fn grade_label_picks_the_greatest_min_at_or_below() { |
| 958 | let s = Settings::try_new(SettingsParams { |
| 959 | grade_bands: bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), |
| 960 | ..params() |
| 961 | }) |
| 962 | .unwrap(); |
| 963 | assert_eq!(s.grade_label(0.0), Some("FF")); |
| 964 | assert_eq!(s.grade_label(49.9), Some("FF")); |
| 965 | assert_eq!(s.grade_label(50.0), Some("CC")); |
| 966 | assert_eq!(s.grade_label(84.9), Some("CC")); |
| 967 | assert_eq!(s.grade_label(85.0), Some("AA")); |
| 968 | assert_eq!(s.grade_label(100.0), Some("AA")); |
| 969 | // With no bands configured there is no label, never a panic. |
| 970 | let bare = Settings::try_new(SettingsParams { |
| 971 | grade_bands: vec![], |
| 972 | ..params() |
| 973 | }) |
| 974 | .unwrap(); |
| 975 | assert_eq!(bare.grade_label(90.0), None); |
| 976 | } |
| 977 | } |