From 3681441ce752afafff7d09b59e68741627863c9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 14 Jul 2026 04:17:36 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams)!:=20move=20weight=20off?= =?UTF-8?q?=20exams=20onto=20their=20kind?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Weighting is school policy, not per-exam data: each settings exam_kinds entry is now {name, weight} (1-100, defaults all 1) and mark reports resolve weights at read time, so editing a kind reweights every exam of that kind at once; an exam keeping a since-removed kind counts as 1. BREAKING CHANGE: exams lose `weight` on the wire and in storage, settings `exam_kinds` become objects. No data migration (pre-customer clean break) — delete ./data/hezarfen.db and reboot. --- README.md | 57 ++++-- src/constant.rs | 25 ++- src/database.rs | 5 +- src/domain/course.rs | 3 +- src/domain/exam.rs | 52 ++---- src/domain/exam_attempt.rs | 3 +- src/domain/settings.rs | 163 ++++++++++++++--- src/lib.rs | 8 +- src/validate.rs | 30 +--- src/web/courses.rs | 25 ++- src/web/dto.rs | 4 +- src/web/exams.rs | 13 +- src/web/marks.rs | 25 ++- src/web/settings.rs | 62 +++++-- tests/common/mod.rs | 4 +- tests/e2e.rs | 12 +- tests/integration.rs | 356 ++++++++++++++++++++++++------------- tests/persistence.rs | 43 ++++- 18 files changed, 570 insertions(+), 320 deletions(-) diff --git a/README.md b/README.md index 26f715e..f202b49 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,10 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager < admin`). Notes are per-user. Attendance is event + attendees: create an event, then mark users present / absent / late / excused. Marks are course-shaped (Google Classroom style): a teacher creates a course, enrolls students, adds -weighted exams inside it, and grades; students read a per-course weighted -average and an overall average from their mark report. Exams run **sync** (one +exams inside it, and grades; students read a per-course weighted average and +an overall average from their mark report — each exam weighted by its **kind** +(midterms can count double, orals once: weights are set per kind in settings, +not per exam). Exams run **sync** (one fixed window), **async** (start anytime inside the window, with a personal time budget), or **open** (sit anytime, optionally timed per attempt); students *sit* them via attempts — retakes metered by a per-exam limit @@ -18,9 +20,10 @@ and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also sessions** with teacher-taken roll call (students never self-mark a lesson), staff clock in/out on a server-stamped **work log**, and every user has an **attendance report** (event + per-course lesson tallies with rates). -School-varying policy is data, not code: exam kinds, attendance statuses, and -grade-display bands live in an editable **settings** singleton, and academic -**terms** are plain rows courses can link to (see "Per-school policy"). +School-varying policy is data, not code: exam kinds (each with its weight in +course averages), attendance statuses, and grade-display bands live in an +editable **settings** singleton, and academic **terms** are plain rows courses +can link to (see "Per-school policy"). Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …) constructed only after its restrictions pass — invalid input can't be @@ -272,11 +275,11 @@ marks/attendance reports narrow to the courses the caller manages. | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ | | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) | | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) | -| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, weight, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager) | +| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind | | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) | | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) | | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) | -| PATCH | `/exams/{id}` | teacher | Edit exam incl. `weight`, schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | +| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) | | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) | | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) | | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) | @@ -306,7 +309,7 @@ marks/attendance reports narrow to the courses the caller manages. | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | -| GET | `/settings` | student | The school's policy: `exam_kinds`, `attendance_statuses`, `grade_bands` | +| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` | | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") | | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) | | GET | `/terms` | student | List terms, newest first | @@ -318,8 +321,10 @@ marks/attendance reports narrow to the courses the caller manages. the core four `present | absent | late | excused` always exist, plus whatever the school added. `kind` must be one of the school's exam kinds (`GET /settings`; defaults: -`homework | quiz | midterm | final | project | oral`) — informational -metadata; the average is driven by `weight`, an integer `1`–`100` set per exam. +`homework | quiz | midterm | final | project | oral`). The kind carries the +exam's weight in the course average — an integer `1`–`100` set per **kind** in +settings (defaults all `1`), resolved when a report is read; an exam whose +kind was later removed from settings counts with weight `1`. A course may carry a `term_id` (`null` = unassigned); on `PATCH /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null` clears it. @@ -364,10 +369,15 @@ Every school runs differently; the parts that vary are data, not code. One editable `settings` singleton (`GET /settings` for any signed-in user, `PATCH /settings` for manager+) carries three knobs: -- **`exam_kinds`** — the accepted `kind` values for new exams. Defaults to - `homework, quiz, midterm, final, project, oral`; replace the list with - whatever the school grades (`lab`, `presentation`, …). Kinds stay - informational — `weight` drives every average. +- **`exam_kinds`** — the accepted `kind` values for new exams, each an + object `{name, weight}`. The weight (`1`–`100`) is how many times an exam + of that kind counts into its course average — weighting is school policy, + set once per kind, never per exam. Defaults to `homework, quiz, midterm, + final, project, oral`, all weighing `1` (a plain average); replace the + list with whatever the school grades and weighs (`{"name": "final", + "weight": 3}`, …). Reports resolve weights live: editing a weight + re-weights every exam of that kind at once, and an exam keeping a + since-removed kind counts with weight `1`. - **`attendance_statuses`** — what attendance marking accepts. The core four (`present`, `absent`, `late`, `excused`) are mandatory because the attendance rate is defined over them (`(present+late) / @@ -482,10 +492,10 @@ along with results; unenrolling mid-exam hides the student from the monitor roster but keeps the attempt and mark rows, mirroring the marks report. > **Upgrading a pre-course database**: `exam` rows created before courses -> existed lack the now-required `course` and `weight` fields and will fail to -> deserialize. For a dev database, delete `./data/hezarfen.db` and reboot; to -> keep data, backfill manually with the SurrealDB CLI (server stopped), e.g. -> `UPDATE exam SET course = course:, weight = 1 WHERE course = NONE;` +> existed lack the now-required `course` field and will fail to deserialize. +> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data, +> backfill manually with the SurrealDB CLI (server stopped), e.g. +> `UPDATE exam SET course = course: WHERE course = NONE;` > after creating a course to attach them to. > > **Upgrading to the attempts/rejoin build needs nothing manual**: the boot @@ -493,6 +503,12 @@ roster but keeps the attempt and mark rows, mirroring the marks report. > `seq = 1` on existing rows, and swaps the single-attempt unique index for > the per-sitting one. Pre-upgrade attempts keep their record ids and count > as sitting #1. +> +> **Upgrading to the kind-weight build is a clean break**: weights moved off +> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with +> no data migration. A database from an older build has string kinds and a +> per-exam `weight` column the code no longer understands — delete +> `./data/hezarfen.db` and reboot. ## Taking an exam: questions, answers & the exam room @@ -679,6 +695,9 @@ curl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json' curl -s -b $JAR $BASE/events/$EV/attendance # courses + weighted marks (as a teacher) +# optional, manager+: weigh midterms triple — school policy, per kind +curl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \ + -d '{"exam_kinds":[{"name":"midterm","weight":3},{"name":"quiz","weight":1}]}' # find the student to enroll (here: a registered user "veli"): fragment # search over username/name, role-narrowed (teacher+) SID=$(curl -s -b $JAR "$BASE/users/search?q=vel&role=student" \ @@ -688,7 +707,7 @@ CO=$(curl -s -b $JAR $BASE/courses -H 'content-type: application/json' \ curl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \ -d "{\"user_id\":\"$SID\"}" EX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \ - -d '{"title":"midterm","kind":"midterm","weight":3}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) + -d '{"title":"midterm","kind":"midterm"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4) curl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \ -d "{\"mark\":90,\"user_id\":\"$SID\"}" curl -s -b $JAR $BASE/exams/$EX/statistics diff --git a/src/constant.rs b/src/constant.rs index 15fa3b5..c5aaf2d 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -51,10 +51,18 @@ pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", pub const MAX_SESSION_TOPIC_LEN: usize = 200; -/// 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"]; +/// The default exam kinds with their weights; schools replace the list via +/// `PATCH /settings`. An exam's kind decides how heavily it counts into the +/// course average — the defaults all weigh 1 (a plain average) so weighting +/// is opt-in policy, not baked-in opinion. +pub const DEFAULT_EXAM_KINDS: [(&str, i64); 6] = [ + ("homework", 1), + ("quiz", 1), + ("midterm", 1), + ("final", 1), + ("project", 1), + ("oral", 1), +]; /// Bounds for the school-editable lists in settings (exam kinds, attendance /// statuses): entry count and per-entry character length. @@ -117,10 +125,11 @@ pub const MAX_ANSWER_TEXT_LEN: usize = 10_000; pub const MIN_MARK: i64 = 0; pub const MAX_MARK: i64 = 100; -/// Inclusive bounds for an exam's weight in the course average. The minimum of -/// 1 keeps every graded exam counted and the average's denominator non-zero. -pub const MIN_EXAM_WEIGHT: i64 = 1; -pub const MAX_EXAM_WEIGHT: i64 = 100; +/// Inclusive bounds for an exam kind's weight in the course average. The +/// minimum of 1 keeps every graded exam counted and the average's denominator +/// non-zero. +pub const MIN_EXAM_KIND_WEIGHT: i64 = 1; +pub const MAX_EXAM_KIND_WEIGHT: i64 = 100; pub const SESSION_DURATION_DAYS: i64 = 7; diff --git a/src/database.rs b/src/database.rs index 7af80ab..42fe7be 100644 --- a/src/database.rs +++ b/src/database.rs @@ -121,7 +121,6 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; - DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int; DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option; DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option; DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option; @@ -172,7 +171,9 @@ const MIGRATION: &str = " 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 exam_kinds ON settings TYPE array; + DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string; + DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int; 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; diff --git a/src/domain/course.rs b/src/domain/course.rs index 48b8f8c..e83b6f8 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -61,7 +61,8 @@ impl CourseDescription { } /// A course: the unit exams and enrollments hang off. Marks are computed per -/// course from its exams' weights. May belong to an academic term. +/// course, each exam weighted by its kind's settings weight. May belong to an +/// academic term. #[derive(Debug, Clone, SurrealValue)] pub struct Course { id: CourseId, diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 9cb76be..b304eef 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -4,12 +4,13 @@ use ulid::Ulid; use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS}; use crate::database::{Database, EXAM_TABLE}; use crate::domain::course::CourseId; +use crate::domain::settings::ExamKindDef; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{ validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional, - validate_required, validate_weight, + validate_required, }; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -65,16 +66,16 @@ impl ExamDescription { } /// 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. +/// ([`crate::domain::settings::Settings::get_exam_kinds`]). The kind carries +/// the exam's weight in the course average (set per kind in settings, not per +/// exam). 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, allowed: &[String]) -> Result { - if !allowed.iter().any(|kind| kind == value) { + pub fn try_new(value: &str, allowed: &[ExamKindDef]) -> Result { + if !allowed.iter().any(|kind| kind.get_name() == value) { return Err(ValidationError::Invalid { field: "kind", reason: "is not one of this school's exam kinds (see GET /settings)", @@ -88,22 +89,6 @@ impl ExamKind { } } -/// A validated exam weight, held to `[MIN_EXAM_WEIGHT, MAX_EXAM_WEIGHT]`. The -/// exam counts `weight` times into its course's average. -#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] -pub struct ExamWeight(i64); - -impl ExamWeight { - pub fn try_new(value: i64) -> Result { - validate_weight(value)?; - Ok(Self(value)) - } - - pub fn as_i64(&self) -> i64 { - self.0 - } -} - /// A validated exam mode: `sync` (everyone sits inside one fixed window), /// `async` (each student starts inside the window and gets `duration_ms`), or /// `open` (no window — sit anytime, with an optional per-attempt duration). @@ -262,7 +247,6 @@ pub struct Exam { title: ExamTitle, description: ExamDescription, kind: ExamKind, - weight: ExamWeight, // The schedule, flattened into columns (SCHEMAFULL keeps them typed). // Always written through an `ExamSchedule`, so the invariants above hold // for every stored row; pre-schedule rows read back as all-`None`. @@ -301,10 +285,6 @@ impl Exam { &self.kind } - pub fn get_weight(&self) -> ExamWeight { - self.weight - } - pub fn get_mode(&self) -> Option<&ExamMode> { self.mode.as_ref() } @@ -357,7 +337,6 @@ impl Exam { title: ExamTitle, description: ExamDescription, kind: ExamKind, - weight: ExamWeight, schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, @@ -370,7 +349,6 @@ impl Exam { title, description, kind, - weight, mode: schedule.mode, starts_at: schedule.starts_at, ends_at: schedule.ends_at, @@ -432,7 +410,6 @@ impl Exam { title: ExamTitle, description: ExamDescription, kind: ExamKind, - weight: ExamWeight, schedule: ExamSchedule, max_attempts: ExamAttemptLimit, allow_rejoin: bool, @@ -441,7 +418,6 @@ impl Exam { self.title = title; self.description = description; self.kind = kind; - self.weight = weight; self.mode = schedule.mode; self.starts_at = schedule.starts_at; self.ends_at = schedule.ends_at; @@ -489,7 +465,7 @@ mod tests { #[tokio::test] async fn kind_must_be_in_the_allowed_list() { - let allowed: Vec = crate::domain::settings::Settings::defaults() + let allowed: Vec = crate::domain::settings::Settings::defaults() .get_exam_kinds() .to_vec(); for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { @@ -498,7 +474,7 @@ mod tests { 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()]; + let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()]; 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 @@ -506,14 +482,6 @@ mod tests { assert!(ExamKind::try_new("Lab", &custom).is_err()); } - #[tokio::test] - async fn weight_range_is_enforced() { - assert_eq!(ExamWeight::try_new(1).unwrap().as_i64(), 1); - assert_eq!(ExamWeight::try_new(100).unwrap().as_i64(), 100); - assert!(ExamWeight::try_new(0).is_err()); - assert!(ExamWeight::try_new(101).is_err()); - } - #[tokio::test] async fn mode_must_be_known() { for mode in ["sync", "async", "open"] { diff --git a/src/domain/exam_attempt.rs b/src/domain/exam_attempt.rs index bf0097d..019020f 100644 --- a/src/domain/exam_attempt.rs +++ b/src/domain/exam_attempt.rs @@ -321,7 +321,7 @@ mod tests { use crate::database::init_mem; use crate::domain::course::CourseId; use crate::domain::exam::{ - ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, + ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; use crate::domain::exam_answer::ExamAnswer; use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec}; @@ -339,7 +339,6 @@ mod tests { ExamTitle::try_new("practice").unwrap(), ExamDescription::try_new("").unwrap(), ExamKind::try_new("quiz", &kinds).unwrap(), - ExamWeight::try_new(1).unwrap(), ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None) .unwrap(), ExamAttemptLimit::try_new(max_attempts).unwrap(), diff --git a/src/domain/settings.rs b/src/domain/settings.rs index 0a74e50..78008d8 100644 --- a/src/domain/settings.rs +++ b/src/domain/settings.rs @@ -1,5 +1,6 @@ -//! School-adjustable policy: which exam kinds exist, which attendance -//! statuses the roll call accepts, and how numeric marks display as grades. +//! School-adjustable policy: which exam kinds exist (and how much each +//! weighs in course averages), 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 @@ -8,8 +9,9 @@ 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, + DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS, + MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, + MIN_EXAM_KIND_WEIGHT, MIN_MARK, }; use crate::database::{Database, SETTINGS_TABLE}; use crate::error::{AppError, ValidationError}; @@ -17,6 +19,46 @@ use crate::error::{AppError, ValidationError}; /// The singleton's fixed key: one school per deployment, one settings row. const SETTINGS_KEY: &str = "school"; +/// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight: +/// how many times an exam of that kind counts into its course's average. +/// Weight lives here, not on the exam — reweighting a kind reweights every +/// exam of that kind at once. +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct ExamKindDef { + name: String, + weight: i64, +} + +impl ExamKindDef { + pub fn try_new(name: &str, weight: i64) -> Result { + let name = name.trim(); + if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN { + return Err(ValidationError::Invalid { + field: "exam_kinds", + reason: "kind names must be 1 to 50 characters", + }); + } + if !(MIN_EXAM_KIND_WEIGHT..=MAX_EXAM_KIND_WEIGHT).contains(&weight) { + return Err(ValidationError::Invalid { + field: "exam_kinds", + reason: "kind weights must be between 1 and 100", + }); + } + Ok(Self { + name: name.to_string(), + weight, + }) + } + + pub fn get_name(&self) -> &str { + &self.name + } + + pub fn get_weight(&self) -> i64 { + self.weight + } +} + /// 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)] @@ -61,7 +103,7 @@ impl GradeBand { #[derive(Debug, Clone, SurrealValue)] pub struct Settings { id: RecordId, - exam_kinds: Vec, + exam_kinds: Vec, attendance_statuses: Vec, grade_bands: Vec, } @@ -76,7 +118,12 @@ impl Settings { pub fn defaults() -> Self { Self { id: Self::record_id(), - exam_kinds: DEFAULT_EXAM_KINDS.map(String::from).to_vec(), + exam_kinds: DEFAULT_EXAM_KINDS + .map(|(name, weight)| ExamKindDef { + name: name.to_string(), + weight, + }) + .to_vec(), attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(), grade_bands: Vec::new(), } @@ -89,11 +136,17 @@ impl Settings { /// 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, + exam_kinds: Vec, attendance_statuses: Vec, grade_bands: Vec, ) -> Result { - let exam_kinds = validate_list("exam_kinds", exam_kinds)?; + // Per-entry rules (name shape, weight range) hold structurally on any + // `ExamKindDef`; here only the list-level rules need checking. + let names: Vec = exam_kinds + .iter() + .map(|kind| kind.get_name().to_string()) + .collect(); + validate_list("exam_kinds", names)?; let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?; if DEFAULT_ATTENDANCE_STATUSES .iter() @@ -138,10 +191,21 @@ impl Settings { }) } - pub fn get_exam_kinds(&self) -> &[String] { + pub fn get_exam_kinds(&self) -> &[ExamKindDef] { &self.exam_kinds } + /// The weight of the kind named `kind` (exact match, like kind + /// validation), or `None` when the school no longer lists it. Callers + /// averaging marks fall back to weight 1 — an exam keeps its retired kind + /// (settings edits never rewrite history), so it must still count. + pub fn exam_kind_weight(&self, kind: &str) -> Option { + self.exam_kinds + .iter() + .find(|def| def.get_name() == kind) + .map(ExamKindDef::get_weight) + } + pub fn get_attendance_statuses(&self) -> &[String] { &self.attendance_statuses } @@ -255,8 +319,18 @@ fn validate_list(field: &'static str, values: Vec) -> Result mod tests { use super::*; - fn kinds(list: &[&str]) -> Vec { - list.iter().map(|s| s.to_string()).collect() + fn kinds(list: &[&str]) -> Vec { + list.iter() + .map(|s| ExamKindDef::try_new(s, 1).unwrap()) + .collect() + } + + fn names(settings: &Settings) -> Vec<&str> { + settings + .get_exam_kinds() + .iter() + .map(ExamKindDef::get_name) + .collect() } fn bands(list: &[(i64, &str)]) -> Vec { @@ -279,21 +353,60 @@ mod tests { } #[tokio::test] - async fn lists_are_trimmed_bounded_and_deduped() { + async fn kind_defs_hold_name_and_weight_rules() { + // Names are trimmed; blank or over-long names die. + assert_eq!( + ExamKindDef::try_new(" lab ", 1).unwrap().get_name(), + "lab" + ); + assert!(ExamKindDef::try_new(" ", 1).is_err()); + assert!(ExamKindDef::try_new(&"x".repeat(51), 1).is_err()); + // Weights are held to 1–100 — 0 would erase the kind's exams from the + // average, and negatives would corrupt it. + for weight in [1, 50, 100] { + assert_eq!( + ExamKindDef::try_new("oral", weight).unwrap().get_weight(), + weight + ); + } + assert!(ExamKindDef::try_new("oral", 0).is_err()); + assert!(ExamKindDef::try_new("oral", -1).is_err()); + assert!(ExamKindDef::try_new("oral", 101).is_err()); + } + + #[tokio::test] + async fn lists_are_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. + let s = Settings::try_new(kinds(&["lab", "quiz"]), statuses.clone(), vec![]).unwrap(); + assert_eq!(names(&s), ["lab", "quiz"]); + // Empty list and case-insensitive duplicate names are 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(); + let too_many: Vec = (0..21) + .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap()) + .collect(); assert!(Settings::try_new(too_many, statuses, vec![]).is_err()); } + #[tokio::test] + async fn kind_weights_resolve_by_exact_name() { + let statuses = Settings::defaults().get_attendance_statuses().to_vec(); + let s = Settings::try_new( + vec![ + ExamKindDef::try_new("midterm", 2).unwrap(), + ExamKindDef::try_new("final", 3).unwrap(), + ], + statuses, + vec![], + ) + .unwrap(); + assert_eq!(s.exam_kind_weight("final"), Some(3)); + assert_eq!(s.exam_kind_weight("midterm"), Some(2)); + // Exact match, case included — same contract as kind validation. + assert_eq!(s.exam_kind_weight("Final"), None); + assert_eq!(s.exam_kind_weight("oral"), None); + } + #[tokio::test] async fn core_attendance_statuses_are_mandatory() { let kinds = Settings::defaults().get_exam_kinds().to_vec(); @@ -364,7 +477,7 @@ mod tests { .await .unwrap(); let loaded = Settings::load(&db).await.unwrap(); - assert_eq!(loaded.get_exam_kinds(), ["lab"]); + assert_eq!(names(&loaded), ["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. @@ -376,7 +489,7 @@ mod tests { 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"]); + assert_eq!(names(&rows[0]), ["quiz"]); } #[tokio::test] @@ -410,7 +523,7 @@ mod tests { // B's edit must survive A's stale write attempt. let after = Settings::load(&db).await.unwrap(); assert_eq!( - after.get_exam_kinds(), + names(&after), ["lab"], "a concurrent editor's exam kinds must not be silently reverted" ); @@ -428,7 +541,7 @@ mod tests { .await .unwrap() .expect("a merge over the current row applies"); - assert_eq!(saved.get_exam_kinds(), ["lab"]); + assert_eq!(names(&saved), ["lab"]); assert_eq!(saved.get_grade_bands().len(), 2); } @@ -448,7 +561,7 @@ mod tests { .await .unwrap() .expect("the first save applies"); - assert_eq!(saved.get_exam_kinds(), ["lab"]); + assert_eq!(names(&saved), ["lab"]); let mut result = db.query("SELECT * FROM settings").await.unwrap(); let rows: Vec = result.take(0).unwrap(); assert_eq!(rows.len(), 1, "still one singleton row"); diff --git a/src/lib.rs b/src/lib.rs index 56d7322..4f70ce2 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. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. 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.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room. 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 with their course-average weights, attendance statuses, grade-display bands) lives in an editable settings singleton, and courses may link to academic terms.", ), modifiers(&SecurityAddon), tags( @@ -45,9 +45,9 @@ use crate::state::AppState; (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (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/open scheduling, attempts with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), - (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 = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), + (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), + (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, 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+"), ), )] diff --git a/src/validate.rs b/src/validate.rs index 796284d..956fd3f 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,11 +2,10 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, 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, UNLIMITED_EXAM_ATTEMPTS, - USERNAME_SEPARATORS, + EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN, + MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK, + MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, + UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS, }; use crate::error::ValidationError; @@ -264,17 +263,6 @@ pub fn validate_mark(value: i64) -> Result<(), ValidationError> { } } -pub fn validate_weight(value: i64) -> Result<(), ValidationError> { - if (MIN_EXAM_WEIGHT..=MAX_EXAM_WEIGHT).contains(&value) { - Ok(()) - } else { - Err(ValidationError::Invalid { - field: "weight", - reason: "must be between 1 and 100", - }) - } -} - #[cfg(test)] mod tests { use super::*; @@ -443,14 +431,4 @@ mod tests { assert!(validate_mark(-1).is_err()); assert!(validate_mark(101).is_err()); } - - #[tokio::test] - async fn weight_rules() { - for weight in [1, 50, 100] { - assert!(validate_weight(weight).is_ok()); - } - assert!(validate_weight(0).is_err()); - assert!(validate_weight(-1).is_err()); - assert!(validate_weight(101).is_err()); - } } diff --git a/src/web/courses.rs b/src/web/courses.rs index b18041c..45364a8 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -14,7 +14,7 @@ use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, - ExamTitle, ExamWeight, + ExamTitle, }; use crate::domain::role::Role; use crate::domain::settings::Settings; @@ -75,12 +75,10 @@ struct CreateExamInCourse { description: Option, /// 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. + /// The kind's settings-configured weight decides how heavily the exam + /// counts into the course average. #[schema(example = "midterm")] kind: String, - /// How many times this exam counts into the course average, `1`–`100`. - #[schema(example = 3)] - weight: i64, /// `sync` (one fixed window for everyone), `async` (each student starts /// inside the window and gets `duration_ms`), or `open` (no window — sit /// anytime). Omit for an offline-graded draft that cannot be sat. @@ -487,12 +485,13 @@ async fn unenroll( // ---- exams in a course ---------------------------------------------------- /// Create an exam inside a course. Requires teacher+ and course management -/// rights; the exam's marks count `weight` times into the course average. -/// Omit `mode` for an offline-graded draft nobody can sit; `sync`/`async` -/// take a window (async also `duration_ms`), `open` is sittable anytime with -/// an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` = -/// unlimited) meters retakes and `allow_rejoin` (default `true`) is the -/// exam-room door — both stay editable while the exam runs. +/// rights; the exam's marks count into the course average with its kind's +/// weight (`GET /settings`). Omit `mode` for an offline-graded draft nobody +/// can sit; `sync`/`async` take a window (async also `duration_ms`), `open` +/// is sittable anytime with an optional per-attempt `duration_ms`. +/// `max_attempts` (default 1, `0` = unlimited) meters retakes and +/// `allow_rejoin` (default `true`) is the exam-room door — both stay editable +/// while the exam runs. #[utoipa::path( post, path = "/{id}/exams", @@ -502,7 +501,7 @@ async fn unenroll( request_body = CreateExamInCourse, responses( (status = 201, description = "Exam created", body = ExamResponse), - (status = 400, description = "Invalid fields, kind, weight, attempt limit, or schedule (malformed window, or times in the past)", body = ErrorResponse), + (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or times in the past)", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), @@ -527,7 +526,6 @@ async fn create_exam_in_course( let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; 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); check_not_past("starts_at", starts_at)?; @@ -548,7 +546,6 @@ async fn create_exam_in_course( title, description, kind, - weight, schedule, max_attempts, req.allow_rejoin.unwrap_or(true), diff --git a/src/web/dto.rs b/src/web/dto.rs index 2c0aed0..1b2c9dc 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -207,8 +207,9 @@ pub struct ExamResponse { pub course: String, pub title: String, pub description: String, + /// The assessment form. Its weight in the course average is school policy: + /// `GET /settings` maps each kind to a weight. pub kind: String, - pub weight: i64, /// `sync`, `async`, or `open`; `null` for an offline-graded draft /// (not sittable). #[schema(example = "sync")] @@ -237,7 +238,6 @@ impl ExamResponse { title: exam.get_title().as_str().to_string(), description: exam.get_description().as_str().to_string(), kind: exam.get_kind().as_str().to_string(), - weight: exam.get_weight().as_i64(), mode: exam.get_mode().map(|m| m.as_str().to_string()), starts_at: exam.get_starts_at().map(|t| t.as_millis()), ends_at: exam.get_ends_at().map(|t| t.as_millis()), diff --git a/src/web/exams.rs b/src/web/exams.rs index beed9c6..241ac51 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -18,7 +18,7 @@ use crate::domain::course::Course; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, - ExamSchedule, ExamTitle, ExamWeight, + ExamSchedule, ExamTitle, }; use crate::domain::exam_answer::{ExamAnswer, auto_score}; use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; @@ -68,8 +68,10 @@ pub fn routes() -> OpenApiRouter { struct UpdateExam { title: Option, description: Option, + /// The assessment form — one of the school's exam kinds (`GET /settings`). + /// Changing it re-weights the exam: the course average uses the kind's + /// settings-configured weight. kind: Option, - weight: Option, /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null` /// to turn the exam back into an offline draft. Frozen once anyone has /// started an attempt. Switching to `open` requires clearing @@ -232,7 +234,7 @@ async fn get_exam( request_body = UpdateExam, responses( (status = 200, description = "Updated exam", body = ExamResponse), - (status = 400, description = "Invalid fields, kind, weight, attempt limit, or schedule (malformed window, or newly set times in the past)", body = ErrorResponse), + (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or newly set times in the past)", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), @@ -273,10 +275,6 @@ async fn update_exam( } None => exam.get_kind().clone(), }; - let weight = match req.weight { - Some(weight) => ExamWeight::try_new(weight)?, - None => exam.get_weight(), - }; // Merge the schedule (set / clear / keep per field), then re-validate it // as a unit — a PATCH can't leave a half-schedule behind. Only values this @@ -331,7 +329,6 @@ async fn update_exam( title, description, kind, - weight, schedule, max_attempts, allow_rejoin, diff --git a/src/web/marks.rs b/src/web/marks.rs index 1edb9ab..dd185f8 100644 --- a/src/web/marks.rs +++ b/src/web/marks.rs @@ -33,6 +33,9 @@ struct MarkEntry { exam: String, title: String, kind: String, + /// The kind's weight from the school settings, resolved at request time — + /// how many times this mark counts into the course average. `1` when the + /// school no longer lists the kind. weight: i64, mark: i64, /// The mark's label from the school's grade bands (`GET /settings`); @@ -71,7 +74,8 @@ struct MarksReport { } /// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The -/// zero-denominator guard is structural — `ExamWeight` already forbids 0. +/// zero-denominator guard is structural — kind weights are 1–100 and retired +/// kinds resolve to 1, so a weight is never 0. fn weighted_average(pairs: &[(i64, i64)]) -> Option { let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum(); if total_weight == 0 { @@ -82,10 +86,10 @@ fn weighted_average(pairs: &[(i64, i64)]) -> Option { } /// Assemble the report: for each enrolled course, join the course's exams -/// (weights) with the user's graded results, then average. A `viewer` narrows -/// the report to the courses that viewer manages (self-reports and manager+ -/// reports pass `None` and see everything); the overall average follows the -/// narrowed set. +/// with the user's graded results, weigh each mark by its exam kind's +/// settings weight, then average. A `viewer` narrows the report to the +/// courses that viewer manages (self-reports and manager+ reports pass `None` +/// and see everything); the overall average follows the narrowed set. async fn build_report( user: &UserId, viewer: Option<&User>, @@ -96,7 +100,7 @@ async fn build_report( courses.retain(|course| can_manage_course(course, viewer)); } - // One settings read labels the whole report. + // One settings read weighs and labels the whole report. let school = Settings::load(db).await?; let mut blocks = Vec::with_capacity(courses.len()); @@ -113,18 +117,23 @@ async fn build_report( let Some(exam) = by_key.get(result.get_exam().key()) else { continue; }; + // The kind's current settings weight; an exam keeps a retired + // kind, and its marks then count once. + let weight = school + .exam_kind_weight(exam.get_kind().as_str()) + .unwrap_or(1); entries.push(MarkEntry { exam: exam.get_id().key().to_string(), title: exam.get_title().as_str().to_string(), kind: exam.get_kind().as_str().to_string(), - weight: exam.get_weight().as_i64(), + weight, 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())); + pairs.push((result.get_mark().as_i64(), weight)); } let average = weighted_average(&pairs); diff --git a/src/web/settings.rs b/src/web/settings.rs index 37281c1..47afed5 100644 --- a/src/web/settings.rs +++ b/src/web/settings.rs @@ -6,7 +6,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::SETTINGS_UPDATE_RETRIES; -use crate::domain::settings::{GradeBand, Settings}; +use crate::domain::settings::{ExamKindDef, GradeBand, Settings}; use crate::error::{AppError, ErrorResponse}; use crate::state::AppState; @@ -16,6 +16,19 @@ pub fn routes() -> OpenApiRouter { OpenApiRouter::new().routes(routes!(get_settings, update_settings)) } +/// One exam kind the school runs, with its weight in course averages. An exam +/// of this kind counts `weight` times into `Σ(mark×weight) / Σ(weight)`. +#[derive(Serialize, Deserialize, ToSchema)] +struct ExamKindDto { + /// The `kind` value exams carry, 1–50 characters. + #[schema(example = "midterm")] + name: String, + /// The kind's weight in the course average, `1`–`100`. Editing it + /// re-weights every exam of this kind at once. + #[schema(example = 2)] + weight: i64, +} + /// One grade-display band: marks at or above `min` (and below the next band's /// `min`) render as `label`. #[derive(Serialize, Deserialize, ToSchema)] @@ -28,13 +41,19 @@ struct GradeBandDto { label: String, } -/// The school's policy: which exam kinds exist, which attendance statuses the -/// roll call accepts, and how numeric marks display as grades. +/// The school's policy: which exam kinds exist (and their weights in course +/// averages), 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 `kind` values for new exams, each with its weight in the + /// course average. + #[schema(example = json!([ + {"name": "midterm", "weight": 2}, + {"name": "final", "weight": 3}, + {"name": "oral", "weight": 1}, + ]))] + 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"]))] @@ -46,7 +65,14 @@ struct SettingsResponse { impl SettingsResponse { fn new(settings: &Settings) -> Self { Self { - exam_kinds: settings.get_exam_kinds().to_vec(), + exam_kinds: settings + .get_exam_kinds() + .iter() + .map(|kind| ExamKindDto { + name: kind.get_name().to_string(), + weight: kind.get_weight(), + }) + .collect(), attendance_statuses: settings.get_attendance_statuses().to_vec(), grade_bands: settings .get_grade_bands() @@ -62,9 +88,9 @@ impl SettingsResponse { #[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: 1–20 entries with unique names, + /// each name 1–50 characters, each weight `1`–`100`. + 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>, @@ -97,7 +123,10 @@ async fn get_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. +/// new writes are held to the new lists. Kind weights, though, apply live: +/// mark reports read them at request time, so editing a weight re-weights +/// every exam of that kind, and an exam whose kind was removed from the list +/// counts with weight 1 until the kind returns. #[utoipa::path( patch, path = "/", @@ -124,10 +153,13 @@ async fn update_settings( for _ in 0..SETTINGS_UPDATE_RETRIES { let current = Settings::load(&st.db).await?; - let exam_kinds = req - .exam_kinds - .clone() - .unwrap_or_else(|| current.get_exam_kinds().to_vec()); + let exam_kinds = match &req.exam_kinds { + Some(kinds) => kinds + .iter() + .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight)) + .collect::, _>>()?, + None => current.get_exam_kinds().to_vec(), + }; let attendance_statuses = req .attendance_statuses .clone() diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 7eabbe5..98641e8 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -143,20 +143,20 @@ pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String { } /// Create an exam inside `course` as `cookie` (asserts 201); returns its id. +/// The exam's weight in the course average comes from its kind (settings). pub async fn create_exam( app: &Router, cookie: &str, course: &str, title: &str, kind: &str, - weight: i64, ) -> String { let res = send( app, "POST", &format!("/courses/{course}/exams"), Some(cookie), - Some(json!({ "title": title, "kind": kind, "weight": weight })), + Some(json!({ "title": title, "kind": kind })), ) .await; assert_eq!(res.status, StatusCode::CREATED, "create exam {title}"); diff --git a/tests/e2e.rs b/tests/e2e.rs index 406b8ae..54cf481 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -448,7 +448,7 @@ async fn live_exam_stream_pushes_snapshots_over_http() { let exam: Value = teacher .post(format!("{base}/courses/{course_id}/exams")) .json(&json!({ - "title": "final", "kind": "final", "weight": 2, + "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, })) .send() @@ -655,7 +655,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom { let exam: Value = teacher .post(format!("{base}/courses/{course_id}/exams")) .json(&json!({ - "title": "final", "kind": "final", "weight": 2, + "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + window_ms, })) .send() @@ -847,7 +847,7 @@ async fn exam_room_rejects_bad_handshakes() { let unscheduled: Value = room .teacher .post(format!("{}/courses/{}/exams", room.base, room.course_id)) - .json(&json!({ "title": "homework", "kind": "homework", "weight": 1 })) + .json(&json!({ "title": "homework", "kind": "homework" })) .send() .await .unwrap() @@ -1176,7 +1176,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() { .teacher .post(format!("{}/courses/{}/exams", room.base, room.course_id)) .json(&json!({ - "title": "practice", "kind": "quiz", "weight": 1, + "title": "practice", "kind": "quiz", "mode": "open", "max_attempts": 2, "allow_rejoin": false, })) .send() @@ -1280,7 +1280,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() { .teacher .post(format!("{}/courses/{}/exams", room.base, room.course_id)) .json(&json!({ - "title": "practice", "kind": "quiz", "weight": 1, + "title": "practice", "kind": "quiz", "mode": "open", "max_attempts": 2, })) .send() @@ -1465,7 +1465,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() { .teacher .post(format!("{}/courses/{}/exams", room.base, room.course_id)) .json(&json!({ - "title": "practice", "kind": "quiz", "weight": 1, + "title": "practice", "kind": "quiz", "mode": "open", "max_attempts": 2, })) .send() diff --git a/tests/integration.rs b/tests/integration.rs index ae6e692..bff5950 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -874,13 +874,14 @@ async fn exams_are_course_scoped_and_course_guarded() { "POST", &format!("/courses/{course_id}/exams"), Some(&ali), - Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz", "weight": 2 })), + Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })), ) .await; assert_eq!(ex.status, StatusCode::CREATED); assert_eq!(ex.body["kind"], "quiz"); assert_eq!(ex.body["course"], course_id); - assert_eq!(ex.body["weight"], 2); + // Weight lives on the kind (settings), not the exam. + assert_eq!(ex.body.get("weight"), None); let exam_id = id_of(&ex.body); // A teacher outside the course sees none of it: not the exam, not the @@ -971,7 +972,7 @@ async fn exams_are_course_scoped_and_course_guarded() { StatusCode::FORBIDDEN ); - // Course creator edits (partial) — kind flips homework, title/weight kept. + // Course creator edits (partial) — kind flips homework, title kept. let res = send( &app, "PATCH", @@ -983,7 +984,6 @@ async fn exams_are_course_scoped_and_course_guarded() { assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["kind"], "homework"); assert_eq!(res.body["title"], "ch3"); - assert_eq!(res.body["weight"], 2); } #[tokio::test] @@ -1000,7 +1000,7 @@ async fn exam_input_validation() { "POST", &exams_uri, Some(&ali), - Some(json!({"title":" ","kind":"quiz","weight":1})) + Some(json!({"title":" ","kind":"quiz"})) ) .await .status, @@ -1013,7 +1013,7 @@ async fn exam_input_validation() { "POST", &exams_uri, Some(&ali), - Some(json!({"title":"t","kind":"essay","weight":1})) + Some(json!({"title":"t","kind":"essay"})) ) .await .status, @@ -1025,41 +1025,12 @@ async fn exam_input_validation() { "POST", &exams_uri, Some(&ali), - Some(json!({"title":"t","kind":"final","weight":1})) + Some(json!({"title":"t","kind":"final"})) ) .await .status, StatusCode::CREATED ); - // Weight out of range or missing -> 400 / 422. - for weight in [json!(0), json!(101), json!(-1)] { - assert_eq!( - send( - &app, - "POST", - &exams_uri, - Some(&ali), - Some(json!({"title":"t","kind":"quiz","weight":weight})) - ) - .await - .status, - StatusCode::BAD_REQUEST, - "weight {weight}" - ); - } - assert_eq!( - send( - &app, - "POST", - &exams_uri, - Some(&ali), - Some(json!({"title":"t","kind":"quiz"})) - ) - .await - .status, - StatusCode::UNPROCESSABLE_ENTITY, - "missing weight is a body schema error" - ); // Missing exam -> 404. assert_eq!( send(&app, "GET", "/exams/nope", Some(&ali), None) @@ -1079,7 +1050,7 @@ async fn grading_upsert_and_own_result() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &alice_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await; // Before grading, the student's own result is 404. assert_eq!( @@ -1211,7 +1182,7 @@ async fn grading_rbac_and_validation() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &alice_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework").await; // Students cannot create exams, grade anyone, list all results, or delete a result. assert_eq!( @@ -1220,7 +1191,7 @@ async fn grading_rbac_and_validation() { "POST", &format!("/courses/{course_id}/exams"), Some(&alice), - Some(json!({"title":"x","kind":"quiz","weight":1})) + Some(json!({"title":"x","kind":"quiz"})) ) .await .status, @@ -1326,7 +1297,7 @@ async fn deleting_exam_cascades_results() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &alice_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz").await; send( &app, "POST", @@ -1702,7 +1673,7 @@ async fn exam_creation_lives_under_courses() { "POST", "/exams", Some(&teacher), - Some(json!({"title":"t","kind":"quiz","weight":1})) + Some(json!({"title":"t","kind":"quiz"})) ) .await .status, @@ -1710,18 +1681,17 @@ async fn exam_creation_lives_under_courses() { ); let course_id = create_course(&app, &teacher, "algebra").await; - // Creation inside the course echoes course + weight. + // Creation inside the course echoes the course. let res = send( &app, "POST", &format!("/courses/{course_id}/exams"), Some(&teacher), - Some(json!({"title":"mt","kind":"midterm","weight":3})), + Some(json!({"title":"mt","kind":"midterm"})), ) .await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["course"], course_id); - assert_eq!(res.body["weight"], 3); // A teacher who doesn't manage the course cannot add exams to it. assert_eq!( @@ -1730,7 +1700,7 @@ async fn exam_creation_lives_under_courses() { "POST", &format!("/courses/{course_id}/exams"), Some(&veli), - Some(json!({"title":"x","kind":"quiz","weight":1})) + Some(json!({"title":"x","kind":"quiz"})) ) .await .status, @@ -1790,7 +1760,7 @@ async fn grading_requires_enrollment() { let alice_id = me_id(&app, &alice).await; let course_id = create_course(&app, &teacher, "algebra").await; - let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await; let grade_uri = format!("/exams/{exam_id}/results"); let grade_body = json!({ "mark": 70, "user_id": alice_id }); @@ -1882,7 +1852,7 @@ async fn exam_writes_follow_course_management() { let course_id = create_course(&app, &teacher, "algebra").await; // A manager creates an exam in the teacher's course... - let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm", 2).await; + let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm").await; // ...and the course creator (not the exam's creator) can edit and delete it. assert_eq!( @@ -1891,11 +1861,11 @@ async fn exam_writes_follow_course_management() { "PATCH", &format!("/exams/{exam_id}"), Some(&teacher), - Some(json!({"weight":5})) + Some(json!({"title":"renamed"})) ) .await - .body["weight"], - 5 + .body["title"], + "renamed" ); // An unrelated teacher still cannot. assert_eq!( @@ -1904,7 +1874,7 @@ async fn exam_writes_follow_course_management() { "PATCH", &format!("/exams/{exam_id}"), Some(&veli), - Some(json!({"weight":1})) + Some(json!({"title":"hijack"})) ) .await .status, @@ -1936,7 +1906,7 @@ async fn exam_statistics_summarize_results() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &alice_id).await; enroll(&app, &teacher, &course_id, &bob_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await; let stats_uri = format!("/exams/{exam_id}/statistics"); // Nothing graded yet: zero count, null aggregates. @@ -1974,19 +1944,37 @@ async fn exam_statistics_summarize_results() { } #[tokio::test] -async fn weighted_averages_follow_exam_weights() { +async fn weighted_averages_follow_kind_weights() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "teacher", "teacher").await; + let manager = login_as(&app, &db, "boss", "manager").await; let alice = login(&app, "alice").await; let alice_id = me_id(&app, &alice).await; + // Weights are school policy, per kind: quizzes count once, midterms three + // times (the defaults are all 1). + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [ + {"name": "quiz", "weight": 1}, + {"name": "midterm", "weight": 3}, + {"name": "final", "weight": 4}, + {"name": "homework", "weight": 1}, + ]})), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80. let algebra = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &algebra, &alice_id).await; - let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz", 1).await; - let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm", 3).await; + let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz").await; + let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm").await; // A third exam stays ungraded and must not drag the average. - create_exam(&app, &teacher, &algebra, "final", "final", 4).await; + create_exam(&app, &teacher, &algebra, "final", "final").await; for (exam, mark) in [(&quiz, 50), (&midterm, 90)] { let res = send( &app, @@ -2002,7 +1990,7 @@ async fn weighted_averages_follow_exam_weights() { // Course B: enrolled, nothing graded -> null average. let physics = create_course(&app, &teacher, "physics").await; enroll(&app, &teacher, &physics, &alice_id).await; - create_exam(&app, &teacher, &physics, "hw", "homework", 1).await; + create_exam(&app, &teacher, &physics, "hw", "homework").await; let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; assert_eq!(report.status, StatusCode::OK); @@ -2019,6 +2007,14 @@ async fn weighted_averages_follow_exam_weights() { assert_eq!(algebra_block["average"], 80.0); assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2); + // Each entry carries its kind's resolved weight. + let midterm_entry = algebra_block["results"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["kind"] == "midterm") + .unwrap(); + assert_eq!(midterm_entry["weight"], 3); assert_eq!(physics_block["average"], serde_json::Value::Null); assert_eq!(physics_block["results"].as_array().unwrap().len(), 0); // Overall skips the null course instead of zeroing it. @@ -2026,6 +2022,75 @@ async fn weighted_averages_follow_exam_weights() { assert_eq!(report.body["user"], alice_id); } +/// Kind weights resolve at report time: editing a kind's weight re-weights +/// already-graded exams, and a kind removed from settings counts once. +#[tokio::test] +async fn kind_weight_edits_reweight_reports_live() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + let manager = login_as(&app, &db, "boss", "manager").await; + let alice = login(&app, "alice").await; + let alice_id = me_id(&app, &alice).await; + + let course = create_course(&app, &teacher, "algebra").await; + enroll(&app, &teacher, &course, &alice_id).await; + let quiz = create_exam(&app, &teacher, &course, "q", "quiz").await; + let oral = create_exam(&app, &teacher, &course, "o", "oral").await; + for (exam, mark) in [(&quiz, 40), (&oral, 80)] { + let res = send( + &app, + "POST", + &format!("/exams/{exam}/results"), + Some(&teacher), + Some(json!({ "mark": mark, "user_id": alice_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + } + + // Default weights (all 1): plain mean of 40 and 80. + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.body["courses"][0]["average"], 60.0); + + // Triple the oral weight — the already-graded exam follows immediately: + // (40 + 240) / 4 = 70. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [ + {"name": "quiz", "weight": 1}, + {"name": "oral", "weight": 3}, + ]})), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.body["courses"][0]["average"], 70.0); + + // Retire the oral kind altogether: its exam keeps counting, weight 1. + let res = send( + &app, + "PATCH", + "/settings", + Some(&manager), + Some(json!({ "exam_kinds": [{"name": "quiz", "weight": 1}] })), + ) + .await; + assert_eq!(res.status, StatusCode::OK); + let report = send(&app, "GET", "/marks/me", Some(&alice), None).await; + assert_eq!(report.body["courses"][0]["average"], 60.0); + let oral_entry = report.body["courses"][0]["results"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["kind"] == "oral") + .unwrap() + .clone(); + assert_eq!(oral_entry["weight"], 1); +} + #[tokio::test] async fn marks_reports_are_self_or_teacher_scoped() { let (app, db) = app_and_db().await; @@ -2077,7 +2142,7 @@ async fn course_data_is_walled_off_from_other_teachers() { let course_id = create_course(&app, &owner, "algebra").await; enroll(&app, &owner, &course_id, &alice_id).await; - let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz", 2).await; + let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz").await; let res = send( &app, "POST", @@ -2179,7 +2244,7 @@ async fn deleting_course_cascades_enrollments_exams_and_results() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &alice_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await; send( &app, "POST", @@ -2805,7 +2870,7 @@ async fn concurrent_exam_grades_never_collide() { let student_id = me_id(&app, &student).await; let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &student_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz").await; let mut handles = Vec::new(); for mark in 0..24i64 { @@ -2989,7 +3054,7 @@ async fn graders_cannot_grade_themselves() { let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &teacher_id).await; enroll(&app, &teacher, &course_id, &boss_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz", 1).await; + let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz").await; // Self-grading is forbidden at every privilege level, not just for teachers. // (The teacher owns the course; the manager clears the gate by role.) @@ -3410,7 +3475,7 @@ async fn exam_scheduling_validates_and_echoes() { &teacher, &course, json!({ - "title": "midterm", "kind": "midterm", "weight": 2, + "title": "midterm", "kind": "midterm", "mode": "sync", "starts_at": now + 60_000, "ends_at": now + 120_000, }), ) @@ -3427,7 +3492,7 @@ async fn exam_scheduling_validates_and_echoes() { &teacher, &course, json!({ - "title": "takehome", "kind": "quiz", "weight": 1, + "title": "takehome", "kind": "quiz", "mode": "async", "starts_at": now, "ends_at": now + 7_200_000, "duration_ms": 5_400_000, }), @@ -3443,7 +3508,7 @@ async fn exam_scheduling_validates_and_echoes() { &app, &teacher, &course, - json!({ "title": "homework", "kind": "homework", "weight": 1 }), + json!({ "title": "homework", "kind": "homework" }), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -3461,7 +3526,7 @@ async fn exam_scheduling_validates_and_echoes() { &teacher, &course, json!({ - "title": "practice", "kind": "quiz", "weight": 1, "mode": "open", + "title": "practice", "kind": "quiz", "mode": "open", "duration_ms": 5_400_000, "max_attempts": 0, "allow_rejoin": false, }), ) @@ -3478,80 +3543,80 @@ async fn exam_scheduling_validates_and_echoes() { for (label, body) in [ ( "unknown mode", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "weekly", + json!({ "title": "x", "kind": "quiz", "mode": "weekly", "starts_at": now, "ends_at": now + 1_000 }), ), ( "times without mode", - json!({ "title": "x", "kind": "quiz", "weight": 1, "starts_at": now }), + json!({ "title": "x", "kind": "quiz", "starts_at": now }), ), ( "duration without mode", - json!({ "title": "x", "kind": "quiz", "weight": 1, "duration_ms": 60_000 }), + json!({ "title": "x", "kind": "quiz", "duration_ms": 60_000 }), ), ( "sync missing ends_at", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now }), ), ( "sync with duration", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now, "ends_at": now + 1_000, "duration_ms": 60_000 }), ), ( "async without duration", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async", + json!({ "title": "x", "kind": "quiz", "mode": "async", "starts_at": now, "ends_at": now + 1_000 }), ), ( "backwards window", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now + 2_000, "ends_at": now + 1_000 }), ), ( "empty window", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now, "ends_at": now }), ), ( "duration too short", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async", + json!({ "title": "x", "kind": "quiz", "mode": "async", "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 59_999 }), ), ( "duration too long", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async", + json!({ "title": "x", "kind": "quiz", "mode": "async", "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 86_400_001 }), ), ( "past starts_at", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now - 3_600_000, "ends_at": now + 3_600_000 }), ), ( // starts_at is future so the rejection can only come from ends_at. "past ends_at", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync", + json!({ "title": "x", "kind": "quiz", "mode": "sync", "starts_at": now + 3_600_000, "ends_at": now - 3_600_000 }), ), ( "open with a window", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "open", + json!({ "title": "x", "kind": "quiz", "mode": "open", "starts_at": now + 60_000, "ends_at": now + 120_000 }), ), ( "open with only an ends_at", - json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "open", + json!({ "title": "x", "kind": "quiz", "mode": "open", "ends_at": now + 120_000 }), ), ( "negative attempt limit", - json!({ "title": "x", "kind": "quiz", "weight": 1, "max_attempts": -1 }), + json!({ "title": "x", "kind": "quiz", "max_attempts": -1 }), ), ( "attempt limit over the cap", - json!({ "title": "x", "kind": "quiz", "weight": 1, "max_attempts": 101 }), + json!({ "title": "x", "kind": "quiz", "max_attempts": 101 }), ), ] { let res = create_exam_with(&app, &teacher, &course, body).await; @@ -3574,7 +3639,7 @@ async fn schedule_times_cannot_be_backdated() { &app, &teacher, &course, - json!({ "title": "running", "kind": "quiz", "weight": 1, + json!({ "title": "running", "kind": "quiz", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -3623,7 +3688,7 @@ async fn schedule_times_cannot_be_backdated() { &app, &teacher, &course, - json!({ "title": "graced", "kind": "quiz", "weight": 1, + json!({ "title": "graced", "kind": "quiz", "mode": "sync", "starts_at": now - 30_000, "ends_at": now + 600_000 }), ) .await; @@ -3658,7 +3723,7 @@ async fn sync_attempt_lifecycle_feeds_the_live_monitor() { &app, &teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 3, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }), ) .await; @@ -3811,7 +3876,7 @@ async fn closed_window_flags_no_shows_as_absent() { &app, &teacher, &course, - json!({ "title": "midterm", "kind": "midterm", "weight": 2, + json!({ "title": "midterm", "kind": "midterm", "mode": "sync", "starts_at": now - 50_000, "ends_at": now + 600_000 }), ) .await; @@ -3904,7 +3969,7 @@ async fn closed_window_flags_no_shows_as_absent() { &app, &teacher, &course, - json!({ "title": "essay", "kind": "homework", "weight": 1, "mode": "open" }), + json!({ "title": "essay", "kind": "homework", "mode": "open" }), ) .await; let res = send( @@ -3935,7 +4000,7 @@ async fn async_deadline_is_start_plus_duration_clamped_to_window() { &app, &teacher, &course, - json!({ "title": "quiz", "kind": "quiz", "weight": 1, + json!({ "title": "quiz", "kind": "quiz", "mode": "async", "starts_at": now - 1_000, "ends_at": now + 6_000_000, "duration_ms": 60_000 }), ) @@ -3958,7 +4023,7 @@ async fn async_deadline_is_start_plus_duration_clamped_to_window() { &app, &teacher, &course, - json!({ "title": "quiz2", "kind": "quiz", "weight": 1, + json!({ "title": "quiz2", "kind": "quiz", "mode": "async", "starts_at": now - 1_000, "ends_at": ends, "duration_ms": 60_000 }), ) @@ -3986,7 +4051,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() { let now = Timestamp::now().as_millis(); // Unscheduled exams cannot be sat at all. - let unscheduled = create_exam(&app, &teacher, &course, "hw", "homework", 1).await; + let unscheduled = create_exam(&app, &teacher, &course, "hw", "homework").await; let res = send( &app, "POST", @@ -4002,7 +4067,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() { &app, &teacher, &course, - json!({ "title": "later", "kind": "quiz", "weight": 1, + json!({ "title": "later", "kind": "quiz", "mode": "sync", "starts_at": now + 600_000, "ends_at": now + 1_200_000 }), ) .await; @@ -4021,7 +4086,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() { &teacher, &course, // Inside the backdating grace, yet already closed by the clock. - json!({ "title": "gone", "kind": "quiz", "weight": 1, + json!({ "title": "gone", "kind": "quiz", "mode": "sync", "starts_at": now - 50_000, "ends_at": now - 10_000 }), ) .await; @@ -4040,7 +4105,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() { &app, &teacher, &course, - json!({ "title": "open", "kind": "quiz", "weight": 1, + json!({ "title": "open", "kind": "quiz", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -4090,7 +4155,7 @@ async fn finish_rejects_double_submit_missing_attempt_and_expiry() { &app, &teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 1, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -4140,7 +4205,7 @@ async fn finish_rejects_double_submit_missing_attempt_and_expiry() { &app, &teacher, &course, - json!({ "title": "blitz", "kind": "quiz", "weight": 1, + json!({ "title": "blitz", "kind": "quiz", "mode": "sync", "starts_at": now - 1_000, "ends_at": Timestamp::now().as_millis() + 1_500 }), ) @@ -4195,7 +4260,7 @@ async fn mode_freezes_after_attempts_but_times_extend_live() { &app, &teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 1, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }), ) .await; @@ -4305,7 +4370,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() { let course = create_course(&app, &teacher, "hist").await; enroll(&app, &teacher, &course, &student_id).await; let now = Timestamp::now().as_millis(); - let schedule = json!({ "title": "final", "kind": "final", "weight": 1, + let schedule = json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }); // Deleting the exam removes its attempts. @@ -4382,7 +4447,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() { &app, &teacher, &course, - json!({ "title": "drill", "kind": "quiz", "weight": 1, + json!({ "title": "drill", "kind": "quiz", "mode": "open", "max_attempts": 2 }), ) .await; @@ -4573,7 +4638,7 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() { &app, &teacher, &course, - json!({ "title": "sprint", "kind": "quiz", "weight": 1, + json!({ "title": "sprint", "kind": "quiz", "mode": "open", "duration_ms": 60_000 }), ) .await; @@ -4602,7 +4667,7 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() { &app, &teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 1, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": ends, "max_attempts": 3 }), ) @@ -4687,7 +4752,7 @@ async fn live_stream_is_sse_and_teacher_scoped() { &app, &teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 1, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -4770,7 +4835,7 @@ async fn open_exam_with_student( app, teacher, &course, - json!({ "title": "final", "kind": "final", "weight": 1, + json!({ "title": "final", "kind": "final", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -4784,7 +4849,7 @@ async fn question_crud_validation_and_rbac() { let other_teacher = login_as(&app, &db, "q_t2", "teacher").await; let student = login(&app, "quinn").await; let course = create_course(&app, &teacher, "logic").await; - let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; // A choice question echoes its full authoring view, correct included. let res = send( @@ -4996,7 +5061,7 @@ async fn question_crud_validation_and_rbac() { assert_eq!(res.status, StatusCode::FORBIDDEN); // Unknown ids are 404s — including a question under the wrong exam. - let other_exam = create_exam(&app, &teacher, &course, "quiz", "quiz", 1).await; + let other_exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await; for (method, uri) in [ ("POST", "/exams/missing/questions".to_string()), ("GET", "/exams/missing/questions".to_string()), @@ -5311,7 +5376,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() { ) .await; assert_eq!(res.status, StatusCode::NOT_FOUND); - let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz", 1).await; + let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz").await; let foreign_q = create_question( &app, &teacher, @@ -5511,7 +5576,7 @@ async fn answer_saves_stop_at_the_deadline() { &app, &teacher, &course, - json!({ "title": "blitz", "kind": "quiz", "weight": 1, + json!({ "title": "blitz", "kind": "quiz", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }), ) .await; @@ -5848,7 +5913,7 @@ async fn questions_and_answers_cascade_with_deletes() { &app, &teacher, &course, - json!({ "title": "retake", "kind": "quiz", "weight": 1, + json!({ "title": "retake", "kind": "quiz", "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), ) .await; @@ -5908,7 +5973,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() { let (app, db) = app_and_db().await; let teacher = login_as(&app, &db, "rv_t", "teacher").await; let course = create_course(&app, &teacher, "sets").await; - let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; let question = create_question( &app, &teacher, @@ -5989,7 +6054,7 @@ async fn question_authoring_follows_course_management() { let teacher = login_as(&app, &db, "own_t", "teacher").await; let boss = login_as(&app, &db, "own_m", "manager").await; let course = create_course(&app, &teacher, "greek").await; - let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await; + let exam = create_exam(&app, &teacher, &course, "final", "final").await; // A manager+ authors questions in anyone's course, like every other // course-management write. @@ -7167,7 +7232,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() { // The exam catalog derives from the same visible set and must not double // the course's exams either. - let exam = create_exam(&app, &teacher, &course, "mt", "quiz", 1).await; + let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await; let res = send(&app, "GET", "/exams", Some(&teacher), None).await; let exams = res.body.as_array().unwrap(); assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}"); @@ -7187,12 +7252,20 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() { let res = send(&app, "GET", "/settings", None, None).await; assert_eq!(res.status, StatusCode::UNAUTHORIZED); - // Any authenticated user reads; the defaults mirror the old constants. + // Any authenticated user reads; the defaults mirror the old constants, + // every kind weighing 1 until the school says otherwise. let res = send(&app, "GET", "/settings", Some(&student), None).await; assert_eq!(res.status, StatusCode::OK); assert_eq!( res.body["exam_kinds"], - json!(["homework", "quiz", "midterm", "final", "project", "oral"]) + json!([ + {"name": "homework", "weight": 1}, + {"name": "quiz", "weight": 1}, + {"name": "midterm", "weight": 1}, + {"name": "final", "weight": 1}, + {"name": "project", "weight": 1}, + {"name": "oral", "weight": 1}, + ]) ); assert_eq!( res.body["attendance_statuses"], @@ -7207,7 +7280,7 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() { "PATCH", "/settings", Some(cookie), - Some(json!({ "exam_kinds": ["lab"] })), + Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })), ) .await; assert_eq!(res.status, StatusCode::FORBIDDEN); @@ -7219,11 +7292,20 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() { "PATCH", "/settings", Some(&manager), - Some(json!({ "exam_kinds": ["lab", "Quiz"] })), + Some(json!({ "exam_kinds": [ + {"name": "lab", "weight": 2}, + {"name": "Quiz", "weight": 1}, + ]})), ) .await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(res.body["exam_kinds"], json!(["lab", "Quiz"])); + assert_eq!( + res.body["exam_kinds"], + json!([ + {"name": "lab", "weight": 2}, + {"name": "Quiz", "weight": 1}, + ]) + ); assert_eq!( res.body["attendance_statuses"], json!(["present", "absent", "late", "excused"]) @@ -7231,7 +7313,8 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() { // Every reader sees the new policy at once. let res = send(&app, "GET", "/settings", Some(&student), None).await; - assert_eq!(res.body["exam_kinds"], json!(["lab", "Quiz"])); + assert_eq!(res.body["exam_kinds"][0]["name"], "lab"); + assert_eq!(res.body["exam_kinds"][0]["weight"], 2); } #[tokio::test] @@ -7240,11 +7323,19 @@ async fn settings_validation_rejects_bad_lists_and_bands() { let manager = login_as(&app, &db, "val.manager", "manager").await; let bad = [ - json!({ "exam_kinds": [] }), // a school needs at least one kind - json!({ "exam_kinds": [" "] }), // blank entry - json!({ "exam_kinds": ["Lab", "lab"] }), // case-insensitive duplicate + json!({ "exam_kinds": [] }), // a school needs at least one kind + json!({ "exam_kinds": [{"name": " ", "weight": 1}] }), // blank name + // Case-insensitive duplicate names. + json!({ "exam_kinds": [ + {"name": "Lab", "weight": 1}, + {"name": "lab", "weight": 2}, + ]}), + // Weights are held to 1–100. + json!({ "exam_kinds": [{"name": "quiz", "weight": 0}] }), + json!({ "exam_kinds": [{"name": "quiz", "weight": 101}] }), + json!({ "exam_kinds": [{"name": "quiz", "weight": -1}] }), json!({ "attendance_statuses": ["present", "absent", "late"] }), // core dropped - json!({ "grade_bands": [{ "min": 50, "label": "CC" }] }), // no band starts at 0 + json!({ "grade_bands": [{ "min": 50, "label": "CC" }] }), // no band starts at 0 json!({ "grade_bands": [{ "min": 0, "label": "F" }, { "min": 0, "label": "E" }] }), json!({ "grade_bands": [{ "min": -1, "label": "F" }] }), json!({ "grade_bands": [{ "min": 101, "label": "A" }] }), @@ -7275,7 +7366,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() { let manager = login_as(&app, &db, "kind.manager", "manager").await; let course = create_course(&app, &teacher, "Chemistry").await; - let exam = create_exam(&app, &teacher, &course, "Midterm", "midterm", 1).await; + let exam = create_exam(&app, &teacher, &course, "Midterm", "midterm").await; // The school swaps its kind list wholesale. let res = send( @@ -7283,7 +7374,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() { "PATCH", "/settings", Some(&manager), - Some(json!({ "exam_kinds": ["lab"] })), + Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })), ) .await; assert_eq!(res.status, StatusCode::OK); @@ -7293,7 +7384,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() { &app, &teacher, &course, - json!({ "title": "Retired kind", "kind": "midterm", "weight": 1 }), + json!({ "title": "Retired kind", "kind": "midterm" }), ) .await; assert_eq!(res.status, StatusCode::BAD_REQUEST); @@ -7301,7 +7392,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() { &app, &teacher, &course, - json!({ "title": "Lab 1", "kind": "lab", "weight": 1 }), + json!({ "title": "Lab 1", "kind": "lab" }), ) .await; assert_eq!(res.status, StatusCode::CREATED); @@ -7449,7 +7540,7 @@ async fn grade_bands_label_the_marks_report() { let course = create_course(&app, &teacher, "Physics").await; enroll(&app, &teacher, &course, &student_id).await; - let exam = create_exam(&app, &teacher, &course, "Final", "final", 2).await; + let exam = create_exam(&app, &teacher, &course, "Final", "final").await; let res = send( &app, "POST", @@ -7814,7 +7905,7 @@ async fn grade_band_boundary_applies_to_the_weighted_average() { let course = create_course(&app, &teacher, "Calculus").await; enroll(&app, &teacher, &course, &student_id).await; for (title, mark) in [("Quiz A", 80), ("Quiz B", 90)] { - let exam = create_exam(&app, &teacher, &course, title, "quiz", 1).await; + let exam = create_exam(&app, &teacher, &course, title, "quiz").await; let res = send( &app, "POST", @@ -7851,16 +7942,25 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() { assert_eq!(res.status, StatusCode::OK); assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 6); - // Admin clears the manager bar (hierarchy, not equality), and entries + // Admin clears the manager bar (hierarchy, not equality), and kind names // arrive trimmed on the wire. let res = send( &app, "PATCH", "/settings", Some(&admin), - Some(json!({ "exam_kinds": [" lab ", "quiz"] })), + Some(json!({ "exam_kinds": [ + {"name": " lab ", "weight": 2}, + {"name": "quiz", "weight": 1}, + ]})), ) .await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(res.body["exam_kinds"], json!(["lab", "quiz"])); + assert_eq!( + res.body["exam_kinds"], + json!([ + {"name": "lab", "weight": 2}, + {"name": "quiz", "weight": 1}, + ]) + ); } diff --git a/tests/persistence.rs b/tests/persistence.rs index 822be76..8a06943 100644 --- a/tests/persistence.rs +++ b/tests/persistence.rs @@ -206,8 +206,9 @@ async fn profile_survives_reopen() { } } -/// A course with an enrollment, a weighted exam, and a graded mark survives a -/// close + reopen — the weighted report is rebuilt from disk. +/// A course with an enrollment, an exam whose kind carries a weight, and a +/// graded mark survives a close + reopen — the weighted report (settings +/// included) is rebuilt from disk. #[tokio::test] async fn course_marks_survive_reopen() { let dir = tempfile::tempdir().unwrap(); @@ -215,7 +216,8 @@ async fn course_marks_survive_reopen() { let teacher_creds = json!({ "username": "hoca", "password": "secret1" }); let student_creds = json!({ "username": "ali", "password": "secret1" }); - // First boot: teacher sets up a course, enrolls the student, grades 80. + // First boot: the manager-teacher weighs midterms double, sets up a + // course, enrolls the student, grades 80. { let db = database::init(&cfg).await.expect("first open"); let app = build_router(state(db.clone())); @@ -227,7 +229,7 @@ async fn course_marks_survive_reopen() { StatusCode::CREATED ); } - set_role(&db, "hoca", "teacher").await; + set_role(&db, "hoca", "manager").await; let teacher = send( &app, "POST", @@ -250,9 +252,24 @@ async fn course_marks_survive_reopen() { .unwrap(); let student_id = me_id(&app, &student).await; + assert_eq!( + send( + &app, + "PATCH", + "/settings", + Some(&teacher), + Some(json!({ "exam_kinds": [ + {"name": "midterm", "weight": 2}, + {"name": "quiz", "weight": 1}, + ]})), + ) + .await + .status, + StatusCode::OK + ); let course_id = create_course(&app, &teacher, "algebra").await; enroll(&app, &teacher, &course_id, &student_id).await; - let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm", 2).await; + let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm").await; assert_eq!( send( &app, @@ -267,7 +284,8 @@ async fn course_marks_survive_reopen() { ); } - // Second boot: the report, roster, and exam weight are all rebuilt from disk. + // Second boot: the report, roster, and kind weight (via the settings row) + // are all rebuilt from disk. { let db = reopen(&cfg).await; let app = build_router(state(db)); @@ -328,7 +346,10 @@ async fn settings_and_terms_survive_reopen() { "/settings", Some(&cookie), Some(json!({ - "exam_kinds": ["lab", "quiz"], + "exam_kinds": [ + { "name": "lab", "weight": 2 }, + { "name": "quiz", "weight": 1 }, + ], "grade_bands": [{ "min": 0, "label": "F" }, { "min": 50, "label": "P" }], })), ) @@ -368,7 +389,13 @@ async fn settings_and_terms_survive_reopen() { let res = send(&app, "GET", "/settings", Some(&cookie), None).await; assert_eq!(res.status, StatusCode::OK); - assert_eq!(res.body["exam_kinds"], json!(["lab", "quiz"])); + assert_eq!( + res.body["exam_kinds"], + json!([ + { "name": "lab", "weight": 2 }, + { "name": "quiz", "weight": 1 }, + ]) + ); assert_eq!(res.body["grade_bands"][0]["label"], "P"); let res = send(&app, "GET", &format!("/terms/{term}"), Some(&cookie), None).await;