forge
Explore
Log in

Don't you dare go Hollow

Move weight off exams onto their kind

Browse files at this commit

3681441ce752afafff7d09b59e68741627863c9bAhmet Kaan GümüşParent: a0f200e
  • feat
    • move weight off exams onto their kind
Show full message
✨ feat(exams)!: move weight off exams onto their kind

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.mdmodified+38 -19
@@ -6,8 +6,10 @@ Session-cookie auth with four hierarchical roles (`student < teacher < manager
6 < admin`). Notes are per-user. Attendance is event + attendees: create an event,6 < admin`). Notes are per-user. Attendance is event + attendees: create an event,
7 then mark users present / absent / late / excused. Marks are course-shaped7 then mark users present / absent / late / excused. Marks are course-shaped
8 (Google Classroom style): a teacher creates a course, enrolls students, adds8 (Google Classroom style): a teacher creates a course, enrolls students, adds
9-weighted exams inside it, and grades; students read a per-course weighted9+exams inside it, and grades; students read a per-course weighted average and
10-average and an overall average from their mark report. Exams run **sync** (one10+an overall average from their mark report — each exam weighted by its **kind**
11+(midterms can count double, orals once: weights are set per kind in settings,
12+not per exam). Exams run **sync** (one
11 fixed window), **async** (start anytime inside the window, with a personal13 fixed window), **async** (start anytime inside the window, with a personal
12 time budget), or **open** (sit anytime, optionally timed per attempt);14 time budget), or **open** (sit anytime, optionally timed per attempt);
13 students *sit* them via attempts — retakes metered by a per-exam limit15 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
18 sessions** with teacher-taken roll call (students never self-mark a lesson),20 sessions** with teacher-taken roll call (students never self-mark a lesson),
19 staff clock in/out on a server-stamped **work log**, and every user has an21 staff clock in/out on a server-stamped **work log**, and every user has an
20 **attendance report** (event + per-course lesson tallies with rates).22 **attendance report** (event + per-course lesson tallies with rates).
21-School-varying policy is data, not code: exam kinds, attendance statuses, and23+School-varying policy is data, not code: exam kinds (each with its weight in
22-grade-display bands live in an editable **settings** singleton, and academic24+course averages), attendance statuses, and grade-display bands live in an
23-**terms** are plain rows courses can link to (see "Per-school policy").25+editable **settings** singleton, and academic **terms** are plain rows courses
26+can link to (see "Per-school policy").
24 27
25 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)28 Every field is a validated newtype (`Username(String)`, `NoteTitle(String)`, …)
26 constructed only after its restrictions pass — invalid input can't be29 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.
272 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ |275 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled** students; the teacher's own row needs manager+ |
273 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) |276 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) |
274 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |277 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
275-| 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) |278+| 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 |
276 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) |279 | GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) |
277 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) |280 | GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) |
278 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |281 | GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |
279-| 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) |282+| 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) |
280 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |283 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, and answers (course manager) |
281 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |284 | POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled** student (upsert; course manager) |
282 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) |285 | 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.
306 | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |309 | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) |
307 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |310 | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies |
308 | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) |311 | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) |
309-| GET | `/settings` | student | The school's policy: `exam_kinds`, `attendance_statuses`, `grade_bands` |312+| GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands` |
310 | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") |313 | PATCH | `/settings` | manager | Replace any subset of the three lists, each wholesale; concurrent edits merge, never silently revert each other (see "Per-school policy") |
311 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |314 | POST | `/terms` | manager | `{name, starts_at, ends_at}` — past dates allowed (calendar backfill) |
312 | GET | `/terms` | student | List terms, newest first |315 | GET | `/terms` | student | List terms, newest first |
@@ -318,8 +321,10 @@ marks/attendance reports narrow to the courses the caller manages.
318 the core four `present | absent | late | excused` always exist, plus whatever321 the core four `present | absent | late | excused` always exist, plus whatever
319 the school added.322 the school added.
320 `kind` must be one of the school's exam kinds (`GET /settings`; defaults:323 `kind` must be one of the school's exam kinds (`GET /settings`; defaults:
321-`homework | quiz | midterm | final | project | oral`) — informational324+`homework | quiz | midterm | final | project | oral`). The kind carries the
322-metadata; the average is driven by `weight`, an integer `1`–`100` set per exam.325+exam's weight in the course average — an integer `1`–`100` set per **kind** in
326+settings (defaults all `1`), resolved when a report is read; an exam whose
327+kind was later removed from settings counts with weight `1`.
323 A course may carry a `term_id` (`null` = unassigned); on `PATCH328 A course may carry a `term_id` (`null` = unassigned); on `PATCH
324 /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`329 /courses/{id}`, an omitted `term_id` keeps the link and an explicit `null`
325 clears it.330 clears it.
@@ -364,10 +369,15 @@ Every school runs differently; the parts that vary are data, not code. One
364 editable `settings` singleton (`GET /settings` for any signed-in user,369 editable `settings` singleton (`GET /settings` for any signed-in user,
365 `PATCH /settings` for manager+) carries three knobs:370 `PATCH /settings` for manager+) carries three knobs:
366 371
367-- **`exam_kinds`** — the accepted `kind` values for new exams. Defaults to372+- **`exam_kinds`** — the accepted `kind` values for new exams, each an
368- `homework, quiz, midterm, final, project, oral`; replace the list with373+ object `{name, weight}`. The weight (`1`–`100`) is how many times an exam
369- whatever the school grades (`lab`, `presentation`, …). Kinds stay374+ of that kind counts into its course average — weighting is school policy,
370- informational — `weight` drives every average.375+ set once per kind, never per exam. Defaults to `homework, quiz, midterm,
376+ final, project, oral`, all weighing `1` (a plain average); replace the
377+ list with whatever the school grades and weighs (`{"name": "final",
378+ "weight": 3}`, …). Reports resolve weights live: editing a weight
379+ re-weights every exam of that kind at once, and an exam keeping a
380+ since-removed kind counts with weight `1`.
371 - **`attendance_statuses`** — what attendance marking accepts. The core four381 - **`attendance_statuses`** — what attendance marking accepts. The core four
372 (`present`, `absent`, `late`, `excused`) are mandatory because the382 (`present`, `absent`, `late`, `excused`) are mandatory because the
373 attendance rate is defined over them (`(present+late) /383 attendance rate is defined over them (`(present+late) /
@@ -482,10 +492,10 @@ along with results; unenrolling mid-exam hides the student from the monitor
482 roster but keeps the attempt and mark rows, mirroring the marks report.492 roster but keeps the attempt and mark rows, mirroring the marks report.
483 493
484 > **Upgrading a pre-course database**: `exam` rows created before courses494 > **Upgrading a pre-course database**: `exam` rows created before courses
485-> existed lack the now-required `course` and `weight` fields and will fail to495+> existed lack the now-required `course` field and will fail to deserialize.
486-> deserialize. For a dev database, delete `./data/hezarfen.db` and reboot; to496+> For a dev database, delete `./data/hezarfen.db` and reboot; to keep data,
487-> keep data, backfill manually with the SurrealDB CLI (server stopped), e.g.497+> backfill manually with the SurrealDB CLI (server stopped), e.g.
488-> `UPDATE exam SET course = course:<id>, weight = 1 WHERE course = NONE;`498+> `UPDATE exam SET course = course:<id> WHERE course = NONE;`
489 > after creating a course to attach them to.499 > after creating a course to attach them to.
490 >500 >
491 > **Upgrading to the attempts/rejoin build needs nothing manual**: the boot501 > **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.
493 > `seq = 1` on existing rows, and swaps the single-attempt unique index for503 > `seq = 1` on existing rows, and swaps the single-attempt unique index for
494 > the per-sitting one. Pre-upgrade attempts keep their record ids and count504 > the per-sitting one. Pre-upgrade attempts keep their record ids and count
495 > as sitting #1.505 > as sitting #1.
506+>
507+> **Upgrading to the kind-weight build is a clean break**: weights moved off
508+> exams onto the settings `exam_kinds` entries (`{name, weight}` objects) with
509+> no data migration. A database from an older build has string kinds and a
510+> per-exam `weight` column the code no longer understands — delete
511+> `./data/hezarfen.db` and reboot.
496 512
497 ## Taking an exam: questions, answers & the exam room513 ## Taking an exam: questions, answers & the exam room
498 514
@@ -679,6 +695,9 @@ curl -s -b $JAR $BASE/events/$EV/attendance -H 'content-type: application/json'
679 curl -s -b $JAR $BASE/events/$EV/attendance695 curl -s -b $JAR $BASE/events/$EV/attendance
680 696
681 # courses + weighted marks (as a teacher)697 # courses + weighted marks (as a teacher)
698+# optional, manager+: weigh midterms triple — school policy, per kind
699+curl -s -b $JAR -X PATCH $BASE/settings -H 'content-type: application/json' \
700+ -d '{"exam_kinds":[{"name":"midterm","weight":3},{"name":"quiz","weight":1}]}'
682 # find the student to enroll (here: a registered user "veli"): fragment701 # find the student to enroll (here: a registered user "veli"): fragment
683 # search over username/name, role-narrowed (teacher+)702 # search over username/name, role-narrowed (teacher+)
684 SID=$(curl -s -b $JAR "$BASE/users/search?q=vel&role=student" \703 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' \
688 curl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \707 curl -s -b $JAR $BASE/courses/$CO/enrollments -H 'content-type: application/json' \
689 -d "{\"user_id\":\"$SID\"}"708 -d "{\"user_id\":\"$SID\"}"
690 EX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \709 EX=$(curl -s -b $JAR $BASE/courses/$CO/exams -H 'content-type: application/json' \
691- -d '{"title":"midterm","kind":"midterm","weight":3}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)710+ -d '{"title":"midterm","kind":"midterm"}' | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
692 curl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \711 curl -s -b $JAR $BASE/exams/$EX/results -H 'content-type: application/json' \
693 -d "{\"mark\":90,\"user_id\":\"$SID\"}"712 -d "{\"mark\":90,\"user_id\":\"$SID\"}"
694 curl -s -b $JAR $BASE/exams/$EX/statistics713 curl -s -b $JAR $BASE/exams/$EX/statistics
src/constant.rsmodified+17 -8
@@ -51,10 +51,18 @@ pub const DEFAULT_ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late",
51 51
52 pub const MAX_SESSION_TOPIC_LEN: usize = 200;52 pub const MAX_SESSION_TOPIC_LEN: usize = 200;
53 53
54-/// The default exam kinds; schools replace the list via `PATCH /settings`.54+/// The default exam kinds with their weights; schools replace the list via
55-/// Informational metadata only — `weight` drives the course average.55+/// `PATCH /settings`. An exam's kind decides how heavily it counts into the
56-pub const DEFAULT_EXAM_KINDS: [&str; 6] =56+/// course average — the defaults all weigh 1 (a plain average) so weighting
57- ["homework", "quiz", "midterm", "final", "project", "oral"];57+/// is opt-in policy, not baked-in opinion.
58+pub const DEFAULT_EXAM_KINDS: [(&str, i64); 6] = [
59+ ("homework", 1),
60+ ("quiz", 1),
61+ ("midterm", 1),
62+ ("final", 1),
63+ ("project", 1),
64+ ("oral", 1),
65+];
58 66
59 /// Bounds for the school-editable lists in settings (exam kinds, attendance67 /// Bounds for the school-editable lists in settings (exam kinds, attendance
60 /// statuses): entry count and per-entry character length.68 /// statuses): entry count and per-entry character length.
@@ -117,10 +125,11 @@ pub const MAX_ANSWER_TEXT_LEN: usize = 10_000;
117 pub const MIN_MARK: i64 = 0;125 pub const MIN_MARK: i64 = 0;
118 pub const MAX_MARK: i64 = 100;126 pub const MAX_MARK: i64 = 100;
119 127
120-/// Inclusive bounds for an exam's weight in the course average. The minimum of128+/// Inclusive bounds for an exam kind's weight in the course average. The
121-/// 1 keeps every graded exam counted and the average's denominator non-zero.129+/// minimum of 1 keeps every graded exam counted and the average's denominator
122-pub const MIN_EXAM_WEIGHT: i64 = 1;130+/// non-zero.
123-pub const MAX_EXAM_WEIGHT: i64 = 100;131+pub const MIN_EXAM_KIND_WEIGHT: i64 = 1;
132+pub const MAX_EXAM_KIND_WEIGHT: i64 = 100;
124 133
125 pub const SESSION_DURATION_DAYS: i64 = 7;134 pub const SESSION_DURATION_DAYS: i64 = 7;
126 135
src/database.rsmodified+3 -2
@@ -121,7 +121,6 @@ const MIGRATION: &str = "
121 DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;121 DEFINE FIELD IF NOT EXISTS title ON exam TYPE string;
122 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;122 DEFINE FIELD IF NOT EXISTS description ON exam TYPE string;
123 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;123 DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string;
124- DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int;
125 DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;124 DEFINE FIELD IF NOT EXISTS mode ON exam TYPE option<string>;
126 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;125 DEFINE FIELD IF NOT EXISTS starts_at ON exam TYPE option<int>;
127 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;126 DEFINE FIELD IF NOT EXISTS ends_at ON exam TYPE option<int>;
@@ -172,7 +171,9 @@ const MIGRATION: &str = "
172 DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE;171 DEFINE INDEX IF NOT EXISTS exam_result_exam_user ON exam_result FIELDS exam, user UNIQUE;
173 172
174 DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;173 DEFINE TABLE IF NOT EXISTS settings SCHEMAFULL;
175- DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<string>;174+ DEFINE FIELD IF NOT EXISTS exam_kinds ON settings TYPE array<object>;
175+ DEFINE FIELD IF NOT EXISTS exam_kinds.*.name ON settings TYPE string;
176+ DEFINE FIELD IF NOT EXISTS exam_kinds.*.weight ON settings TYPE int;
176 DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;177 DEFINE FIELD IF NOT EXISTS attendance_statuses ON settings TYPE array<string>;
177 DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;178 DEFINE FIELD IF NOT EXISTS grade_bands ON settings TYPE array<object>;
178 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;179 DEFINE FIELD IF NOT EXISTS grade_bands.*.min ON settings TYPE int;
src/domain/course.rsmodified+2 -1
@@ -61,7 +61,8 @@ impl CourseDescription {
61 }61 }
62 62
63 /// A course: the unit exams and enrollments hang off. Marks are computed per63 /// A course: the unit exams and enrollments hang off. Marks are computed per
64-/// course from its exams' weights. May belong to an academic term.64+/// course, each exam weighted by its kind's settings weight. May belong to an
65+/// academic term.
65 #[derive(Debug, Clone, SurrealValue)]66 #[derive(Debug, Clone, SurrealValue)]
66 pub struct Course {67 pub struct Course {
67 id: CourseId,68 id: CourseId,
src/domain/exam.rsmodified+10 -42
@@ -4,12 +4,13 @@ use ulid::Ulid;
4 use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS};4 use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN, UNLIMITED_EXAM_ATTEMPTS};
5 use crate::database::{Database, EXAM_TABLE};5 use crate::database::{Database, EXAM_TABLE};
6 use crate::domain::course::CourseId;6 use crate::domain::course::CourseId;
7+use crate::domain::settings::ExamKindDef;
7 use crate::domain::timestamp::Timestamp;8 use crate::domain::timestamp::Timestamp;
8 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
9 use crate::error::{AppError, ValidationError};10 use crate::error::{AppError, ValidationError};
10 use crate::validate::{11 use crate::validate::{
11 validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,12 validate_attempt_limit, validate_exam_duration, validate_exam_mode, validate_optional,
12- validate_required, validate_weight,13+ validate_required,
13 };14 };
14 15
15 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]16 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -65,16 +66,16 @@ impl ExamDescription {
65 }66 }
66 67
67 /// A validated exam kind — one of the school's configured kinds68 /// A validated exam kind — one of the school's configured kinds
68-/// ([`crate::domain::settings::Settings::get_exam_kinds`]). Informational69+/// ([`crate::domain::settings::Settings::get_exam_kinds`]). The kind carries
69-/// metadata only — `weight` drives the course average. Stored exams keep70+/// the exam's weight in the course average (set per kind in settings, not per
70-/// their kind even if the school later edits the list; only new writes are71+/// exam). Stored exams keep their kind even if the school later edits the
71-/// held to the current one.72+/// list; only new writes are held to the current one.
72 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]73 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
73 pub struct ExamKind(String);74 pub struct ExamKind(String);
74 75
75 impl ExamKind {76 impl ExamKind {
76- pub fn try_new(value: &str, allowed: &[String]) -> Result<Self, ValidationError> {77+ pub fn try_new(value: &str, allowed: &[ExamKindDef]) -> Result<Self, ValidationError> {
77- if !allowed.iter().any(|kind| kind == value) {78+ if !allowed.iter().any(|kind| kind.get_name() == value) {
78 return Err(ValidationError::Invalid {79 return Err(ValidationError::Invalid {
79 field: "kind",80 field: "kind",
80 reason: "is not one of this school's exam kinds (see GET /settings)",81 reason: "is not one of this school's exam kinds (see GET /settings)",
@@ -88,22 +89,6 @@ impl ExamKind {
88 }89 }
89 }90 }
90 91
91-/// A validated exam weight, held to `[MIN_EXAM_WEIGHT, MAX_EXAM_WEIGHT]`. The
92-/// exam counts `weight` times into its course's average.
93-#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)]
94-pub struct ExamWeight(i64);
95-
96-impl ExamWeight {
97- pub fn try_new(value: i64) -> Result<Self, ValidationError> {
98- validate_weight(value)?;
99- Ok(Self(value))
100- }
101-
102- pub fn as_i64(&self) -> i64 {
103- self.0
104- }
105-}
106-
107 /// A validated exam mode: `sync` (everyone sits inside one fixed window),92 /// A validated exam mode: `sync` (everyone sits inside one fixed window),
108 /// `async` (each student starts inside the window and gets `duration_ms`), or93 /// `async` (each student starts inside the window and gets `duration_ms`), or
109 /// `open` (no window — sit anytime, with an optional per-attempt duration).94 /// `open` (no window — sit anytime, with an optional per-attempt duration).
@@ -262,7 +247,6 @@ pub struct Exam {
262 title: ExamTitle,247 title: ExamTitle,
263 description: ExamDescription,248 description: ExamDescription,
264 kind: ExamKind,249 kind: ExamKind,
265- weight: ExamWeight,
266 // The schedule, flattened into columns (SCHEMAFULL keeps them typed).250 // The schedule, flattened into columns (SCHEMAFULL keeps them typed).
267 // Always written through an `ExamSchedule`, so the invariants above hold251 // Always written through an `ExamSchedule`, so the invariants above hold
268 // for every stored row; pre-schedule rows read back as all-`None`.252 // for every stored row; pre-schedule rows read back as all-`None`.
@@ -301,10 +285,6 @@ impl Exam {
301 &self.kind285 &self.kind
302 }286 }
303 287
304- pub fn get_weight(&self) -> ExamWeight {
305- self.weight
306- }
307-
308 pub fn get_mode(&self) -> Option<&ExamMode> {288 pub fn get_mode(&self) -> Option<&ExamMode> {
309 self.mode.as_ref()289 self.mode.as_ref()
310 }290 }
@@ -357,7 +337,6 @@ impl Exam {
357 title: ExamTitle,337 title: ExamTitle,
358 description: ExamDescription,338 description: ExamDescription,
359 kind: ExamKind,339 kind: ExamKind,
360- weight: ExamWeight,
361 schedule: ExamSchedule,340 schedule: ExamSchedule,
362 max_attempts: ExamAttemptLimit,341 max_attempts: ExamAttemptLimit,
363 allow_rejoin: bool,342 allow_rejoin: bool,
@@ -370,7 +349,6 @@ impl Exam {
370 title,349 title,
371 description,350 description,
372 kind,351 kind,
373- weight,
374 mode: schedule.mode,352 mode: schedule.mode,
375 starts_at: schedule.starts_at,353 starts_at: schedule.starts_at,
376 ends_at: schedule.ends_at,354 ends_at: schedule.ends_at,
@@ -432,7 +410,6 @@ impl Exam {
432 title: ExamTitle,410 title: ExamTitle,
433 description: ExamDescription,411 description: ExamDescription,
434 kind: ExamKind,412 kind: ExamKind,
435- weight: ExamWeight,
436 schedule: ExamSchedule,413 schedule: ExamSchedule,
437 max_attempts: ExamAttemptLimit,414 max_attempts: ExamAttemptLimit,
438 allow_rejoin: bool,415 allow_rejoin: bool,
@@ -441,7 +418,6 @@ impl Exam {
441 self.title = title;418 self.title = title;
442 self.description = description;419 self.description = description;
443 self.kind = kind;420 self.kind = kind;
444- self.weight = weight;
445 self.mode = schedule.mode;421 self.mode = schedule.mode;
446 self.starts_at = schedule.starts_at;422 self.starts_at = schedule.starts_at;
447 self.ends_at = schedule.ends_at;423 self.ends_at = schedule.ends_at;
@@ -489,7 +465,7 @@ mod tests {
489 465
490 #[tokio::test]466 #[tokio::test]
491 async fn kind_must_be_in_the_allowed_list() {467 async fn kind_must_be_in_the_allowed_list() {
492- let allowed: Vec<String> = crate::domain::settings::Settings::defaults()468+ let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults()
493 .get_exam_kinds()469 .get_exam_kinds()
494 .to_vec();470 .to_vec();
495 for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {471 for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] {
@@ -498,7 +474,7 @@ mod tests {
498 assert!(ExamKind::try_new("essay", &allowed).is_err());474 assert!(ExamKind::try_new("essay", &allowed).is_err());
499 assert!(ExamKind::try_new("", &allowed).is_err());475 assert!(ExamKind::try_new("", &allowed).is_err());
500 // A school-defined list swaps the acceptance set wholesale.476 // A school-defined list swaps the acceptance set wholesale.
501- let custom = vec!["lab".to_string()];477+ let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()];
502 assert!(ExamKind::try_new("lab", &custom).is_ok());478 assert!(ExamKind::try_new("lab", &custom).is_ok());
503 assert!(ExamKind::try_new("midterm", &custom).is_err());479 assert!(ExamKind::try_new("midterm", &custom).is_err());
504 // Matching is exact, case included — the settings list is the wire480 // Matching is exact, case included — the settings list is the wire
@@ -506,14 +482,6 @@ mod tests {
506 assert!(ExamKind::try_new("Lab", &custom).is_err());482 assert!(ExamKind::try_new("Lab", &custom).is_err());
507 }483 }
508 484
509- #[tokio::test]
510- async fn weight_range_is_enforced() {
511- assert_eq!(ExamWeight::try_new(1).unwrap().as_i64(), 1);
512- assert_eq!(ExamWeight::try_new(100).unwrap().as_i64(), 100);
513- assert!(ExamWeight::try_new(0).is_err());
514- assert!(ExamWeight::try_new(101).is_err());
515- }
516-
517 #[tokio::test]485 #[tokio::test]
518 async fn mode_must_be_known() {486 async fn mode_must_be_known() {
519 for mode in ["sync", "async", "open"] {487 for mode in ["sync", "async", "open"] {
src/domain/exam_attempt.rsmodified+1 -2
@@ -321,7 +321,7 @@ mod tests {
321 use crate::database::init_mem;321 use crate::database::init_mem;
322 use crate::domain::course::CourseId;322 use crate::domain::course::CourseId;
323 use crate::domain::exam::{323 use crate::domain::exam::{
324- ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight,324+ ExamAttemptLimit, ExamDescription, ExamKind, ExamMode, ExamSchedule, ExamTitle,
325 };325 };
326 use crate::domain::exam_answer::ExamAnswer;326 use crate::domain::exam_answer::ExamAnswer;
327 use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec};327 use crate::domain::exam_question::{ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec};
@@ -339,7 +339,6 @@ mod tests {
339 ExamTitle::try_new("practice").unwrap(),339 ExamTitle::try_new("practice").unwrap(),
340 ExamDescription::try_new("").unwrap(),340 ExamDescription::try_new("").unwrap(),
341 ExamKind::try_new("quiz", &kinds).unwrap(),341 ExamKind::try_new("quiz", &kinds).unwrap(),
342- ExamWeight::try_new(1).unwrap(),
343 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)342 ExamSchedule::try_new(Some(ExamMode::try_new("open").unwrap()), None, None, None)
344 .unwrap(),343 .unwrap(),
345 ExamAttemptLimit::try_new(max_attempts).unwrap(),344 ExamAttemptLimit::try_new(max_attempts).unwrap(),
src/domain/settings.rsmodified+138 -25
@@ -1,5 +1,6 @@
1-//! School-adjustable policy: which exam kinds exist, which attendance1+//! School-adjustable policy: which exam kinds exist (and how much each
2-//! statuses the roll call accepts, and how numeric marks display as grades.2+//! weighs in course averages), which attendance statuses the roll call
3+//! accepts, and how numeric marks display as grades.
3 //!4 //!
4 //! One singleton record (`settings:school` — one school per deployment). An5 //! One singleton record (`settings:school` — one school per deployment). An
5 //! absent record means "the defaults from `constant.rs`", so a fresh or6 //! absent record means "the defaults from `constant.rs`", so a fresh or
@@ -8,8 +9,9 @@
8 use surrealdb::types::{RecordId, SurrealValue};9 use surrealdb::types::{RecordId, SurrealValue};
9 10
10 use crate::constant::{11 use crate::constant::{
11- DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_GRADE_BANDS, MAX_GRADE_LABEL_LEN,12+ DEFAULT_ATTENDANCE_STATUSES, DEFAULT_EXAM_KINDS, MAX_EXAM_KIND_WEIGHT, MAX_GRADE_BANDS,
12- MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN, MIN_MARK,13+ MAX_GRADE_LABEL_LEN, MAX_MARK, MAX_SETTINGS_ITEM_LEN, MAX_SETTINGS_LIST_LEN,
14+ MIN_EXAM_KIND_WEIGHT, MIN_MARK,
13 };15 };
14 use crate::database::{Database, SETTINGS_TABLE};16 use crate::database::{Database, SETTINGS_TABLE};
15 use crate::error::{AppError, ValidationError};17 use crate::error::{AppError, ValidationError};
@@ -17,6 +19,46 @@ use crate::error::{AppError, ValidationError};
17 /// The singleton's fixed key: one school per deployment, one settings row.19 /// The singleton's fixed key: one school per deployment, one settings row.
18 const SETTINGS_KEY: &str = "school";20 const SETTINGS_KEY: &str = "school";
19 21
22+/// One exam kind the school runs (`"midterm"`, `"oral"`, …) with its weight:
23+/// how many times an exam of that kind counts into its course's average.
24+/// Weight lives here, not on the exam — reweighting a kind reweights every
25+/// exam of that kind at once.
26+#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
27+pub struct ExamKindDef {
28+ name: String,
29+ weight: i64,
30+}
31+
32+impl ExamKindDef {
33+ pub fn try_new(name: &str, weight: i64) -> Result<Self, ValidationError> {
34+ let name = name.trim();
35+ if name.is_empty() || name.chars().count() > MAX_SETTINGS_ITEM_LEN {
36+ return Err(ValidationError::Invalid {
37+ field: "exam_kinds",
38+ reason: "kind names must be 1 to 50 characters",
39+ });
40+ }
41+ if !(MIN_EXAM_KIND_WEIGHT..=MAX_EXAM_KIND_WEIGHT).contains(&weight) {
42+ return Err(ValidationError::Invalid {
43+ field: "exam_kinds",
44+ reason: "kind weights must be between 1 and 100",
45+ });
46+ }
47+ Ok(Self {
48+ name: name.to_string(),
49+ weight,
50+ })
51+ }
52+
53+ pub fn get_name(&self) -> &str {
54+ &self.name
55+ }
56+
57+ pub fn get_weight(&self) -> i64 {
58+ self.weight
59+ }
60+}
61+
20 /// One grade-display band: marks at or above `min` (and below the next band's62 /// One grade-display band: marks at or above `min` (and below the next band's
21 /// `min`) render as `label`. Display only — storage and averaging stay numeric.63 /// `min`) render as `label`. Display only — storage and averaging stay numeric.
22 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]64 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -61,7 +103,7 @@ impl GradeBand {
61 #[derive(Debug, Clone, SurrealValue)]103 #[derive(Debug, Clone, SurrealValue)]
62 pub struct Settings {104 pub struct Settings {
63 id: RecordId,105 id: RecordId,
64- exam_kinds: Vec<String>,106+ exam_kinds: Vec<ExamKindDef>,
65 attendance_statuses: Vec<String>,107 attendance_statuses: Vec<String>,
66 grade_bands: Vec<GradeBand>,108 grade_bands: Vec<GradeBand>,
67 }109 }
@@ -76,7 +118,12 @@ impl Settings {
76 pub fn defaults() -> Self {118 pub fn defaults() -> Self {
77 Self {119 Self {
78 id: Self::record_id(),120 id: Self::record_id(),
79- exam_kinds: DEFAULT_EXAM_KINDS.map(String::from).to_vec(),121+ exam_kinds: DEFAULT_EXAM_KINDS
122+ .map(|(name, weight)| ExamKindDef {
123+ name: name.to_string(),
124+ weight,
125+ })
126+ .to_vec(),
80 attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(),127 attendance_statuses: DEFAULT_ATTENDANCE_STATUSES.map(String::from).to_vec(),
81 grade_bands: Vec::new(),128 grade_bands: Vec::new(),
82 }129 }
@@ -89,11 +136,17 @@ impl Settings {
89 /// display), otherwise their mins are unique and one band must start at 0136 /// display), otherwise their mins are unique and one band must start at 0
90 /// so every mark maps to a label.137 /// so every mark maps to a label.
91 pub fn try_new(138 pub fn try_new(
92- exam_kinds: Vec<String>,139+ exam_kinds: Vec<ExamKindDef>,
93 attendance_statuses: Vec<String>,140 attendance_statuses: Vec<String>,
94 grade_bands: Vec<GradeBand>,141 grade_bands: Vec<GradeBand>,
95 ) -> Result<Self, ValidationError> {142 ) -> Result<Self, ValidationError> {
96- let exam_kinds = validate_list("exam_kinds", exam_kinds)?;143+ // Per-entry rules (name shape, weight range) hold structurally on any
144+ // `ExamKindDef`; here only the list-level rules need checking.
145+ let names: Vec<String> = exam_kinds
146+ .iter()
147+ .map(|kind| kind.get_name().to_string())
148+ .collect();
149+ validate_list("exam_kinds", names)?;
97 let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?;150 let attendance_statuses = validate_list("attendance_statuses", attendance_statuses)?;
98 if DEFAULT_ATTENDANCE_STATUSES151 if DEFAULT_ATTENDANCE_STATUSES
99 .iter()152 .iter()
@@ -138,10 +191,21 @@ impl Settings {
138 })191 })
139 }192 }
140 193
141- pub fn get_exam_kinds(&self) -> &[String] {194+ pub fn get_exam_kinds(&self) -> &[ExamKindDef] {
142 &self.exam_kinds195 &self.exam_kinds
143 }196 }
144 197
198+ /// The weight of the kind named `kind` (exact match, like kind
199+ /// validation), or `None` when the school no longer lists it. Callers
200+ /// averaging marks fall back to weight 1 — an exam keeps its retired kind
201+ /// (settings edits never rewrite history), so it must still count.
202+ pub fn exam_kind_weight(&self, kind: &str) -> Option<i64> {
203+ self.exam_kinds
204+ .iter()
205+ .find(|def| def.get_name() == kind)
206+ .map(ExamKindDef::get_weight)
207+ }
208+
145 pub fn get_attendance_statuses(&self) -> &[String] {209 pub fn get_attendance_statuses(&self) -> &[String] {
146 &self.attendance_statuses210 &self.attendance_statuses
147 }211 }
@@ -255,8 +319,18 @@ fn validate_list(field: &'static str, values: Vec<String>) -> Result<Vec<String>
255 mod tests {319 mod tests {
256 use super::*;320 use super::*;
257 321
258- fn kinds(list: &[&str]) -> Vec<String> {322+ fn kinds(list: &[&str]) -> Vec<ExamKindDef> {
259- list.iter().map(|s| s.to_string()).collect()323+ list.iter()
324+ .map(|s| ExamKindDef::try_new(s, 1).unwrap())
325+ .collect()
326+ }
327+
328+ fn names(settings: &Settings) -> Vec<&str> {
329+ settings
330+ .get_exam_kinds()
331+ .iter()
332+ .map(ExamKindDef::get_name)
333+ .collect()
260 }334 }
261 335
262 fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> {336 fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> {
@@ -279,21 +353,60 @@ mod tests {
279 }353 }
280 354
281 #[tokio::test]355 #[tokio::test]
282- async fn lists_are_trimmed_bounded_and_deduped() {356+ async fn kind_defs_hold_name_and_weight_rules() {
357+ // Names are trimmed; blank or over-long names die.
358+ assert_eq!(
359+ ExamKindDef::try_new(" lab ", 1).unwrap().get_name(),
360+ "lab"
361+ );
362+ assert!(ExamKindDef::try_new(" ", 1).is_err());
363+ assert!(ExamKindDef::try_new(&"x".repeat(51), 1).is_err());
364+ // Weights are held to 1–100 — 0 would erase the kind's exams from the
365+ // average, and negatives would corrupt it.
366+ for weight in [1, 50, 100] {
367+ assert_eq!(
368+ ExamKindDef::try_new("oral", weight).unwrap().get_weight(),
369+ weight
370+ );
371+ }
372+ assert!(ExamKindDef::try_new("oral", 0).is_err());
373+ assert!(ExamKindDef::try_new("oral", -1).is_err());
374+ assert!(ExamKindDef::try_new("oral", 101).is_err());
375+ }
376+
377+ #[tokio::test]
378+ async fn lists_are_bounded_and_deduped() {
283 let statuses = Settings::defaults().get_attendance_statuses().to_vec();379 let statuses = Settings::defaults().get_attendance_statuses().to_vec();
284- // Trimming happens before storage.380+ let s = Settings::try_new(kinds(&["lab", "quiz"]), statuses.clone(), vec![]).unwrap();
285- let s = Settings::try_new(kinds(&[" lab ", "quiz"]), statuses.clone(), vec![]).unwrap();381+ assert_eq!(names(&s), ["lab", "quiz"]);
286- assert_eq!(s.get_exam_kinds(), ["lab", "quiz"]);382+ // Empty list and case-insensitive duplicate names are rejected.
287- // Empty list, blank entry, over-long entry, and case-insensitive
288- // duplicates are all rejected.
289 assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err());383 assert!(Settings::try_new(vec![], statuses.clone(), vec![]).is_err());
290- assert!(Settings::try_new(kinds(&[" "]), statuses.clone(), vec![]).is_err());
291- assert!(Settings::try_new(kinds(&[&"x".repeat(51)]), statuses.clone(), vec![]).is_err());
292 assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err());384 assert!(Settings::try_new(kinds(&["Lab", "lab"]), statuses.clone(), vec![]).is_err());
293- let too_many: Vec<String> = (0..21).map(|i| format!("kind{i}")).collect();385+ let too_many: Vec<ExamKindDef> = (0..21)
386+ .map(|i| ExamKindDef::try_new(&format!("kind{i}"), 1).unwrap())
387+ .collect();
294 assert!(Settings::try_new(too_many, statuses, vec![]).is_err());388 assert!(Settings::try_new(too_many, statuses, vec![]).is_err());
295 }389 }
296 390
391+ #[tokio::test]
392+ async fn kind_weights_resolve_by_exact_name() {
393+ let statuses = Settings::defaults().get_attendance_statuses().to_vec();
394+ let s = Settings::try_new(
395+ vec![
396+ ExamKindDef::try_new("midterm", 2).unwrap(),
397+ ExamKindDef::try_new("final", 3).unwrap(),
398+ ],
399+ statuses,
400+ vec![],
401+ )
402+ .unwrap();
403+ assert_eq!(s.exam_kind_weight("final"), Some(3));
404+ assert_eq!(s.exam_kind_weight("midterm"), Some(2));
405+ // Exact match, case included — same contract as kind validation.
406+ assert_eq!(s.exam_kind_weight("Final"), None);
407+ assert_eq!(s.exam_kind_weight("oral"), None);
408+ }
409+
297 #[tokio::test]410 #[tokio::test]
298 async fn core_attendance_statuses_are_mandatory() {411 async fn core_attendance_statuses_are_mandatory() {
299 let kinds = Settings::defaults().get_exam_kinds().to_vec();412 let kinds = Settings::defaults().get_exam_kinds().to_vec();
@@ -364,7 +477,7 @@ mod tests {
364 .await477 .await
365 .unwrap();478 .unwrap();
366 let loaded = Settings::load(&db).await.unwrap();479 let loaded = Settings::load(&db).await.unwrap();
367- assert_eq!(loaded.get_exam_kinds(), ["lab"]);480+ assert_eq!(names(&loaded), ["lab"]);
368 assert_eq!(loaded.get_grade_bands().len(), 2);481 assert_eq!(loaded.get_grade_bands().len(), 2);
369 assert_eq!(loaded.grade_label(60.0), Some("P"));482 assert_eq!(loaded.grade_label(60.0), Some("P"));
370 // A second save lands on the same singleton row, not a new one.483 // A second save lands on the same singleton row, not a new one.
@@ -376,7 +489,7 @@ mod tests {
376 let mut result = db.query("SELECT * FROM settings").await.unwrap();489 let mut result = db.query("SELECT * FROM settings").await.unwrap();
377 let rows: Vec<Settings> = result.take(0).unwrap();490 let rows: Vec<Settings> = result.take(0).unwrap();
378 assert_eq!(rows.len(), 1);491 assert_eq!(rows.len(), 1);
379- assert_eq!(rows[0].get_exam_kinds(), ["quiz"]);492+ assert_eq!(names(&rows[0]), ["quiz"]);
380 }493 }
381 494
382 #[tokio::test]495 #[tokio::test]
@@ -410,7 +523,7 @@ mod tests {
410 // B's edit must survive A's stale write attempt.523 // B's edit must survive A's stale write attempt.
411 let after = Settings::load(&db).await.unwrap();524 let after = Settings::load(&db).await.unwrap();
412 assert_eq!(525 assert_eq!(
413- after.get_exam_kinds(),526+ names(&after),
414 ["lab"],527 ["lab"],
415 "a concurrent editor's exam kinds must not be silently reverted"528 "a concurrent editor's exam kinds must not be silently reverted"
416 );529 );
@@ -428,7 +541,7 @@ mod tests {
428 .await541 .await
429 .unwrap()542 .unwrap()
430 .expect("a merge over the current row applies");543 .expect("a merge over the current row applies");
431- assert_eq!(saved.get_exam_kinds(), ["lab"]);544+ assert_eq!(names(&saved), ["lab"]);
432 assert_eq!(saved.get_grade_bands().len(), 2);545 assert_eq!(saved.get_grade_bands().len(), 2);
433 }546 }
434 547
@@ -448,7 +561,7 @@ mod tests {
448 .await561 .await
449 .unwrap()562 .unwrap()
450 .expect("the first save applies");563 .expect("the first save applies");
451- assert_eq!(saved.get_exam_kinds(), ["lab"]);564+ assert_eq!(names(&saved), ["lab"]);
452 let mut result = db.query("SELECT * FROM settings").await.unwrap();565 let mut result = db.query("SELECT * FROM settings").await.unwrap();
453 let rows: Vec<Settings> = result.take(0).unwrap();566 let rows: Vec<Settings> = result.take(0).unwrap();
454 assert_eq!(rows.len(), 1, "still one singleton row");567 assert_eq!(rows.len(), 1, "still one singleton row");
src/lib.rsmodified+4 -4
@@ -32,7 +32,7 @@ use crate::state::AppState;
32 info(32 info(
33 title = "Hezarfen Backend API",33 title = "Hezarfen Backend API",
34 version = env!("CARGO_PKG_VERSION"),34 version = env!("CARGO_PKG_VERSION"),
35- 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.",35+ 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.",
36 ),36 ),
37 modifiers(&SecurityAddon),37 modifiers(&SecurityAddon),
38 tags(38 tags(
@@ -45,9 +45,9 @@ use crate::state::AppState;
45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),45 (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
47 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),47 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
48- (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"),48+ (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"),
49- (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured"),49+ (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)"),
50- (name = "settings", description = "School policy, one singleton: exam kinds, attendance statuses, grade-display bands. Read: any authenticated user; edit: manager+"),50+ (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+"),
51 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),51 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),
52 ),52 ),
53 )]53 )]
src/validate.rsmodified+4 -26
@@ -2,11 +2,10 @@
2 //! the value, so an existing newtype is always valid (parse, don't validate).2 //! the value, so an existing newtype is always valid (parse, don't validate).
3 3
4 use crate::constant::{4 use crate::constant::{
5- EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_EXAM_WEIGHT, MAX_MARK,5+ EXAM_MODES, MAX_EMAIL_LEN, MAX_EXAM_ATTEMPTS, MAX_EXAM_DURATION_MS, MAX_MARK, MAX_PASSWORD_LEN,
6- MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN,6+ MAX_PHONE_DIGITS, MAX_QUESTION_POINTS, MAX_USERNAME_LEN, MIN_EXAM_DURATION_MS, MIN_MARK,
7- MIN_EXAM_DURATION_MS, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS,7+ MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS,
8- MIN_QUESTION_POINTS, MIN_USERNAME_LEN, QUESTION_KINDS, UNLIMITED_EXAM_ATTEMPTS,8+ UNLIMITED_EXAM_ATTEMPTS, USERNAME_SEPARATORS,
9- USERNAME_SEPARATORS,
10 };9 };
11 use crate::error::ValidationError;10 use crate::error::ValidationError;
12 11
@@ -264,17 +263,6 @@ pub fn validate_mark(value: i64) -> Result<(), ValidationError> {
264 }263 }
265 }264 }
266 265
267-pub fn validate_weight(value: i64) -> Result<(), ValidationError> {
268- if (MIN_EXAM_WEIGHT..=MAX_EXAM_WEIGHT).contains(&value) {
269- Ok(())
270- } else {
271- Err(ValidationError::Invalid {
272- field: "weight",
273- reason: "must be between 1 and 100",
274- })
275- }
276-}
277-
278 #[cfg(test)]266 #[cfg(test)]
279 mod tests {267 mod tests {
280 use super::*;268 use super::*;
@@ -443,14 +431,4 @@ mod tests {
443 assert!(validate_mark(-1).is_err());431 assert!(validate_mark(-1).is_err());
444 assert!(validate_mark(101).is_err());432 assert!(validate_mark(101).is_err());
445 }433 }
446-
447- #[tokio::test]
448- async fn weight_rules() {
449- for weight in [1, 50, 100] {
450- assert!(validate_weight(weight).is_ok());
451- }
452- assert!(validate_weight(0).is_err());
453- assert!(validate_weight(-1).is_err());
454- assert!(validate_weight(101).is_err());
455- }
456 }434 }
src/web/courses.rsmodified+11 -14
@@ -14,7 +14,7 @@ use crate::domain::course_session::{CourseSession, SessionTopic};
14 use crate::domain::enrollment::Enrollment;14 use crate::domain::enrollment::Enrollment;
15 use crate::domain::exam::{15 use crate::domain::exam::{
16 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,16 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
17- ExamTitle, ExamWeight,17+ ExamTitle,
18 };18 };
19 use crate::domain::role::Role;19 use crate::domain::role::Role;
20 use crate::domain::settings::Settings;20 use crate::domain::settings::Settings;
@@ -75,12 +75,10 @@ struct CreateExamInCourse {
75 description: Option<String>,75 description: Option<String>,
76 /// The assessment form — one of the school's exam kinds (`GET /settings`;76 /// The assessment form — one of the school's exam kinds (`GET /settings`;
77 /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`).77 /// defaults: `homework`, `quiz`, `midterm`, `final`, `project`, `oral`).
78- /// Informational — `weight` drives the course average.78+ /// The kind's settings-configured weight decides how heavily the exam
79+ /// counts into the course average.
79 #[schema(example = "midterm")]80 #[schema(example = "midterm")]
80 kind: String,81 kind: String,
81- /// How many times this exam counts into the course average, `1`–`100`.
82- #[schema(example = 3)]
83- weight: i64,
84 /// `sync` (one fixed window for everyone), `async` (each student starts82 /// `sync` (one fixed window for everyone), `async` (each student starts
85 /// inside the window and gets `duration_ms`), or `open` (no window — sit83 /// inside the window and gets `duration_ms`), or `open` (no window — sit
86 /// anytime). Omit for an offline-graded draft that cannot be sat.84 /// anytime). Omit for an offline-graded draft that cannot be sat.
@@ -487,12 +485,13 @@ async fn unenroll(
487 // ---- exams in a course ----------------------------------------------------485 // ---- exams in a course ----------------------------------------------------
488 486
489 /// Create an exam inside a course. Requires teacher+ and course management487 /// Create an exam inside a course. Requires teacher+ and course management
490-/// rights; the exam's marks count `weight` times into the course average.488+/// rights; the exam's marks count into the course average with its kind's
491-/// Omit `mode` for an offline-graded draft nobody can sit; `sync`/`async`489+/// weight (`GET /settings`). Omit `mode` for an offline-graded draft nobody
492-/// take a window (async also `duration_ms`), `open` is sittable anytime with490+/// can sit; `sync`/`async` take a window (async also `duration_ms`), `open`
493-/// an optional per-attempt `duration_ms`. `max_attempts` (default 1, `0` =491+/// is sittable anytime with an optional per-attempt `duration_ms`.
494-/// unlimited) meters retakes and `allow_rejoin` (default `true`) is the492+/// `max_attempts` (default 1, `0` = unlimited) meters retakes and
495-/// exam-room door — both stay editable while the exam runs.493+/// `allow_rejoin` (default `true`) is the exam-room door — both stay editable
494+/// while the exam runs.
496 #[utoipa::path(495 #[utoipa::path(
497 post,496 post,
498 path = "/{id}/exams",497 path = "/{id}/exams",
@@ -502,7 +501,7 @@ async fn unenroll(
502 request_body = CreateExamInCourse,501 request_body = CreateExamInCourse,
503 responses(502 responses(
504 (status = 201, description = "Exam created", body = ExamResponse),503 (status = 201, description = "Exam created", body = ExamResponse),
505- (status = 400, description = "Invalid fields, kind, weight, attempt limit, or schedule (malformed window, or times in the past)", body = ErrorResponse),504+ (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or times in the past)", body = ErrorResponse),
506 (status = 401, description = "Not authenticated", body = ErrorResponse),505 (status = 401, description = "Not authenticated", body = ErrorResponse),
507 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),506 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
508 (status = 404, description = "Course not found", body = ErrorResponse),507 (status = 404, description = "Course not found", body = ErrorResponse),
@@ -527,7 +526,6 @@ async fn create_exam_in_course(
527 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;526 let description = ExamDescription::try_new(&req.description.unwrap_or_default())?;
528 let school = Settings::load(&st.db).await?;527 let school = Settings::load(&st.db).await?;
529 let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?;528 let kind = ExamKind::try_new(&req.kind, school.get_exam_kinds())?;
530- let weight = ExamWeight::try_new(req.weight)?;
531 let starts_at = req.starts_at.map(Timestamp::from_millis);529 let starts_at = req.starts_at.map(Timestamp::from_millis);
532 let ends_at = req.ends_at.map(Timestamp::from_millis);530 let ends_at = req.ends_at.map(Timestamp::from_millis);
533 check_not_past("starts_at", starts_at)?;531 check_not_past("starts_at", starts_at)?;
@@ -548,7 +546,6 @@ async fn create_exam_in_course(
548 title,546 title,
549 description,547 description,
550 kind,548 kind,
551- weight,
552 schedule,549 schedule,
553 max_attempts,550 max_attempts,
554 req.allow_rejoin.unwrap_or(true),551 req.allow_rejoin.unwrap_or(true),
src/web/dto.rsmodified+2 -2
@@ -207,8 +207,9 @@ pub struct ExamResponse {
207 pub course: String,207 pub course: String,
208 pub title: String,208 pub title: String,
209 pub description: String,209 pub description: String,
210+ /// The assessment form. Its weight in the course average is school policy:
211+ /// `GET /settings` maps each kind to a weight.
210 pub kind: String,212 pub kind: String,
211- pub weight: i64,
212 /// `sync`, `async`, or `open`; `null` for an offline-graded draft213 /// `sync`, `async`, or `open`; `null` for an offline-graded draft
213 /// (not sittable).214 /// (not sittable).
214 #[schema(example = "sync")]215 #[schema(example = "sync")]
@@ -237,7 +238,6 @@ impl ExamResponse {
237 title: exam.get_title().as_str().to_string(),238 title: exam.get_title().as_str().to_string(),
238 description: exam.get_description().as_str().to_string(),239 description: exam.get_description().as_str().to_string(),
239 kind: exam.get_kind().as_str().to_string(),240 kind: exam.get_kind().as_str().to_string(),
240- weight: exam.get_weight().as_i64(),
241 mode: exam.get_mode().map(|m| m.as_str().to_string()),241 mode: exam.get_mode().map(|m| m.as_str().to_string()),
242 starts_at: exam.get_starts_at().map(|t| t.as_millis()),242 starts_at: exam.get_starts_at().map(|t| t.as_millis()),
243 ends_at: exam.get_ends_at().map(|t| t.as_millis()),243 ends_at: exam.get_ends_at().map(|t| t.as_millis()),
src/web/exams.rsmodified+5 -8
@@ -18,7 +18,7 @@ use crate::domain::course::Course;
18 use crate::domain::enrollment::Enrollment;18 use crate::domain::enrollment::Enrollment;
19 use crate::domain::exam::{19 use crate::domain::exam::{
20 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,20 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode,
21- ExamSchedule, ExamTitle, ExamWeight,21+ ExamSchedule, ExamTitle,
22 };22 };
23 use crate::domain::exam_answer::{ExamAnswer, auto_score};23 use crate::domain::exam_answer::{ExamAnswer, auto_score};
24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};24 use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
@@ -68,8 +68,10 @@ pub fn routes() -> OpenApiRouter<AppState> {
68 struct UpdateExam {68 struct UpdateExam {
69 title: Option<String>,69 title: Option<String>,
70 description: Option<String>,70 description: Option<String>,
71+ /// The assessment form — one of the school's exam kinds (`GET /settings`).
72+ /// Changing it re-weights the exam: the course average uses the kind's
73+ /// settings-configured weight.
71 kind: Option<String>,74 kind: Option<String>,
72- weight: Option<i64>,
73 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`75 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
74 /// to turn the exam back into an offline draft. Frozen once anyone has76 /// to turn the exam back into an offline draft. Frozen once anyone has
75 /// started an attempt. Switching to `open` requires clearing77 /// started an attempt. Switching to `open` requires clearing
@@ -232,7 +234,7 @@ async fn get_exam(
232 request_body = UpdateExam,234 request_body = UpdateExam,
233 responses(235 responses(
234 (status = 200, description = "Updated exam", body = ExamResponse),236 (status = 200, description = "Updated exam", body = ExamResponse),
235- (status = 400, description = "Invalid fields, kind, weight, attempt limit, or schedule (malformed window, or newly set times in the past)", body = ErrorResponse),237+ (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, or newly set times in the past)", body = ErrorResponse),
236 (status = 401, description = "Not authenticated", body = ErrorResponse),238 (status = 401, description = "Not authenticated", body = ErrorResponse),
237 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),239 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
238 (status = 404, description = "Not found", body = ErrorResponse),240 (status = 404, description = "Not found", body = ErrorResponse),
@@ -273,10 +275,6 @@ async fn update_exam(
273 }275 }
274 None => exam.get_kind().clone(),276 None => exam.get_kind().clone(),
275 };277 };
276- let weight = match req.weight {
277- Some(weight) => ExamWeight::try_new(weight)?,
278- None => exam.get_weight(),
279- };
280 278
281 // Merge the schedule (set / clear / keep per field), then re-validate it279 // Merge the schedule (set / clear / keep per field), then re-validate it
282 // as a unit — a PATCH can't leave a half-schedule behind. Only values this280 // as a unit — a PATCH can't leave a half-schedule behind. Only values this
@@ -331,7 +329,6 @@ async fn update_exam(
331 title,329 title,
332 description,330 description,
333 kind,331 kind,
334- weight,
335 schedule,332 schedule,
336 max_attempts,333 max_attempts,
337 allow_rejoin,334 allow_rejoin,
src/web/marks.rsmodified+17 -8
@@ -33,6 +33,9 @@ struct MarkEntry {
33 exam: String,33 exam: String,
34 title: String,34 title: String,
35 kind: String,35 kind: String,
36+ /// The kind's weight from the school settings, resolved at request time —
37+ /// how many times this mark counts into the course average. `1` when the
38+ /// school no longer lists the kind.
36 weight: i64,39 weight: i64,
37 mark: i64,40 mark: i64,
38 /// The mark's label from the school's grade bands (`GET /settings`);41 /// The mark's label from the school's grade bands (`GET /settings`);
@@ -71,7 +74,8 @@ struct MarksReport {
71 }74 }
72 75
73 /// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The76 /// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The
74-/// zero-denominator guard is structural — `ExamWeight` already forbids 0.77+/// zero-denominator guard is structural — kind weights are 1–100 and retired
78+/// kinds resolve to 1, so a weight is never 0.
75 fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {79 fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {
76 let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum();80 let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum();
77 if total_weight == 0 {81 if total_weight == 0 {
@@ -82,10 +86,10 @@ fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {
82 }86 }
83 87
84 /// Assemble the report: for each enrolled course, join the course's exams88 /// Assemble the report: for each enrolled course, join the course's exams
85-/// (weights) with the user's graded results, then average. A `viewer` narrows89+/// with the user's graded results, weigh each mark by its exam kind's
86-/// the report to the courses that viewer manages (self-reports and manager+90+/// settings weight, then average. A `viewer` narrows the report to the
87-/// reports pass `None` and see everything); the overall average follows the91+/// courses that viewer manages (self-reports and manager+ reports pass `None`
88-/// narrowed set.92+/// and see everything); the overall average follows the narrowed set.
89 async fn build_report(93 async fn build_report(
90 user: &UserId,94 user: &UserId,
91 viewer: Option<&User>,95 viewer: Option<&User>,
@@ -96,7 +100,7 @@ async fn build_report(
96 courses.retain(|course| can_manage_course(course, viewer));100 courses.retain(|course| can_manage_course(course, viewer));
97 }101 }
98 102
99- // One settings read labels the whole report.103+ // One settings read weighs and labels the whole report.
100 let school = Settings::load(db).await?;104 let school = Settings::load(db).await?;
101 105
102 let mut blocks = Vec::with_capacity(courses.len());106 let mut blocks = Vec::with_capacity(courses.len());
@@ -113,18 +117,23 @@ async fn build_report(
113 let Some(exam) = by_key.get(result.get_exam().key()) else {117 let Some(exam) = by_key.get(result.get_exam().key()) else {
114 continue;118 continue;
115 };119 };
120+ // The kind's current settings weight; an exam keeps a retired
121+ // kind, and its marks then count once.
122+ let weight = school
123+ .exam_kind_weight(exam.get_kind().as_str())
124+ .unwrap_or(1);
116 entries.push(MarkEntry {125 entries.push(MarkEntry {
117 exam: exam.get_id().key().to_string(),126 exam: exam.get_id().key().to_string(),
118 title: exam.get_title().as_str().to_string(),127 title: exam.get_title().as_str().to_string(),
119 kind: exam.get_kind().as_str().to_string(),128 kind: exam.get_kind().as_str().to_string(),
120- weight: exam.get_weight().as_i64(),129+ weight,
121 mark: result.get_mark().as_i64(),130 mark: result.get_mark().as_i64(),
122 grade: school131 grade: school
123 .grade_label(result.get_mark().as_i64() as f64)132 .grade_label(result.get_mark().as_i64() as f64)
124 .map(str::to_string),133 .map(str::to_string),
125 graded_by: result.get_graded_by().key().to_string(),134 graded_by: result.get_graded_by().key().to_string(),
126 });135 });
127- pairs.push((result.get_mark().as_i64(), exam.get_weight().as_i64()));136+ pairs.push((result.get_mark().as_i64(), weight));
128 }137 }
129 138
130 let average = weighted_average(&pairs);139 let average = weighted_average(&pairs);
src/web/settings.rsmodified+47 -15
@@ -6,7 +6,7 @@ use utoipa_axum::router::OpenApiRouter;
6 use utoipa_axum::routes;6 use utoipa_axum::routes;
7 7
8 use crate::constant::SETTINGS_UPDATE_RETRIES;8 use crate::constant::SETTINGS_UPDATE_RETRIES;
9-use crate::domain::settings::{GradeBand, Settings};9+use crate::domain::settings::{ExamKindDef, GradeBand, Settings};
10 use crate::error::{AppError, ErrorResponse};10 use crate::error::{AppError, ErrorResponse};
11 use crate::state::AppState;11 use crate::state::AppState;
12 12
@@ -16,6 +16,19 @@ pub fn routes() -> OpenApiRouter<AppState> {
16 OpenApiRouter::new().routes(routes!(get_settings, update_settings))16 OpenApiRouter::new().routes(routes!(get_settings, update_settings))
17 }17 }
18 18
19+/// One exam kind the school runs, with its weight in course averages. An exam
20+/// of this kind counts `weight` times into `Σ(mark×weight) / Σ(weight)`.
21+#[derive(Serialize, Deserialize, ToSchema)]
22+struct ExamKindDto {
23+ /// The `kind` value exams carry, 1–50 characters.
24+ #[schema(example = "midterm")]
25+ name: String,
26+ /// The kind's weight in the course average, `1`–`100`. Editing it
27+ /// re-weights every exam of this kind at once.
28+ #[schema(example = 2)]
29+ weight: i64,
30+}
31+
19 /// One grade-display band: marks at or above `min` (and below the next band's32 /// One grade-display band: marks at or above `min` (and below the next band's
20 /// `min`) render as `label`.33 /// `min`) render as `label`.
21 #[derive(Serialize, Deserialize, ToSchema)]34 #[derive(Serialize, Deserialize, ToSchema)]
@@ -28,13 +41,19 @@ struct GradeBandDto {
28 label: String,41 label: String,
29 }42 }
30 43
31-/// The school's policy: which exam kinds exist, which attendance statuses the44+/// The school's policy: which exam kinds exist (and their weights in course
32-/// roll call accepts, and how numeric marks display as grades.45+/// averages), which attendance statuses the roll call accepts, and how
46+/// numeric marks display as grades.
33 #[derive(Serialize, ToSchema)]47 #[derive(Serialize, ToSchema)]
34 struct SettingsResponse {48 struct SettingsResponse {
35- /// Accepted `kind` values for new exams.49+ /// Accepted `kind` values for new exams, each with its weight in the
36- #[schema(example = json!(["homework", "quiz", "midterm", "final", "project", "oral"]))]50+ /// course average.
37- exam_kinds: Vec<String>,51+ #[schema(example = json!([
52+ {"name": "midterm", "weight": 2},
53+ {"name": "final", "weight": 3},
54+ {"name": "oral", "weight": 1},
55+ ]))]
56+ exam_kinds: Vec<ExamKindDto>,
38 /// Accepted `status` values for attendance marking. Always contains the57 /// Accepted `status` values for attendance marking. Always contains the
39 /// core four (`present`, `absent`, `late`, `excused`).58 /// core four (`present`, `absent`, `late`, `excused`).
40 #[schema(example = json!(["present", "absent", "late", "excused"]))]59 #[schema(example = json!(["present", "absent", "late", "excused"]))]
@@ -46,7 +65,14 @@ struct SettingsResponse {
46 impl SettingsResponse {65 impl SettingsResponse {
47 fn new(settings: &Settings) -> Self {66 fn new(settings: &Settings) -> Self {
48 Self {67 Self {
49- exam_kinds: settings.get_exam_kinds().to_vec(),68+ exam_kinds: settings
69+ .get_exam_kinds()
70+ .iter()
71+ .map(|kind| ExamKindDto {
72+ name: kind.get_name().to_string(),
73+ weight: kind.get_weight(),
74+ })
75+ .collect(),
50 attendance_statuses: settings.get_attendance_statuses().to_vec(),76 attendance_statuses: settings.get_attendance_statuses().to_vec(),
51 grade_bands: settings77 grade_bands: settings
52 .get_grade_bands()78 .get_grade_bands()
@@ -62,9 +88,9 @@ impl SettingsResponse {
62 88
63 #[derive(Deserialize, ToSchema)]89 #[derive(Deserialize, ToSchema)]
64 struct UpdateSettings {90 struct UpdateSettings {
65- /// Replaces the whole list when present: 1–20 unique entries, each 1–5091+ /// Replaces the whole list when present: 1–20 entries with unique names,
66- /// characters.92+ /// each name 1–50 characters, each weight `1`–`100`.
67- exam_kinds: Option<Vec<String>>,93+ exam_kinds: Option<Vec<ExamKindDto>>,
68 /// Replaces the whole list when present; must keep `present`, `absent`,94 /// Replaces the whole list when present; must keep `present`, `absent`,
69 /// `late`, `excused` (the attendance rate is defined over them).95 /// `late`, `excused` (the attendance rate is defined over them).
70 attendance_statuses: Option<Vec<String>>,96 attendance_statuses: Option<Vec<String>>,
@@ -97,7 +123,10 @@ async fn get_settings(
97 /// Update the school's policy. Requires manager+. Omitted fields keep their123 /// Update the school's policy. Requires manager+. Omitted fields keep their
98 /// value; a present field replaces its list wholesale. Existing rows are124 /// value; a present field replaces its list wholesale. Existing rows are
99 /// untouched — a removed exam kind or status lives on in old records; only125 /// untouched — a removed exam kind or status lives on in old records; only
100-/// new writes are held to the new lists.126+/// new writes are held to the new lists. Kind weights, though, apply live:
127+/// mark reports read them at request time, so editing a weight re-weights
128+/// every exam of that kind, and an exam whose kind was removed from the list
129+/// counts with weight 1 until the kind returns.
101 #[utoipa::path(130 #[utoipa::path(
102 patch,131 patch,
103 path = "/",132 path = "/",
@@ -124,10 +153,13 @@ async fn update_settings(
124 for _ in 0..SETTINGS_UPDATE_RETRIES {153 for _ in 0..SETTINGS_UPDATE_RETRIES {
125 let current = Settings::load(&st.db).await?;154 let current = Settings::load(&st.db).await?;
126 155
127- let exam_kinds = req156+ let exam_kinds = match &req.exam_kinds {
128- .exam_kinds157+ Some(kinds) => kinds
129- .clone()158+ .iter()
130- .unwrap_or_else(|| current.get_exam_kinds().to_vec());159+ .map(|kind| ExamKindDef::try_new(&kind.name, kind.weight))
160+ .collect::<Result<Vec<_>, _>>()?,
161+ None => current.get_exam_kinds().to_vec(),
162+ };
131 let attendance_statuses = req163 let attendance_statuses = req
132 .attendance_statuses164 .attendance_statuses
133 .clone()165 .clone()
tests/common/mod.rsmodified+2 -2
@@ -143,20 +143,20 @@ pub async fn create_course(app: &Router, cookie: &str, title: &str) -> String {
143 }143 }
144 144
145 /// Create an exam inside `course` as `cookie` (asserts 201); returns its id.145 /// Create an exam inside `course` as `cookie` (asserts 201); returns its id.
146+/// The exam's weight in the course average comes from its kind (settings).
146 pub async fn create_exam(147 pub async fn create_exam(
147 app: &Router,148 app: &Router,
148 cookie: &str,149 cookie: &str,
149 course: &str,150 course: &str,
150 title: &str,151 title: &str,
151 kind: &str,152 kind: &str,
152- weight: i64,
153 ) -> String {153 ) -> String {
154 let res = send(154 let res = send(
155 app,155 app,
156 "POST",156 "POST",
157 &format!("/courses/{course}/exams"),157 &format!("/courses/{course}/exams"),
158 Some(cookie),158 Some(cookie),
159- Some(json!({ "title": title, "kind": kind, "weight": weight })),159+ Some(json!({ "title": title, "kind": kind })),
160 )160 )
161 .await;161 .await;
162 assert_eq!(res.status, StatusCode::CREATED, "create exam {title}");162 assert_eq!(res.status, StatusCode::CREATED, "create exam {title}");
tests/e2e.rsmodified+6 -6
@@ -448,7 +448,7 @@ async fn live_exam_stream_pushes_snapshots_over_http() {
448 let exam: Value = teacher448 let exam: Value = teacher
449 .post(format!("{base}/courses/{course_id}/exams"))449 .post(format!("{base}/courses/{course_id}/exams"))
450 .json(&json!({450 .json(&json!({
451- "title": "final", "kind": "final", "weight": 2,451+ "title": "final", "kind": "final",
452 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000,452 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000,
453 }))453 }))
454 .send()454 .send()
@@ -655,7 +655,7 @@ async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
655 let exam: Value = teacher655 let exam: Value = teacher
656 .post(format!("{base}/courses/{course_id}/exams"))656 .post(format!("{base}/courses/{course_id}/exams"))
657 .json(&json!({657 .json(&json!({
658- "title": "final", "kind": "final", "weight": 2,658+ "title": "final", "kind": "final",
659 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + window_ms,659 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + window_ms,
660 }))660 }))
661 .send()661 .send()
@@ -847,7 +847,7 @@ async fn exam_room_rejects_bad_handshakes() {
847 let unscheduled: Value = room847 let unscheduled: Value = room
848 .teacher848 .teacher
849 .post(format!("{}/courses/{}/exams", room.base, room.course_id))849 .post(format!("{}/courses/{}/exams", room.base, room.course_id))
850- .json(&json!({ "title": "homework", "kind": "homework", "weight": 1 }))850+ .json(&json!({ "title": "homework", "kind": "homework" }))
851 .send()851 .send()
852 .await852 .await
853 .unwrap()853 .unwrap()
@@ -1176,7 +1176,7 @@ async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1176 .teacher1176 .teacher
1177 .post(format!("{}/courses/{}/exams", room.base, room.course_id))1177 .post(format!("{}/courses/{}/exams", room.base, room.course_id))
1178 .json(&json!({1178 .json(&json!({
1179- "title": "practice", "kind": "quiz", "weight": 1,1179+ "title": "practice", "kind": "quiz",
1180 "mode": "open", "max_attempts": 2, "allow_rejoin": false,1180 "mode": "open", "max_attempts": 2, "allow_rejoin": false,
1181 }))1181 }))
1182 .send()1182 .send()
@@ -1280,7 +1280,7 @@ async fn exam_room_messages_bind_to_their_own_sitting() {
1280 .teacher1280 .teacher
1281 .post(format!("{}/courses/{}/exams", room.base, room.course_id))1281 .post(format!("{}/courses/{}/exams", room.base, room.course_id))
1282 .json(&json!({1282 .json(&json!({
1283- "title": "practice", "kind": "quiz", "weight": 1,1283+ "title": "practice", "kind": "quiz",
1284 "mode": "open", "max_attempts": 2,1284 "mode": "open", "max_attempts": 2,
1285 }))1285 }))
1286 .send()1286 .send()
@@ -1465,7 +1465,7 @@ async fn exam_room_open_mode_runs_untimed_and_retakes() {
1465 .teacher1465 .teacher
1466 .post(format!("{}/courses/{}/exams", room.base, room.course_id))1466 .post(format!("{}/courses/{}/exams", room.base, room.course_id))
1467 .json(&json!({1467 .json(&json!({
1468- "title": "practice", "kind": "quiz", "weight": 1,1468+ "title": "practice", "kind": "quiz",
1469 "mode": "open", "max_attempts": 2,1469 "mode": "open", "max_attempts": 2,
1470 }))1470 }))
1471 .send()1471 .send()
tests/integration.rsmodified+228 -128
@@ -874,13 +874,14 @@ async fn exams_are_course_scoped_and_course_guarded() {
874 "POST",874 "POST",
875 &format!("/courses/{course_id}/exams"),875 &format!("/courses/{course_id}/exams"),
876 Some(&ali),876 Some(&ali),
877- Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz", "weight": 2 })),877+ Some(json!({ "title": "ch3", "description": "algebra", "kind": "quiz" })),
878 )878 )
879 .await;879 .await;
880 assert_eq!(ex.status, StatusCode::CREATED);880 assert_eq!(ex.status, StatusCode::CREATED);
881 assert_eq!(ex.body["kind"], "quiz");881 assert_eq!(ex.body["kind"], "quiz");
882 assert_eq!(ex.body["course"], course_id);882 assert_eq!(ex.body["course"], course_id);
883- assert_eq!(ex.body["weight"], 2);883+ // Weight lives on the kind (settings), not the exam.
884+ assert_eq!(ex.body.get("weight"), None);
884 let exam_id = id_of(&ex.body);885 let exam_id = id_of(&ex.body);
885 886
886 // A teacher outside the course sees none of it: not the exam, not the887 // 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() {
971 StatusCode::FORBIDDEN972 StatusCode::FORBIDDEN
972 );973 );
973 974
974- // Course creator edits (partial) — kind flips homework, title/weight kept.975+ // Course creator edits (partial) — kind flips homework, title kept.
975 let res = send(976 let res = send(
976 &app,977 &app,
977 "PATCH",978 "PATCH",
@@ -983,7 +984,6 @@ async fn exams_are_course_scoped_and_course_guarded() {
983 assert_eq!(res.status, StatusCode::OK);984 assert_eq!(res.status, StatusCode::OK);
984 assert_eq!(res.body["kind"], "homework");985 assert_eq!(res.body["kind"], "homework");
985 assert_eq!(res.body["title"], "ch3");986 assert_eq!(res.body["title"], "ch3");
986- assert_eq!(res.body["weight"], 2);
987 }987 }
988 988
989 #[tokio::test]989 #[tokio::test]
@@ -1000,7 +1000,7 @@ async fn exam_input_validation() {
1000 "POST",1000 "POST",
1001 &exams_uri,1001 &exams_uri,
1002 Some(&ali),1002 Some(&ali),
1003- Some(json!({"title":" ","kind":"quiz","weight":1}))1003+ Some(json!({"title":" ","kind":"quiz"}))
1004 )1004 )
1005 .await1005 .await
1006 .status,1006 .status,
@@ -1013,7 +1013,7 @@ async fn exam_input_validation() {
1013 "POST",1013 "POST",
1014 &exams_uri,1014 &exams_uri,
1015 Some(&ali),1015 Some(&ali),
1016- Some(json!({"title":"t","kind":"essay","weight":1}))1016+ Some(json!({"title":"t","kind":"essay"}))
1017 )1017 )
1018 .await1018 .await
1019 .status,1019 .status,
@@ -1025,41 +1025,12 @@ async fn exam_input_validation() {
1025 "POST",1025 "POST",
1026 &exams_uri,1026 &exams_uri,
1027 Some(&ali),1027 Some(&ali),
1028- Some(json!({"title":"t","kind":"final","weight":1}))1028+ Some(json!({"title":"t","kind":"final"}))
1029 )1029 )
1030 .await1030 .await
1031 .status,1031 .status,
1032 StatusCode::CREATED1032 StatusCode::CREATED
1033 );1033 );
1034- // Weight out of range or missing -> 400 / 422.
1035- for weight in [json!(0), json!(101), json!(-1)] {
1036- assert_eq!(
1037- send(
1038- &app,
1039- "POST",
1040- &exams_uri,
1041- Some(&ali),
1042- Some(json!({"title":"t","kind":"quiz","weight":weight}))
1043- )
1044- .await
1045- .status,
1046- StatusCode::BAD_REQUEST,
1047- "weight {weight}"
1048- );
1049- }
1050- assert_eq!(
1051- send(
1052- &app,
1053- "POST",
1054- &exams_uri,
1055- Some(&ali),
1056- Some(json!({"title":"t","kind":"quiz"}))
1057- )
1058- .await
1059- .status,
1060- StatusCode::UNPROCESSABLE_ENTITY,
1061- "missing weight is a body schema error"
1062- );
1063 // Missing exam -> 404.1034 // Missing exam -> 404.
1064 assert_eq!(1035 assert_eq!(
1065 send(&app, "GET", "/exams/nope", Some(&ali), None)1036 send(&app, "GET", "/exams/nope", Some(&ali), None)
@@ -1079,7 +1050,7 @@ async fn grading_upsert_and_own_result() {
1079 1050
1080 let course_id = create_course(&app, &teacher, "algebra").await;1051 let course_id = create_course(&app, &teacher, "algebra").await;
1081 enroll(&app, &teacher, &course_id, &alice_id).await;1052 enroll(&app, &teacher, &course_id, &alice_id).await;
1082- let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;1053+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await;
1083 1054
1084 // Before grading, the student's own result is 404.1055 // Before grading, the student's own result is 404.
1085 assert_eq!(1056 assert_eq!(
@@ -1211,7 +1182,7 @@ async fn grading_rbac_and_validation() {
1211 1182
1212 let course_id = create_course(&app, &teacher, "algebra").await;1183 let course_id = create_course(&app, &teacher, "algebra").await;
1213 enroll(&app, &teacher, &course_id, &alice_id).await;1184 enroll(&app, &teacher, &course_id, &alice_id).await;
1214- let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework", 1).await;1185+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "homework").await;
1215 1186
1216 // Students cannot create exams, grade anyone, list all results, or delete a result.1187 // Students cannot create exams, grade anyone, list all results, or delete a result.
1217 assert_eq!(1188 assert_eq!(
@@ -1220,7 +1191,7 @@ async fn grading_rbac_and_validation() {
1220 "POST",1191 "POST",
1221 &format!("/courses/{course_id}/exams"),1192 &format!("/courses/{course_id}/exams"),
1222 Some(&alice),1193 Some(&alice),
1223- Some(json!({"title":"x","kind":"quiz","weight":1}))1194+ Some(json!({"title":"x","kind":"quiz"}))
1224 )1195 )
1225 .await1196 .await
1226 .status,1197 .status,
@@ -1326,7 +1297,7 @@ async fn deleting_exam_cascades_results() {
1326 1297
1327 let course_id = create_course(&app, &teacher, "algebra").await;1298 let course_id = create_course(&app, &teacher, "algebra").await;
1328 enroll(&app, &teacher, &course_id, &alice_id).await;1299 enroll(&app, &teacher, &course_id, &alice_id).await;
1329- let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await;1300+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz").await;
1330 send(1301 send(
1331 &app,1302 &app,
1332 "POST",1303 "POST",
@@ -1702,7 +1673,7 @@ async fn exam_creation_lives_under_courses() {
1702 "POST",1673 "POST",
1703 "/exams",1674 "/exams",
1704 Some(&teacher),1675 Some(&teacher),
1705- Some(json!({"title":"t","kind":"quiz","weight":1}))1676+ Some(json!({"title":"t","kind":"quiz"}))
1706 )1677 )
1707 .await1678 .await
1708 .status,1679 .status,
@@ -1710,18 +1681,17 @@ async fn exam_creation_lives_under_courses() {
1710 );1681 );
1711 1682
1712 let course_id = create_course(&app, &teacher, "algebra").await;1683 let course_id = create_course(&app, &teacher, "algebra").await;
1713- // Creation inside the course echoes course + weight.1684+ // Creation inside the course echoes the course.
1714 let res = send(1685 let res = send(
1715 &app,1686 &app,
1716 "POST",1687 "POST",
1717 &format!("/courses/{course_id}/exams"),1688 &format!("/courses/{course_id}/exams"),
1718 Some(&teacher),1689 Some(&teacher),
1719- Some(json!({"title":"mt","kind":"midterm","weight":3})),1690+ Some(json!({"title":"mt","kind":"midterm"})),
1720 )1691 )
1721 .await;1692 .await;
1722 assert_eq!(res.status, StatusCode::CREATED);1693 assert_eq!(res.status, StatusCode::CREATED);
1723 assert_eq!(res.body["course"], course_id);1694 assert_eq!(res.body["course"], course_id);
1724- assert_eq!(res.body["weight"], 3);
1725 1695
1726 // A teacher who doesn't manage the course cannot add exams to it.1696 // A teacher who doesn't manage the course cannot add exams to it.
1727 assert_eq!(1697 assert_eq!(
@@ -1730,7 +1700,7 @@ async fn exam_creation_lives_under_courses() {
1730 "POST",1700 "POST",
1731 &format!("/courses/{course_id}/exams"),1701 &format!("/courses/{course_id}/exams"),
1732 Some(&veli),1702 Some(&veli),
1733- Some(json!({"title":"x","kind":"quiz","weight":1}))1703+ Some(json!({"title":"x","kind":"quiz"}))
1734 )1704 )
1735 .await1705 .await
1736 .status,1706 .status,
@@ -1790,7 +1760,7 @@ async fn grading_requires_enrollment() {
1790 let alice_id = me_id(&app, &alice).await;1760 let alice_id = me_id(&app, &alice).await;
1791 1761
1792 let course_id = create_course(&app, &teacher, "algebra").await;1762 let course_id = create_course(&app, &teacher, "algebra").await;
1793- let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;1763+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await;
1794 let grade_uri = format!("/exams/{exam_id}/results");1764 let grade_uri = format!("/exams/{exam_id}/results");
1795 let grade_body = json!({ "mark": 70, "user_id": alice_id });1765 let grade_body = json!({ "mark": 70, "user_id": alice_id });
1796 1766
@@ -1882,7 +1852,7 @@ async fn exam_writes_follow_course_management() {
1882 let course_id = create_course(&app, &teacher, "algebra").await;1852 let course_id = create_course(&app, &teacher, "algebra").await;
1883 1853
1884 // A manager creates an exam in the teacher's course...1854 // A manager creates an exam in the teacher's course...
1885- let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm", 2).await;1855+ let exam_id = create_exam(&app, &boss, &course_id, "mt", "midterm").await;
1886 1856
1887 // ...and the course creator (not the exam's creator) can edit and delete it.1857 // ...and the course creator (not the exam's creator) can edit and delete it.
1888 assert_eq!(1858 assert_eq!(
@@ -1891,11 +1861,11 @@ async fn exam_writes_follow_course_management() {
1891 "PATCH",1861 "PATCH",
1892 &format!("/exams/{exam_id}"),1862 &format!("/exams/{exam_id}"),
1893 Some(&teacher),1863 Some(&teacher),
1894- Some(json!({"weight":5}))1864+ Some(json!({"title":"renamed"}))
1895 )1865 )
1896 .await1866 .await
1897- .body["weight"],1867+ .body["title"],
1898- 51868+ "renamed"
1899 );1869 );
1900 // An unrelated teacher still cannot.1870 // An unrelated teacher still cannot.
1901 assert_eq!(1871 assert_eq!(
@@ -1904,7 +1874,7 @@ async fn exam_writes_follow_course_management() {
1904 "PATCH",1874 "PATCH",
1905 &format!("/exams/{exam_id}"),1875 &format!("/exams/{exam_id}"),
1906 Some(&veli),1876 Some(&veli),
1907- Some(json!({"weight":1}))1877+ Some(json!({"title":"hijack"}))
1908 )1878 )
1909 .await1879 .await
1910 .status,1880 .status,
@@ -1936,7 +1906,7 @@ async fn exam_statistics_summarize_results() {
1936 let course_id = create_course(&app, &teacher, "algebra").await;1906 let course_id = create_course(&app, &teacher, "algebra").await;
1937 enroll(&app, &teacher, &course_id, &alice_id).await;1907 enroll(&app, &teacher, &course_id, &alice_id).await;
1938 enroll(&app, &teacher, &course_id, &bob_id).await;1908 enroll(&app, &teacher, &course_id, &bob_id).await;
1939- let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;1909+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await;
1940 let stats_uri = format!("/exams/{exam_id}/statistics");1910 let stats_uri = format!("/exams/{exam_id}/statistics");
1941 1911
1942 // Nothing graded yet: zero count, null aggregates.1912 // Nothing graded yet: zero count, null aggregates.
@@ -1974,19 +1944,37 @@ async fn exam_statistics_summarize_results() {
1974 }1944 }
1975 1945
1976 #[tokio::test]1946 #[tokio::test]
1977-async fn weighted_averages_follow_exam_weights() {1947+async fn weighted_averages_follow_kind_weights() {
1978 let (app, db) = app_and_db().await;1948 let (app, db) = app_and_db().await;
1979 let teacher = login_as(&app, &db, "teacher", "teacher").await;1949 let teacher = login_as(&app, &db, "teacher", "teacher").await;
1950+ let manager = login_as(&app, &db, "boss", "manager").await;
1980 let alice = login(&app, "alice").await;1951 let alice = login(&app, "alice").await;
1981 let alice_id = me_id(&app, &alice).await;1952 let alice_id = me_id(&app, &alice).await;
1982 1953
1954+ // Weights are school policy, per kind: quizzes count once, midterms three
1955+ // times (the defaults are all 1).
1956+ let res = send(
1957+ &app,
1958+ "PATCH",
1959+ "/settings",
1960+ Some(&manager),
1961+ Some(json!({ "exam_kinds": [
1962+ {"name": "quiz", "weight": 1},
1963+ {"name": "midterm", "weight": 3},
1964+ {"name": "final", "weight": 4},
1965+ {"name": "homework", "weight": 1},
1966+ ]})),
1967+ )
1968+ .await;
1969+ assert_eq!(res.status, StatusCode::OK);
1970+
1983 // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80.1971 // Course A: quiz (w1, mark 50) + midterm (w3, mark 90) -> (50 + 270) / 4 = 80.
1984 let algebra = create_course(&app, &teacher, "algebra").await;1972 let algebra = create_course(&app, &teacher, "algebra").await;
1985 enroll(&app, &teacher, &algebra, &alice_id).await;1973 enroll(&app, &teacher, &algebra, &alice_id).await;
1986- let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz", 1).await;1974+ let quiz = create_exam(&app, &teacher, &algebra, "quiz", "quiz").await;
1987- let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm", 3).await;1975+ let midterm = create_exam(&app, &teacher, &algebra, "midterm", "midterm").await;
1988 // A third exam stays ungraded and must not drag the average.1976 // A third exam stays ungraded and must not drag the average.
1989- create_exam(&app, &teacher, &algebra, "final", "final", 4).await;1977+ create_exam(&app, &teacher, &algebra, "final", "final").await;
1990 for (exam, mark) in [(&quiz, 50), (&midterm, 90)] {1978 for (exam, mark) in [(&quiz, 50), (&midterm, 90)] {
1991 let res = send(1979 let res = send(
1992 &app,1980 &app,
@@ -2002,7 +1990,7 @@ async fn weighted_averages_follow_exam_weights() {
2002 // Course B: enrolled, nothing graded -> null average.1990 // Course B: enrolled, nothing graded -> null average.
2003 let physics = create_course(&app, &teacher, "physics").await;1991 let physics = create_course(&app, &teacher, "physics").await;
2004 enroll(&app, &teacher, &physics, &alice_id).await;1992 enroll(&app, &teacher, &physics, &alice_id).await;
2005- create_exam(&app, &teacher, &physics, "hw", "homework", 1).await;1993+ create_exam(&app, &teacher, &physics, "hw", "homework").await;
2006 1994
2007 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;1995 let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
2008 assert_eq!(report.status, StatusCode::OK);1996 assert_eq!(report.status, StatusCode::OK);
@@ -2019,6 +2007,14 @@ async fn weighted_averages_follow_exam_weights() {
2019 2007
2020 assert_eq!(algebra_block["average"], 80.0);2008 assert_eq!(algebra_block["average"], 80.0);
2021 assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2);2009 assert_eq!(algebra_block["results"].as_array().unwrap().len(), 2);
2010+ // Each entry carries its kind's resolved weight.
2011+ let midterm_entry = algebra_block["results"]
2012+ .as_array()
2013+ .unwrap()
2014+ .iter()
2015+ .find(|entry| entry["kind"] == "midterm")
2016+ .unwrap();
2017+ assert_eq!(midterm_entry["weight"], 3);
2022 assert_eq!(physics_block["average"], serde_json::Value::Null);2018 assert_eq!(physics_block["average"], serde_json::Value::Null);
2023 assert_eq!(physics_block["results"].as_array().unwrap().len(), 0);2019 assert_eq!(physics_block["results"].as_array().unwrap().len(), 0);
2024 // Overall skips the null course instead of zeroing it.2020 // Overall skips the null course instead of zeroing it.
@@ -2026,6 +2022,75 @@ async fn weighted_averages_follow_exam_weights() {
2026 assert_eq!(report.body["user"], alice_id);2022 assert_eq!(report.body["user"], alice_id);
2027 }2023 }
2028 2024
2025+/// Kind weights resolve at report time: editing a kind's weight re-weights
2026+/// already-graded exams, and a kind removed from settings counts once.
2027+#[tokio::test]
2028+async fn kind_weight_edits_reweight_reports_live() {
2029+ let (app, db) = app_and_db().await;
2030+ let teacher = login_as(&app, &db, "teacher", "teacher").await;
2031+ let manager = login_as(&app, &db, "boss", "manager").await;
2032+ let alice = login(&app, "alice").await;
2033+ let alice_id = me_id(&app, &alice).await;
2034+
2035+ let course = create_course(&app, &teacher, "algebra").await;
2036+ enroll(&app, &teacher, &course, &alice_id).await;
2037+ let quiz = create_exam(&app, &teacher, &course, "q", "quiz").await;
2038+ let oral = create_exam(&app, &teacher, &course, "o", "oral").await;
2039+ for (exam, mark) in [(&quiz, 40), (&oral, 80)] {
2040+ let res = send(
2041+ &app,
2042+ "POST",
2043+ &format!("/exams/{exam}/results"),
2044+ Some(&teacher),
2045+ Some(json!({ "mark": mark, "user_id": alice_id })),
2046+ )
2047+ .await;
2048+ assert_eq!(res.status, StatusCode::OK);
2049+ }
2050+
2051+ // Default weights (all 1): plain mean of 40 and 80.
2052+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
2053+ assert_eq!(report.body["courses"][0]["average"], 60.0);
2054+
2055+ // Triple the oral weight — the already-graded exam follows immediately:
2056+ // (40 + 240) / 4 = 70.
2057+ let res = send(
2058+ &app,
2059+ "PATCH",
2060+ "/settings",
2061+ Some(&manager),
2062+ Some(json!({ "exam_kinds": [
2063+ {"name": "quiz", "weight": 1},
2064+ {"name": "oral", "weight": 3},
2065+ ]})),
2066+ )
2067+ .await;
2068+ assert_eq!(res.status, StatusCode::OK);
2069+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
2070+ assert_eq!(report.body["courses"][0]["average"], 70.0);
2071+
2072+ // Retire the oral kind altogether: its exam keeps counting, weight 1.
2073+ let res = send(
2074+ &app,
2075+ "PATCH",
2076+ "/settings",
2077+ Some(&manager),
2078+ Some(json!({ "exam_kinds": [{"name": "quiz", "weight": 1}] })),
2079+ )
2080+ .await;
2081+ assert_eq!(res.status, StatusCode::OK);
2082+ let report = send(&app, "GET", "/marks/me", Some(&alice), None).await;
2083+ assert_eq!(report.body["courses"][0]["average"], 60.0);
2084+ let oral_entry = report.body["courses"][0]["results"]
2085+ .as_array()
2086+ .unwrap()
2087+ .iter()
2088+ .find(|entry| entry["kind"] == "oral")
2089+ .unwrap()
2090+ .clone();
2091+ assert_eq!(oral_entry["weight"], 1);
2092+}
2093+
2029 #[tokio::test]2094 #[tokio::test]
2030 async fn marks_reports_are_self_or_teacher_scoped() {2095 async fn marks_reports_are_self_or_teacher_scoped() {
2031 let (app, db) = app_and_db().await;2096 let (app, db) = app_and_db().await;
@@ -2077,7 +2142,7 @@ async fn course_data_is_walled_off_from_other_teachers() {
2077 2142
2078 let course_id = create_course(&app, &owner, "algebra").await;2143 let course_id = create_course(&app, &owner, "algebra").await;
2079 enroll(&app, &owner, &course_id, &alice_id).await;2144 enroll(&app, &owner, &course_id, &alice_id).await;
2080- let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz", 2).await;2145+ let exam_id = create_exam(&app, &owner, &course_id, "mt", "quiz").await;
2081 let res = send(2146 let res = send(
2082 &app,2147 &app,
2083 "POST",2148 "POST",
@@ -2179,7 +2244,7 @@ async fn deleting_course_cascades_enrollments_exams_and_results() {
2179 2244
2180 let course_id = create_course(&app, &teacher, "algebra").await;2245 let course_id = create_course(&app, &teacher, "algebra").await;
2181 enroll(&app, &teacher, &course_id, &alice_id).await;2246 enroll(&app, &teacher, &course_id, &alice_id).await;
2182- let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz", 1).await;2247+ let exam_id = create_exam(&app, &teacher, &course_id, "mt", "quiz").await;
2183 send(2248 send(
2184 &app,2249 &app,
2185 "POST",2250 "POST",
@@ -2805,7 +2870,7 @@ async fn concurrent_exam_grades_never_collide() {
2805 let student_id = me_id(&app, &student).await;2870 let student_id = me_id(&app, &student).await;
2806 let course_id = create_course(&app, &teacher, "algebra").await;2871 let course_id = create_course(&app, &teacher, "algebra").await;
2807 enroll(&app, &teacher, &course_id, &student_id).await;2872 enroll(&app, &teacher, &course_id, &student_id).await;
2808- let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz", 1).await;2873+ let exam_id = create_exam(&app, &teacher, &course_id, "e", "quiz").await;
2809 2874
2810 let mut handles = Vec::new();2875 let mut handles = Vec::new();
2811 for mark in 0..24i64 {2876 for mark in 0..24i64 {
@@ -2989,7 +3054,7 @@ async fn graders_cannot_grade_themselves() {
2989 let course_id = create_course(&app, &teacher, "algebra").await;3054 let course_id = create_course(&app, &teacher, "algebra").await;
2990 enroll(&app, &teacher, &course_id, &teacher_id).await;3055 enroll(&app, &teacher, &course_id, &teacher_id).await;
2991 enroll(&app, &teacher, &course_id, &boss_id).await;3056 enroll(&app, &teacher, &course_id, &boss_id).await;
2992- let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz", 1).await;3057+ let exam_id = create_exam(&app, &teacher, &course_id, "t", "quiz").await;
2993 3058
2994 // Self-grading is forbidden at every privilege level, not just for teachers.3059 // Self-grading is forbidden at every privilege level, not just for teachers.
2995 // (The teacher owns the course; the manager clears the gate by role.)3060 // (The teacher owns the course; the manager clears the gate by role.)
@@ -3410,7 +3475,7 @@ async fn exam_scheduling_validates_and_echoes() {
3410 &teacher,3475 &teacher,
3411 &course,3476 &course,
3412 json!({3477 json!({
3413- "title": "midterm", "kind": "midterm", "weight": 2,3478+ "title": "midterm", "kind": "midterm",
3414 "mode": "sync", "starts_at": now + 60_000, "ends_at": now + 120_000,3479 "mode": "sync", "starts_at": now + 60_000, "ends_at": now + 120_000,
3415 }),3480 }),
3416 )3481 )
@@ -3427,7 +3492,7 @@ async fn exam_scheduling_validates_and_echoes() {
3427 &teacher,3492 &teacher,
3428 &course,3493 &course,
3429 json!({3494 json!({
3430- "title": "takehome", "kind": "quiz", "weight": 1,3495+ "title": "takehome", "kind": "quiz",
3431 "mode": "async", "starts_at": now, "ends_at": now + 7_200_000,3496 "mode": "async", "starts_at": now, "ends_at": now + 7_200_000,
3432 "duration_ms": 5_400_000,3497 "duration_ms": 5_400_000,
3433 }),3498 }),
@@ -3443,7 +3508,7 @@ async fn exam_scheduling_validates_and_echoes() {
3443 &app,3508 &app,
3444 &teacher,3509 &teacher,
3445 &course,3510 &course,
3446- json!({ "title": "homework", "kind": "homework", "weight": 1 }),3511+ json!({ "title": "homework", "kind": "homework" }),
3447 )3512 )
3448 .await;3513 .await;
3449 assert_eq!(res.status, StatusCode::CREATED);3514 assert_eq!(res.status, StatusCode::CREATED);
@@ -3461,7 +3526,7 @@ async fn exam_scheduling_validates_and_echoes() {
3461 &teacher,3526 &teacher,
3462 &course,3527 &course,
3463 json!({3528 json!({
3464- "title": "practice", "kind": "quiz", "weight": 1, "mode": "open",3529+ "title": "practice", "kind": "quiz", "mode": "open",
3465 "duration_ms": 5_400_000, "max_attempts": 0, "allow_rejoin": false,3530 "duration_ms": 5_400_000, "max_attempts": 0, "allow_rejoin": false,
3466 }),3531 }),
3467 )3532 )
@@ -3478,80 +3543,80 @@ async fn exam_scheduling_validates_and_echoes() {
3478 for (label, body) in [3543 for (label, body) in [
3479 (3544 (
3480 "unknown mode",3545 "unknown mode",
3481- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "weekly",3546+ json!({ "title": "x", "kind": "quiz", "mode": "weekly",
3482 "starts_at": now, "ends_at": now + 1_000 }),3547 "starts_at": now, "ends_at": now + 1_000 }),
3483 ),3548 ),
3484 (3549 (
3485 "times without mode",3550 "times without mode",
3486- json!({ "title": "x", "kind": "quiz", "weight": 1, "starts_at": now }),3551+ json!({ "title": "x", "kind": "quiz", "starts_at": now }),
3487 ),3552 ),
3488 (3553 (
3489 "duration without mode",3554 "duration without mode",
3490- json!({ "title": "x", "kind": "quiz", "weight": 1, "duration_ms": 60_000 }),3555+ json!({ "title": "x", "kind": "quiz", "duration_ms": 60_000 }),
3491 ),3556 ),
3492 (3557 (
3493 "sync missing ends_at",3558 "sync missing ends_at",
3494- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3559+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3495 "starts_at": now }),3560 "starts_at": now }),
3496 ),3561 ),
3497 (3562 (
3498 "sync with duration",3563 "sync with duration",
3499- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3564+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3500 "starts_at": now, "ends_at": now + 1_000, "duration_ms": 60_000 }),3565 "starts_at": now, "ends_at": now + 1_000, "duration_ms": 60_000 }),
3501 ),3566 ),
3502 (3567 (
3503 "async without duration",3568 "async without duration",
3504- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async",3569+ json!({ "title": "x", "kind": "quiz", "mode": "async",
3505 "starts_at": now, "ends_at": now + 1_000 }),3570 "starts_at": now, "ends_at": now + 1_000 }),
3506 ),3571 ),
3507 (3572 (
3508 "backwards window",3573 "backwards window",
3509- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3574+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3510 "starts_at": now + 2_000, "ends_at": now + 1_000 }),3575 "starts_at": now + 2_000, "ends_at": now + 1_000 }),
3511 ),3576 ),
3512 (3577 (
3513 "empty window",3578 "empty window",
3514- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3579+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3515 "starts_at": now, "ends_at": now }),3580 "starts_at": now, "ends_at": now }),
3516 ),3581 ),
3517 (3582 (
3518 "duration too short",3583 "duration too short",
3519- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async",3584+ json!({ "title": "x", "kind": "quiz", "mode": "async",
3520 "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 59_999 }),3585 "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 59_999 }),
3521 ),3586 ),
3522 (3587 (
3523 "duration too long",3588 "duration too long",
3524- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "async",3589+ json!({ "title": "x", "kind": "quiz", "mode": "async",
3525 "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 86_400_001 }),3590 "starts_at": now, "ends_at": now + 90_000_000, "duration_ms": 86_400_001 }),
3526 ),3591 ),
3527 (3592 (
3528 "past starts_at",3593 "past starts_at",
3529- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3594+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3530 "starts_at": now - 3_600_000, "ends_at": now + 3_600_000 }),3595 "starts_at": now - 3_600_000, "ends_at": now + 3_600_000 }),
3531 ),3596 ),
3532 (3597 (
3533 // starts_at is future so the rejection can only come from ends_at.3598 // starts_at is future so the rejection can only come from ends_at.
3534 "past ends_at",3599 "past ends_at",
3535- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "sync",3600+ json!({ "title": "x", "kind": "quiz", "mode": "sync",
3536 "starts_at": now + 3_600_000, "ends_at": now - 3_600_000 }),3601 "starts_at": now + 3_600_000, "ends_at": now - 3_600_000 }),
3537 ),3602 ),
3538 (3603 (
3539 "open with a window",3604 "open with a window",
3540- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "open",3605+ json!({ "title": "x", "kind": "quiz", "mode": "open",
3541 "starts_at": now + 60_000, "ends_at": now + 120_000 }),3606 "starts_at": now + 60_000, "ends_at": now + 120_000 }),
3542 ),3607 ),
3543 (3608 (
3544 "open with only an ends_at",3609 "open with only an ends_at",
3545- json!({ "title": "x", "kind": "quiz", "weight": 1, "mode": "open",3610+ json!({ "title": "x", "kind": "quiz", "mode": "open",
3546 "ends_at": now + 120_000 }),3611 "ends_at": now + 120_000 }),
3547 ),3612 ),
3548 (3613 (
3549 "negative attempt limit",3614 "negative attempt limit",
3550- json!({ "title": "x", "kind": "quiz", "weight": 1, "max_attempts": -1 }),3615+ json!({ "title": "x", "kind": "quiz", "max_attempts": -1 }),
3551 ),3616 ),
3552 (3617 (
3553 "attempt limit over the cap",3618 "attempt limit over the cap",
3554- json!({ "title": "x", "kind": "quiz", "weight": 1, "max_attempts": 101 }),3619+ json!({ "title": "x", "kind": "quiz", "max_attempts": 101 }),
3555 ),3620 ),
3556 ] {3621 ] {
3557 let res = create_exam_with(&app, &teacher, &course, body).await;3622 let res = create_exam_with(&app, &teacher, &course, body).await;
@@ -3574,7 +3639,7 @@ async fn schedule_times_cannot_be_backdated() {
3574 &app,3639 &app,
3575 &teacher,3640 &teacher,
3576 &course,3641 &course,
3577- json!({ "title": "running", "kind": "quiz", "weight": 1,3642+ json!({ "title": "running", "kind": "quiz",
3578 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),3643 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
3579 )3644 )
3580 .await;3645 .await;
@@ -3623,7 +3688,7 @@ async fn schedule_times_cannot_be_backdated() {
3623 &app,3688 &app,
3624 &teacher,3689 &teacher,
3625 &course,3690 &course,
3626- json!({ "title": "graced", "kind": "quiz", "weight": 1,3691+ json!({ "title": "graced", "kind": "quiz",
3627 "mode": "sync", "starts_at": now - 30_000, "ends_at": now + 600_000 }),3692 "mode": "sync", "starts_at": now - 30_000, "ends_at": now + 600_000 }),
3628 )3693 )
3629 .await;3694 .await;
@@ -3658,7 +3723,7 @@ async fn sync_attempt_lifecycle_feeds_the_live_monitor() {
3658 &app,3723 &app,
3659 &teacher,3724 &teacher,
3660 &course,3725 &course,
3661- json!({ "title": "final", "kind": "final", "weight": 3,3726+ json!({ "title": "final", "kind": "final",
3662 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }),3727 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }),
3663 )3728 )
3664 .await;3729 .await;
@@ -3811,7 +3876,7 @@ async fn closed_window_flags_no_shows_as_absent() {
3811 &app,3876 &app,
3812 &teacher,3877 &teacher,
3813 &course,3878 &course,
3814- json!({ "title": "midterm", "kind": "midterm", "weight": 2,3879+ json!({ "title": "midterm", "kind": "midterm",
3815 "mode": "sync", "starts_at": now - 50_000, "ends_at": now + 600_000 }),3880 "mode": "sync", "starts_at": now - 50_000, "ends_at": now + 600_000 }),
3816 )3881 )
3817 .await;3882 .await;
@@ -3904,7 +3969,7 @@ async fn closed_window_flags_no_shows_as_absent() {
3904 &app,3969 &app,
3905 &teacher,3970 &teacher,
3906 &course,3971 &course,
3907- json!({ "title": "essay", "kind": "homework", "weight": 1, "mode": "open" }),3972+ json!({ "title": "essay", "kind": "homework", "mode": "open" }),
3908 )3973 )
3909 .await;3974 .await;
3910 let res = send(3975 let res = send(
@@ -3935,7 +4000,7 @@ async fn async_deadline_is_start_plus_duration_clamped_to_window() {
3935 &app,4000 &app,
3936 &teacher,4001 &teacher,
3937 &course,4002 &course,
3938- json!({ "title": "quiz", "kind": "quiz", "weight": 1,4003+ json!({ "title": "quiz", "kind": "quiz",
3939 "mode": "async", "starts_at": now - 1_000, "ends_at": now + 6_000_000,4004 "mode": "async", "starts_at": now - 1_000, "ends_at": now + 6_000_000,
3940 "duration_ms": 60_000 }),4005 "duration_ms": 60_000 }),
3941 )4006 )
@@ -3958,7 +4023,7 @@ async fn async_deadline_is_start_plus_duration_clamped_to_window() {
3958 &app,4023 &app,
3959 &teacher,4024 &teacher,
3960 &course,4025 &course,
3961- json!({ "title": "quiz2", "kind": "quiz", "weight": 1,4026+ json!({ "title": "quiz2", "kind": "quiz",
3962 "mode": "async", "starts_at": now - 1_000, "ends_at": ends,4027 "mode": "async", "starts_at": now - 1_000, "ends_at": ends,
3963 "duration_ms": 60_000 }),4028 "duration_ms": 60_000 }),
3964 )4029 )
@@ -3986,7 +4051,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() {
3986 let now = Timestamp::now().as_millis();4051 let now = Timestamp::now().as_millis();
3987 4052
3988 // Unscheduled exams cannot be sat at all.4053 // Unscheduled exams cannot be sat at all.
3989- let unscheduled = create_exam(&app, &teacher, &course, "hw", "homework", 1).await;4054+ let unscheduled = create_exam(&app, &teacher, &course, "hw", "homework").await;
3990 let res = send(4055 let res = send(
3991 &app,4056 &app,
3992 "POST",4057 "POST",
@@ -4002,7 +4067,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() {
4002 &app,4067 &app,
4003 &teacher,4068 &teacher,
4004 &course,4069 &course,
4005- json!({ "title": "later", "kind": "quiz", "weight": 1,4070+ json!({ "title": "later", "kind": "quiz",
4006 "mode": "sync", "starts_at": now + 600_000, "ends_at": now + 1_200_000 }),4071 "mode": "sync", "starts_at": now + 600_000, "ends_at": now + 1_200_000 }),
4007 )4072 )
4008 .await;4073 .await;
@@ -4021,7 +4086,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() {
4021 &teacher,4086 &teacher,
4022 &course,4087 &course,
4023 // Inside the backdating grace, yet already closed by the clock.4088 // Inside the backdating grace, yet already closed by the clock.
4024- json!({ "title": "gone", "kind": "quiz", "weight": 1,4089+ json!({ "title": "gone", "kind": "quiz",
4025 "mode": "sync", "starts_at": now - 50_000, "ends_at": now - 10_000 }),4090 "mode": "sync", "starts_at": now - 50_000, "ends_at": now - 10_000 }),
4026 )4091 )
4027 .await;4092 .await;
@@ -4040,7 +4105,7 @@ async fn attempts_gate_on_schedule_enrollment_and_window() {
4040 &app,4105 &app,
4041 &teacher,4106 &teacher,
4042 &course,4107 &course,
4043- json!({ "title": "open", "kind": "quiz", "weight": 1,4108+ json!({ "title": "open", "kind": "quiz",
4044 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),4109 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
4045 )4110 )
4046 .await;4111 .await;
@@ -4090,7 +4155,7 @@ async fn finish_rejects_double_submit_missing_attempt_and_expiry() {
4090 &app,4155 &app,
4091 &teacher,4156 &teacher,
4092 &course,4157 &course,
4093- json!({ "title": "final", "kind": "final", "weight": 1,4158+ json!({ "title": "final", "kind": "final",
4094 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),4159 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
4095 )4160 )
4096 .await;4161 .await;
@@ -4140,7 +4205,7 @@ async fn finish_rejects_double_submit_missing_attempt_and_expiry() {
4140 &app,4205 &app,
4141 &teacher,4206 &teacher,
4142 &course,4207 &course,
4143- json!({ "title": "blitz", "kind": "quiz", "weight": 1,4208+ json!({ "title": "blitz", "kind": "quiz",
4144 "mode": "sync", "starts_at": now - 1_000,4209 "mode": "sync", "starts_at": now - 1_000,
4145 "ends_at": Timestamp::now().as_millis() + 1_500 }),4210 "ends_at": Timestamp::now().as_millis() + 1_500 }),
4146 )4211 )
@@ -4195,7 +4260,7 @@ async fn mode_freezes_after_attempts_but_times_extend_live() {
4195 &app,4260 &app,
4196 &teacher,4261 &teacher,
4197 &course,4262 &course,
4198- json!({ "title": "final", "kind": "final", "weight": 1,4263+ json!({ "title": "final", "kind": "final",
4199 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }),4264 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends }),
4200 )4265 )
4201 .await;4266 .await;
@@ -4305,7 +4370,7 @@ async fn attempts_cascade_with_exam_and_course_deletion() {
4305 let course = create_course(&app, &teacher, "hist").await;4370 let course = create_course(&app, &teacher, "hist").await;
4306 enroll(&app, &teacher, &course, &student_id).await;4371 enroll(&app, &teacher, &course, &student_id).await;
4307 let now = Timestamp::now().as_millis();4372 let now = Timestamp::now().as_millis();
4308- let schedule = json!({ "title": "final", "kind": "final", "weight": 1,4373+ let schedule = json!({ "title": "final", "kind": "final",
4309 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 });4374 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 });
4310 4375
4311 // Deleting the exam removes its attempts.4376 // Deleting the exam removes its attempts.
@@ -4382,7 +4447,7 @@ async fn open_exams_sit_anytime_and_retakes_respect_the_limit() {
4382 &app,4447 &app,
4383 &teacher,4448 &teacher,
4384 &course,4449 &course,
4385- json!({ "title": "drill", "kind": "quiz", "weight": 1,4450+ json!({ "title": "drill", "kind": "quiz",
4386 "mode": "open", "max_attempts": 2 }),4451 "mode": "open", "max_attempts": 2 }),
4387 )4452 )
4388 .await;4453 .await;
@@ -4573,7 +4638,7 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() {
4573 &app,4638 &app,
4574 &teacher,4639 &teacher,
4575 &course,4640 &course,
4576- json!({ "title": "sprint", "kind": "quiz", "weight": 1,4641+ json!({ "title": "sprint", "kind": "quiz",
4577 "mode": "open", "duration_ms": 60_000 }),4642 "mode": "open", "duration_ms": 60_000 }),
4578 )4643 )
4579 .await;4644 .await;
@@ -4602,7 +4667,7 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() {
4602 &app,4667 &app,
4603 &teacher,4668 &teacher,
4604 &course,4669 &course,
4605- json!({ "title": "final", "kind": "final", "weight": 1,4670+ json!({ "title": "final", "kind": "final",
4606 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends,4671 "mode": "sync", "starts_at": now - 1_000, "ends_at": ends,
4607 "max_attempts": 3 }),4672 "max_attempts": 3 }),
4608 )4673 )
@@ -4687,7 +4752,7 @@ async fn live_stream_is_sse_and_teacher_scoped() {
4687 &app,4752 &app,
4688 &teacher,4753 &teacher,
4689 &course,4754 &course,
4690- json!({ "title": "final", "kind": "final", "weight": 1,4755+ json!({ "title": "final", "kind": "final",
4691 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),4756 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
4692 )4757 )
4693 .await;4758 .await;
@@ -4770,7 +4835,7 @@ async fn open_exam_with_student(
4770 app,4835 app,
4771 teacher,4836 teacher,
4772 &course,4837 &course,
4773- json!({ "title": "final", "kind": "final", "weight": 1,4838+ json!({ "title": "final", "kind": "final",
4774 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),4839 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
4775 )4840 )
4776 .await;4841 .await;
@@ -4784,7 +4849,7 @@ async fn question_crud_validation_and_rbac() {
4784 let other_teacher = login_as(&app, &db, "q_t2", "teacher").await;4849 let other_teacher = login_as(&app, &db, "q_t2", "teacher").await;
4785 let student = login(&app, "quinn").await;4850 let student = login(&app, "quinn").await;
4786 let course = create_course(&app, &teacher, "logic").await;4851 let course = create_course(&app, &teacher, "logic").await;
4787- let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await;4852+ let exam = create_exam(&app, &teacher, &course, "final", "final").await;
4788 4853
4789 // A choice question echoes its full authoring view, correct included.4854 // A choice question echoes its full authoring view, correct included.
4790 let res = send(4855 let res = send(
@@ -4996,7 +5061,7 @@ async fn question_crud_validation_and_rbac() {
4996 assert_eq!(res.status, StatusCode::FORBIDDEN);5061 assert_eq!(res.status, StatusCode::FORBIDDEN);
4997 5062
4998 // Unknown ids are 404s — including a question under the wrong exam.5063 // Unknown ids are 404s — including a question under the wrong exam.
4999- let other_exam = create_exam(&app, &teacher, &course, "quiz", "quiz", 1).await;5064+ let other_exam = create_exam(&app, &teacher, &course, "quiz", "quiz").await;
5000 for (method, uri) in [5065 for (method, uri) in [
5001 ("POST", "/exams/missing/questions".to_string()),5066 ("POST", "/exams/missing/questions".to_string()),
5002 ("GET", "/exams/missing/questions".to_string()),5067 ("GET", "/exams/missing/questions".to_string()),
@@ -5311,7 +5376,7 @@ async fn answer_saves_gate_on_attempt_state_and_kind() {
5311 )5376 )
5312 .await;5377 .await;
5313 assert_eq!(res.status, StatusCode::NOT_FOUND);5378 assert_eq!(res.status, StatusCode::NOT_FOUND);
5314- let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz", 1).await;5379+ let foreign_exam = create_exam(&app, &teacher, &course, "other", "quiz").await;
5315 let foreign_q = create_question(5380 let foreign_q = create_question(
5316 &app,5381 &app,
5317 &teacher,5382 &teacher,
@@ -5511,7 +5576,7 @@ async fn answer_saves_stop_at_the_deadline() {
5511 &app,5576 &app,
5512 &teacher,5577 &teacher,
5513 &course,5578 &course,
5514- json!({ "title": "blitz", "kind": "quiz", "weight": 1,5579+ json!({ "title": "blitz", "kind": "quiz",
5515 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }),5580 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 1_500 }),
5516 )5581 )
5517 .await;5582 .await;
@@ -5848,7 +5913,7 @@ async fn questions_and_answers_cascade_with_deletes() {
5848 &app,5913 &app,
5849 &teacher,5914 &teacher,
5850 &course,5915 &course,
5851- json!({ "title": "retake", "kind": "quiz", "weight": 1,5916+ json!({ "title": "retake", "kind": "quiz",
5852 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),5917 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }),
5853 )5918 )
5854 .await;5919 .await;
@@ -5908,7 +5973,7 @@ async fn question_patch_revalidates_the_stale_kind_bundle() {
5908 let (app, db) = app_and_db().await;5973 let (app, db) = app_and_db().await;
5909 let teacher = login_as(&app, &db, "rv_t", "teacher").await;5974 let teacher = login_as(&app, &db, "rv_t", "teacher").await;
5910 let course = create_course(&app, &teacher, "sets").await;5975 let course = create_course(&app, &teacher, "sets").await;
5911- let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await;5976+ let exam = create_exam(&app, &teacher, &course, "final", "final").await;
5912 let question = create_question(5977 let question = create_question(
5913 &app,5978 &app,
5914 &teacher,5979 &teacher,
@@ -5989,7 +6054,7 @@ async fn question_authoring_follows_course_management() {
5989 let teacher = login_as(&app, &db, "own_t", "teacher").await;6054 let teacher = login_as(&app, &db, "own_t", "teacher").await;
5990 let boss = login_as(&app, &db, "own_m", "manager").await;6055 let boss = login_as(&app, &db, "own_m", "manager").await;
5991 let course = create_course(&app, &teacher, "greek").await;6056 let course = create_course(&app, &teacher, "greek").await;
5992- let exam = create_exam(&app, &teacher, &course, "final", "final", 1).await;6057+ let exam = create_exam(&app, &teacher, &course, "final", "final").await;
5993 6058
5994 // A manager+ authors questions in anyone's course, like every other6059 // A manager+ authors questions in anyone's course, like every other
5995 // course-management write.6060 // course-management write.
@@ -7167,7 +7232,7 @@ async fn course_catalog_lists_a_creator_enrolled_course_once() {
7167 7232
7168 // The exam catalog derives from the same visible set and must not double7233 // The exam catalog derives from the same visible set and must not double
7169 // the course's exams either.7234 // the course's exams either.
7170- let exam = create_exam(&app, &teacher, &course, "mt", "quiz", 1).await;7235+ let exam = create_exam(&app, &teacher, &course, "mt", "quiz").await;
7171 let res = send(&app, "GET", "/exams", Some(&teacher), None).await;7236 let res = send(&app, "GET", "/exams", Some(&teacher), None).await;
7172 let exams = res.body.as_array().unwrap();7237 let exams = res.body.as_array().unwrap();
7173 assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}");7238 assert_eq!(exams.len(), 1, "one exam listed once: {exams:?}");
@@ -7187,12 +7252,20 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() {
7187 let res = send(&app, "GET", "/settings", None, None).await;7252 let res = send(&app, "GET", "/settings", None, None).await;
7188 assert_eq!(res.status, StatusCode::UNAUTHORIZED);7253 assert_eq!(res.status, StatusCode::UNAUTHORIZED);
7189 7254
7190- // Any authenticated user reads; the defaults mirror the old constants.7255+ // Any authenticated user reads; the defaults mirror the old constants,
7256+ // every kind weighing 1 until the school says otherwise.
7191 let res = send(&app, "GET", "/settings", Some(&student), None).await;7257 let res = send(&app, "GET", "/settings", Some(&student), None).await;
7192 assert_eq!(res.status, StatusCode::OK);7258 assert_eq!(res.status, StatusCode::OK);
7193 assert_eq!(7259 assert_eq!(
7194 res.body["exam_kinds"],7260 res.body["exam_kinds"],
7195- json!(["homework", "quiz", "midterm", "final", "project", "oral"])7261+ json!([
7262+ {"name": "homework", "weight": 1},
7263+ {"name": "quiz", "weight": 1},
7264+ {"name": "midterm", "weight": 1},
7265+ {"name": "final", "weight": 1},
7266+ {"name": "project", "weight": 1},
7267+ {"name": "oral", "weight": 1},
7268+ ])
7196 );7269 );
7197 assert_eq!(7270 assert_eq!(
7198 res.body["attendance_statuses"],7271 res.body["attendance_statuses"],
@@ -7207,7 +7280,7 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() {
7207 "PATCH",7280 "PATCH",
7208 "/settings",7281 "/settings",
7209 Some(cookie),7282 Some(cookie),
7210- Some(json!({ "exam_kinds": ["lab"] })),7283+ Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })),
7211 )7284 )
7212 .await;7285 .await;
7213 assert_eq!(res.status, StatusCode::FORBIDDEN);7286 assert_eq!(res.status, StatusCode::FORBIDDEN);
@@ -7219,11 +7292,20 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() {
7219 "PATCH",7292 "PATCH",
7220 "/settings",7293 "/settings",
7221 Some(&manager),7294 Some(&manager),
7222- Some(json!({ "exam_kinds": ["lab", "Quiz"] })),7295+ Some(json!({ "exam_kinds": [
7296+ {"name": "lab", "weight": 2},
7297+ {"name": "Quiz", "weight": 1},
7298+ ]})),
7223 )7299 )
7224 .await;7300 .await;
7225 assert_eq!(res.status, StatusCode::OK);7301 assert_eq!(res.status, StatusCode::OK);
7226- assert_eq!(res.body["exam_kinds"], json!(["lab", "Quiz"]));7302+ assert_eq!(
7303+ res.body["exam_kinds"],
7304+ json!([
7305+ {"name": "lab", "weight": 2},
7306+ {"name": "Quiz", "weight": 1},
7307+ ])
7308+ );
7227 assert_eq!(7309 assert_eq!(
7228 res.body["attendance_statuses"],7310 res.body["attendance_statuses"],
7229 json!(["present", "absent", "late", "excused"])7311 json!(["present", "absent", "late", "excused"])
@@ -7231,7 +7313,8 @@ async fn settings_serve_defaults_and_gate_edits_to_manager() {
7231 7313
7232 // Every reader sees the new policy at once.7314 // Every reader sees the new policy at once.
7233 let res = send(&app, "GET", "/settings", Some(&student), None).await;7315 let res = send(&app, "GET", "/settings", Some(&student), None).await;
7234- assert_eq!(res.body["exam_kinds"], json!(["lab", "Quiz"]));7316+ assert_eq!(res.body["exam_kinds"][0]["name"], "lab");
7317+ assert_eq!(res.body["exam_kinds"][0]["weight"], 2);
7235 }7318 }
7236 7319
7237 #[tokio::test]7320 #[tokio::test]
@@ -7240,11 +7323,19 @@ async fn settings_validation_rejects_bad_lists_and_bands() {
7240 let manager = login_as(&app, &db, "val.manager", "manager").await;7323 let manager = login_as(&app, &db, "val.manager", "manager").await;
7241 7324
7242 let bad = [7325 let bad = [
7243- json!({ "exam_kinds": [] }), // a school needs at least one kind7326+ json!({ "exam_kinds": [] }), // a school needs at least one kind
7244- json!({ "exam_kinds": [" "] }), // blank entry7327+ json!({ "exam_kinds": [{"name": " ", "weight": 1}] }), // blank name
7245- json!({ "exam_kinds": ["Lab", "lab"] }), // case-insensitive duplicate7328+ // Case-insensitive duplicate names.
7329+ json!({ "exam_kinds": [
7330+ {"name": "Lab", "weight": 1},
7331+ {"name": "lab", "weight": 2},
7332+ ]}),
7333+ // Weights are held to 1–100.
7334+ json!({ "exam_kinds": [{"name": "quiz", "weight": 0}] }),
7335+ json!({ "exam_kinds": [{"name": "quiz", "weight": 101}] }),
7336+ json!({ "exam_kinds": [{"name": "quiz", "weight": -1}] }),
7246 json!({ "attendance_statuses": ["present", "absent", "late"] }), // core dropped7337 json!({ "attendance_statuses": ["present", "absent", "late"] }), // core dropped
7247- json!({ "grade_bands": [{ "min": 50, "label": "CC" }] }), // no band starts at 07338+ json!({ "grade_bands": [{ "min": 50, "label": "CC" }] }), // no band starts at 0
7248 json!({ "grade_bands": [{ "min": 0, "label": "F" }, { "min": 0, "label": "E" }] }),7339 json!({ "grade_bands": [{ "min": 0, "label": "F" }, { "min": 0, "label": "E" }] }),
7249 json!({ "grade_bands": [{ "min": -1, "label": "F" }] }),7340 json!({ "grade_bands": [{ "min": -1, "label": "F" }] }),
7250 json!({ "grade_bands": [{ "min": 101, "label": "A" }] }),7341 json!({ "grade_bands": [{ "min": 101, "label": "A" }] }),
@@ -7275,7 +7366,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() {
7275 let manager = login_as(&app, &db, "kind.manager", "manager").await;7366 let manager = login_as(&app, &db, "kind.manager", "manager").await;
7276 7367
7277 let course = create_course(&app, &teacher, "Chemistry").await;7368 let course = create_course(&app, &teacher, "Chemistry").await;
7278- let exam = create_exam(&app, &teacher, &course, "Midterm", "midterm", 1).await;7369+ let exam = create_exam(&app, &teacher, &course, "Midterm", "midterm").await;
7279 7370
7280 // The school swaps its kind list wholesale.7371 // The school swaps its kind list wholesale.
7281 let res = send(7372 let res = send(
@@ -7283,7 +7374,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() {
7283 "PATCH",7374 "PATCH",
7284 "/settings",7375 "/settings",
7285 Some(&manager),7376 Some(&manager),
7286- Some(json!({ "exam_kinds": ["lab"] })),7377+ Some(json!({ "exam_kinds": [{"name": "lab", "weight": 1}] })),
7287 )7378 )
7288 .await;7379 .await;
7289 assert_eq!(res.status, StatusCode::OK);7380 assert_eq!(res.status, StatusCode::OK);
@@ -7293,7 +7384,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() {
7293 &app,7384 &app,
7294 &teacher,7385 &teacher,
7295 &course,7386 &course,
7296- json!({ "title": "Retired kind", "kind": "midterm", "weight": 1 }),7387+ json!({ "title": "Retired kind", "kind": "midterm" }),
7297 )7388 )
7298 .await;7389 .await;
7299 assert_eq!(res.status, StatusCode::BAD_REQUEST);7390 assert_eq!(res.status, StatusCode::BAD_REQUEST);
@@ -7301,7 +7392,7 @@ async fn exam_kinds_follow_settings_for_new_writes_only() {
7301 &app,7392 &app,
7302 &teacher,7393 &teacher,
7303 &course,7394 &course,
7304- json!({ "title": "Lab 1", "kind": "lab", "weight": 1 }),7395+ json!({ "title": "Lab 1", "kind": "lab" }),
7305 )7396 )
7306 .await;7397 .await;
7307 assert_eq!(res.status, StatusCode::CREATED);7398 assert_eq!(res.status, StatusCode::CREATED);
@@ -7449,7 +7540,7 @@ async fn grade_bands_label_the_marks_report() {
7449 7540
7450 let course = create_course(&app, &teacher, "Physics").await;7541 let course = create_course(&app, &teacher, "Physics").await;
7451 enroll(&app, &teacher, &course, &student_id).await;7542 enroll(&app, &teacher, &course, &student_id).await;
7452- let exam = create_exam(&app, &teacher, &course, "Final", "final", 2).await;7543+ let exam = create_exam(&app, &teacher, &course, "Final", "final").await;
7453 let res = send(7544 let res = send(
7454 &app,7545 &app,
7455 "POST",7546 "POST",
@@ -7814,7 +7905,7 @@ async fn grade_band_boundary_applies_to_the_weighted_average() {
7814 let course = create_course(&app, &teacher, "Calculus").await;7905 let course = create_course(&app, &teacher, "Calculus").await;
7815 enroll(&app, &teacher, &course, &student_id).await;7906 enroll(&app, &teacher, &course, &student_id).await;
7816 for (title, mark) in [("Quiz A", 80), ("Quiz B", 90)] {7907 for (title, mark) in [("Quiz A", 80), ("Quiz B", 90)] {
7817- let exam = create_exam(&app, &teacher, &course, title, "quiz", 1).await;7908+ let exam = create_exam(&app, &teacher, &course, title, "quiz").await;
7818 let res = send(7909 let res = send(
7819 &app,7910 &app,
7820 "POST",7911 "POST",
@@ -7851,16 +7942,25 @@ async fn settings_accept_admin_edits_trim_entries_and_noop_on_empty_patch() {
7851 assert_eq!(res.status, StatusCode::OK);7942 assert_eq!(res.status, StatusCode::OK);
7852 assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 6);7943 assert_eq!(res.body["exam_kinds"].as_array().unwrap().len(), 6);
7853 7944
7854- // Admin clears the manager bar (hierarchy, not equality), and entries7945+ // Admin clears the manager bar (hierarchy, not equality), and kind names
7855 // arrive trimmed on the wire.7946 // arrive trimmed on the wire.
7856 let res = send(7947 let res = send(
7857 &app,7948 &app,
7858 "PATCH",7949 "PATCH",
7859 "/settings",7950 "/settings",
7860 Some(&admin),7951 Some(&admin),
7861- Some(json!({ "exam_kinds": [" lab ", "quiz"] })),7952+ Some(json!({ "exam_kinds": [
7953+ {"name": " lab ", "weight": 2},
7954+ {"name": "quiz", "weight": 1},
7955+ ]})),
7862 )7956 )
7863 .await;7957 .await;
7864 assert_eq!(res.status, StatusCode::OK);7958 assert_eq!(res.status, StatusCode::OK);
7865- assert_eq!(res.body["exam_kinds"], json!(["lab", "quiz"]));7959+ assert_eq!(
7960+ res.body["exam_kinds"],
7961+ json!([
7962+ {"name": "lab", "weight": 2},
7963+ {"name": "quiz", "weight": 1},
7964+ ])
7965+ );
7866 }7966 }
tests/persistence.rsmodified+35 -8
@@ -206,8 +206,9 @@ async fn profile_survives_reopen() {
206 }206 }
207 }207 }
208 208
209-/// A course with an enrollment, a weighted exam, and a graded mark survives a209+/// A course with an enrollment, an exam whose kind carries a weight, and a
210-/// close + reopen — the weighted report is rebuilt from disk.210+/// graded mark survives a close + reopen — the weighted report (settings
211+/// included) is rebuilt from disk.
211 #[tokio::test]212 #[tokio::test]
212 async fn course_marks_survive_reopen() {213 async fn course_marks_survive_reopen() {
213 let dir = tempfile::tempdir().unwrap();214 let dir = tempfile::tempdir().unwrap();
@@ -215,7 +216,8 @@ async fn course_marks_survive_reopen() {
215 let teacher_creds = json!({ "username": "hoca", "password": "secret1" });216 let teacher_creds = json!({ "username": "hoca", "password": "secret1" });
216 let student_creds = json!({ "username": "ali", "password": "secret1" });217 let student_creds = json!({ "username": "ali", "password": "secret1" });
217 218
218- // First boot: teacher sets up a course, enrolls the student, grades 80.219+ // First boot: the manager-teacher weighs midterms double, sets up a
220+ // course, enrolls the student, grades 80.
219 {221 {
220 let db = database::init(&cfg).await.expect("first open");222 let db = database::init(&cfg).await.expect("first open");
221 let app = build_router(state(db.clone()));223 let app = build_router(state(db.clone()));
@@ -227,7 +229,7 @@ async fn course_marks_survive_reopen() {
227 StatusCode::CREATED229 StatusCode::CREATED
228 );230 );
229 }231 }
230- set_role(&db, "hoca", "teacher").await;232+ set_role(&db, "hoca", "manager").await;
231 let teacher = send(233 let teacher = send(
232 &app,234 &app,
233 "POST",235 "POST",
@@ -250,9 +252,24 @@ async fn course_marks_survive_reopen() {
250 .unwrap();252 .unwrap();
251 let student_id = me_id(&app, &student).await;253 let student_id = me_id(&app, &student).await;
252 254
255+ assert_eq!(
256+ send(
257+ &app,
258+ "PATCH",
259+ "/settings",
260+ Some(&teacher),
261+ Some(json!({ "exam_kinds": [
262+ {"name": "midterm", "weight": 2},
263+ {"name": "quiz", "weight": 1},
264+ ]})),
265+ )
266+ .await
267+ .status,
268+ StatusCode::OK
269+ );
253 let course_id = create_course(&app, &teacher, "algebra").await;270 let course_id = create_course(&app, &teacher, "algebra").await;
254 enroll(&app, &teacher, &course_id, &student_id).await;271 enroll(&app, &teacher, &course_id, &student_id).await;
255- let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm", 2).await;272+ let exam_id = create_exam(&app, &teacher, &course_id, "midterm", "midterm").await;
256 assert_eq!(273 assert_eq!(
257 send(274 send(
258 &app,275 &app,
@@ -267,7 +284,8 @@ async fn course_marks_survive_reopen() {
267 );284 );
268 }285 }
269 286
270- // Second boot: the report, roster, and exam weight are all rebuilt from disk.287+ // Second boot: the report, roster, and kind weight (via the settings row)
288+ // are all rebuilt from disk.
271 {289 {
272 let db = reopen(&cfg).await;290 let db = reopen(&cfg).await;
273 let app = build_router(state(db));291 let app = build_router(state(db));
@@ -328,7 +346,10 @@ async fn settings_and_terms_survive_reopen() {
328 "/settings",346 "/settings",
329 Some(&cookie),347 Some(&cookie),
330 Some(json!({348 Some(json!({
331- "exam_kinds": ["lab", "quiz"],349+ "exam_kinds": [
350+ { "name": "lab", "weight": 2 },
351+ { "name": "quiz", "weight": 1 },
352+ ],
332 "grade_bands": [{ "min": 0, "label": "F" }, { "min": 50, "label": "P" }],353 "grade_bands": [{ "min": 0, "label": "F" }, { "min": 50, "label": "P" }],
333 })),354 })),
334 )355 )
@@ -368,7 +389,13 @@ async fn settings_and_terms_survive_reopen() {
368 389
369 let res = send(&app, "GET", "/settings", Some(&cookie), None).await;390 let res = send(&app, "GET", "/settings", Some(&cookie), None).await;
370 assert_eq!(res.status, StatusCode::OK);391 assert_eq!(res.status, StatusCode::OK);
371- assert_eq!(res.body["exam_kinds"], json!(["lab", "quiz"]));392+ assert_eq!(
393+ res.body["exam_kinds"],
394+ json!([
395+ { "name": "lab", "weight": 2 },
396+ { "name": "quiz", "weight": 1 },
397+ ])
398+ );
372 assert_eq!(res.body["grade_bands"][0]["label"], "P");399 assert_eq!(res.body["grade_bands"][0]["label"], "P");
373 400
374 let res = send(&app, "GET", &format!("/terms/{term}"), Some(&cookie), None).await;401 let res = send(&app, "GET", &format!("/terms/{term}"), Some(&cookie), None).await;