From ea8bfebe718c4d495b5b87bd3ed313ab632e5226 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 13 Jul 2026 05:58:15 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(school):=20editable=20policy?= =?UTF-8?q?=20settings=20+=20academic=20terms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every school differs; the varying parts become data instead of code: - settings singleton (GET any user, PATCH manager+): exam kinds, attendance statuses, grade-display bands. Absent row = old hardcoded defaults, so existing databases behave unchanged. - core four attendance statuses stay mandatory — the attendance rate is defined over them; school extras tally rate-neutral under a new `custom` bucket in reports. - grade bands are display-only over the canonical 0-100 marks: reports gain grade/average_grade/overall_grade labels, stored marks never change with the display scale. - terms are rows (semester/trimester/quarter all fit); courses link via nullable term_id, term delete unlinks, past dates allowed for mid-year calendar backfill. - settings edits never rewrite stored rows: retired kinds and statuses live on in old records; only new writes validate against the current lists. --- src/constant.rs | 24 ++- src/database.rs | 15 ++ src/domain/attendance.rs | 36 +++- src/domain/course.rs | 12 +- src/domain/exam.rs | 39 +++-- src/domain/mod.rs | 2 + src/domain/settings.rs | 357 +++++++++++++++++++++++++++++++++++++++ src/domain/term.rs | 149 ++++++++++++++++ src/lib.rs | 8 +- src/validate.rs | 48 +----- src/web/attendance.rs | 27 ++- src/web/courses.rs | 29 +++- src/web/dto.rs | 4 + src/web/events.rs | 7 +- src/web/exams.rs | 9 +- src/web/marks.rs | 22 ++- src/web/mod.rs | 2 + src/web/sessions.rs | 7 +- src/web/settings.rs | 137 +++++++++++++++ src/web/terms.rs | 226 +++++++++++++++++++++++++ 20 files changed, 1069 insertions(+), 91 deletions(-) create mode 100644 src/domain/settings.rs create mode 100644 src/domain/term.rs create mode 100644 src/web/settings.rs create mode 100644 src/web/terms.rs diff --git a/src/constant.rs b/src/constant.rs index 5ba4ef3..714b81f 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -44,14 +44,28 @@ pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; pub const MAX_COURSE_TITLE_LEN: usize = 200; pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; -/// The only accepted attendance states. -pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; +/// The default attendance states, and also the mandatory core: a school may +/// add its own statuses via `PATCH /settings`, but these four can never be +/// removed — the attendance rate's semantics are defined over them. +pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; pub const MAX_SESSION_TOPIC_LEN: usize = 200; -/// The only accepted exam kinds. Informational metadata only — `weight` drives -/// the course average. -pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; +/// The default exam kinds; schools replace the list via `PATCH /settings`. +/// Informational metadata only — `weight` drives the course average. +pub const DEFAULT_EXAM_KINDS: [&str; 6] = + ["homework", "quiz", "midterm", "final", "project", "oral"]; + +/// Bounds for the school-editable lists in settings (exam kinds, attendance +/// statuses): entry count and per-entry character length. +pub const MAX_SETTINGS_LIST_LEN: usize = 20; +pub const MAX_SETTINGS_ITEM_LEN: usize = 50; + +/// Bounds for the grade-display bands in settings. +pub const MAX_GRADE_BANDS: usize = 20; +pub const MAX_GRADE_LABEL_LEN: usize = 20; + +pub const MAX_TERM_NAME_LEN: usize = 100; /// The only accepted exam modes. `sync`: everyone sits the exam inside one /// fixed window. `async`: each student starts inside the window and gets their diff --git a/src/database.rs b/src/database.rs index a838fab..88154da 100644 --- a/src/database.rs +++ b/src/database.rs @@ -23,6 +23,8 @@ pub const ENROLLMENT_TABLE: &str = "enrollment"; pub const COURSE_SESSION_TABLE: &str = "course_session"; pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; pub const WORK_ENTRY_TABLE: &str = "work_entry"; +pub const SETTINGS_TABLE: &str = "settings"; +pub const TERM_TABLE: &str = "term"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot. @@ -67,10 +69,16 @@ const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; + DEFINE TABLE IF NOT EXISTS term SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS name ON term TYPE string; + DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; + DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; + DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; DEFINE FIELD IF NOT EXISTS title ON course TYPE string; DEFINE FIELD IF NOT EXISTS description ON course TYPE string; + DEFINE FIELD IF NOT EXISTS term ON course TYPE option>; DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; @@ -151,6 +159,13 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS mark ON exam_result TYPE int; DEFINE FIELD IF NOT EXISTS graded_by ON exam_result TYPE record; DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE; + + DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int; + DEFINE FIELD IF NOT EXISTS grade_bands.*.label ON settings TYPE string; "; /// Open the file-backed database and apply the schema. diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 4173b27..775f55b 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -4,7 +4,6 @@ use crate::database::{ATTENDANCE_TABLE, Database}; use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -use crate::validate::validate_status; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct AttendanceId(RecordId); @@ -33,13 +32,21 @@ impl AttendanceId { } } -/// A validated attendance state: present | absent | late | excused. +/// A validated attendance state — one of the school's configured statuses +/// ([`crate::domain::settings::Settings::get_attendance_statuses`]): the core +/// `present | absent | late | excused` plus any the school added. Stored rows +/// keep their status even if the school later edits the list. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct AttendanceStatus(String); impl AttendanceStatus { - pub fn try_new(value: &str) -> Result { - validate_status(value)?; + pub fn try_new(value: &str, allowed: &[String]) -> Result { + if !allowed.iter().any(|status| status == value) { + return Err(ValidationError::Invalid { + field: "status", + reason: "is not one of this school's attendance statuses (see GET /settings)", + }); + } Ok(Self(value.to_string())) } @@ -146,11 +153,24 @@ mod tests { use super::*; #[tokio::test] - async fn status_must_be_known() { + async fn status_must_be_in_the_allowed_list() { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_attendance_statuses() + .to_vec(); for status in ["present", "absent", "late", "excused"] { - assert_eq!(AttendanceStatus::try_new(status).unwrap().as_str(), status); + assert_eq!( + AttendanceStatus::try_new(status, &allowed).unwrap().as_str(), + status + ); } - assert!(AttendanceStatus::try_new("maybe").is_err()); - assert!(AttendanceStatus::try_new("").is_err()); + assert!(AttendanceStatus::try_new("maybe", &allowed).is_err()); + assert!(AttendanceStatus::try_new("", &allowed).is_err()); + // A school-added status is accepted once it's in the list. + let extended: Vec = allowed + .iter() + .cloned() + .chain(["online".to_string()]) + .collect(); + assert!(AttendanceStatus::try_new("online", &extended).is_ok()); } } diff --git a/src/domain/course.rs b/src/domain/course.rs index 6ce73c3..48b8f8c 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -3,6 +3,7 @@ use ulid::Ulid; use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; use crate::database::{COURSE_TABLE, Database}; +use crate::domain::term::TermId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -60,13 +61,14 @@ impl CourseDescription { } /// A course: the unit exams and enrollments hang off. Marks are computed per -/// course from its exams' weights. +/// course from its exams' weights. May belong to an academic term. #[derive(Debug, Clone, SurrealValue)] pub struct Course { id: CourseId, creator: UserId, title: CourseTitle, description: CourseDescription, + term: Option, } impl Course { @@ -86,6 +88,10 @@ impl Course { &self.description } + pub fn get_term(&self) -> Option<&TermId> { + self.term.as_ref() + } + pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } @@ -94,6 +100,7 @@ impl Course { creator: &UserId, title: CourseTitle, description: CourseDescription, + term: Option, db: &Database, ) -> Result { let course = Course { @@ -101,6 +108,7 @@ impl Course { creator: creator.clone(), title, description, + term, }; let created: Option = db.create(course.id.record()).content(course).await?; created.ok_or_else(|| AppError::Internal("failed to create course".into())) @@ -162,10 +170,12 @@ impl Course { mut self, title: CourseTitle, description: CourseDescription, + term: Option, db: &Database, ) -> Result { self.title = title; self.description = description; + self.term = term; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index e05ef40..c8a88df 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -8,8 +8,8 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{ - validate_exam_duration, validate_exam_kind, validate_exam_mode, validate_optional, - validate_required, validate_weight, + validate_exam_duration, validate_exam_mode, validate_optional, validate_required, + validate_weight, }; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -64,15 +64,22 @@ impl ExamDescription { } } -/// A validated exam kind: `homework` | `quiz` | `midterm` | `final` | -/// `project` | `oral`. Informational metadata only — `weight` drives the -/// course average. +/// A validated exam kind — one of the school's configured kinds +/// ([`crate::domain::settings::Settings::get_exam_kinds`]). Informational +/// metadata only — `weight` drives the course average. Stored exams keep +/// their kind even if the school later edits the list; only new writes are +/// held to the current one. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamKind(String); impl ExamKind { - pub fn try_new(value: &str) -> Result { - validate_exam_kind(value)?; + pub fn try_new(value: &str, allowed: &[String]) -> Result { + if !allowed.iter().any(|kind| kind == value) { + return Err(ValidationError::Invalid { + field: "kind", + reason: "is not one of this school's exam kinds (see GET /settings)", + }); + } Ok(Self(value.to_string())) } @@ -406,12 +413,22 @@ mod tests { } #[tokio::test] - async fn kind_must_be_known() { + async fn kind_must_be_in_the_allowed_list() { + let allowed: Vec = crate::domain::settings::Settings::defaults() + .get_exam_kinds() + .to_vec(); for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { - assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); + assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); } - assert!(ExamKind::try_new("essay").is_err()); - assert!(ExamKind::try_new("").is_err()); + assert!(ExamKind::try_new("essay", &allowed).is_err()); + assert!(ExamKind::try_new("", &allowed).is_err()); + // A school-defined list swaps the acceptance set wholesale. + let custom = vec!["lab".to_string()]; + assert!(ExamKind::try_new("lab", &custom).is_ok()); + assert!(ExamKind::try_new("midterm", &custom).is_err()); + // Matching is exact, case included — the settings list is the wire + // truth, not a case-folded suggestion. + assert!(ExamKind::try_new("Lab", &custom).is_err()); } #[tokio::test] diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 5d35a60..8dd365e 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -17,6 +17,8 @@ pub mod profile; pub mod role; pub mod session; pub mod session_attendance; +pub mod settings; +pub mod term; pub mod timestamp; pub mod user; pub mod work_entry; diff --git a/src/domain/settings.rs b/src/domain/settings.rs new file mode 100644 index 0000000..b4e7688 --- /dev/null +++ b/src/domain/settings.rs @@ -0,0 +1,357 @@ +//! School-adjustable policy: which exam kinds exist, which attendance +//! statuses the roll call accepts, and how numeric marks display as grades. +//! +//! One singleton record (`settings:school` — one school per deployment). An +//! absent record means "the defaults from `constant.rs`", so a fresh or +//! pre-existing database needs no seeding and behaves exactly as before. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::{ + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN, + MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_MARK, +}; +use crate::database::{Database, SETTINGS_TABLE}; +use crate::error::{AppError, ValidationError}; + +/// The singleton's fixed key: one school per deployment, one settings row. +const SETTINGS_KEY: &str = "school"; + +/// One grade-display band: marks at or above `min` (and below the next band's +/// `min`) render as `label`. Display only — storage and averaging stay numeric. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct GradeBand { + min: i64, + label: String, +} + +impl GradeBand { + pub fn try_new(min: i64, label: &str) -> Result { + if !(MIN_MARK..=MAX_MARK).contains(&min) { + return Err(ValidationError::Invalid { + field: "grade_bands", + reason: "band mins must be between 0 and 100", + }); + } + let label = label.trim(); + if label.is_empty() || label.chars().count() > MAX_GRADE_LABEL_LEN { + return Err(ValidationError::Invalid { + field: "grade_bands", + reason: "band labels must be 1 to 20 characters", + }); + } + Ok(Self { + min, + label: label.to_string(), + }) + } + + pub fn get_min(&self) -> i64 { + self.min + } + + pub fn get_label(&self) -> &str { + &self.label + } +} + +/// The school's policy knobs, validated as a whole (parse, don't validate — +/// like every other entity, an existing `Settings` is always internally +/// consistent). +#[derive(Debug, Clone, SurrealValue)] +pub struct Settings { + id: RecordId, + exam_kinds: Vec, + attendance_statuses: Vec, + grade_bands: Vec, +} + +impl Settings { + fn record_id() -> RecordId { + RecordId::new(SETTINGS_TABLE, SETTINGS_KEY) + } + + /// The out-of-the-box policy — mirrors the constants that were previously + /// hard-coded, so a school that never touches `/settings` sees no change. + pub fn defaults() -> Self { + Self { + id: Self::record_id(), + exam_kinds: DEFAULT_EXAM_KINDS.map(String::from).to_vec(), + attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), + grade_bands: Vec::new(), + } + } + + /// Validate a full policy. List entries are trimmed; kinds and statuses + /// must be non-empty, unique (case-insensitive), and bounded; the four + /// core attendance statuses can never be removed (the attendance rate's + /// semantics are defined over them). Bands may be empty (numeric-only + /// display), otherwise their mins are unique and one band must start at 0 + /// so every mark maps to a label. + pub fn try_new( + exam_kinds: Vec, + attendance_statuses: Vec, + grade_bands: Vec, + ) -> Result { + let exam_kinds = validate_list("exam_kinds", exam_kinds)?; + let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?; + if DEFAULT_ATTENDANCE_STATUSES + .iter() + .any(|core| !attendance_statuses.iter().any(|s| s == core)) + { + return Err(ValidationError::Invalid { + field: "attendance_statuses", + reason: "must keep the core statuses: present, absent, late, excused", + }); + } + + if grade_bands.len() > MAX_GRADE_BANDS { + return Err(ValidationError::Invalid { + field: "grade_bands", + reason: "must contain at most 20 bands", + }); + } + let mut mins: Vec = grade_bands.iter().map(GradeBand::get_min).collect(); + mins.sort_unstable(); + mins.dedup(); + if mins.len() != grade_bands.len() { + return Err(ValidationError::Invalid { + field: "grade_bands", + reason: "band mins must be unique", + }); + } + if !grade_bands.is_empty() && !mins.contains(&MIN_MARK) { + return Err(ValidationError::Invalid { + field: "grade_bands", + reason: "one band must start at 0 so every mark gets a label", + }); + } + // Canonical order: highest band first, matching lookup direction. + let mut grade_bands = grade_bands; + grade_bands.sort_by_key(|band| std::cmp::Reverse(band.get_min())); + + Ok(Self { + id: Self::record_id(), + exam_kinds, + attendance_statuses, + grade_bands, + }) + } + + pub fn get_exam_kinds(&self) -> &[String] { + &self.exam_kinds + } + + pub fn get_attendance_statuses(&self) -> &[String] { + &self.attendance_statuses + } + + pub fn get_grade_bands(&self) -> &[GradeBand] { + &self.grade_bands + } + + /// The label of the band `mark` falls into: the band with the greatest + /// `min` at or below it. `None` when no bands are configured. Takes an + /// `f64` so course averages label the same way plain marks do. + pub fn grade_label(&self, mark: f64) -> Option<&str> { + self.grade_bands + .iter() + .filter(|band| band.get_min() as f64 <= mark) + .max_by_key(|band| band.get_min()) + .map(GradeBand::get_label) + } + + /// The stored policy, or the defaults when no row exists yet. + pub async fn load(db: &Database) -> Result { + let found: Option = db.select(Self::record_id()).await?; + Ok(found.unwrap_or_else(Self::defaults)) + } + + /// Persist the policy (single UPSERT on the fixed singleton id). + pub async fn save(self, db: &Database) -> Result { + let saved: Option = db.upsert(Self::record_id()).content(self).await?; + saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) + } +} + +/// Shared rules for the editable string lists: 1–20 trimmed, non-empty, +/// ≤50-char entries with no case-insensitive duplicates. +fn validate_list( + field: &'static str, + values: Vec, +) -> Result, ValidationError> { + if values.is_empty() { + return Err(ValidationError::Empty(field)); + } + if values.len() > MAX_SETTINGS_LIST_LEN { + return Err(ValidationError::Invalid { + field, + reason: "must contain at most 20 entries", + }); + } + let mut trimmed = Vec::with_capacity(values.len()); + for value in &values { + let value = value.trim(); + if value.is_empty() || value.chars().count() > MAX_SETTINGS_ITEM_LEN { + return Err(ValidationError::Invalid { + field, + reason: "entries must be 1 to 50 characters", + }); + } + trimmed.push(value.to_string()); + } + let mut folded: Vec = trimmed.iter().map(|v| v.to_lowercase()).collect(); + folded.sort_unstable(); + folded.dedup(); + if folded.len() != trimmed.len() { + return Err(ValidationError::Invalid { + field, + reason: "entries must be unique (case-insensitive)", + }); + } + Ok(trimmed) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() + } + + fn bands(list: &[(i64, &str)]) -> Vec { + list.iter() + .map(|(min, label)| GradeBand::try_new(*min, label).unwrap()) + .collect() + } + + #[tokio::test] + async fn defaults_are_a_valid_policy() { + let defaults = Settings::defaults(); + let rebuilt = Settings::try_new( + defaults.get_exam_kinds().to_vec(), + defaults.get_attendance_statuses().to_vec(), + defaults.get_grade_bands().to_vec(), + ) + .unwrap(); + assert_eq!(rebuilt.get_exam_kinds(), defaults.get_exam_kinds()); + assert!(defaults.get_grade_bands().is_empty()); + } + + #[tokio::test] + async fn lists_are_trimmed_bounded_and_deduped() { + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); + // Trimming happens before storage. + let s = Settings::try_new(kinds(&[" lab ", "quiz"]), statuses.clone(), vec![]).unwrap(); + assert_eq!(s.get_exam_kinds(), ["lab", "quiz"]); + // Empty list, blank entry, over-long entry, and case-insensitive + // duplicates are all rejected. + assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err()); + assert!(Settings::try_new(kinds(&[" "]), statuses.clone(), vec![]).is_err()); + assert!(Settings::try_new(kinds(&[&"x".repeat(51)]), statuses.clone(), vec![]).is_err()); + assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err()); + let too_many: Vec = (0..21).map(|i| format!("kind{i}")).collect(); + assert!(Settings::try_new(too_many, statuses, vec![]).is_err()); + } + + #[tokio::test] + async fn core_attendance_statuses_are_mandatory() { + let kinds = Settings::defaults().get_exam_kinds().to_vec(); + // Extras on top of the core are fine. + let extended = statuses_with(&["online"]); + assert!(Settings::try_new(kinds.clone(), extended, vec![]).is_ok()); + // Dropping any core status is not. + let missing: Vec = statuses_with(&[]) + .into_iter() + .filter(|s| s != "late") + .collect(); + assert!(Settings::try_new(kinds, missing, vec![]).is_err()); + } + + fn statuses_with(extra: &[&str]) -> Vec { + DEFAULT_ATTENDANCE_STATUSES + .iter() + .map(|s| s.to_string()) + .chain(extra.iter().map(|s| s.to_string())) + .collect() + } + + #[tokio::test] + async fn band_rules() { + // Per-band validation: min range and label shape. + assert!(GradeBand::try_new(-1, "FF").is_err()); + assert!(GradeBand::try_new(101, "AA").is_err()); + assert!(GradeBand::try_new(50, " ").is_err()); + assert!(GradeBand::try_new(50, &"x".repeat(21)).is_err()); + assert_eq!(GradeBand::try_new(50, " CC ").unwrap().get_label(), "CC"); + + let defaults = Settings::defaults(); + let ok = |b: Vec| { + Settings::try_new( + defaults.get_exam_kinds().to_vec(), + defaults.get_attendance_statuses().to_vec(), + b, + ) + }; + // Empty = numeric-only display. + assert!(ok(vec![]).is_ok()); + // Duplicate mins die; a set without a 0-band dies (marks below the + // lowest band would have no label). + assert!(ok(bands(&[(0, "F"), (0, "E")])).is_err()); + assert!(ok(bands(&[(50, "CC"), (85, "AA")])).is_err()); + assert!(ok(bands(&[(0, "FF"), (50, "CC"), (85, "AA")])).is_ok()); + } + + #[tokio::test] + async fn load_save_roundtrip_on_the_singleton() { + let db = crate::database::init_mem().await.unwrap(); + // No row yet → the defaults, not an error. + let loaded = Settings::load(&db).await.unwrap(); + assert_eq!( + loaded.get_exam_kinds(), + Settings::defaults().get_exam_kinds() + ); + // Save a custom policy and read it back — bands (nested objects under + // a FLEXIBLE field) must survive the trip. + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); + Settings::try_new(kinds(&["lab"]), statuses.clone(), bands(&[(0, "F"), (50, "P")])) + .unwrap() + .save(&db) + .await + .unwrap(); + let loaded = Settings::load(&db).await.unwrap(); + assert_eq!(loaded.get_exam_kinds(), ["lab"]); + assert_eq!(loaded.get_grade_bands().len(), 2); + assert_eq!(loaded.grade_label(60.0), Some("P")); + // A second save lands on the same singleton row, not a new one. + Settings::try_new(kinds(&["quiz"]), statuses, vec![]) + .unwrap() + .save(&db) + .await + .unwrap(); + let mut result = db.query("SELECT * FROM settings").await.unwrap(); + let rows: Vec = result.take(0).unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_exam_kinds(), ["quiz"]); + } + + #[tokio::test] + async fn grade_label_picks_the_greatest_min_at_or_below() { + let defaults = Settings::defaults(); + let s = Settings::try_new( + defaults.get_exam_kinds().to_vec(), + defaults.get_attendance_statuses().to_vec(), + bands(&[(0, "FF"), (50, "CC"), (85, "AA")]), + ) + .unwrap(); + assert_eq!(s.grade_label(0.0), Some("FF")); + assert_eq!(s.grade_label(49.9), Some("FF")); + assert_eq!(s.grade_label(50.0), Some("CC")); + assert_eq!(s.grade_label(84.9), Some("CC")); + assert_eq!(s.grade_label(85.0), Some("AA")); + assert_eq!(s.grade_label(100.0), Some("AA")); + // No bands configured → no label, never a panic. + assert_eq!(Settings::defaults().grade_label(90.0), None); + } +} diff --git a/src/domain/term.rs b/src/domain/term.rs new file mode 100644 index 0000000..ce4ccb8 --- /dev/null +++ b/src/domain/term.rs @@ -0,0 +1,149 @@ +//! An academic term — semester, trimester, quarter, whatever this school +//! runs; the structure is just rows, so it needs no code change per school. +//! Courses may link to one term. +//! +//! Terms are calendar structure, not schedules: a school adopting the app +//! mid-year legitimately creates a term that already started, so the no-past +//! rule that guards exams/lessons/events deliberately does not apply here. + +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::MAX_TERM_NAME_LEN; +use crate::database::{Database, TERM_TABLE}; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_required; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct TermId(RecordId); + +impl TermId { + pub fn generate() -> Self { + Self(RecordId::new(TERM_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(TERM_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct TermName(String); + +impl TermName { + pub fn try_new(value: &str) -> Result { + validate_required("name", value, MAX_TERM_NAME_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One term on the school's academic calendar. Both ends are required — a +/// term is a date range by definition. +#[derive(Debug, Clone, SurrealValue)] +pub struct Term { + id: TermId, + name: TermName, + starts_at: Timestamp, + ends_at: Timestamp, +} + +impl Term { + pub fn get_id(&self) -> &TermId { + &self.id + } + + pub fn get_name(&self) -> &TermName { + &self.name + } + + pub fn get_starts_at(&self) -> Timestamp { + self.starts_at + } + + pub fn get_ends_at(&self) -> Timestamp { + self.ends_at + } + + pub async fn create( + name: TermName, + starts_at: Timestamp, + ends_at: Timestamp, + db: &Database, + ) -> Result { + let term = Term { + id: TermId::generate(), + name, + starts_at, + ends_at, + }; + let created: Option = db.create(term.id.record()).content(term).await?; + created.ok_or_else(|| AppError::Internal("failed to create term".into())) + } + + pub async fn read(id: &TermId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every term, newest first — the school calendar is small by nature. + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM term ORDER BY starts_at DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + name: TermName, + starts_at: Timestamp, + ends_at: Timestamp, + db: &Database, + ) -> Result { + self.name = name; + self.starts_at = starts_at; + self.ends_at = ends_at; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the term. Courses keep existing — they just lose the link, so + /// deleting a term can never take a course (or its marks) with it. + pub async fn delete(self, db: &Database) -> Result { + db.query("UPDATE course SET term = NONE WHERE term = $term") + .bind(("term", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn name_is_required_and_bounded() { + assert!(TermName::try_new("2026 Fall").is_ok()); + assert!(TermName::try_new("").is_err()); + assert!(TermName::try_new(" ").is_err()); + assert!(TermName::try_new(&"x".repeat(101)).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs index e81e874..0aa9a82 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( @@ -46,7 +46,9 @@ use crate::state::AppState; (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), (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"), - (name = "marks", description = "Weighted mark reports per course and overall"), + (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured"), + (name = "settings", description = "School policy, one singleton: exam kinds, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"), + (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), ), )] struct ApiDoc; @@ -85,6 +87,8 @@ pub fn build_router(state: AppState) -> Router { .nest("/marks", web::marks::routes()) .nest("/work", web::work::routes()) .nest("/attendance", web::attendance::routes()) + .nest("/settings", web::settings::routes()) + .nest("/terms", web::terms::routes()) .split_for_parts(); // Catch-all per-IP limit over every route (Swagger included). Kept inside diff --git a/src/validate.rs b/src/validate.rs index a8a4935..504aa5e 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,10 +2,10 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - ATTENDANCE_STATUSES, EXAM_KINDS, EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, - MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, - MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, - MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS, + EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_DURATION_MS, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, + MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, + MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, + MIN_USERNAME_LEN, QUESTION_KINDS, USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -195,28 +195,6 @@ pub fn validate_phone(value: &str) -> Result<(), ValidationError> { Ok(()) } -pub fn validate_status(value: &str) -> Result<(), ValidationError> { - if ATTENDANCE_STATUSES.contains(&value) { - Ok(()) - } else { - Err(ValidationError::Invalid { - field: "status", - reason: "must be one of: present, absent, late, excused", - }) - } -} - -pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { - if EXAM_KINDS.contains(&value) { - Ok(()) - } else { - Err(ValidationError::Invalid { - field: "kind", - reason: "must be one of: homework, quiz, midterm, final, project, oral", - }) - } -} - pub fn validate_exam_mode(value: &str) -> Result<(), ValidationError> { if EXAM_MODES.contains(&value) { Ok(()) @@ -394,24 +372,6 @@ mod tests { assert!(validate_phone("55+5123456").is_err()); // + only allowed in front } - #[tokio::test] - async fn status_rules() { - for status in ["present", "absent", "late", "excused"] { - assert!(validate_status(status).is_ok()); - } - assert!(validate_status("maybe").is_err()); - assert!(validate_status("").is_err()); - } - - #[tokio::test] - async fn exam_kind_rules() { - for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { - assert!(validate_exam_kind(kind).is_ok()); - } - assert!(validate_exam_kind("essay").is_err()); - assert!(validate_exam_kind("").is_err()); - } - #[tokio::test] async fn exam_mode_rules() { for mode in ["sync", "async"] { diff --git a/src/web/attendance.rs b/src/web/attendance.rs index f7df648..5e33256 100644 --- a/src/web/attendance.rs +++ b/src/web/attendance.rs @@ -32,11 +32,15 @@ struct StatusCounts { absent: u64, late: u64, excused: u64, - /// All rows, `excused` included. + /// Tallies of the school-added statuses (`GET /settings`), keyed by + /// status. Rate-neutral like `excused`: their semantics are the school's, + /// so they count into `total` only. + custom: HashMap, + /// All rows, `excused` and custom statuses included. total: u64, /// `(present + late) / (present + absent + late)` — being late is still /// attending, and an excused absence counts against no one. `null` when - /// every row is excused (or there are none). + /// every row is excused/custom (or there are none). rate: Option, } @@ -49,8 +53,8 @@ impl StatusCounts { "present" => counts.present += 1, "absent" => counts.absent += 1, "late" => counts.late += 1, - // `AttendanceStatus` admits exactly four values. - _ => counts.excused += 1, + "excused" => counts.excused += 1, + custom => *counts.custom.entry(custom.to_string()).or_default() += 1, } } counts.rate = attendance_rate(counts.present, counts.absent, counts.late); @@ -215,17 +219,24 @@ mod tests { #[tokio::test] async fn tally_buckets_every_status() { - let statuses: Vec = ["present", "present", "late", "absent", "excused"] + let allowed: Vec = ["present", "absent", "late", "excused", "online"] .iter() - .map(|s| AttendanceStatus::try_new(s).unwrap()) + .map(|s| s.to_string()) .collect(); + let statuses: Vec = + ["present", "present", "late", "absent", "excused", "online"] + .iter() + .map(|s| AttendanceStatus::try_new(s, &allowed).unwrap()) + .collect(); let counts = StatusCounts::tally(statuses.iter()); assert_eq!(counts.present, 2); assert_eq!(counts.late, 1); assert_eq!(counts.absent, 1); assert_eq!(counts.excused, 1); - assert_eq!(counts.total, 5); - // (2 + 1) / (2 + 1 + 1) + // A school-added status lands in its own bucket — never in `excused`. + assert_eq!(counts.custom.get("online"), Some(&1)); + assert_eq!(counts.total, 6); + // Rate ignores excused and custom rows: (2 + 1) / (2 + 1 + 1). assert_eq!(counts.rate, Some(0.75)); } } diff --git a/src/web/courses.rs b/src/web/courses.rs index beadf18..8574abb 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -16,15 +16,17 @@ use crate::domain::exam::{ Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, }; use crate::domain::role::Role; +use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; use super::sessions::resolve_session_teacher; +use super::terms::resolve_term; use super::{ CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse, - check_not_past, check_time_range, person_map, + check_not_past, check_time_range, person_map, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -43,12 +45,19 @@ struct CreateCourse { #[schema(example = "Algebra")] title: String, description: Option, + /// The academic term this course belongs to (`GET /terms`). Optional. + term_id: Option, } #[derive(Deserialize, ToSchema)] struct UpdateCourse { title: Option, description: Option, + /// Omit to keep the current term, send `null` to unlink, or send a term + /// id to (re)assign. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + term_id: Option>, } #[derive(Deserialize, ToSchema)] @@ -63,8 +72,9 @@ struct CreateExamInCourse { #[schema(example = "Midterm")] title: String, description: Option, - /// The assessment form: `homework`, `quiz`, `midterm`, `final`, `project`, - /// or `oral`. Informational — `weight` drives the course average. + /// The assessment form — one of the school's exam kinds (`GET /settings`; + /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`). + /// Informational — `weight` drives the course average. #[schema(example = "midterm")] kind: String, /// How many times this exam counts into the course average, `1`–`100`. @@ -177,7 +187,8 @@ async fn create_course( ) -> Result<(StatusCode, Json), AppError> { let title = CourseTitle::try_new(&req.title)?; let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; - let course = Course::create(user.get_id(), title, description, &st.db).await?; + let term = resolve_term(req.term_id.as_deref(), &st.db).await?; + let course = Course::create(user.get_id(), title, description, term, &st.db).await?; Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) } @@ -291,8 +302,13 @@ async fn update_course( Some(ref description) => CourseDescription::try_new(description)?, None => course.get_description().clone(), }; + let term = match req.term_id { + // Explicit `null` clears the link; a value must name a real term. + Some(update) => resolve_term(update.as_deref(), &st.db).await?, + None => course.get_term().cloned(), + }; - let updated = course.update(title, description, &st.db).await?; + let updated = course.update(title, description, term, &st.db).await?; Ok(Json(CourseResponse::new(&updated))) } @@ -496,7 +512,8 @@ async fn create_exam_in_course( let title = ExamTitle::try_new(&req.title)?; let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; - let kind = ExamKind::try_new(&req.kind)?; + let school = Settings::load(&st.db).await?; + let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?; let weight = ExamWeight::try_new(req.weight)?; let starts_at = req.starts_at.map(Timestamp::from_millis); let ends_at = req.ends_at.map(Timestamp::from_millis); diff --git a/src/web/dto.rs b/src/web/dto.rs index 3889066..10b9690 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -150,6 +150,9 @@ pub struct CourseResponse { #[schema(example = "Algebra")] pub title: String, pub description: String, + /// The academic term this course belongs to (`GET /terms`); `null` when + /// unassigned. + pub term: Option, } impl CourseResponse { @@ -159,6 +162,7 @@ impl CourseResponse { creator: course.get_creator().key().to_string(), title: course.get_title().as_str().to_string(), description: course.get_description().as_str().to_string(), + term: course.get_term().map(|term| term.key().to_string()), } } } diff --git a/src/web/events.rs b/src/web/events.rs index ec135c8..504ff4e 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -11,6 +11,7 @@ use utoipa_axum::routes; use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::event::{Event, EventDescription, EventId, EventTitle}; use crate::domain::role::Role; +use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -58,7 +59,8 @@ struct UpdateEvent { #[derive(Deserialize, ToSchema)] struct MarkAttendance { - /// One of the accepted attendance statuses (e.g. `present`, `absent`). + /// One of the school's attendance statuses (`GET /settings`; the core + /// four are `present`, `absent`, `late`, `excused`). #[schema(example = "present")] status: String, /// Target user id. Defaults to the caller when omitted. @@ -333,7 +335,8 @@ async fn mark( .await? .ok_or(AppError::NotFound)?; - let status = AttendanceStatus::try_new(&req.status)?; + let school = Settings::load(&st.db).await?; + let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; let target = match req.user_id { Some(ref key) => UserId::from_key(key), None => user.get_id().clone(), diff --git a/src/web/exams.rs b/src/web/exams.rs index 24c2761..32de503 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -27,6 +27,7 @@ use crate::domain::exam_question::{ }; use crate::domain::exam_result::{ExamResult, Mark}; use crate::domain::role::Role; +use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -252,7 +253,13 @@ async fn update_exam( None => exam.get_description().clone(), }; let kind = match req.kind { - Some(ref kind) => ExamKind::try_new(kind)?, + // Only a kind this request sets is held to the current settings list — + // a stored kind survives later list edits, like past times survive + // the no-past rule. + Some(ref kind) => { + let school = Settings::load(&st.db).await?; + ExamKind::try_new(kind, school.get_exam_kinds())? + } None => exam.get_kind().clone(), }; let weight = match req.weight { diff --git a/src/web/marks.rs b/src/web/marks.rs index 214e907..1edb9ab 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -12,6 +12,7 @@ use crate::domain::course::Course; use crate::domain::exam::Exam; use crate::domain::exam_result::ExamResult; use crate::domain::role::Role; +use crate::domain::settings::Settings; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; @@ -34,6 +35,10 @@ struct MarkEntry { kind: String, weight: i64, mark: i64, + /// The mark's label from the school's grade bands (`GET /settings`); + /// `null` when no bands are configured. + #[schema(example = "AA")] + grade: Option, graded_by: String, } @@ -46,6 +51,9 @@ struct CourseMarks { /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while /// nothing is graded. average: Option, + /// The average's label from the school's grade bands; `null` when there + /// is no average or no bands are configured. + average_grade: Option, } /// A student's full mark report across their enrolled courses. @@ -57,6 +65,9 @@ struct MarksReport { /// Plain mean of the non-null course averages; `null` while no course has /// a graded exam. overall_average: Option, + /// The overall average's label from the school's grade bands; `null` when + /// there is no average or no bands are configured. + overall_grade: Option, } /// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The @@ -85,6 +96,9 @@ async fn build_report( courses.retain(|course| can_manage_course(course, viewer)); } + // One settings read labels the whole report. + let school = Settings::load(db).await?; + let mut blocks = Vec::with_capacity(courses.len()); for course in &courses { let exams = Exam::list_for_course(course.get_id(), db).await?; @@ -105,14 +119,19 @@ async fn build_report( kind: exam.get_kind().as_str().to_string(), weight: exam.get_weight().as_i64(), mark: result.get_mark().as_i64(), + grade: school + .grade_label(result.get_mark().as_i64() as f64) + .map(str::to_string), graded_by: result.get_graded_by().key().to_string(), }); pairs.push((result.get_mark().as_i64(), exam.get_weight().as_i64())); } + let average = weighted_average(&pairs); blocks.push(CourseMarks { course: CourseResponse::new(course), - average: weighted_average(&pairs), + average, + average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), results: entries, }); } @@ -125,6 +144,7 @@ async fn build_report( user: user.key().to_string(), courses: blocks, overall_average, + overall_grade: overall_average.and_then(|a| school.grade_label(a).map(str::to_string)), }) } diff --git a/src/web/mod.rs b/src/web/mod.rs index 76a9f36..3d780a6 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -12,6 +12,8 @@ pub mod exams; pub mod marks; pub mod notes; pub mod sessions; +pub mod settings; +pub mod terms; pub mod users; pub mod work; diff --git a/src/web/sessions.rs b/src/web/sessions.rs index f36deb0..11be8e4 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -15,6 +15,7 @@ use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic use crate::domain::enrollment::Enrollment; use crate::domain::role::Role; use crate::domain::session_attendance::SessionAttendance; +use crate::domain::settings::Settings; use crate::domain::timestamp::Timestamp; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -50,7 +51,8 @@ struct UpdateSession { #[derive(Deserialize, ToSchema)] struct MarkRollCall { - /// One of the accepted attendance statuses (e.g. `present`, `absent`). + /// One of the school's attendance statuses (`GET /settings`; the core + /// four are `present`, `absent`, `late`, `excused`). #[schema(example = "present")] status: String, /// Whose roll-call state to record: an enrolled student, or the session's @@ -295,7 +297,8 @@ async fn mark_roll_call( )); } - let status = AttendanceStatus::try_new(&req.status)?; + let school = Settings::load(&st.db).await?; + let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; let target = UserId::from_key(&req.user_id); // Target user must exist. diff --git a/src/web/settings.rs b/src/web/settings.rs new file mode 100644 index 0000000..632650a --- /dev/null +++ b/src/web/settings.rs @@ -0,0 +1,137 @@ +use axum::Json; +use axum::extract::State; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::settings::{GradeBand, Settings}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::{CurrentUser, RequireManager}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(get_settings, update_settings)) +} + +/// One grade-display band: marks at or above `min` (and below the next band's +/// `min`) render as `label`. +#[derive(Serialize, Deserialize, ToSchema)] +struct GradeBandDto { + /// Lowest mark of the band, `0`–`100`. One band must start at `0`. + #[schema(example = 85)] + min: i64, + /// What that range shows as, 1–20 characters (`"AA"`, `"5"`, `"pass"`). + #[schema(example = "AA")] + label: String, +} + +/// The school's policy: which exam kinds exist, which attendance statuses the +/// roll call accepts, and how numeric marks display as grades. +#[derive(Serialize, ToSchema)] +struct SettingsResponse { + /// Accepted `kind` values for new exams. + #[schema(example = json!(["homework", "quiz", "midterm", "final", "project", "oral"]))] + exam_kinds: Vec, + /// Accepted `status` values for attendance marking. Always contains the + /// core four (`present`, `absent`, `late`, `excused`). + #[schema(example = json!(["present", "absent", "late", "excused"]))] + attendance_statuses: Vec, + /// Grade-display bands, highest first. Empty = marks display numeric-only. + grade_bands: Vec, +} + +impl SettingsResponse { + fn new(settings: &Settings) -> Self { + Self { + exam_kinds: settings.get_exam_kinds().to_vec(), + attendance_statuses: settings.get_attendance_statuses().to_vec(), + grade_bands: settings + .get_grade_bands() + .iter() + .map(|band| GradeBandDto { + min: band.get_min(), + label: band.get_label().to_string(), + }) + .collect(), + } + } +} + +#[derive(Deserialize, ToSchema)] +struct UpdateSettings { + /// Replaces the whole list when present: 1–20 unique entries, each 1–50 + /// characters. + exam_kinds: Option>, + /// Replaces the whole list when present; must keep `present`, `absent`, + /// `late`, `excused` (the attendance rate is defined over them). + attendance_statuses: Option>, + /// Replaces the whole set when present. `[]` clears the bands (numeric-only + /// marks); otherwise mins are unique and one band must start at `0`. + grade_bands: Option>, +} + +/// The school's current policy. Any authenticated user — clients need it to +/// render pickers and grades. Falls back to the built-in defaults until a +/// manager edits it. +#[utoipa::path( + get, + path = "/", + tag = "settings", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The school's policy", body = SettingsResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn get_settings( + State(st): State, + CurrentUser(_user): CurrentUser, +) -> Result, AppError> { + let settings = Settings::load(&st.db).await?; + Ok(Json(SettingsResponse::new(&settings))) +} + +/// Update the school's policy. Requires manager+. Omitted fields keep their +/// value; a present field replaces its list wholesale. Existing rows are +/// untouched — a removed exam kind or status lives on in old records; only +/// new writes are held to the new lists. +#[utoipa::path( + patch, + path = "/", + tag = "settings", + security(("session_cookie" = [])), + request_body = UpdateSettings, + responses( + (status = 200, description = "Updated policy", body = SettingsResponse), + (status = 400, description = "Invalid lists or bands", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + ), +)] +async fn update_settings( + State(st): State, + RequireManager(_user): RequireManager, + Json(req): Json, +) -> Result, AppError> { + let current = Settings::load(&st.db).await?; + + let exam_kinds = req + .exam_kinds + .unwrap_or_else(|| current.get_exam_kinds().to_vec()); + let attendance_statuses = req + .attendance_statuses + .unwrap_or_else(|| current.get_attendance_statuses().to_vec()); + let grade_bands = match req.grade_bands { + Some(bands) => bands + .into_iter() + .map(|band| GradeBand::try_new(band.min, &band.label)) + .collect::, _>>()?, + None => current.get_grade_bands().to_vec(), + }; + + let settings = Settings::try_new(exam_kinds, attendance_statuses, grade_bands)?; + let saved = settings.save(&st.db).await?; + Ok(Json(SettingsResponse::new(&saved))) +} diff --git a/src/web/terms.rs b/src/web/terms.rs new file mode 100644 index 0000000..df4d152 --- /dev/null +++ b/src/web/terms.rs @@ -0,0 +1,226 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::term::{Term, TermId, TermName}; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{CurrentUser, RequireManager, check_time_range}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_term, list_terms)) + .routes(routes!(get_term, update_term, delete_term)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateTerm { + #[schema(example = "2026 Fall")] + name: String, + /// Term start, UTC unix-milliseconds. May lie in the past — a school + /// adopting the app mid-year backfills its calendar legitimately. + #[schema(example = 1_780_000_000_000_i64)] + starts_at: i64, + /// Term end, UTC unix-milliseconds; must not precede `starts_at`. + #[schema(example = 1_790_000_000_000_i64)] + ends_at: i64, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateTerm { + name: Option, + starts_at: Option, + ends_at: Option, +} + +#[derive(Serialize, ToSchema)] +struct TermResponse { + id: String, + #[schema(example = "2026 Fall")] + name: String, + /// Term start, UTC unix-milliseconds. + starts_at: i64, + /// Term end, UTC unix-milliseconds. + ends_at: i64, +} + +impl TermResponse { + fn new(term: &Term) -> Self { + Self { + id: term.get_id().key().to_string(), + name: term.get_name().as_str().to_string(), + starts_at: term.get_starts_at().as_millis(), + ends_at: term.get_ends_at().as_millis(), + } + } +} + +/// Turn an optional request-supplied term id into a validated reference — +/// `None` stays `None`, an unknown id is a `400` naming the field. Shared by +/// the course create/update handlers. +pub(crate) async fn resolve_term( + id: Option<&str>, + db: &Database, +) -> Result, AppError> { + let Some(id) = id else { + return Ok(None); + }; + let term = Term::read(&TermId::from_key(id), db) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { + field: "term_id", + reason: "term does not exist", + }))?; + Ok(Some(term.get_id().clone())) +} + +/// Create an academic term. Requires manager+. Past dates are allowed — +/// terms are calendar structure, not schedules. +#[utoipa::path( + post, + path = "/", + tag = "terms", + security(("session_cookie" = [])), + request_body = CreateTerm, + responses( + (status = 201, description = "Term created", body = TermResponse), + (status = 400, description = "Invalid name or range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + ), +)] +async fn create_term( + State(st): State, + RequireManager(_user): RequireManager, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let name = TermName::try_new(&req.name)?; + let starts_at = Timestamp::from_millis(req.starts_at); + let ends_at = Timestamp::from_millis(req.ends_at); + check_time_range(Some(starts_at), Some(ends_at))?; + let term = Term::create(name, starts_at, ends_at, &st.db).await?; + Ok((StatusCode::CREATED, Json(TermResponse::new(&term)))) +} + +/// List every term, newest first. Any authenticated user — students need the +/// calendar to make sense of their courses. +#[utoipa::path( + get, + path = "/", + tag = "terms", + security(("session_cookie" = [])), + responses( + (status = 200, description = "All terms", body = [TermResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_terms( + State(st): State, + CurrentUser(_user): CurrentUser, +) -> Result>, AppError> { + let terms = Term::list_all(&st.db).await?; + Ok(Json(terms.iter().map(TermResponse::new).collect())) +} + +/// Fetch a single term by id. +#[utoipa::path( + get, + path = "/{id}", + tag = "terms", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Term id")), + responses( + (status = 200, description = "The term", body = TermResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_term( + State(st): State, + CurrentUser(_user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let term = Term::read(&TermId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(TermResponse::new(&term))) +} + +/// Update a term. Requires manager+. Omitted fields keep their value; the +/// merged range must stay ordered. +#[utoipa::path( + patch, + path = "/{id}", + tag = "terms", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Term id")), + request_body = UpdateTerm, + responses( + (status = 200, description = "Updated term", body = TermResponse), + (status = 400, description = "Invalid name or range", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_term( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let term = Term::read(&TermId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + + let name = match req.name { + Some(ref name) => TermName::try_new(name)?, + None => term.get_name().clone(), + }; + let starts_at = req + .starts_at + .map(Timestamp::from_millis) + .unwrap_or_else(|| term.get_starts_at()); + let ends_at = req + .ends_at + .map(Timestamp::from_millis) + .unwrap_or_else(|| term.get_ends_at()); + check_time_range(Some(starts_at), Some(ends_at))?; + + let updated = term.update(name, starts_at, ends_at, &st.db).await?; + Ok(Json(TermResponse::new(&updated))) +} + +/// Delete a term. Requires manager+. Courses linked to it survive — they just +/// lose the term link. +#[utoipa::path( + delete, + path = "/{id}", + tag = "terms", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Term id")), + responses( + (status = 204, description = "Deleted (courses unlinked)"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_term( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result { + let term = Term::read(&TermId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + term.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +}