Editable policy settings + academic terms
Browse files at this commitea8bfebe718c4d495b5b87bd3ed313ab632e5226Parent: 1d1485a- feat
- editable policy settings + academic terms
20 changed files +1069 -91
- src/constant.rs +19 -5
- src/database.rs +15 -0
- src/domain/attendance.rs +28 -8
- src/domain/course.rs +11 -1
- src/domain/exam.rs +28 -11
- src/domain/mod.rs +2 -0
- src/domain/settings.rs +357 -0
- src/domain/term.rs +149 -0
- src/lib.rs +6 -2
- src/validate.rs +4 -44
- src/web/attendance.rs +19 -8
- src/web/courses.rs +23 -6
- src/web/dto.rs +4 -0
- src/web/events.rs +5 -2
- src/web/exams.rs +8 -1
- src/web/marks.rs +21 -1
- src/web/mod.rs +2 -0
- src/web/sessions.rs +5 -2
- src/web/settings.rs +137 -0
- src/web/terms.rs +226 -0
src/constant.rsmodified+19 -5
| @@ -44,14 +44,28 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; | ||
| 44 | 44 | pub const MAX_COURSE_TITLE_LEN: usize = 200; |
| 45 | 45 | pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; |
| 46 | 46 | |
| 47 | -/// The only accepted attendance states. | |
| 48 | -pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; | |
| 47 | +/// The default attendance states, and also the mandatory core: a school may | |
| 48 | +/// add its own statuses via `PATCH /settings`, but these four can never be | |
| 49 | +/// removed — the attendance rate's semantics are defined over them. | |
| 50 | +pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; | |
| 49 | 51 | |
| 50 | 52 | pub const MAX_SESSION_TOPIC_LEN: usize = 200; |
| 51 | 53 | |
| 52 | -/// The only accepted exam kinds. Informational metadata only — `weight` drives | |
| 53 | -/// the course average. | |
| 54 | -pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; | |
| 54 | +/// The default exam kinds; schools replace the list via `PATCH /settings`. | |
| 55 | +/// Informational metadata only — `weight` drives the course average. | |
| 56 | +pub const DEFAULT_EXAM_KINDS: [&str; 6] = | |
| 57 | + ["homework", "quiz", "midterm", "final", "project", "oral"]; | |
| 58 | + | |
| 59 | +/// Bounds for the school-editable lists in settings (exam kinds, attendance | |
| 60 | +/// statuses): entry count and per-entry character length. | |
| 61 | +pub const MAX_SETTINGS_LIST_LEN: usize = 20; | |
| 62 | +pub const MAX_SETTINGS_ITEM_LEN: usize = 50; | |
| 63 | + | |
| 64 | +/// Bounds for the grade-display bands in settings. | |
| 65 | +pub const MAX_GRADE_BANDS: usize = 20; | |
| 66 | +pub const MAX_GRADE_LABEL_LEN: usize = 20; | |
| 67 | + | |
| 68 | +pub const MAX_TERM_NAME_LEN: usize = 100; | |
| 55 | 69 | |
| 56 | 70 | /// The only accepted exam modes. `sync`: everyone sits the exam inside one |
| 57 | 71 | /// fixed window. `async`: each student starts inside the window and gets their |
src/database.rsmodified+15 -0
| @@ -23,6 +23,8 @@ pub const ENROLLMENT_TABLE: &str = "enrollment"; | ||
| 23 | 23 | pub const COURSE_SESSION_TABLE: &str = "course_session"; |
| 24 | 24 | pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; |
| 25 | 25 | pub const WORK_ENTRY_TABLE: &str = "work_entry"; |
| 26 | +pub const SETTINGS_TABLE: &str = "settings"; | |
| 27 | +pub const TERM_TABLE: &str = "term"; | |
| 26 | 28 | |
| 27 | 29 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 28 | 30 | /// Idempotent — safe to run on every boot. |
| @@ -67,10 +69,16 @@ const MIGRATION: &str = " | ||
| 67 | 69 | DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; |
| 68 | 70 | DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; |
| 69 | 71 | |
| 72 | + DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; | |
| 73 | + DEFINE FIELD IF NOT EXISTS name ON term TYPE string; | |
| 74 | + DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; | |
| 75 | + DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; | |
| 76 | + | |
| 70 | 77 | DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; |
| 71 | 78 | DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>; |
| 72 | 79 | DEFINE FIELD IF NOT EXISTS title ON course TYPE string; |
| 73 | 80 | DEFINE FIELD IF NOT EXISTS description ON course TYPE string; |
| 81 | + DEFINE FIELD IF NOT EXISTS term ON course TYPE option<record<term>>; | |
| 74 | 82 | |
| 75 | 83 | DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; |
| 76 | 84 | DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>; |
| @@ -151,6 +159,13 @@ const MIGRATION: &str = " | ||
| 151 | 159 | DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; |
| 152 | 160 | DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record<user>; |
| 153 | 161 | DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE; |
| 162 | + | |
| 163 | + DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; | |
| 164 | + DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<string>; | |
| 165 | + DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>; | |
| 166 | + DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>; | |
| 167 | + DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; | |
| 168 | + DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; | |
| 154 | 169 | "; |
| 155 | 170 | |
| 156 | 171 | /// Open the file-backed database and apply the schema. |
src/domain/attendance.rsmodified+28 -8
| @@ -4,7 +4,6 @@ use crate::database::{ATTENDANCE_TABLE, Database}; | ||
| 4 | 4 | use crate::domain::event::EventId; |
| 5 | 5 | use crate::domain::user::UserId; |
| 6 | 6 | use crate::error::{AppError, ValidationError}; |
| 7 | -use crate::validate::validate_status; | |
| 8 | 7 | |
| 9 | 8 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 10 | 9 | pub struct AttendanceId(RecordId); |
| @@ -33,13 +32,21 @@ impl AttendanceId { | ||
| 33 | 32 | } |
| 34 | 33 | } |
| 35 | 34 | |
| 36 | -/// A validated attendance state: present | absent | late | excused. | |
| 35 | +/// A validated attendance state — one of the school's configured statuses | |
| 36 | +/// ([`crate::domain::settings::Settings::get_attendance_statuses`]): the core | |
| 37 | +/// `present | absent | late | excused` plus any the school added. Stored rows | |
| 38 | +/// keep their status even if the school later edits the list. | |
| 37 | 39 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 38 | 40 | pub struct AttendanceStatus(String); |
| 39 | 41 | |
| 40 | 42 | impl AttendanceStatus { |
| 41 | - pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 42 | - validate_status(value)?; | |
| 43 | + pub fn try_new(value: &str, allowed: &[String]) -> Result<Self, ValidationError> { | |
| 44 | + if !allowed.iter().any(|status| status == value) { | |
| 45 | + return Err(ValidationError::Invalid { | |
| 46 | + field: "status", | |
| 47 | + reason: "is not one of this school's attendance statuses (see GET /settings)", | |
| 48 | + }); | |
| 49 | + } | |
| 43 | 50 | Ok(Self(value.to_string())) |
| 44 | 51 | } |
| 45 | 52 | |
| @@ -146,11 +153,24 @@ mod tests { | ||
| 146 | 153 | use super::*; |
| 147 | 154 | |
| 148 | 155 | #[tokio::test] |
| 149 | - async fn status_must_be_known() { | |
| 156 | + async fn status_must_be_in_the_allowed_list() { | |
| 157 | + let allowed: Vec<String> = crate::domain::settings::Settings::defaults() | |
| 158 | + .get_attendance_statuses() | |
| 159 | + .to_vec(); | |
| 150 | 160 | for status in ["present", "absent", "late", "excused"] { |
| 151 | - assert_eq!(AttendanceStatus::try_new(status).unwrap().as_str(), status); | |
| 161 | + assert_eq!( | |
| 162 | + AttendanceStatus::try_new(status, &allowed).unwrap().as_str(), | |
| 163 | + status | |
| 164 | + ); | |
| 152 | 165 | } |
| 153 | - assert!(AttendanceStatus::try_new("maybe").is_err()); | |
| 154 | - assert!(AttendanceStatus::try_new("").is_err()); | |
| 166 | + assert!(AttendanceStatus::try_new("maybe", &allowed).is_err()); | |
| 167 | + assert!(AttendanceStatus::try_new("", &allowed).is_err()); | |
| 168 | + // A school-added status is accepted once it's in the list. | |
| 169 | + let extended: Vec<String> = allowed | |
| 170 | + .iter() | |
| 171 | + .cloned() | |
| 172 | + .chain(["online".to_string()]) | |
| 173 | + .collect(); | |
| 174 | + assert!(AttendanceStatus::try_new("online", &extended).is_ok()); | |
| 155 | 175 | } |
| 156 | 176 | } |
src/domain/course.rsmodified+11 -1
| @@ -3,6 +3,7 @@ use ulid::Ulid; | ||
| 3 | 3 | |
| 4 | 4 | use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; |
| 5 | 5 | use crate::database::{COURSE_TABLE, Database}; |
| 6 | +use crate::domain::term::TermId; | |
| 6 | 7 | use crate::domain::user::UserId; |
| 7 | 8 | use crate::error::{AppError, ValidationError}; |
| 8 | 9 | use crate::validate::{validate_optional, validate_required}; |
| @@ -60,13 +61,14 @@ impl CourseDescription { | ||
| 60 | 61 | } |
| 61 | 62 | |
| 62 | 63 | /// A course: the unit exams and enrollments hang off. Marks are computed per |
| 63 | -/// course from its exams' weights. | |
| 64 | +/// course from its exams' weights. May belong to an academic term. | |
| 64 | 65 | #[derive(Debug, Clone, SurrealValue)] |
| 65 | 66 | pub struct Course { |
| 66 | 67 | id: CourseId, |
| 67 | 68 | creator: UserId, |
| 68 | 69 | title: CourseTitle, |
| 69 | 70 | description: CourseDescription, |
| 71 | + term: Option<TermId>, | |
| 70 | 72 | } |
| 71 | 73 | |
| 72 | 74 | impl Course { |
| @@ -86,6 +88,10 @@ impl Course { | ||
| 86 | 88 | &self.description |
| 87 | 89 | } |
| 88 | 90 | |
| 91 | + pub fn get_term(&self) -> Option<&TermId> { | |
| 92 | + self.term.as_ref() | |
| 93 | + } | |
| 94 | + | |
| 89 | 95 | pub fn is_creator(&self, user: &UserId) -> bool { |
| 90 | 96 | &self.creator == user |
| 91 | 97 | } |
| @@ -94,6 +100,7 @@ impl Course { | ||
| 94 | 100 | creator: &UserId, |
| 95 | 101 | title: CourseTitle, |
| 96 | 102 | description: CourseDescription, |
| 103 | + term: Option<TermId>, | |
| 97 | 104 | db: &Database, |
| 98 | 105 | ) -> Result<Course, AppError> { |
| 99 | 106 | let course = Course { |
| @@ -101,6 +108,7 @@ impl Course { | ||
| 101 | 108 | creator: creator.clone(), |
| 102 | 109 | title, |
| 103 | 110 | description, |
| 111 | + term, | |
| 104 | 112 | }; |
| 105 | 113 | let created: Option<Course> = db.create(course.id.record()).content(course).await?; |
| 106 | 114 | created.ok_or_else(|| AppError::Internal("failed to create course".into())) |
| @@ -162,10 +170,12 @@ impl Course { | ||
| 162 | 170 | mut self, |
| 163 | 171 | title: CourseTitle, |
| 164 | 172 | description: CourseDescription, |
| 173 | + term: Option<TermId>, | |
| 165 | 174 | db: &Database, |
| 166 | 175 | ) -> Result<Course, AppError> { |
| 167 | 176 | self.title = title; |
| 168 | 177 | self.description = description; |
| 178 | + self.term = term; | |
| 169 | 179 | let updated: Option<Course> = db.update(self.id.record()).content(self).await?; |
| 170 | 180 | updated.ok_or(AppError::NotFound) |
| 171 | 181 | } |
src/domain/exam.rsmodified+28 -11
| @@ -8,8 +8,8 @@ use crate::domain::timestamp::Timestamp; | ||
| 8 | 8 | use crate::domain::user::UserId; |
| 9 | 9 | use crate::error::{AppError, ValidationError}; |
| 10 | 10 | use crate::validate::{ |
| 11 | - validate_exam_duration, validate_exam_kind, validate_exam_mode, validate_optional, | |
| 12 | - validate_required, validate_weight, | |
| 11 | + validate_exam_duration, validate_exam_mode, validate_optional, validate_required, | |
| 12 | + validate_weight, | |
| 13 | 13 | }; |
| 14 | 14 | |
| 15 | 15 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -64,15 +64,22 @@ impl ExamDescription { | ||
| 64 | 64 | } |
| 65 | 65 | } |
| 66 | 66 | |
| 67 | -/// A validated exam kind: `homework` | `quiz` | `midterm` | `final` | | |
| 68 | -/// `project` | `oral`. Informational metadata only — `weight` drives the | |
| 69 | -/// course average. | |
| 67 | +/// A validated exam kind — one of the school's configured kinds | |
| 68 | +/// ([`crate::domain::settings::Settings::get_exam_kinds`]). Informational | |
| 69 | +/// metadata only — `weight` drives the course average. Stored exams keep | |
| 70 | +/// their kind even if the school later edits the list; only new writes are | |
| 71 | +/// held to the current one. | |
| 70 | 72 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 71 | 73 | pub struct ExamKind(String); |
| 72 | 74 | |
| 73 | 75 | impl ExamKind { |
| 74 | - pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 75 | - validate_exam_kind(value)?; | |
| 76 | + pub fn try_new(value: &str, allowed: &[String]) -> Result<Self, ValidationError> { | |
| 77 | + if !allowed.iter().any(|kind| kind == value) { | |
| 78 | + return Err(ValidationError::Invalid { | |
| 79 | + field: "kind", | |
| 80 | + reason: "is not one of this school's exam kinds (see GET /settings)", | |
| 81 | + }); | |
| 82 | + } | |
| 76 | 83 | Ok(Self(value.to_string())) |
| 77 | 84 | } |
| 78 | 85 | |
| @@ -406,12 +413,22 @@ mod tests { | ||
| 406 | 413 | } |
| 407 | 414 | |
| 408 | 415 | #[tokio::test] |
| 409 | - async fn kind_must_be_known() { | |
| 416 | + async fn kind_must_be_in_the_allowed_list() { | |
| 417 | + let allowed: Vec<String> = crate::domain::settings::Settings::defaults() | |
| 418 | + .get_exam_kinds() | |
| 419 | + .to_vec(); | |
| 410 | 420 | for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { |
| 411 | - assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); | |
| 421 | + assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); | |
| 412 | 422 | } |
| 413 | - assert!(ExamKind::try_new("essay").is_err()); | |
| 414 | - assert!(ExamKind::try_new("").is_err()); | |
| 423 | + assert!(ExamKind::try_new("essay", &allowed).is_err()); | |
| 424 | + assert!(ExamKind::try_new("", &allowed).is_err()); | |
| 425 | + // A school-defined list swaps the acceptance set wholesale. | |
| 426 | + let custom = vec!["lab".to_string()]; | |
| 427 | + assert!(ExamKind::try_new("lab", &custom).is_ok()); | |
| 428 | + assert!(ExamKind::try_new("midterm", &custom).is_err()); | |
| 429 | + // Matching is exact, case included — the settings list is the wire | |
| 430 | + // truth, not a case-folded suggestion. | |
| 431 | + assert!(ExamKind::try_new("Lab", &custom).is_err()); | |
| 415 | 432 | } |
| 416 | 433 | |
| 417 | 434 | #[tokio::test] |
src/domain/mod.rsmodified+2 -0
| @@ -17,6 +17,8 @@ pub mod profile; | ||
| 17 | 17 | pub mod role; |
| 18 | 18 | pub mod session; |
| 19 | 19 | pub mod session_attendance; |
| 20 | +pub mod settings; | |
| 21 | +pub mod term; | |
| 20 | 22 | pub mod timestamp; |
| 21 | 23 | pub mod user; |
| 22 | 24 | pub mod work_entry; |
src/domain/settings.rsadded+357 -0
| @@ -0,0 +1,357 @@ | ||
| 1 | +//! School-adjustable policy: which exam kinds exist, which attendance | |
| 2 | +//! statuses the roll call accepts, and how numeric marks display as grades. | |
| 3 | +//! | |
| 4 | +//! One singleton record (`settings:school` — one school per deployment). An | |
| 5 | +//! absent record means "the defaults from `constant.rs`", so a fresh or | |
| 6 | +//! pre-existing database needs no seeding and behaves exactly as before. | |
| 7 | + | |
| 8 | +use surrealdb::types::{RecordId, SurrealValue}; | |
| 9 | + | |
| 10 | +use crate::constant::{ | |
| 11 | + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, | |
| 12 | + MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_MARK, | |
| 13 | +}; | |
| 14 | +use crate::database::{Database, SETTINGS_TABLE}; | |
| 15 | +use crate::error::{AppError, ValidationError}; | |
| 16 | + | |
| 17 | +/// The singleton's fixed key: one school per deployment, one settings row. | |
| 18 | +const SETTINGS_KEY: &str = "school"; | |
| 19 | + | |
| 20 | +/// One grade-display band: marks at or above `min` (and below the next band's | |
| 21 | +/// `min`) render as `label`. Display only — storage and averaging stay numeric. | |
| 22 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 23 | +pub struct GradeBand { | |
| 24 | + min: i64, | |
| 25 | + label: String, | |
| 26 | +} | |
| 27 | + | |
| 28 | +impl GradeBand { | |
| 29 | + pub fn try_new(min: i64, label: &str) -> Result<Self, ValidationError> { | |
| 30 | + if !(MIN_MARK..=MAX_MARK).contains(&min) { | |
| 31 | + return Err(ValidationError::Invalid { | |
| 32 | + field: "grade_bands", | |
| 33 | + reason: "band mins must be between 0 and 100", | |
| 34 | + }); | |
| 35 | + } | |
| 36 | + let label = label.trim(); | |
| 37 | + if label.is_empty() || label.chars().count() > MAX_GRADE_LABEL_LEN { | |
| 38 | + return Err(ValidationError::Invalid { | |
| 39 | + field: "grade_bands", | |
| 40 | + reason: "band labels must be 1 to 20 characters", | |
| 41 | + }); | |
| 42 | + } | |
| 43 | + Ok(Self { | |
| 44 | + min, | |
| 45 | + label: label.to_string(), | |
| 46 | + }) | |
| 47 | + } | |
| 48 | + | |
| 49 | + pub fn get_min(&self) -> i64 { | |
| 50 | + self.min | |
| 51 | + } | |
| 52 | + | |
| 53 | + pub fn get_label(&self) -> &str { | |
| 54 | + &self.label | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +/// The school's policy knobs, validated as a whole (parse, don't validate — | |
| 59 | +/// like every other entity, an existing `Settings` is always internally | |
| 60 | +/// consistent). | |
| 61 | +#[derive(Debug, Clone, SurrealValue)] | |
| 62 | +pub struct Settings { | |
| 63 | + id: RecordId, | |
| 64 | + exam_kinds: Vec<String>, | |
| 65 | + attendance_statuses: Vec<String>, | |
| 66 | + grade_bands: Vec<GradeBand>, | |
| 67 | +} | |
| 68 | + | |
| 69 | +impl Settings { | |
| 70 | + fn record_id() -> RecordId { | |
| 71 | + RecordId::new(SETTINGS_TABLE, SETTINGS_KEY) | |
| 72 | + } | |
| 73 | + | |
| 74 | + /// The out-of-the-box policy — mirrors the constants that were previously | |
| 75 | + /// hard-coded, so a school that never touches `/settings` sees no change. | |
| 76 | + pub fn defaults() -> Self { | |
| 77 | + Self { | |
| 78 | + id: Self::record_id(), | |
| 79 | + exam_kinds: DEFAULT_EXAM_KINDS.map(String::from).to_vec(), | |
| 80 | + attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), | |
| 81 | + grade_bands: Vec::new(), | |
| 82 | + } | |
| 83 | + } | |
| 84 | + | |
| 85 | + /// Validate a full policy. List entries are trimmed; kinds and statuses | |
| 86 | + /// must be non-empty, unique (case-insensitive), and bounded; the four | |
| 87 | + /// core attendance statuses can never be removed (the attendance rate's | |
| 88 | + /// semantics are defined over them). Bands may be empty (numeric-only | |
| 89 | + /// display), otherwise their mins are unique and one band must start at 0 | |
| 90 | + /// so every mark maps to a label. | |
| 91 | + pub fn try_new( | |
| 92 | + exam_kinds: Vec<String>, | |
| 93 | + attendance_statuses: Vec<String>, | |
| 94 | + grade_bands: Vec<GradeBand>, | |
| 95 | + ) -> Result<Self, ValidationError> { | |
| 96 | + let exam_kinds = validate_list("exam_kinds", exam_kinds)?; | |
| 97 | + let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?; | |
| 98 | + if DEFAULT_ATTENDANCE_STATUSES | |
| 99 | + .iter() | |
| 100 | + .any(|core| !attendance_statuses.iter().any(|s| s == core)) | |
| 101 | + { | |
| 102 | + return Err(ValidationError::Invalid { | |
| 103 | + field: "attendance_statuses", | |
| 104 | + reason: "must keep the core statuses: present, absent, late, excused", | |
| 105 | + }); | |
| 106 | + } | |
| 107 | + | |
| 108 | + if grade_bands.len() > MAX_GRADE_BANDS { | |
| 109 | + return Err(ValidationError::Invalid { | |
| 110 | + field: "grade_bands", | |
| 111 | + reason: "must contain at most 20 bands", | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + let mut mins: Vec<i64> = grade_bands.iter().map(GradeBand::get_min).collect(); | |
| 115 | + mins.sort_unstable(); | |
| 116 | + mins.dedup(); | |
| 117 | + if mins.len() != grade_bands.len() { | |
| 118 | + return Err(ValidationError::Invalid { | |
| 119 | + field: "grade_bands", | |
| 120 | + reason: "band mins must be unique", | |
| 121 | + }); | |
| 122 | + } | |
| 123 | + if !grade_bands.is_empty() && !mins.contains(&MIN_MARK) { | |
| 124 | + return Err(ValidationError::Invalid { | |
| 125 | + field: "grade_bands", | |
| 126 | + reason: "one band must start at 0 so every mark gets a label", | |
| 127 | + }); | |
| 128 | + } | |
| 129 | + // Canonical order: highest band first, matching lookup direction. | |
| 130 | + let mut grade_bands = grade_bands; | |
| 131 | + grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min())); | |
| 132 | + | |
| 133 | + Ok(Self { | |
| 134 | + id: Self::record_id(), | |
| 135 | + exam_kinds, | |
| 136 | + attendance_statuses, | |
| 137 | + grade_bands, | |
| 138 | + }) | |
| 139 | + } | |
| 140 | + | |
| 141 | + pub fn get_exam_kinds(&self) -> &[String] { | |
| 142 | + &self.exam_kinds | |
| 143 | + } | |
| 144 | + | |
| 145 | + pub fn get_attendance_statuses(&self) -> &[String] { | |
| 146 | + &self.attendance_statuses | |
| 147 | + } | |
| 148 | + | |
| 149 | + pub fn get_grade_bands(&self) -> &[GradeBand] { | |
| 150 | + &self.grade_bands | |
| 151 | + } | |
| 152 | + | |
| 153 | + /// The label of the band `mark` falls into: the band with the greatest | |
| 154 | + /// `min` at or below it. `None` when no bands are configured. Takes an | |
| 155 | + /// `f64` so course averages label the same way plain marks do. | |
| 156 | + pub fn grade_label(&self, mark: f64) -> Option<&str> { | |
| 157 | + self.grade_bands | |
| 158 | + .iter() | |
| 159 | + .filter(|band| band.get_min() as f64 <= mark) | |
| 160 | + .max_by_key(|band| band.get_min()) | |
| 161 | + .map(GradeBand::get_label) | |
| 162 | + } | |
| 163 | + | |
| 164 | + /// The stored policy, or the defaults when no row exists yet. | |
| 165 | + pub async fn load(db: &Database) -> Result<Settings, AppError> { | |
| 166 | + let found: Option<Settings> = db.select(Self::record_id()).await?; | |
| 167 | + Ok(found.unwrap_or_else(Self::defaults)) | |
| 168 | + } | |
| 169 | + | |
| 170 | + /// Persist the policy (single UPSERT on the fixed singleton id). | |
| 171 | + pub async fn save(self, db: &Database) -> Result<Settings, AppError> { | |
| 172 | + let saved: Option<Settings> = db.upsert(Self::record_id()).content(self).await?; | |
| 173 | + saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) | |
| 174 | + } | |
| 175 | +} | |
| 176 | + | |
| 177 | +/// Shared rules for the editable string lists: 1–20 trimmed, non-empty, | |
| 178 | +/// ≤50-char entries with no case-insensitive duplicates. | |
| 179 | +fn validate_list( | |
| 180 | + field: &'static str, | |
| 181 | + values: Vec<String>, | |
| 182 | +) -> Result<Vec<String>, ValidationError> { | |
| 183 | + if values.is_empty() { | |
| 184 | + return Err(ValidationError::Empty(field)); | |
| 185 | + } | |
| 186 | + if values.len() > MAX_SETTINGS_LIST_LEN { | |
| 187 | + return Err(ValidationError::Invalid { | |
| 188 | + field, | |
| 189 | + reason: "must contain at most 20 entries", | |
| 190 | + }); | |
| 191 | + } | |
| 192 | + let mut trimmed = Vec::with_capacity(values.len()); | |
| 193 | + for value in &values { | |
| 194 | + let value = value.trim(); | |
| 195 | + if value.is_empty() || value.chars().count() > MAX_SETTINGS_ITEM_LEN { | |
| 196 | + return Err(ValidationError::Invalid { | |
| 197 | + field, | |
| 198 | + reason: "entries must be 1 to 50 characters", | |
| 199 | + }); | |
| 200 | + } | |
| 201 | + trimmed.push(value.to_string()); | |
| 202 | + } | |
| 203 | + let mut folded: Vec<String> = trimmed.iter().map(|v| v.to_lowercase()).collect(); | |
| 204 | + folded.sort_unstable(); | |
| 205 | + folded.dedup(); | |
| 206 | + if folded.len() != trimmed.len() { | |
| 207 | + return Err(ValidationError::Invalid { | |
| 208 | + field, | |
| 209 | + reason: "entries must be unique (case-insensitive)", | |
| 210 | + }); | |
| 211 | + } | |
| 212 | + Ok(trimmed) | |
| 213 | +} | |
| 214 | + | |
| 215 | +#[cfg(test)] | |
| 216 | +mod tests { | |
| 217 | + use super::*; | |
| 218 | + | |
| 219 | + fn kinds(list: &[&str]) -> Vec<String> { | |
| 220 | + list.iter().map(|s| s.to_string()).collect() | |
| 221 | + } | |
| 222 | + | |
| 223 | + fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> { | |
| 224 | + list.iter() | |
| 225 | + .map(|(min, label)| GradeBand::try_new(*min, label).unwrap()) | |
| 226 | + .collect() | |
| 227 | + } | |
| 228 | + | |
| 229 | + #[tokio::test] | |
| 230 | + async fn defaults_are_a_valid_policy() { | |
| 231 | + let defaults = Settings::defaults(); | |
| 232 | + let rebuilt = Settings::try_new( | |
| 233 | + defaults.get_exam_kinds().to_vec(), | |
| 234 | + defaults.get_attendance_statuses().to_vec(), | |
| 235 | + defaults.get_grade_bands().to_vec(), | |
| 236 | + ) | |
| 237 | + .unwrap(); | |
| 238 | + assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); | |
| 239 | + assert!(defaults.get_grade_bands().is_empty()); | |
| 240 | + } | |
| 241 | + | |
| 242 | + #[tokio::test] | |
| 243 | + async fn lists_are_trimmed_bounded_and_deduped() { | |
| 244 | + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); | |
| 245 | + // Trimming happens before storage. | |
| 246 | + let s = Settings::try_new(kinds(&[" lab ", "quiz"]), statuses.clone(), vec![]).unwrap(); | |
| 247 | + assert_eq!(s.get_exam_kinds(), ["lab", "quiz"]); | |
| 248 | + // Empty list, blank entry, over-long entry, and case-insensitive | |
| 249 | + // duplicates are all rejected. | |
| 250 | + assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err()); | |
| 251 | + assert!(Settings::try_new(kinds(&[" "]), statuses.clone(), vec![]).is_err()); | |
| 252 | + assert!(Settings::try_new(kinds(&[&"x".repeat(51)]), statuses.clone(), vec![]).is_err()); | |
| 253 | + assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err()); | |
| 254 | + let too_many: Vec<String> = (0..21).map(|i| format!("kind{i}")).collect(); | |
| 255 | + assert!(Settings::try_new(too_many, statuses, vec![]).is_err()); | |
| 256 | + } | |
| 257 | + | |
| 258 | + #[tokio::test] | |
| 259 | + async fn core_attendance_statuses_are_mandatory() { | |
| 260 | + let kinds = Settings::defaults().get_exam_kinds().to_vec(); | |
| 261 | + // Extras on top of the core are fine. | |
| 262 | + let extended = statuses_with(&["online"]); | |
| 263 | + assert!(Settings::try_new(kinds.clone(), extended, vec![]).is_ok()); | |
| 264 | + // Dropping any core status is not. | |
| 265 | + let missing: Vec<String> = statuses_with(&[]) | |
| 266 | + .into_iter() | |
| 267 | + .filter(|s| s != "late") | |
| 268 | + .collect(); | |
| 269 | + assert!(Settings::try_new(kinds, missing, vec![]).is_err()); | |
| 270 | + } | |
| 271 | + | |
| 272 | + fn statuses_with(extra: &[&str]) -> Vec<String> { | |
| 273 | + DEFAULT_ATTENDANCE_STATUSES | |
| 274 | + .iter() | |
| 275 | + .map(|s| s.to_string()) | |
| 276 | + .chain(extra.iter().map(|s| s.to_string())) | |
| 277 | + .collect() | |
| 278 | + } | |
| 279 | + | |
| 280 | + #[tokio::test] | |
| 281 | + async fn band_rules() { | |
| 282 | + // Per-band validation: min range and label shape. | |
| 283 | + assert!(GradeBand::try_new(-1, "FF").is_err()); | |
| 284 | + assert!(GradeBand::try_new(101, "AA").is_err()); | |
| 285 | + assert!(GradeBand::try_new(50, " ").is_err()); | |
| 286 | + assert!(GradeBand::try_new(50, &"x".repeat(21)).is_err()); | |
| 287 | + assert_eq!(GradeBand::try_new(50, " CC ").unwrap().get_label(), "CC"); | |
| 288 | + | |
| 289 | + let defaults = Settings::defaults(); | |
| 290 | + let ok = |b: Vec<GradeBand>| { | |
| 291 | + Settings::try_new( | |
| 292 | + defaults.get_exam_kinds().to_vec(), | |
| 293 | + defaults.get_attendance_statuses().to_vec(), | |
| 294 | + b, | |
| 295 | + ) | |
| 296 | + }; | |
| 297 | + // Empty = numeric-only display. | |
| 298 | + assert!(ok(vec![]).is_ok()); | |
| 299 | + // Duplicate mins die; a set without a 0-band dies (marks below the | |
| 300 | + // lowest band would have no label). | |
| 301 | + assert!(ok(bands(&[(0, "F"), (0, "E")])).is_err()); | |
| 302 | + assert!(ok(bands(&[(50, "CC"), (85, "AA")])).is_err()); | |
| 303 | + assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); | |
| 304 | + } | |
| 305 | + | |
| 306 | + #[tokio::test] | |
| 307 | + async fn load_save_roundtrip_on_the_singleton() { | |
| 308 | + let db = crate::database::init_mem().await.unwrap(); | |
| 309 | + // No row yet → the defaults, not an error. | |
| 310 | + let loaded = Settings::load(&db).await.unwrap(); | |
| 311 | + assert_eq!( | |
| 312 | + loaded.get_exam_kinds(), | |
| 313 | + Settings::defaults().get_exam_kinds() | |
| 314 | + ); | |
| 315 | + // Save a custom policy and read it back — bands (nested objects under | |
| 316 | + // a FLEXIBLE field) must survive the trip. | |
| 317 | + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); | |
| 318 | + Settings::try_new(kinds(&["lab"]), statuses.clone(), bands(&[(0, "F"), (50, "P")])) | |
| 319 | + .unwrap() | |
| 320 | + .save(&db) | |
| 321 | + .await | |
| 322 | + .unwrap(); | |
| 323 | + let loaded = Settings::load(&db).await.unwrap(); | |
| 324 | + assert_eq!(loaded.get_exam_kinds(), ["lab"]); | |
| 325 | + assert_eq!(loaded.get_grade_bands().len(), 2); | |
| 326 | + assert_eq!(loaded.grade_label(60.0), Some("P")); | |
| 327 | + // A second save lands on the same singleton row, not a new one. | |
| 328 | + Settings::try_new(kinds(&["quiz"]), statuses, vec![]) | |
| 329 | + .unwrap() | |
| 330 | + .save(&db) | |
| 331 | + .await | |
| 332 | + .unwrap(); | |
| 333 | + let mut result = db.query("SELECT * FROM settings").await.unwrap(); | |
| 334 | + let rows: Vec<Settings> = result.take(0).unwrap(); | |
| 335 | + assert_eq!(rows.len(), 1); | |
| 336 | + assert_eq!(rows[0].get_exam_kinds(), ["quiz"]); | |
| 337 | + } | |
| 338 | + | |
| 339 | + #[tokio::test] | |
| 340 | + async fn grade_label_picks_the_greatest_min_at_or_below() { | |
| 341 | + let defaults = Settings::defaults(); | |
| 342 | + let s = Settings::try_new( | |
| 343 | + defaults.get_exam_kinds().to_vec(), | |
| 344 | + defaults.get_attendance_statuses().to_vec(), | |
| 345 | + bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), | |
| 346 | + ) | |
| 347 | + .unwrap(); | |
| 348 | + assert_eq!(s.grade_label(0.0), Some("FF")); | |
| 349 | + assert_eq!(s.grade_label(49.9), Some("FF")); | |
| 350 | + assert_eq!(s.grade_label(50.0), Some("CC")); | |
| 351 | + assert_eq!(s.grade_label(84.9), Some("CC")); | |
| 352 | + assert_eq!(s.grade_label(85.0), Some("AA")); | |
| 353 | + assert_eq!(s.grade_label(100.0), Some("AA")); | |
| 354 | + // No bands configured → no label, never a panic. | |
| 355 | + assert_eq!(Settings::defaults().grade_label(90.0), None); | |
| 356 | + } | |
| 357 | +} |
src/domain/term.rsadded+149 -0
| @@ -0,0 +1,149 @@ | ||
| 1 | +//! An academic term — semester, trimester, quarter, whatever this school | |
| 2 | +//! runs; the structure is just rows, so it needs no code change per school. | |
| 3 | +//! Courses may link to one term. | |
| 4 | +//! | |
| 5 | +//! Terms are calendar structure, not schedules: a school adopting the app | |
| 6 | +//! mid-year legitimately creates a term that already started, so the no-past | |
| 7 | +//! rule that guards exams/lessons/events deliberately does not apply here. | |
| 8 | + | |
| 9 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |
| 10 | +use ulid::Ulid; | |
| 11 | + | |
| 12 | +use crate::constant::MAX_TERM_NAME_LEN; | |
| 13 | +use crate::database::{Database, TERM_TABLE}; | |
| 14 | +use crate::domain::timestamp::Timestamp; | |
| 15 | +use crate::error::{AppError, ValidationError}; | |
| 16 | +use crate::validate::validate_required; | |
| 17 | + | |
| 18 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 19 | +pub struct TermId(RecordId); | |
| 20 | + | |
| 21 | +impl TermId { | |
| 22 | + pub fn generate() -> Self { | |
| 23 | + Self(RecordId::new(TERM_TABLE, Ulid::new().to_string())) | |
| 24 | + } | |
| 25 | + | |
| 26 | + pub fn from_key(key: &str) -> Self { | |
| 27 | + Self(RecordId::new(TERM_TABLE, key)) | |
| 28 | + } | |
| 29 | + | |
| 30 | + pub fn record(&self) -> RecordId { | |
| 31 | + self.0.clone() | |
| 32 | + } | |
| 33 | + | |
| 34 | + pub fn key(&self) -> &str { | |
| 35 | + match &self.0.key { | |
| 36 | + RecordIdKey::String(key) => key, | |
| 37 | + _ => "", | |
| 38 | + } | |
| 39 | + } | |
| 40 | +} | |
| 41 | + | |
| 42 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | |
| 43 | +pub struct TermName(String); | |
| 44 | + | |
| 45 | +impl TermName { | |
| 46 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | |
| 47 | + validate_required("name", value, MAX_TERM_NAME_LEN)?; | |
| 48 | + Ok(Self(value.to_string())) | |
| 49 | + } | |
| 50 | + | |
| 51 | + pub fn as_str(&self) -> &str { | |
| 52 | + &self.0 | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +/// One term on the school's academic calendar. Both ends are required — a | |
| 57 | +/// term is a date range by definition. | |
| 58 | +#[derive(Debug, Clone, SurrealValue)] | |
| 59 | +pub struct Term { | |
| 60 | + id: TermId, | |
| 61 | + name: TermName, | |
| 62 | + starts_at: Timestamp, | |
| 63 | + ends_at: Timestamp, | |
| 64 | +} | |
| 65 | + | |
| 66 | +impl Term { | |
| 67 | + pub fn get_id(&self) -> &TermId { | |
| 68 | + &self.id | |
| 69 | + } | |
| 70 | + | |
| 71 | + pub fn get_name(&self) -> &TermName { | |
| 72 | + &self.name | |
| 73 | + } | |
| 74 | + | |
| 75 | + pub fn get_starts_at(&self) -> Timestamp { | |
| 76 | + self.starts_at | |
| 77 | + } | |
| 78 | + | |
| 79 | + pub fn get_ends_at(&self) -> Timestamp { | |
| 80 | + self.ends_at | |
| 81 | + } | |
| 82 | + | |
| 83 | + pub async fn create( | |
| 84 | + name: TermName, | |
| 85 | + starts_at: Timestamp, | |
| 86 | + ends_at: Timestamp, | |
| 87 | + db: &Database, | |
| 88 | + ) -> Result<Term, AppError> { | |
| 89 | + let term = Term { | |
| 90 | + id: TermId::generate(), | |
| 91 | + name, | |
| 92 | + starts_at, | |
| 93 | + ends_at, | |
| 94 | + }; | |
| 95 | + let created: Option<Term> = db.create(term.id.record()).content(term).await?; | |
| 96 | + created.ok_or_else(|| AppError::Internal("failed to create term".into())) | |
| 97 | + } | |
| 98 | + | |
| 99 | + pub async fn read(id: &TermId, db: &Database) -> Result<Option<Term>, AppError> { | |
| 100 | + Ok(db.select(id.record()).await?) | |
| 101 | + } | |
| 102 | + | |
| 103 | + /// Every term, newest first — the school calendar is small by nature. | |
| 104 | + pub async fn list_all(db: &Database) -> Result<Vec<Term>, AppError> { | |
| 105 | + let mut result = db | |
| 106 | + .query("SELECT * FROM term ORDER BY starts_at DESC") | |
| 107 | + .await? | |
| 108 | + .check()?; | |
| 109 | + Ok(result.take::<Vec<Term>>(0)?) | |
| 110 | + } | |
| 111 | + | |
| 112 | + pub async fn update( | |
| 113 | + mut self, | |
| 114 | + name: TermName, | |
| 115 | + starts_at: Timestamp, | |
| 116 | + ends_at: Timestamp, | |
| 117 | + db: &Database, | |
| 118 | + ) -> Result<Term, AppError> { | |
| 119 | + self.name = name; | |
| 120 | + self.starts_at = starts_at; | |
| 121 | + self.ends_at = ends_at; | |
| 122 | + let updated: Option<Term> = db.update(self.id.record()).content(self).await?; | |
| 123 | + updated.ok_or(AppError::NotFound) | |
| 124 | + } | |
| 125 | + | |
| 126 | + /// Delete the term. Courses keep existing — they just lose the link, so | |
| 127 | + /// deleting a term can never take a course (or its marks) with it. | |
| 128 | + pub async fn delete(self, db: &Database) -> Result<Term, AppError> { | |
| 129 | + db.query("UPDATE course SET term = NONE WHERE term = $term") | |
| 130 | + .bind(("term", self.id.record())) | |
| 131 | + .await? | |
| 132 | + .check()?; | |
| 133 | + let deleted: Option<Term> = db.delete(self.id.record()).await?; | |
| 134 | + deleted.ok_or(AppError::NotFound) | |
| 135 | + } | |
| 136 | +} | |
| 137 | + | |
| 138 | +#[cfg(test)] | |
| 139 | +mod tests { | |
| 140 | + use super::*; | |
| 141 | + | |
| 142 | + #[tokio::test] | |
| 143 | + async fn name_is_required_and_bounded() { | |
| 144 | + assert!(TermName::try_new("2026 Fall").is_ok()); | |
| 145 | + assert!(TermName::try_new("").is_err()); | |
| 146 | + assert!(TermName::try_new(" ").is_err()); | |
| 147 | + assert!(TermName::try_new(&"x".repeat(101)).is_err()); | |
| 148 | + } | |
| 149 | +} |
src/lib.rsmodified+6 -2
| @@ -32,7 +32,7 @@ use crate::state::AppState; | ||
| 32 | 32 | info( |
| 33 | 33 | title = "Hezarfen Backend API", |
| 34 | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates.", | |
| 35 | + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Courses carry lesson sessions with teacher-taken roll call; staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms.", | |
| 36 | 36 | ), |
| 37 | 37 | modifiers(&SecurityAddon), |
| 38 | 38 | tags( |
| @@ -46,7 +46,9 @@ use crate::state::AppState; | ||
| 46 | 46 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 47 | 47 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), |
| 48 | 48 | (name = "exams", description = "Exams (per course, weighted): results, sync/async scheduling, attempts, questions/answers, and live monitoring. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames, see the README's \"Taking an exam\" section for the protocol"), |
| 49 | - (name = "marks", description = "Weighted mark reports per course and overall"), | |
| 49 | + (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured"), | |
| 50 | + (name = "settings", description = "School policy, one singleton: exam kinds, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"), | |
| 51 | + (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), | |
| 50 | 52 | ), |
| 51 | 53 | )] |
| 52 | 54 | struct ApiDoc; |
| @@ -85,6 +87,8 @@ pub fn build_router(state: AppState) -> Router { | ||
| 85 | 87 | .nest("/marks", web::marks::routes()) |
| 86 | 88 | .nest("/work", web::work::routes()) |
| 87 | 89 | .nest("/attendance", web::attendance::routes()) |
| 90 | + .nest("/settings", web::settings::routes()) | |
| 91 | + .nest("/terms", web::terms::routes()) | |
| 88 | 92 | .split_for_parts(); |
| 89 | 93 | |
| 90 | 94 | // Catch-all per-IP limit over every route (Swagger included). Kept inside |
src/validate.rsmodified+4 -44
| @@ -2,10 +2,10 @@ | ||
| 2 | 2 | //! the value, so an existing newtype is always valid (parse, don't validate). |
| 3 | 3 | |
| 4 | 4 | use crate::constant::{ |
| 5 | - ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, | |
| 6 | - MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, | |
| 7 | - MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, | |
| 8 | - MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS, | |
| 5 | + EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, | |
| 6 | + MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, | |
| 7 | + MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, | |
| 8 | + MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS, | |
| 9 | 9 | }; |
| 10 | 10 | use crate::error::ValidationError; |
| 11 | 11 | |
| @@ -195,28 +195,6 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> { | ||
| 195 | 195 | Ok(()) |
| 196 | 196 | } |
| 197 | 197 | |
| 198 | -pub fn validate_status(value: &str) -> Result<(), ValidationError> { | |
| 199 | - if ATTENDANCE_STATUSES.contains(&value) { | |
| 200 | - Ok(()) | |
| 201 | - } else { | |
| 202 | - Err(ValidationError::Invalid { | |
| 203 | - field: "status", | |
| 204 | - reason: "must be one of: present, absent, late, excused", | |
| 205 | - }) | |
| 206 | - } | |
| 207 | -} | |
| 208 | - | |
| 209 | -pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { | |
| 210 | - if EXAM_KINDS.contains(&value) { | |
| 211 | - Ok(()) | |
| 212 | - } else { | |
| 213 | - Err(ValidationError::Invalid { | |
| 214 | - field: "kind", | |
| 215 | - reason: "must be one of: homework, quiz, midterm, final, project, oral", | |
| 216 | - }) | |
| 217 | - } | |
| 218 | -} | |
| 219 | - | |
| 220 | 198 | pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { |
| 221 | 199 | if EXAM_MODES.contains(&value) { |
| 222 | 200 | Ok(()) |
| @@ -394,24 +372,6 @@ mod tests { | ||
| 394 | 372 | assert!(validate_phone("55+5123456").is_err()); // + only allowed in front |
| 395 | 373 | } |
| 396 | 374 | |
| 397 | - #[tokio::test] | |
| 398 | - async fn status_rules() { | |
| 399 | - for status in ["present", "absent", "late", "excused"] { | |
| 400 | - assert!(validate_status(status).is_ok()); | |
| 401 | - } | |
| 402 | - assert!(validate_status("maybe").is_err()); | |
| 403 | - assert!(validate_status("").is_err()); | |
| 404 | - } | |
| 405 | - | |
| 406 | - #[tokio::test] | |
| 407 | - async fn exam_kind_rules() { | |
| 408 | - for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { | |
| 409 | - assert!(validate_exam_kind(kind).is_ok()); | |
| 410 | - } | |
| 411 | - assert!(validate_exam_kind("essay").is_err()); | |
| 412 | - assert!(validate_exam_kind("").is_err()); | |
| 413 | - } | |
| 414 | - | |
| 415 | 375 | #[tokio::test] |
| 416 | 376 | async fn exam_mode_rules() { |
| 417 | 377 | for mode in ["sync", "async"] { |
src/web/attendance.rsmodified+19 -8
| @@ -32,11 +32,15 @@ struct StatusCounts { | ||
| 32 | 32 | absent: u64, |
| 33 | 33 | late: u64, |
| 34 | 34 | excused: u64, |
| 35 | - /// All rows, `excused` included. | |
| 35 | + /// Tallies of the school-added statuses (`GET /settings`), keyed by | |
| 36 | + /// status. Rate-neutral like `excused`: their semantics are the school's, | |
| 37 | + /// so they count into `total` only. | |
| 38 | + custom: HashMap<String, u64>, | |
| 39 | + /// All rows, `excused` and custom statuses included. | |
| 36 | 40 | total: u64, |
| 37 | 41 | /// `(present + late) / (present + absent + late)` — being late is still |
| 38 | 42 | /// attending, and an excused absence counts against no one. `null` when |
| 39 | - /// every row is excused (or there are none). | |
| 43 | + /// every row is excused/custom (or there are none). | |
| 40 | 44 | rate: Option<f64>, |
| 41 | 45 | } |
| 42 | 46 | |
| @@ -49,8 +53,8 @@ impl StatusCounts { | ||
| 49 | 53 | "present" => counts.present += 1, |
| 50 | 54 | "absent" => counts.absent += 1, |
| 51 | 55 | "late" => counts.late += 1, |
| 52 | - // `AttendanceStatus` admits exactly four values. | |
| 53 | - _ => counts.excused += 1, | |
| 56 | + "excused" => counts.excused += 1, | |
| 57 | + custom => *counts.custom.entry(custom.to_string()).or_default() += 1, | |
| 54 | 58 | } |
| 55 | 59 | } |
| 56 | 60 | counts.rate = attendance_rate(counts.present, counts.absent, counts.late); |
| @@ -215,17 +219,24 @@ mod tests { | ||
| 215 | 219 | |
| 216 | 220 | #[tokio::test] |
| 217 | 221 | async fn tally_buckets_every_status() { |
| 218 | - let statuses: Vec<AttendanceStatus> = ["present", "present", "late", "absent", "excused"] | |
| 222 | + let allowed: Vec<String> = ["present", "absent", "late", "excused", "online"] | |
| 219 | 223 | .iter() |
| 220 | - .map(|s| AttendanceStatus::try_new(s).unwrap()) | |
| 224 | + .map(|s| s.to_string()) | |
| 221 | 225 | .collect(); |
| 226 | + let statuses: Vec<AttendanceStatus> = | |
| 227 | + ["present", "present", "late", "absent", "excused", "online"] | |
| 228 | + .iter() | |
| 229 | + .map(|s| AttendanceStatus::try_new(s, &allowed).unwrap()) | |
| 230 | + .collect(); | |
| 222 | 231 | let counts = StatusCounts::tally(statuses.iter()); |
| 223 | 232 | assert_eq!(counts.present, 2); |
| 224 | 233 | assert_eq!(counts.late, 1); |
| 225 | 234 | assert_eq!(counts.absent, 1); |
| 226 | 235 | assert_eq!(counts.excused, 1); |
| 227 | - assert_eq!(counts.total, 5); | |
| 228 | - // (2 + 1) / (2 + 1 + 1) | |
| 236 | + // A school-added status lands in its own bucket — never in `excused`. | |
| 237 | + assert_eq!(counts.custom.get("online"), Some(&1)); | |
| 238 | + assert_eq!(counts.total, 6); | |
| 239 | + // Rate ignores excused and custom rows: (2 + 1) / (2 + 1 + 1). | |
| 229 | 240 | assert_eq!(counts.rate, Some(0.75)); |
| 230 | 241 | } |
| 231 | 242 | } |
src/web/courses.rsmodified+23 -6
| @@ -16,15 +16,17 @@ use crate::domain::exam::{ | ||
| 16 | 16 | Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, |
| 17 | 17 | }; |
| 18 | 18 | use crate::domain::role::Role; |
| 19 | +use crate::domain::settings::Settings; | |
| 19 | 20 | use crate::domain::timestamp::Timestamp; |
| 20 | 21 | use crate::domain::user::{User, UserId}; |
| 21 | 22 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 22 | 23 | use crate::state::AppState; |
| 23 | 24 | |
| 24 | 25 | use super::sessions::resolve_session_teacher; |
| 26 | +use super::terms::resolve_term; | |
| 25 | 27 | use super::{ |
| 26 | 28 | CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse, |
| 27 | - check_not_past, check_time_range, person_map, | |
| 29 | + check_not_past, check_time_range, person_map, set_or_clear, | |
| 28 | 30 | }; |
| 29 | 31 | |
| 30 | 32 | pub fn routes() -> OpenApiRouter<AppState> { |
| @@ -43,12 +45,19 @@ struct CreateCourse { | ||
| 43 | 45 | #[schema(example = "Algebra")] |
| 44 | 46 | title: String, |
| 45 | 47 | description: Option<String>, |
| 48 | + /// The academic term this course belongs to (`GET /terms`). Optional. | |
| 49 | + term_id: Option<String>, | |
| 46 | 50 | } |
| 47 | 51 | |
| 48 | 52 | #[derive(Deserialize, ToSchema)] |
| 49 | 53 | struct UpdateCourse { |
| 50 | 54 | title: Option<String>, |
| 51 | 55 | description: Option<String>, |
| 56 | + /// Omit to keep the current term, send `null` to unlink, or send a term | |
| 57 | + /// id to (re)assign. | |
| 58 | + #[serde(default, deserialize_with = "set_or_clear")] | |
| 59 | + #[schema(value_type = Option<String>)] | |
| 60 | + term_id: Option<Option<String>>, | |
| 52 | 61 | } |
| 53 | 62 | |
| 54 | 63 | #[derive(Deserialize, ToSchema)] |
| @@ -63,8 +72,9 @@ struct CreateExamInCourse { | ||
| 63 | 72 | #[schema(example = "Midterm")] |
| 64 | 73 | title: String, |
| 65 | 74 | description: Option<String>, |
| 66 | - /// The assessment form: `homework`, `quiz`, `midterm`, `final`, `project`, | |
| 67 | - /// or `oral`. Informational — `weight` drives the course average. | |
| 75 | + /// The assessment form — one of the school's exam kinds (`GET /settings`; | |
| 76 | + /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`). | |
| 77 | + /// Informational — `weight` drives the course average. | |
| 68 | 78 | #[schema(example = "midterm")] |
| 69 | 79 | kind: String, |
| 70 | 80 | /// How many times this exam counts into the course average, `1`–`100`. |
| @@ -177,7 +187,8 @@ async fn create_course( | ||
| 177 | 187 | ) -> Result<(StatusCode, Json<CourseResponse>), AppError> { |
| 178 | 188 | let title = CourseTitle::try_new(&req.title)?; |
| 179 | 189 | let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; |
| 180 | - let course = Course::create(user.get_id(), title, description, &st.db).await?; | |
| 190 | + let term = resolve_term(req.term_id.as_deref(), &st.db).await?; | |
| 191 | + let course = Course::create(user.get_id(), title, description, term, &st.db).await?; | |
| 181 | 192 | Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) |
| 182 | 193 | } |
| 183 | 194 | |
| @@ -291,8 +302,13 @@ async fn update_course( | ||
| 291 | 302 | Some(ref description) => CourseDescription::try_new(description)?, |
| 292 | 303 | None => course.get_description().clone(), |
| 293 | 304 | }; |
| 305 | + let term = match req.term_id { | |
| 306 | + // Explicit `null` clears the link; a value must name a real term. | |
| 307 | + Some(update) => resolve_term(update.as_deref(), &st.db).await?, | |
| 308 | + None => course.get_term().cloned(), | |
| 309 | + }; | |
| 294 | 310 | |
| 295 | - let updated = course.update(title, description, &st.db).await?; | |
| 311 | + let updated = course.update(title, description, term, &st.db).await?; | |
| 296 | 312 | Ok(Json(CourseResponse::new(&updated))) |
| 297 | 313 | } |
| 298 | 314 | |
| @@ -496,7 +512,8 @@ async fn create_exam_in_course( | ||
| 496 | 512 | |
| 497 | 513 | let title = ExamTitle::try_new(&req.title)?; |
| 498 | 514 | let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; |
| 499 | - let kind = ExamKind::try_new(&req.kind)?; | |
| 515 | + let school = Settings::load(&st.db).await?; | |
| 516 | + let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?; | |
| 500 | 517 | let weight = ExamWeight::try_new(req.weight)?; |
| 501 | 518 | let starts_at = req.starts_at.map(Timestamp::from_millis); |
| 502 | 519 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
src/web/dto.rsmodified+4 -0
| @@ -150,6 +150,9 @@ pub struct CourseResponse { | ||
| 150 | 150 | #[schema(example = "Algebra")] |
| 151 | 151 | pub title: String, |
| 152 | 152 | pub description: String, |
| 153 | + /// The academic term this course belongs to (`GET /terms`); `null` when | |
| 154 | + /// unassigned. | |
| 155 | + pub term: Option<String>, | |
| 153 | 156 | } |
| 154 | 157 | |
| 155 | 158 | impl CourseResponse { |
| @@ -159,6 +162,7 @@ impl CourseResponse { | ||
| 159 | 162 | creator: course.get_creator().key().to_string(), |
| 160 | 163 | title: course.get_title().as_str().to_string(), |
| 161 | 164 | description: course.get_description().as_str().to_string(), |
| 165 | + term: course.get_term().map(|term| term.key().to_string()), | |
| 162 | 166 | } |
| 163 | 167 | } |
| 164 | 168 | } |
src/web/events.rsmodified+5 -2
| @@ -11,6 +11,7 @@ use utoipa_axum::routes; | ||
| 11 | 11 | use crate::domain::attendance::{Attendance, AttendanceStatus}; |
| 12 | 12 | use crate::domain::event::{Event, EventDescription, EventId, EventTitle}; |
| 13 | 13 | use crate::domain::role::Role; |
| 14 | +use crate::domain::settings::Settings; | |
| 14 | 15 | use crate::domain::timestamp::Timestamp; |
| 15 | 16 | use crate::domain::user::{User, UserId}; |
| 16 | 17 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -58,7 +59,8 @@ struct UpdateEvent { | ||
| 58 | 59 | |
| 59 | 60 | #[derive(Deserialize, ToSchema)] |
| 60 | 61 | struct MarkAttendance { |
| 61 | - /// One of the accepted attendance statuses (e.g. `present`, `absent`). | |
| 62 | + /// One of the school's attendance statuses (`GET /settings`; the core | |
| 63 | + /// four are `present`, `absent`, `late`, `excused`). | |
| 62 | 64 | #[schema(example = "present")] |
| 63 | 65 | status: String, |
| 64 | 66 | /// Target user id. Defaults to the caller when omitted. |
| @@ -333,7 +335,8 @@ async fn mark( | ||
| 333 | 335 | .await? |
| 334 | 336 | .ok_or(AppError::NotFound)?; |
| 335 | 337 | |
| 336 | - let status = AttendanceStatus::try_new(&req.status)?; | |
| 338 | + let school = Settings::load(&st.db).await?; | |
| 339 | + let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; | |
| 337 | 340 | let target = match req.user_id { |
| 338 | 341 | Some(ref key) => UserId::from_key(key), |
| 339 | 342 | None => user.get_id().clone(), |
src/web/exams.rsmodified+8 -1
| @@ -27,6 +27,7 @@ use crate::domain::exam_question::{ | ||
| 27 | 27 | }; |
| 28 | 28 | use crate::domain::exam_result::{ExamResult, Mark}; |
| 29 | 29 | use crate::domain::role::Role; |
| 30 | +use crate::domain::settings::Settings; | |
| 30 | 31 | use crate::domain::timestamp::Timestamp; |
| 31 | 32 | use crate::domain::user::{User, UserId}; |
| 32 | 33 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -252,7 +253,13 @@ async fn update_exam( | ||
| 252 | 253 | None => exam.get_description().clone(), |
| 253 | 254 | }; |
| 254 | 255 | let kind = match req.kind { |
| 255 | - Some(ref kind) => ExamKind::try_new(kind)?, | |
| 256 | + // Only a kind this request sets is held to the current settings list — | |
| 257 | + // a stored kind survives later list edits, like past times survive | |
| 258 | + // the no-past rule. | |
| 259 | + Some(ref kind) => { | |
| 260 | + let school = Settings::load(&st.db).await?; | |
| 261 | + ExamKind::try_new(kind, school.get_exam_kinds())? | |
| 262 | + } | |
| 256 | 263 | None => exam.get_kind().clone(), |
| 257 | 264 | }; |
| 258 | 265 | let weight = match req.weight { |
src/web/marks.rsmodified+21 -1
| @@ -12,6 +12,7 @@ use crate::domain::course::Course; | ||
| 12 | 12 | use crate::domain::exam::Exam; |
| 13 | 13 | use crate::domain::exam_result::ExamResult; |
| 14 | 14 | use crate::domain::role::Role; |
| 15 | +use crate::domain::settings::Settings; | |
| 15 | 16 | use crate::domain::user::{User, UserId}; |
| 16 | 17 | use crate::error::{AppError, ErrorResponse}; |
| 17 | 18 | use crate::state::AppState; |
| @@ -34,6 +35,10 @@ struct MarkEntry { | ||
| 34 | 35 | kind: String, |
| 35 | 36 | weight: i64, |
| 36 | 37 | mark: i64, |
| 38 | + /// The mark's label from the school's grade bands (`GET /settings`); | |
| 39 | + /// `null` when no bands are configured. | |
| 40 | + #[schema(example = "AA")] | |
| 41 | + grade: Option<String>, | |
| 37 | 42 | graded_by: String, |
| 38 | 43 | } |
| 39 | 44 | |
| @@ -46,6 +51,9 @@ struct CourseMarks { | ||
| 46 | 51 | /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while |
| 47 | 52 | /// nothing is graded. |
| 48 | 53 | average: Option<f64>, |
| 54 | + /// The average's label from the school's grade bands; `null` when there | |
| 55 | + /// is no average or no bands are configured. | |
| 56 | + average_grade: Option<String>, | |
| 49 | 57 | } |
| 50 | 58 | |
| 51 | 59 | /// A student's full mark report across their enrolled courses. |
| @@ -57,6 +65,9 @@ struct MarksReport { | ||
| 57 | 65 | /// Plain mean of the non-null course averages; `null` while no course has |
| 58 | 66 | /// a graded exam. |
| 59 | 67 | overall_average: Option<f64>, |
| 68 | + /// The overall average's label from the school's grade bands; `null` when | |
| 69 | + /// there is no average or no bands are configured. | |
| 70 | + overall_grade: Option<String>, | |
| 60 | 71 | } |
| 61 | 72 | |
| 62 | 73 | /// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The |
| @@ -85,6 +96,9 @@ async fn build_report( | ||
| 85 | 96 | courses.retain(|course| can_manage_course(course, viewer)); |
| 86 | 97 | } |
| 87 | 98 | |
| 99 | + // One settings read labels the whole report. | |
| 100 | + let school = Settings::load(db).await?; | |
| 101 | + | |
| 88 | 102 | let mut blocks = Vec::with_capacity(courses.len()); |
| 89 | 103 | for course in &courses { |
| 90 | 104 | let exams = Exam::list_for_course(course.get_id(), db).await?; |
| @@ -105,14 +119,19 @@ async fn build_report( | ||
| 105 | 119 | kind: exam.get_kind().as_str().to_string(), |
| 106 | 120 | weight: exam.get_weight().as_i64(), |
| 107 | 121 | mark: result.get_mark().as_i64(), |
| 122 | + grade: school | |
| 123 | + .grade_label(result.get_mark().as_i64() as f64) | |
| 124 | + .map(str::to_string), | |
| 108 | 125 | graded_by: result.get_graded_by().key().to_string(), |
| 109 | 126 | }); |
| 110 | 127 | pairs.push((result.get_mark().as_i64(), exam.get_weight().as_i64())); |
| 111 | 128 | } |
| 112 | 129 | |
| 130 | + let average = weighted_average(&pairs); | |
| 113 | 131 | blocks.push(CourseMarks { |
| 114 | 132 | course: CourseResponse::new(course), |
| 115 | - average: weighted_average(&pairs), | |
| 133 | + average, | |
| 134 | + average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), | |
| 116 | 135 | results: entries, |
| 117 | 136 | }); |
| 118 | 137 | } |
| @@ -125,6 +144,7 @@ async fn build_report( | ||
| 125 | 144 | user: user.key().to_string(), |
| 126 | 145 | courses: blocks, |
| 127 | 146 | overall_average, |
| 147 | + overall_grade: overall_average.and_then(|a| school.grade_label(a).map(str::to_string)), | |
| 128 | 148 | }) |
| 129 | 149 | } |
| 130 | 150 |
src/web/mod.rsmodified+2 -0
| @@ -12,6 +12,8 @@ pub mod exams; | ||
| 12 | 12 | pub mod marks; |
| 13 | 13 | pub mod notes; |
| 14 | 14 | pub mod sessions; |
| 15 | +pub mod settings; | |
| 16 | +pub mod terms; | |
| 15 | 17 | pub mod users; |
| 16 | 18 | pub mod work; |
| 17 | 19 |
src/web/sessions.rsmodified+5 -2
| @@ -15,6 +15,7 @@ use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic | ||
| 15 | 15 | use crate::domain::enrollment::Enrollment; |
| 16 | 16 | use crate::domain::role::Role; |
| 17 | 17 | use crate::domain::session_attendance::SessionAttendance; |
| 18 | +use crate::domain::settings::Settings; | |
| 18 | 19 | use crate::domain::timestamp::Timestamp; |
| 19 | 20 | use crate::domain::user::{User, UserId}; |
| 20 | 21 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -50,7 +51,8 @@ struct UpdateSession { | ||
| 50 | 51 | |
| 51 | 52 | #[derive(Deserialize, ToSchema)] |
| 52 | 53 | struct MarkRollCall { |
| 53 | - /// One of the accepted attendance statuses (e.g. `present`, `absent`). | |
| 54 | + /// One of the school's attendance statuses (`GET /settings`; the core | |
| 55 | + /// four are `present`, `absent`, `late`, `excused`). | |
| 54 | 56 | #[schema(example = "present")] |
| 55 | 57 | status: String, |
| 56 | 58 | /// Whose roll-call state to record: an enrolled student, or the session's |
| @@ -295,7 +297,8 @@ async fn mark_roll_call( | ||
| 295 | 297 | )); |
| 296 | 298 | } |
| 297 | 299 | |
| 298 | - let status = AttendanceStatus::try_new(&req.status)?; | |
| 300 | + let school = Settings::load(&st.db).await?; | |
| 301 | + let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; | |
| 299 | 302 | let target = UserId::from_key(&req.user_id); |
| 300 | 303 | |
| 301 | 304 | // Target user must exist. |
src/web/settings.rsadded+137 -0
| @@ -0,0 +1,137 @@ | ||
| 1 | +use axum::Json; | |
| 2 | +use axum::extract::State; | |
| 3 | +use serde::{Deserialize, Serialize}; | |
| 4 | +use utoipa::ToSchema; | |
| 5 | +use utoipa_axum::router::OpenApiRouter; | |
| 6 | +use utoipa_axum::routes; | |
| 7 | + | |
| 8 | +use crate::domain::settings::{GradeBand, Settings}; | |
| 9 | +use crate::error::{AppError, ErrorResponse}; | |
| 10 | +use crate::state::AppState; | |
| 11 | + | |
| 12 | +use super::{CurrentUser, RequireManager}; | |
| 13 | + | |
| 14 | +pub fn routes() -> OpenApiRouter<AppState> { | |
| 15 | + OpenApiRouter::new().routes(routes!(get_settings, update_settings)) | |
| 16 | +} | |
| 17 | + | |
| 18 | +/// One grade-display band: marks at or above `min` (and below the next band's | |
| 19 | +/// `min`) render as `label`. | |
| 20 | +#[derive(Serialize, Deserialize, ToSchema)] | |
| 21 | +struct GradeBandDto { | |
| 22 | + /// Lowest mark of the band, `0`–`100`. One band must start at `0`. | |
| 23 | + #[schema(example = 85)] | |
| 24 | + min: i64, | |
| 25 | + /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`). | |
| 26 | + #[schema(example = "AA")] | |
| 27 | + label: String, | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// The school's policy: which exam kinds exist, which attendance statuses the | |
| 31 | +/// roll call accepts, and how numeric marks display as grades. | |
| 32 | +#[derive(Serialize, ToSchema)] | |
| 33 | +struct SettingsResponse { | |
| 34 | + /// Accepted `kind` values for new exams. | |
| 35 | + #[schema(example = json!(["homework", "quiz", "midterm", "final", "project", "oral"]))] | |
| 36 | + exam_kinds: Vec<String>, | |
| 37 | + /// Accepted `status` values for attendance marking. Always contains the | |
| 38 | + /// core four (`present`, `absent`, `late`, `excused`). | |
| 39 | + #[schema(example = json!(["present", "absent", "late", "excused"]))] | |
| 40 | + attendance_statuses: Vec<String>, | |
| 41 | + /// Grade-display bands, highest first. Empty = marks display numeric-only. | |
| 42 | + grade_bands: Vec<GradeBandDto>, | |
| 43 | +} | |
| 44 | + | |
| 45 | +impl SettingsResponse { | |
| 46 | + fn new(settings: &Settings) -> Self { | |
| 47 | + Self { | |
| 48 | + exam_kinds: settings.get_exam_kinds().to_vec(), | |
| 49 | + attendance_statuses: settings.get_attendance_statuses().to_vec(), | |
| 50 | + grade_bands: settings | |
| 51 | + .get_grade_bands() | |
| 52 | + .iter() | |
| 53 | + .map(|band| GradeBandDto { | |
| 54 | + min: band.get_min(), | |
| 55 | + label: band.get_label().to_string(), | |
| 56 | + }) | |
| 57 | + .collect(), | |
| 58 | + } | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +#[derive(Deserialize, ToSchema)] | |
| 63 | +struct UpdateSettings { | |
| 64 | + /// Replaces the whole list when present: 1–20 unique entries, each 1–50 | |
| 65 | + /// characters. | |
| 66 | + exam_kinds: Option<Vec<String>>, | |
| 67 | + /// Replaces the whole list when present; must keep `present`, `absent`, | |
| 68 | + /// `late`, `excused` (the attendance rate is defined over them). | |
| 69 | + attendance_statuses: Option<Vec<String>>, | |
| 70 | + /// Replaces the whole set when present. `[]` clears the bands (numeric-only | |
| 71 | + /// marks); otherwise mins are unique and one band must start at `0`. | |
| 72 | + grade_bands: Option<Vec<GradeBandDto>>, | |
| 73 | +} | |
| 74 | + | |
| 75 | +/// The school's current policy. Any authenticated user — clients need it to | |
| 76 | +/// render pickers and grades. Falls back to the built-in defaults until a | |
| 77 | +/// manager edits it. | |
| 78 | +#[utoipa::path( | |
| 79 | + get, | |
| 80 | + path = "/", | |
| 81 | + tag = "settings", | |
| 82 | + security(("session_cookie" = [])), | |
| 83 | + responses( | |
| 84 | + (status = 200, description = "The school's policy", body = SettingsResponse), | |
| 85 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 86 | + ), | |
| 87 | +)] | |
| 88 | +async fn get_settings( | |
| 89 | + State(st): State<AppState>, | |
| 90 | + CurrentUser(_user): CurrentUser, | |
| 91 | +) -> Result<Json<SettingsResponse>, AppError> { | |
| 92 | + let settings = Settings::load(&st.db).await?; | |
| 93 | + Ok(Json(SettingsResponse::new(&settings))) | |
| 94 | +} | |
| 95 | + | |
| 96 | +/// Update the school's policy. Requires manager+. Omitted fields keep their | |
| 97 | +/// value; a present field replaces its list wholesale. Existing rows are | |
| 98 | +/// untouched — a removed exam kind or status lives on in old records; only | |
| 99 | +/// new writes are held to the new lists. | |
| 100 | +#[utoipa::path( | |
| 101 | + patch, | |
| 102 | + path = "/", | |
| 103 | + tag = "settings", | |
| 104 | + security(("session_cookie" = [])), | |
| 105 | + request_body = UpdateSettings, | |
| 106 | + responses( | |
| 107 | + (status = 200, description = "Updated policy", body = SettingsResponse), | |
| 108 | + (status = 400, description = "Invalid lists or bands", body = ErrorResponse), | |
| 109 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 110 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 111 | + ), | |
| 112 | +)] | |
| 113 | +async fn update_settings( | |
| 114 | + State(st): State<AppState>, | |
| 115 | + RequireManager(_user): RequireManager, | |
| 116 | + Json(req): Json<UpdateSettings>, | |
| 117 | +) -> Result<Json<SettingsResponse>, AppError> { | |
| 118 | + let current = Settings::load(&st.db).await?; | |
| 119 | + | |
| 120 | + let exam_kinds = req | |
| 121 | + .exam_kinds | |
| 122 | + .unwrap_or_else(|| current.get_exam_kinds().to_vec()); | |
| 123 | + let attendance_statuses = req | |
| 124 | + .attendance_statuses | |
| 125 | + .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); | |
| 126 | + let grade_bands = match req.grade_bands { | |
| 127 | + Some(bands) => bands | |
| 128 | + .into_iter() | |
| 129 | + .map(|band| GradeBand::try_new(band.min, &band.label)) | |
| 130 | + .collect::<Result<Vec<_>, _>>()?, | |
| 131 | + None => current.get_grade_bands().to_vec(), | |
| 132 | + }; | |
| 133 | + | |
| 134 | + let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; | |
| 135 | + let saved = settings.save(&st.db).await?; | |
| 136 | + Ok(Json(SettingsResponse::new(&saved))) | |
| 137 | +} |
src/web/terms.rsadded+226 -0
| @@ -0,0 +1,226 @@ | ||
| 1 | +use axum::Json; | |
| 2 | +use axum::extract::{Path, State}; | |
| 3 | +use axum::http::StatusCode; | |
| 4 | +use serde::{Deserialize, Serialize}; | |
| 5 | +use utoipa::ToSchema; | |
| 6 | +use utoipa_axum::router::OpenApiRouter; | |
| 7 | +use utoipa_axum::routes; | |
| 8 | + | |
| 9 | +use crate::database::Database; | |
| 10 | +use crate::domain::term::{Term, TermId, TermName}; | |
| 11 | +use crate::domain::timestamp::Timestamp; | |
| 12 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | |
| 13 | +use crate::state::AppState; | |
| 14 | + | |
| 15 | +use super::{CurrentUser, RequireManager, check_time_range}; | |
| 16 | + | |
| 17 | +pub fn routes() -> OpenApiRouter<AppState> { | |
| 18 | + OpenApiRouter::new() | |
| 19 | + .routes(routes!(create_term, list_terms)) | |
| 20 | + .routes(routes!(get_term, update_term, delete_term)) | |
| 21 | +} | |
| 22 | + | |
| 23 | +#[derive(Deserialize, ToSchema)] | |
| 24 | +struct CreateTerm { | |
| 25 | + #[schema(example = "2026 Fall")] | |
| 26 | + name: String, | |
| 27 | + /// Term start, UTC unix-milliseconds. May lie in the past — a school | |
| 28 | + /// adopting the app mid-year backfills its calendar legitimately. | |
| 29 | + #[schema(example = 1_780_000_000_000_i64)] | |
| 30 | + starts_at: i64, | |
| 31 | + /// Term end, UTC unix-milliseconds; must not precede `starts_at`. | |
| 32 | + #[schema(example = 1_790_000_000_000_i64)] | |
| 33 | + ends_at: i64, | |
| 34 | +} | |
| 35 | + | |
| 36 | +#[derive(Deserialize, ToSchema)] | |
| 37 | +struct UpdateTerm { | |
| 38 | + name: Option<String>, | |
| 39 | + starts_at: Option<i64>, | |
| 40 | + ends_at: Option<i64>, | |
| 41 | +} | |
| 42 | + | |
| 43 | +#[derive(Serialize, ToSchema)] | |
| 44 | +struct TermResponse { | |
| 45 | + id: String, | |
| 46 | + #[schema(example = "2026 Fall")] | |
| 47 | + name: String, | |
| 48 | + /// Term start, UTC unix-milliseconds. | |
| 49 | + starts_at: i64, | |
| 50 | + /// Term end, UTC unix-milliseconds. | |
| 51 | + ends_at: i64, | |
| 52 | +} | |
| 53 | + | |
| 54 | +impl TermResponse { | |
| 55 | + fn new(term: &Term) -> Self { | |
| 56 | + Self { | |
| 57 | + id: term.get_id().key().to_string(), | |
| 58 | + name: term.get_name().as_str().to_string(), | |
| 59 | + starts_at: term.get_starts_at().as_millis(), | |
| 60 | + ends_at: term.get_ends_at().as_millis(), | |
| 61 | + } | |
| 62 | + } | |
| 63 | +} | |
| 64 | + | |
| 65 | +/// Turn an optional request-supplied term id into a validated reference — | |
| 66 | +/// `None` stays `None`, an unknown id is a `400` naming the field. Shared by | |
| 67 | +/// the course create/update handlers. | |
| 68 | +pub(crate) async fn resolve_term( | |
| 69 | + id: Option<&str>, | |
| 70 | + db: &Database, | |
| 71 | +) -> Result<Option<TermId>, AppError> { | |
| 72 | + let Some(id) = id else { | |
| 73 | + return Ok(None); | |
| 74 | + }; | |
| 75 | + let term = Term::read(&TermId::from_key(id), db) | |
| 76 | + .await? | |
| 77 | + .ok_or(AppError::Validation(ValidationError::Invalid { | |
| 78 | + field: "term_id", | |
| 79 | + reason: "term does not exist", | |
| 80 | + }))?; | |
| 81 | + Ok(Some(term.get_id().clone())) | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// Create an academic term. Requires manager+. Past dates are allowed — | |
| 85 | +/// terms are calendar structure, not schedules. | |
| 86 | +#[utoipa::path( | |
| 87 | + post, | |
| 88 | + path = "/", | |
| 89 | + tag = "terms", | |
| 90 | + security(("session_cookie" = [])), | |
| 91 | + request_body = CreateTerm, | |
| 92 | + responses( | |
| 93 | + (status = 201, description = "Term created", body = TermResponse), | |
| 94 | + (status = 400, description = "Invalid name or range", body = ErrorResponse), | |
| 95 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 96 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 97 | + ), | |
| 98 | +)] | |
| 99 | +async fn create_term( | |
| 100 | + State(st): State<AppState>, | |
| 101 | + RequireManager(_user): RequireManager, | |
| 102 | + Json(req): Json<CreateTerm>, | |
| 103 | +) -> Result<(StatusCode, Json<TermResponse>), AppError> { | |
| 104 | + let name = TermName::try_new(&req.name)?; | |
| 105 | + let starts_at = Timestamp::from_millis(req.starts_at); | |
| 106 | + let ends_at = Timestamp::from_millis(req.ends_at); | |
| 107 | + check_time_range(Some(starts_at), Some(ends_at))?; | |
| 108 | + let term = Term::create(name, starts_at, ends_at, &st.db).await?; | |
| 109 | + Ok((StatusCode::CREATED, Json(TermResponse::new(&term)))) | |
| 110 | +} | |
| 111 | + | |
| 112 | +/// List every term, newest first. Any authenticated user — students need the | |
| 113 | +/// calendar to make sense of their courses. | |
| 114 | +#[utoipa::path( | |
| 115 | + get, | |
| 116 | + path = "/", | |
| 117 | + tag = "terms", | |
| 118 | + security(("session_cookie" = [])), | |
| 119 | + responses( | |
| 120 | + (status = 200, description = "All terms", body = [TermResponse]), | |
| 121 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 122 | + ), | |
| 123 | +)] | |
| 124 | +async fn list_terms( | |
| 125 | + State(st): State<AppState>, | |
| 126 | + CurrentUser(_user): CurrentUser, | |
| 127 | +) -> Result<Json<Vec<TermResponse>>, AppError> { | |
| 128 | + let terms = Term::list_all(&st.db).await?; | |
| 129 | + Ok(Json(terms.iter().map(TermResponse::new).collect())) | |
| 130 | +} | |
| 131 | + | |
| 132 | +/// Fetch a single term by id. | |
| 133 | +#[utoipa::path( | |
| 134 | + get, | |
| 135 | + path = "/{id}", | |
| 136 | + tag = "terms", | |
| 137 | + security(("session_cookie" = [])), | |
| 138 | + params(("id" = String, Path, description = "Term id")), | |
| 139 | + responses( | |
| 140 | + (status = 200, description = "The term", body = TermResponse), | |
| 141 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 142 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 143 | + ), | |
| 144 | +)] | |
| 145 | +async fn get_term( | |
| 146 | + State(st): State<AppState>, | |
| 147 | + CurrentUser(_user): CurrentUser, | |
| 148 | + Path(id): Path<String>, | |
| 149 | +) -> Result<Json<TermResponse>, AppError> { | |
| 150 | + let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 151 | + .await? | |
| 152 | + .ok_or(AppError::NotFound)?; | |
| 153 | + Ok(Json(TermResponse::new(&term))) | |
| 154 | +} | |
| 155 | + | |
| 156 | +/// Update a term. Requires manager+. Omitted fields keep their value; the | |
| 157 | +/// merged range must stay ordered. | |
| 158 | +#[utoipa::path( | |
| 159 | + patch, | |
| 160 | + path = "/{id}", | |
| 161 | + tag = "terms", | |
| 162 | + security(("session_cookie" = [])), | |
| 163 | + params(("id" = String, Path, description = "Term id")), | |
| 164 | + request_body = UpdateTerm, | |
| 165 | + responses( | |
| 166 | + (status = 200, description = "Updated term", body = TermResponse), | |
| 167 | + (status = 400, description = "Invalid name or range", body = ErrorResponse), | |
| 168 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 169 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 170 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 171 | + ), | |
| 172 | +)] | |
| 173 | +async fn update_term( | |
| 174 | + State(st): State<AppState>, | |
| 175 | + RequireManager(_user): RequireManager, | |
| 176 | + Path(id): Path<String>, | |
| 177 | + Json(req): Json<UpdateTerm>, | |
| 178 | +) -> Result<Json<TermResponse>, AppError> { | |
| 179 | + let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 180 | + .await? | |
| 181 | + .ok_or(AppError::NotFound)?; | |
| 182 | + | |
| 183 | + let name = match req.name { | |
| 184 | + Some(ref name) => TermName::try_new(name)?, | |
| 185 | + None => term.get_name().clone(), | |
| 186 | + }; | |
| 187 | + let starts_at = req | |
| 188 | + .starts_at | |
| 189 | + .map(Timestamp::from_millis) | |
| 190 | + .unwrap_or_else(|| term.get_starts_at()); | |
| 191 | + let ends_at = req | |
| 192 | + .ends_at | |
| 193 | + .map(Timestamp::from_millis) | |
| 194 | + .unwrap_or_else(|| term.get_ends_at()); | |
| 195 | + check_time_range(Some(starts_at), Some(ends_at))?; | |
| 196 | + | |
| 197 | + let updated = term.update(name, starts_at, ends_at, &st.db).await?; | |
| 198 | + Ok(Json(TermResponse::new(&updated))) | |
| 199 | +} | |
| 200 | + | |
| 201 | +/// Delete a term. Requires manager+. Courses linked to it survive — they just | |
| 202 | +/// lose the term link. | |
| 203 | +#[utoipa::path( | |
| 204 | + delete, | |
| 205 | + path = "/{id}", | |
| 206 | + tag = "terms", | |
| 207 | + security(("session_cookie" = [])), | |
| 208 | + params(("id" = String, Path, description = "Term id")), | |
| 209 | + responses( | |
| 210 | + (status = 204, description = "Deleted (courses unlinked)"), | |
| 211 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 212 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 213 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 214 | + ), | |
| 215 | +)] | |
| 216 | +async fn delete_term( | |
| 217 | + State(st): State<AppState>, | |
| 218 | + RequireManager(_user): RequireManager, | |
| 219 | + Path(id): Path<String>, | |
| 220 | +) -> Result<StatusCode, AppError> { | |
| 221 | + let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 222 | + .await? | |
| 223 | + .ok_or(AppError::NotFound)?; | |
| 224 | + term.delete(&st.db).await?; | |
| 225 | + Ok(StatusCode::NO_CONTENT) | |
| 226 | +} |