Courses, enrollment, and course-scoped weighted exams
Browse files at this commitcd56c5b413414e49bb4283297c66047f2acad586Parent: baceaf5- feat
- courses, enrollment, and course-scoped weighted exams
12 changed files +1001 -101
- src/constant.rs +11 -2
- src/database.rs +17 -0
- src/domain/course.rs +183 -0
- src/domain/enrollment.rs +125 -0
- src/domain/exam.rs +58 -5
- src/domain/mod.rs +2 -0
- src/lib.rs +3 -1
- src/validate.rs +27 -5
- src/web/courses.rs +448 -0
- src/web/dto.rs +52 -0
- src/web/exams.rs +73 -87
- src/web/mod.rs +2 -1
src/constant.rsmodified+11 -2
| @@ -24,14 +24,23 @@ pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; | |||
| 24 | pub const MAX_EXAM_TITLE_LEN: usize = 200; | 24 | pub const MAX_EXAM_TITLE_LEN: usize = 200; |
| 25 | pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; | 25 | pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; |
| 26 | 26 | ||
| 27 | +pub const MAX_COURSE_TITLE_LEN: usize = 200; | ||
| 28 | +pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; | ||
| 29 | + | ||
| 27 | /// The only accepted attendance states. | 30 | /// The only accepted attendance states. |
| 28 | pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; | 31 | pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; |
| 29 | 32 | ||
| 30 | -/// The only accepted exam kinds — an exam is a homework or a quiz, nothing else. | 33 | +/// The only accepted exam kinds. Informational metadata only — `weight` drives |
| 31 | -pub const EXAM_KINDS: [&str; 2] = ["homework", "quiz"]; | 34 | +/// the course average. |
| 35 | +pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; | ||
| 32 | 36 | ||
| 33 | /// Inclusive bounds for an exam mark. | 37 | /// Inclusive bounds for an exam mark. |
| 34 | pub const MIN_MARK: i64 = 0; | 38 | pub const MIN_MARK: i64 = 0; |
| 35 | pub const MAX_MARK: i64 = 100; | 39 | pub const MAX_MARK: i64 = 100; |
| 36 | 40 | ||
| 41 | +/// Inclusive bounds for an exam's weight in the course average. The minimum of | ||
| 42 | +/// 1 keeps every graded exam counted and the average's denominator non-zero. | ||
| 43 | +pub const MIN_EXAM_WEIGHT: i64 = 1; | ||
| 44 | +pub const MAX_EXAM_WEIGHT: i64 = 100; | ||
| 45 | + | ||
| 37 | pub const SESSION_DURATION_DAYS: i64 = 7; | 46 | pub const SESSION_DURATION_DAYS: i64 = 7; |
src/database.rsmodified+17 -0
| @@ -15,6 +15,8 @@ pub const EVENT_TABLE: &str = "event"; | |||
| 15 | pub const ATTENDANCE_TABLE: &str = "attendance"; | 15 | pub const ATTENDANCE_TABLE: &str = "attendance"; |
| 16 | pub const EXAM_TABLE: &str = "exam"; | 16 | pub const EXAM_TABLE: &str = "exam"; |
| 17 | pub const EXAM_RESULT_TABLE: &str = "exam_result"; | 17 | pub const EXAM_RESULT_TABLE: &str = "exam_result"; |
| 18 | +pub const COURSE_TABLE: &str = "course"; | ||
| 19 | +pub const ENROLLMENT_TABLE: &str = "enrollment"; | ||
| 18 | 20 | ||
| 19 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. | 21 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 20 | /// Idempotent — safe to run on every boot. | 22 | /// Idempotent — safe to run on every boot. |
| @@ -58,11 +60,26 @@ const MIGRATION: &str = " | |||
| 58 | DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>; | 60 | DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>; |
| 59 | DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; | 61 | DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; |
| 60 | 62 | ||
| 63 | + DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; | ||
| 64 | + DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>; | ||
| 65 | + DEFINE FIELD IF NOT EXISTS title ON course TYPE string; | ||
| 66 | + DEFINE FIELD IF NOT EXISTS description ON course TYPE string; | ||
| 67 | + | ||
| 68 | + DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; | ||
| 69 | + DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record<course>; | ||
| 70 | + DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record<user>; | ||
| 71 | + DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record<user>; | ||
| 72 | + DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; | ||
| 73 | + DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; | ||
| 74 | + | ||
| 61 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; | 75 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; |
| 62 | DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; | 76 | DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; |
| 77 | + DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>; | ||
| 63 | DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; | 78 | DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; |
| 64 | DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; | 79 | DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; |
| 65 | DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; | 80 | DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; |
| 81 | + DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int; | ||
| 82 | + DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; | ||
| 66 | 83 | ||
| 67 | DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; | 84 | DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; |
| 68 | DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>; | 85 | DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record<exam>; |
src/domain/course.rsadded+183 -0
| @@ -0,0 +1,183 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; | ||
| 5 | +use crate::database::{COURSE_TABLE, Database}; | ||
| 6 | +use crate::domain::user::UserId; | ||
| 7 | +use crate::error::{AppError, ValidationError}; | ||
| 8 | +use crate::validate::{validate_optional, validate_required}; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct CourseId(RecordId); | ||
| 12 | + | ||
| 13 | +impl CourseId { | ||
| 14 | + pub fn generate() -> Self { | ||
| 15 | + Self(RecordId::new(COURSE_TABLE, Ulid::new().to_string())) | ||
| 16 | + } | ||
| 17 | + | ||
| 18 | + pub fn from_key(key: &str) -> Self { | ||
| 19 | + Self(RecordId::new(COURSE_TABLE, key)) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + pub fn record(&self) -> RecordId { | ||
| 23 | + self.0.clone() | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + pub fn key(&self) -> &str { | ||
| 27 | + match &self.0.key { | ||
| 28 | + RecordIdKey::String(key) => key, | ||
| 29 | + _ => "", | ||
| 30 | + } | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 35 | +pub struct CourseTitle(String); | ||
| 36 | + | ||
| 37 | +impl CourseTitle { | ||
| 38 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 39 | + validate_required("title", value, MAX_COURSE_TITLE_LEN)?; | ||
| 40 | + Ok(Self(value.to_string())) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + pub fn as_str(&self) -> &str { | ||
| 44 | + &self.0 | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 49 | +pub struct CourseDescription(String); | ||
| 50 | + | ||
| 51 | +impl CourseDescription { | ||
| 52 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 53 | + validate_optional("description", value, MAX_COURSE_DESCRIPTION_LEN)?; | ||
| 54 | + Ok(Self(value.to_string())) | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + pub fn as_str(&self) -> &str { | ||
| 58 | + &self.0 | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// A course: the unit exams and enrollments hang off. Marks are computed per | ||
| 63 | +/// course from its exams' weights. | ||
| 64 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 65 | +pub struct Course { | ||
| 66 | + id: CourseId, | ||
| 67 | + creator: UserId, | ||
| 68 | + title: CourseTitle, | ||
| 69 | + description: CourseDescription, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +impl Course { | ||
| 73 | + pub fn get_id(&self) -> &CourseId { | ||
| 74 | + &self.id | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + pub fn get_creator(&self) -> &UserId { | ||
| 78 | + &self.creator | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + pub fn get_title(&self) -> &CourseTitle { | ||
| 82 | + &self.title | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + pub fn get_description(&self) -> &CourseDescription { | ||
| 86 | + &self.description | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + pub fn is_creator(&self, user: &UserId) -> bool { | ||
| 90 | + &self.creator == user | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + pub async fn create( | ||
| 94 | + creator: &UserId, | ||
| 95 | + title: CourseTitle, | ||
| 96 | + description: CourseDescription, | ||
| 97 | + db: &Database, | ||
| 98 | + ) -> Result<Course, AppError> { | ||
| 99 | + let course = Course { | ||
| 100 | + id: CourseId::generate(), | ||
| 101 | + creator: creator.clone(), | ||
| 102 | + title, | ||
| 103 | + description, | ||
| 104 | + }; | ||
| 105 | + let created: Option<Course> = db.create(course.id.record()).content(course).await?; | ||
| 106 | + created.ok_or_else(|| AppError::Internal("failed to create course".into())) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + pub async fn read(id: &CourseId, db: &Database) -> Result<Option<Course>, AppError> { | ||
| 110 | + Ok(db.select(id.record()).await?) | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 114 | + let mut result = db | ||
| 115 | + .query("SELECT * FROM course ORDER BY id DESC") | ||
| 116 | + .await? | ||
| 117 | + .check()?; | ||
| 118 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + /// The courses `user` is enrolled in — the spine of `/courses/me` and the | ||
| 122 | + /// marks report. | ||
| 123 | + pub async fn list_enrolled(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 124 | + let mut result = db | ||
| 125 | + .query( | ||
| 126 | + "SELECT * FROM course | ||
| 127 | + WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr) | ||
| 128 | + ORDER BY id DESC", | ||
| 129 | + ) | ||
| 130 | + .bind(("usr", user.record())) | ||
| 131 | + .await? | ||
| 132 | + .check()?; | ||
| 133 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + pub async fn update( | ||
| 137 | + mut self, | ||
| 138 | + title: CourseTitle, | ||
| 139 | + description: CourseDescription, | ||
| 140 | + db: &Database, | ||
| 141 | + ) -> Result<Course, AppError> { | ||
| 142 | + self.title = title; | ||
| 143 | + self.description = description; | ||
| 144 | + let updated: Option<Course> = db.update(self.id.record()).content(self).await?; | ||
| 145 | + updated.ok_or(AppError::NotFound) | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + /// Delete the course and cascade-remove everything inside it: results of | ||
| 149 | + /// its exams, its enrollments, and the exams themselves. The children go in | ||
| 150 | + /// one transaction so a crash can't leave an exam pointing at a deleted | ||
| 151 | + /// course. | ||
| 152 | + pub async fn delete(self, db: &Database) -> Result<Course, AppError> { | ||
| 153 | + db.query( | ||
| 154 | + "BEGIN TRANSACTION; | ||
| 155 | + DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 156 | + DELETE enrollment WHERE course = $course; | ||
| 157 | + DELETE exam WHERE course = $course; | ||
| 158 | + COMMIT TRANSACTION;", | ||
| 159 | + ) | ||
| 160 | + .bind(("course", self.id.record())) | ||
| 161 | + .await? | ||
| 162 | + .check()?; | ||
| 163 | + let deleted: Option<Course> = db.delete(self.id.record()).await?; | ||
| 164 | + deleted.ok_or(AppError::NotFound) | ||
| 165 | + } | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +#[cfg(test)] | ||
| 169 | +mod tests { | ||
| 170 | + use super::*; | ||
| 171 | + | ||
| 172 | + #[tokio::test] | ||
| 173 | + async fn title_is_required() { | ||
| 174 | + assert!(CourseTitle::try_new("algebra").is_ok()); | ||
| 175 | + assert!(CourseTitle::try_new("").is_err()); | ||
| 176 | + assert!(CourseTitle::try_new(" ").is_err()); | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + #[tokio::test] | ||
| 180 | + async fn description_is_optional() { | ||
| 181 | + assert!(CourseDescription::try_new("").is_ok()); | ||
| 182 | + } | ||
| 183 | +} | ||
src/domain/enrollment.rsadded+125 -0
| @@ -0,0 +1,125 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | + | ||
| 3 | +use crate::database::{Database, ENROLLMENT_TABLE}; | ||
| 4 | +use crate::domain::course::CourseId; | ||
| 5 | +use crate::domain::user::UserId; | ||
| 6 | +use crate::error::AppError; | ||
| 7 | + | ||
| 8 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 9 | +pub struct EnrollmentId(RecordId); | ||
| 10 | + | ||
| 11 | +impl EnrollmentId { | ||
| 12 | + /// A deterministic id for the (course, user) pair. The same pair always | ||
| 13 | + /// maps to the same record id, so enrolling is a single atomic UPSERT with | ||
| 14 | + /// no find-then-insert race and one-row-per-pair by construction. ULID keys | ||
| 15 | + /// are alphanumeric, so `_` is an unambiguous joiner. | ||
| 16 | + pub fn composite(course: &CourseId, user: &UserId) -> Self { | ||
| 17 | + Self(RecordId::new( | ||
| 18 | + ENROLLMENT_TABLE, | ||
| 19 | + format!("{}_{}", course.key(), user.key()), | ||
| 20 | + )) | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + pub fn record(&self) -> RecordId { | ||
| 24 | + self.0.clone() | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + pub fn key(&self) -> &str { | ||
| 28 | + match &self.0.key { | ||
| 29 | + RecordIdKey::String(key) => key, | ||
| 30 | + _ => "", | ||
| 31 | + } | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// A user's membership in a course. Grading requires it; removing it hides the | ||
| 36 | +/// user's marks from the report but never deletes result rows. | ||
| 37 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 38 | +pub struct Enrollment { | ||
| 39 | + id: EnrollmentId, | ||
| 40 | + course: CourseId, | ||
| 41 | + user: UserId, | ||
| 42 | + enrolled_by: UserId, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +impl Enrollment { | ||
| 46 | + pub fn get_id(&self) -> &EnrollmentId { | ||
| 47 | + &self.id | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + pub fn get_course(&self) -> &CourseId { | ||
| 51 | + &self.course | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + pub fn get_user(&self) -> &UserId { | ||
| 55 | + &self.user | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + pub fn get_enrolled_by(&self) -> &UserId { | ||
| 59 | + &self.enrolled_by | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + /// Enroll (idempotently) `user` into `course`. One row per (course, user), | ||
| 63 | + /// keyed by a deterministic composite id so this is a single atomic UPSERT — | ||
| 64 | + /// concurrent enrolls for the same pair converge on one row instead of | ||
| 65 | + /// racing the unique index into a 500. | ||
| 66 | + pub async fn enroll( | ||
| 67 | + course: &CourseId, | ||
| 68 | + user: &UserId, | ||
| 69 | + enrolled_by: &UserId, | ||
| 70 | + db: &Database, | ||
| 71 | + ) -> Result<Enrollment, AppError> { | ||
| 72 | + let enrollment = Enrollment { | ||
| 73 | + id: EnrollmentId::composite(course, user), | ||
| 74 | + course: course.clone(), | ||
| 75 | + user: user.clone(), | ||
| 76 | + enrolled_by: enrolled_by.clone(), | ||
| 77 | + }; | ||
| 78 | + let saved: Option<Enrollment> = db | ||
| 79 | + .upsert(enrollment.id.record()) | ||
| 80 | + .content(enrollment) | ||
| 81 | + .await?; | ||
| 82 | + saved.ok_or_else(|| AppError::Internal("failed to enroll user".into())) | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + /// Some(_) iff `user` is enrolled in `course` — the grading gate. | ||
| 86 | + pub async fn read_for_user( | ||
| 87 | + course: &CourseId, | ||
| 88 | + user: &UserId, | ||
| 89 | + db: &Database, | ||
| 90 | + ) -> Result<Option<Enrollment>, AppError> { | ||
| 91 | + let mut result = db | ||
| 92 | + .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1") | ||
| 93 | + .bind(("course", course.record())) | ||
| 94 | + .bind(("usr", user.record())) | ||
| 95 | + .await? | ||
| 96 | + .check()?; | ||
| 97 | + Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next()) | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + pub async fn list_for_course( | ||
| 101 | + course: &CourseId, | ||
| 102 | + db: &Database, | ||
| 103 | + ) -> Result<Vec<Enrollment>, AppError> { | ||
| 104 | + let mut result = db | ||
| 105 | + .query("SELECT * FROM enrollment WHERE course = $course ORDER BY id DESC") | ||
| 106 | + .bind(("course", course.record())) | ||
| 107 | + .await? | ||
| 108 | + .check()?; | ||
| 109 | + Ok(result.take::<Vec<Enrollment>>(0)?) | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + pub async fn remove( | ||
| 113 | + course: &CourseId, | ||
| 114 | + user: &UserId, | ||
| 115 | + db: &Database, | ||
| 116 | + ) -> Result<Option<Enrollment>, AppError> { | ||
| 117 | + let mut result = db | ||
| 118 | + .query("DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE") | ||
| 119 | + .bind(("course", course.record())) | ||
| 120 | + .bind(("usr", user.record())) | ||
| 121 | + .await? | ||
| 122 | + .check()?; | ||
| 123 | + Ok(result.take::<Vec<Enrollment>>(0)?.into_iter().next()) | ||
| 124 | + } | ||
| 125 | +} | ||
src/domain/exam.rsmodified+58 -5
| @@ -3,9 +3,10 @@ use ulid::Ulid; | |||
| 3 | 3 | ||
| 4 | use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; | 4 | use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; |
| 5 | use crate::database::{Database, EXAM_TABLE}; | 5 | use crate::database::{Database, EXAM_TABLE}; |
| 6 | +use crate::domain::course::CourseId; | ||
| 6 | use crate::domain::user::UserId; | 7 | use crate::domain::user::UserId; |
| 7 | use crate::error::{AppError, ValidationError}; | 8 | use crate::error::{AppError, ValidationError}; |
| 8 | -use crate::validate::{validate_exam_kind, validate_optional, validate_required}; | 9 | +use crate::validate::{validate_exam_kind, validate_optional, validate_required, validate_weight}; |
| 9 | 10 | ||
| 10 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 11 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 11 | pub struct ExamId(RecordId); | 12 | pub struct ExamId(RecordId); |
| @@ -59,8 +60,9 @@ impl ExamDescription { | |||
| 59 | } | 60 | } |
| 60 | } | 61 | } |
| 61 | 62 | ||
| 62 | -/// A validated exam kind: `homework` | `quiz`. An exam is never a graded course | 63 | +/// A validated exam kind: `homework` | `quiz` | `midterm` | `final` | |
| 63 | -/// mark — only one of these two assessment forms. | 64 | +/// `project` | `oral`. Informational metadata only — `weight` drives the |
| 65 | +/// course average. | ||
| 64 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 66 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 65 | pub struct ExamKind(String); | 67 | pub struct ExamKind(String); |
| 66 | 68 | ||
| @@ -75,13 +77,31 @@ impl ExamKind { | |||
| 75 | } | 77 | } |
| 76 | } | 78 | } |
| 77 | 79 | ||
| 80 | +/// A validated exam weight, held to `[MIN_EXAM_WEIGHT, MAX_EXAM_WEIGHT]`. The | ||
| 81 | +/// exam counts `weight` times into its course's average. | ||
| 82 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] | ||
| 83 | +pub struct ExamWeight(i64); | ||
| 84 | + | ||
| 85 | +impl ExamWeight { | ||
| 86 | + pub fn try_new(value: i64) -> Result<Self, ValidationError> { | ||
| 87 | + validate_weight(value)?; | ||
| 88 | + Ok(Self(value)) | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + pub fn as_i64(&self) -> i64 { | ||
| 92 | + self.0 | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 78 | #[derive(Debug, Clone, SurrealValue)] | 96 | #[derive(Debug, Clone, SurrealValue)] |
| 79 | pub struct Exam { | 97 | pub struct Exam { |
| 80 | id: ExamId, | 98 | id: ExamId, |
| 81 | creator: UserId, | 99 | creator: UserId, |
| 100 | + course: CourseId, | ||
| 82 | title: ExamTitle, | 101 | title: ExamTitle, |
| 83 | description: ExamDescription, | 102 | description: ExamDescription, |
| 84 | kind: ExamKind, | 103 | kind: ExamKind, |
| 104 | + weight: ExamWeight, | ||
| 85 | } | 105 | } |
| 86 | 106 | ||
| 87 | impl Exam { | 107 | impl Exam { |
| @@ -93,6 +113,10 @@ impl Exam { | |||
| 93 | &self.creator | 113 | &self.creator |
| 94 | } | 114 | } |
| 95 | 115 | ||
| 116 | + pub fn get_course(&self) -> &CourseId { | ||
| 117 | + &self.course | ||
| 118 | + } | ||
| 119 | + | ||
| 96 | pub fn get_title(&self) -> &ExamTitle { | 120 | pub fn get_title(&self) -> &ExamTitle { |
| 97 | &self.title | 121 | &self.title |
| 98 | } | 122 | } |
| @@ -105,23 +129,31 @@ impl Exam { | |||
| 105 | &self.kind | 129 | &self.kind |
| 106 | } | 130 | } |
| 107 | 131 | ||
| 132 | + pub fn get_weight(&self) -> ExamWeight { | ||
| 133 | + self.weight | ||
| 134 | + } | ||
| 135 | + | ||
| 108 | pub fn is_creator(&self, user: &UserId) -> bool { | 136 | pub fn is_creator(&self, user: &UserId) -> bool { |
| 109 | &self.creator == user | 137 | &self.creator == user |
| 110 | } | 138 | } |
| 111 | 139 | ||
| 112 | pub async fn create( | 140 | pub async fn create( |
| 113 | creator: &UserId, | 141 | creator: &UserId, |
| 142 | + course: &CourseId, | ||
| 114 | title: ExamTitle, | 143 | title: ExamTitle, |
| 115 | description: ExamDescription, | 144 | description: ExamDescription, |
| 116 | kind: ExamKind, | 145 | kind: ExamKind, |
| 146 | + weight: ExamWeight, | ||
| 117 | db: &Database, | 147 | db: &Database, |
| 118 | ) -> Result<Exam, AppError> { | 148 | ) -> Result<Exam, AppError> { |
| 119 | let exam = Exam { | 149 | let exam = Exam { |
| 120 | id: ExamId::generate(), | 150 | id: ExamId::generate(), |
| 121 | creator: creator.clone(), | 151 | creator: creator.clone(), |
| 152 | + course: course.clone(), | ||
| 122 | title, | 153 | title, |
| 123 | description, | 154 | description, |
| 124 | kind, | 155 | kind, |
| 156 | + weight, | ||
| 125 | }; | 157 | }; |
| 126 | let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?; | 158 | let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?; |
| 127 | created.ok_or_else(|| AppError::Internal("failed to create exam".into())) | 159 | created.ok_or_else(|| AppError::Internal("failed to create exam".into())) |
| @@ -139,16 +171,29 @@ impl Exam { | |||
| 139 | Ok(result.take::<Vec<Exam>>(0)?) | 171 | Ok(result.take::<Vec<Exam>>(0)?) |
| 140 | } | 172 | } |
| 141 | 173 | ||
| 174 | + pub async fn list_for_course(course: &CourseId, db: &Database) -> Result<Vec<Exam>, AppError> { | ||
| 175 | + let mut result = db | ||
| 176 | + .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC") | ||
| 177 | + .bind(("course", course.record())) | ||
| 178 | + .await? | ||
| 179 | + .check()?; | ||
| 180 | + Ok(result.take::<Vec<Exam>>(0)?) | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + // `course` is deliberately not updatable — moving an exam between courses | ||
| 184 | + // would strand results of students not enrolled in the target course. | ||
| 142 | pub async fn update( | 185 | pub async fn update( |
| 143 | mut self, | 186 | mut self, |
| 144 | title: ExamTitle, | 187 | title: ExamTitle, |
| 145 | description: ExamDescription, | 188 | description: ExamDescription, |
| 146 | kind: ExamKind, | 189 | kind: ExamKind, |
| 190 | + weight: ExamWeight, | ||
| 147 | db: &Database, | 191 | db: &Database, |
| 148 | ) -> Result<Exam, AppError> { | 192 | ) -> Result<Exam, AppError> { |
| 149 | self.title = title; | 193 | self.title = title; |
| 150 | self.description = description; | 194 | self.description = description; |
| 151 | self.kind = kind; | 195 | self.kind = kind; |
| 196 | + self.weight = weight; | ||
| 152 | let updated: Option<Exam> = db.update(self.id.record()).content(self).await?; | 197 | let updated: Option<Exam> = db.update(self.id.record()).content(self).await?; |
| 153 | updated.ok_or(AppError::NotFound) | 198 | updated.ok_or(AppError::NotFound) |
| 154 | } | 199 | } |
| @@ -182,10 +227,18 @@ mod tests { | |||
| 182 | 227 | ||
| 183 | #[tokio::test] | 228 | #[tokio::test] |
| 184 | async fn kind_must_be_known() { | 229 | async fn kind_must_be_known() { |
| 185 | - for kind in ["homework", "quiz"] { | 230 | + for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { |
| 186 | assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); | 231 | assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); |
| 187 | } | 232 | } |
| 188 | - assert!(ExamKind::try_new("final").is_err()); | 233 | + assert!(ExamKind::try_new("essay").is_err()); |
| 189 | assert!(ExamKind::try_new("").is_err()); | 234 | assert!(ExamKind::try_new("").is_err()); |
| 190 | } | 235 | } |
| 236 | + | ||
| 237 | + #[tokio::test] | ||
| 238 | + async fn weight_range_is_enforced() { | ||
| 239 | + assert_eq!(ExamWeight::try_new(1).unwrap().as_i64(), 1); | ||
| 240 | + assert_eq!(ExamWeight::try_new(100).unwrap().as_i64(), 100); | ||
| 241 | + assert!(ExamWeight::try_new(0).is_err()); | ||
| 242 | + assert!(ExamWeight::try_new(101).is_err()); | ||
| 243 | + } | ||
| 191 | } | 244 | } |
src/domain/mod.rsmodified+2 -0
| @@ -3,6 +3,8 @@ | |||
| 3 | //! same typed value flows from HTTP input all the way into the database. | 3 | //! same typed value flows from HTTP input all the way into the database. |
| 4 | 4 | ||
| 5 | pub mod attendance; | 5 | pub mod attendance; |
| 6 | +pub mod course; | ||
| 7 | +pub mod enrollment; | ||
| 6 | pub mod event; | 8 | pub mod event; |
| 7 | pub mod exam; | 9 | pub mod exam; |
| 8 | pub mod exam_result; | 10 | pub mod exam_result; |
src/lib.rsmodified+3 -1
| @@ -41,7 +41,8 @@ use crate::state::AppState; | |||
| 41 | (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), | 41 | (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), |
| 42 | (name = "notes", description = "Per-user notes CRUD"), | 42 | (name = "notes", description = "Per-user notes CRUD"), |
| 43 | (name = "events", description = "Events and attendance"), | 43 | (name = "events", description = "Events and attendance"), |
| 44 | - (name = "exams", description = "Exams (homework/quiz) and student results"), | 44 | + (name = "courses", description = "Courses, enrollment, and course exams"), |
| 45 | + (name = "exams", description = "Exams (per course, weighted) and student results"), | ||
| 45 | ), | 46 | ), |
| 46 | )] | 47 | )] |
| 47 | struct ApiDoc; | 48 | struct ApiDoc; |
| @@ -73,6 +74,7 @@ pub fn build_router(state: AppState) -> Router { | |||
| 73 | .nest("/users", web::users::routes()) | 74 | .nest("/users", web::users::routes()) |
| 74 | .nest("/notes", web::notes::routes()) | 75 | .nest("/notes", web::notes::routes()) |
| 75 | .nest("/events", web::events::routes()) | 76 | .nest("/events", web::events::routes()) |
| 77 | + .nest("/courses", web::courses::routes()) | ||
| 76 | .nest("/exams", web::exams::routes()) | 78 | .nest("/exams", web::exams::routes()) |
| 77 | .split_for_parts(); | 79 | .split_for_parts(); |
| 78 | 80 | ||
src/validate.rsmodified+27 -5
| @@ -2,8 +2,9 @@ | |||
| 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 | - ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, | 5 | + ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, |
| 6 | - MAX_USERNAME_LEN, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_USERNAME_LEN, | 6 | + MAX_PHONE_DIGITS, MAX_USERNAME_LEN, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, |
| 7 | + MIN_PHONE_DIGITS, MIN_USERNAME_LEN, | ||
| 7 | }; | 8 | }; |
| 8 | use crate::error::ValidationError; | 9 | use crate::error::ValidationError; |
| 9 | 10 | ||
| @@ -173,7 +174,7 @@ pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { | |||
| 173 | } else { | 174 | } else { |
| 174 | Err(ValidationError::Invalid { | 175 | Err(ValidationError::Invalid { |
| 175 | field: "kind", | 176 | field: "kind", |
| 176 | - reason: "must be one of: homework, quiz", | 177 | + reason: "must be one of: homework, quiz, midterm, final, project, oral", |
| 177 | }) | 178 | }) |
| 178 | } | 179 | } |
| 179 | } | 180 | } |
| @@ -189,6 +190,17 @@ pub fn validate_mark(value: i64) -> Result<(), ValidationError> { | |||
| 189 | } | 190 | } |
| 190 | } | 191 | } |
| 191 | 192 | ||
| 193 | +pub fn validate_weight(value: i64) -> Result<(), ValidationError> { | ||
| 194 | + if (MIN_EXAM_WEIGHT..=MAX_EXAM_WEIGHT).contains(&value) { | ||
| 195 | + Ok(()) | ||
| 196 | + } else { | ||
| 197 | + Err(ValidationError::Invalid { | ||
| 198 | + field: "weight", | ||
| 199 | + reason: "must be between 1 and 100", | ||
| 200 | + }) | ||
| 201 | + } | ||
| 202 | +} | ||
| 203 | + | ||
| 192 | #[cfg(test)] | 204 | #[cfg(test)] |
| 193 | mod tests { | 205 | mod tests { |
| 194 | use super::*; | 206 | use super::*; |
| @@ -275,10 +287,10 @@ mod tests { | |||
| 275 | 287 | ||
| 276 | #[tokio::test] | 288 | #[tokio::test] |
| 277 | async fn exam_kind_rules() { | 289 | async fn exam_kind_rules() { |
| 278 | - for kind in ["homework", "quiz"] { | 290 | + for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { |
| 279 | assert!(validate_exam_kind(kind).is_ok()); | 291 | assert!(validate_exam_kind(kind).is_ok()); |
| 280 | } | 292 | } |
| 281 | - assert!(validate_exam_kind("final").is_err()); | 293 | + assert!(validate_exam_kind("essay").is_err()); |
| 282 | assert!(validate_exam_kind("").is_err()); | 294 | assert!(validate_exam_kind("").is_err()); |
| 283 | } | 295 | } |
| 284 | 296 | ||
| @@ -290,4 +302,14 @@ mod tests { | |||
| 290 | assert!(validate_mark(-1).is_err()); | 302 | assert!(validate_mark(-1).is_err()); |
| 291 | assert!(validate_mark(101).is_err()); | 303 | assert!(validate_mark(101).is_err()); |
| 292 | } | 304 | } |
| 305 | + | ||
| 306 | + #[tokio::test] | ||
| 307 | + async fn weight_rules() { | ||
| 308 | + for weight in [1, 50, 100] { | ||
| 309 | + assert!(validate_weight(weight).is_ok()); | ||
| 310 | + } | ||
| 311 | + assert!(validate_weight(0).is_err()); | ||
| 312 | + assert!(validate_weight(-1).is_err()); | ||
| 313 | + assert!(validate_weight(101).is_err()); | ||
| 314 | + } | ||
| 293 | } | 315 | } |
src/web/courses.rsadded+448 -0
| @@ -0,0 +1,448 @@ | |||
| 1 | +use axum::Json; | ||
| 2 | +use axum::extract::{Path, State}; | ||
| 3 | +use axum::http::StatusCode; | ||
| 4 | +use serde::{Deserialize, Serialize}; | ||
| 5 | +use utoipa::ToSchema; | ||
| 6 | +use utoipa_axum::router::OpenApiRouter; | ||
| 7 | +use utoipa_axum::routes; | ||
| 8 | + | ||
| 9 | +use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; | ||
| 10 | +use crate::domain::enrollment::Enrollment; | ||
| 11 | +use crate::domain::exam::{Exam, ExamDescription, ExamKind, ExamTitle, ExamWeight}; | ||
| 12 | +use crate::domain::role::Role; | ||
| 13 | +use crate::domain::user::{User, UserId}; | ||
| 14 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 15 | +use crate::state::AppState; | ||
| 16 | + | ||
| 17 | +use super::{CourseResponse, CurrentUser, ExamResponse, RequireTeacher}; | ||
| 18 | + | ||
| 19 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 20 | + OpenApiRouter::new() | ||
| 21 | + .routes(routes!(create_course, list_courses)) | ||
| 22 | + .routes(routes!(my_courses)) | ||
| 23 | + .routes(routes!(get_course, update_course, delete_course)) | ||
| 24 | + .routes(routes!(enroll, list_roster)) | ||
| 25 | + .routes(routes!(unenroll)) | ||
| 26 | + .routes(routes!(create_exam_in_course, list_course_exams)) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +#[derive(Deserialize, ToSchema)] | ||
| 30 | +struct CreateCourse { | ||
| 31 | + #[schema(example = "Algebra")] | ||
| 32 | + title: String, | ||
| 33 | + description: Option<String>, | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +#[derive(Deserialize, ToSchema)] | ||
| 37 | +struct UpdateCourse { | ||
| 38 | + title: Option<String>, | ||
| 39 | + description: Option<String>, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +#[derive(Deserialize, ToSchema)] | ||
| 43 | +struct EnrollUser { | ||
| 44 | + /// The user to enroll. | ||
| 45 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 46 | + user_id: String, | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +#[derive(Deserialize, ToSchema)] | ||
| 50 | +struct CreateExamInCourse { | ||
| 51 | + #[schema(example = "Midterm")] | ||
| 52 | + title: String, | ||
| 53 | + description: Option<String>, | ||
| 54 | + /// The assessment form: `homework`, `quiz`, `midterm`, `final`, `project`, | ||
| 55 | + /// or `oral`. Informational — `weight` drives the course average. | ||
| 56 | + #[schema(example = "midterm")] | ||
| 57 | + kind: String, | ||
| 58 | + /// How many times this exam counts into the course average, `1`–`100`. | ||
| 59 | + #[schema(example = 3)] | ||
| 60 | + weight: i64, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +#[derive(Serialize, ToSchema)] | ||
| 64 | +struct EnrollmentResponse { | ||
| 65 | + id: String, | ||
| 66 | + course: String, | ||
| 67 | + user: String, | ||
| 68 | + enrolled_by: String, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl EnrollmentResponse { | ||
| 72 | + fn new(enrollment: &Enrollment) -> Self { | ||
| 73 | + Self { | ||
| 74 | + id: enrollment.get_id().key().to_string(), | ||
| 75 | + course: enrollment.get_course().key().to_string(), | ||
| 76 | + user: enrollment.get_user().key().to_string(), | ||
| 77 | + enrolled_by: enrollment.get_enrolled_by().key().to_string(), | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Who may write inside a specific course (edit/delete it, enroll, add exams, | ||
| 83 | +/// grade): its creator, or anyone `manager` and above. Callers have already | ||
| 84 | +/// cleared the `teacher` bar via `RequireTeacher`. | ||
| 85 | +pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool { | ||
| 86 | + course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +// ---- courses ------------------------------------------------------------ | ||
| 90 | + | ||
| 91 | +/// Create a course owned by the current user. Requires the `teacher` role or higher. | ||
| 92 | +#[utoipa::path( | ||
| 93 | + post, | ||
| 94 | + path = "/", | ||
| 95 | + tag = "courses", | ||
| 96 | + security(("session_cookie" = [])), | ||
| 97 | + request_body = CreateCourse, | ||
| 98 | + responses( | ||
| 99 | + (status = 201, description = "Course created", body = CourseResponse), | ||
| 100 | + (status = 400, description = "Invalid fields", body = ErrorResponse), | ||
| 101 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 102 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 103 | + ), | ||
| 104 | +)] | ||
| 105 | +async fn create_course( | ||
| 106 | + State(st): State<AppState>, | ||
| 107 | + RequireTeacher(user): RequireTeacher, | ||
| 108 | + Json(req): Json<CreateCourse>, | ||
| 109 | +) -> Result<(StatusCode, Json<CourseResponse>), AppError> { | ||
| 110 | + let title = CourseTitle::try_new(&req.title)?; | ||
| 111 | + let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; | ||
| 112 | + let course = Course::create(user.get_id(), title, description, &st.db).await?; | ||
| 113 | + Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +/// List all courses. | ||
| 117 | +#[utoipa::path( | ||
| 118 | + get, | ||
| 119 | + path = "/", | ||
| 120 | + tag = "courses", | ||
| 121 | + security(("session_cookie" = [])), | ||
| 122 | + responses( | ||
| 123 | + (status = 200, description = "All courses", body = [CourseResponse]), | ||
| 124 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 125 | + ), | ||
| 126 | +)] | ||
| 127 | +async fn list_courses( | ||
| 128 | + State(st): State<AppState>, | ||
| 129 | + _user: CurrentUser, | ||
| 130 | +) -> Result<Json<Vec<CourseResponse>>, AppError> { | ||
| 131 | + let courses = Course::list_all(&st.db).await?; | ||
| 132 | + Ok(Json(courses.iter().map(CourseResponse::new).collect())) | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// The courses the current user is enrolled in. | ||
| 136 | +#[utoipa::path( | ||
| 137 | + get, | ||
| 138 | + path = "/me", | ||
| 139 | + tag = "courses", | ||
| 140 | + security(("session_cookie" = [])), | ||
| 141 | + responses( | ||
| 142 | + (status = 200, description = "The caller's enrolled courses", body = [CourseResponse]), | ||
| 143 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 144 | + ), | ||
| 145 | +)] | ||
| 146 | +async fn my_courses( | ||
| 147 | + State(st): State<AppState>, | ||
| 148 | + CurrentUser(user): CurrentUser, | ||
| 149 | +) -> Result<Json<Vec<CourseResponse>>, AppError> { | ||
| 150 | + let courses = Course::list_enrolled(user.get_id(), &st.db).await?; | ||
| 151 | + Ok(Json(courses.iter().map(CourseResponse::new).collect())) | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// Fetch a single course by id. | ||
| 155 | +#[utoipa::path( | ||
| 156 | + get, | ||
| 157 | + path = "/{id}", | ||
| 158 | + tag = "courses", | ||
| 159 | + security(("session_cookie" = [])), | ||
| 160 | + params(("id" = String, Path, description = "Course id")), | ||
| 161 | + responses( | ||
| 162 | + (status = 200, description = "The course", body = CourseResponse), | ||
| 163 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 164 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 165 | + ), | ||
| 166 | +)] | ||
| 167 | +async fn get_course( | ||
| 168 | + State(st): State<AppState>, | ||
| 169 | + _user: CurrentUser, | ||
| 170 | + Path(id): Path<String>, | ||
| 171 | +) -> Result<Json<CourseResponse>, AppError> { | ||
| 172 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 173 | + .await? | ||
| 174 | + .ok_or(AppError::NotFound)?; | ||
| 175 | + Ok(Json(CourseResponse::new(&course))) | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +/// Update a course. Requires teacher+; the creator may edit their own course | ||
| 179 | +/// and managers/admins may edit anyone's. Omitted fields keep their value. | ||
| 180 | +#[utoipa::path( | ||
| 181 | + patch, | ||
| 182 | + path = "/{id}", | ||
| 183 | + tag = "courses", | ||
| 184 | + security(("session_cookie" = [])), | ||
| 185 | + params(("id" = String, Path, description = "Course id")), | ||
| 186 | + request_body = UpdateCourse, | ||
| 187 | + responses( | ||
| 188 | + (status = 200, description = "Updated course", body = CourseResponse), | ||
| 189 | + (status = 400, description = "Invalid fields", body = ErrorResponse), | ||
| 190 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 191 | + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | ||
| 192 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 193 | + ), | ||
| 194 | +)] | ||
| 195 | +async fn update_course( | ||
| 196 | + State(st): State<AppState>, | ||
| 197 | + RequireTeacher(user): RequireTeacher, | ||
| 198 | + Path(id): Path<String>, | ||
| 199 | + Json(req): Json<UpdateCourse>, | ||
| 200 | +) -> Result<Json<CourseResponse>, AppError> { | ||
| 201 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 202 | + .await? | ||
| 203 | + .ok_or(AppError::NotFound)?; | ||
| 204 | + if !can_manage_course(&course, &user) { | ||
| 205 | + return Err(AppError::Forbidden( | ||
| 206 | + "only the course creator or a manager/admin can edit this course", | ||
| 207 | + )); | ||
| 208 | + } | ||
| 209 | + | ||
| 210 | + let title = match req.title { | ||
| 211 | + Some(ref title) => CourseTitle::try_new(title)?, | ||
| 212 | + None => course.get_title().clone(), | ||
| 213 | + }; | ||
| 214 | + let description = match req.description { | ||
| 215 | + Some(ref description) => CourseDescription::try_new(description)?, | ||
| 216 | + None => course.get_description().clone(), | ||
| 217 | + }; | ||
| 218 | + | ||
| 219 | + let updated = course.update(title, description, &st.db).await?; | ||
| 220 | + Ok(Json(CourseResponse::new(&updated))) | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +/// Delete a course. Requires teacher+; the creator may delete their own course | ||
| 224 | +/// and managers/admins may delete anyone's. Cascades the course's exams, their | ||
| 225 | +/// results, and all enrollments. | ||
| 226 | +#[utoipa::path( | ||
| 227 | + delete, | ||
| 228 | + path = "/{id}", | ||
| 229 | + tag = "courses", | ||
| 230 | + security(("session_cookie" = [])), | ||
| 231 | + params(("id" = String, Path, description = "Course id")), | ||
| 232 | + responses( | ||
| 233 | + (status = 204, description = "Deleted"), | ||
| 234 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 235 | + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | ||
| 236 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 237 | + ), | ||
| 238 | +)] | ||
| 239 | +async fn delete_course( | ||
| 240 | + State(st): State<AppState>, | ||
| 241 | + RequireTeacher(user): RequireTeacher, | ||
| 242 | + Path(id): Path<String>, | ||
| 243 | +) -> Result<StatusCode, AppError> { | ||
| 244 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 245 | + .await? | ||
| 246 | + .ok_or(AppError::NotFound)?; | ||
| 247 | + if !can_manage_course(&course, &user) { | ||
| 248 | + return Err(AppError::Forbidden( | ||
| 249 | + "only the course creator or a manager/admin can delete this course", | ||
| 250 | + )); | ||
| 251 | + } | ||
| 252 | + course.delete(&st.db).await?; | ||
| 253 | + Ok(StatusCode::NO_CONTENT) | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +// ---- enrollments ---------------------------------------------------------- | ||
| 257 | + | ||
| 258 | +/// Enroll a user into a course (idempotent upsert). Requires teacher+ and | ||
| 259 | +/// course management rights. | ||
| 260 | +#[utoipa::path( | ||
| 261 | + post, | ||
| 262 | + path = "/{id}/enrollments", | ||
| 263 | + tag = "courses", | ||
| 264 | + security(("session_cookie" = [])), | ||
| 265 | + params(("id" = String, Path, description = "Course id")), | ||
| 266 | + request_body = EnrollUser, | ||
| 267 | + responses( | ||
| 268 | + (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse), | ||
| 269 | + (status = 400, description = "Unknown user", body = ErrorResponse), | ||
| 270 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 271 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 272 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 273 | + ), | ||
| 274 | +)] | ||
| 275 | +async fn enroll( | ||
| 276 | + State(st): State<AppState>, | ||
| 277 | + RequireTeacher(user): RequireTeacher, | ||
| 278 | + Path(id): Path<String>, | ||
| 279 | + Json(req): Json<EnrollUser>, | ||
| 280 | +) -> Result<Json<EnrollmentResponse>, AppError> { | ||
| 281 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 282 | + .await? | ||
| 283 | + .ok_or(AppError::NotFound)?; | ||
| 284 | + if !can_manage_course(&course, &user) { | ||
| 285 | + return Err(AppError::Forbidden( | ||
| 286 | + "only the course creator or a manager/admin can enroll users", | ||
| 287 | + )); | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + let target = UserId::from_key(&req.user_id); | ||
| 291 | + if User::read(&target, &st.db).await?.is_none() { | ||
| 292 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 293 | + field: "user_id", | ||
| 294 | + reason: "target user does not exist", | ||
| 295 | + })); | ||
| 296 | + } | ||
| 297 | + | ||
| 298 | + let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; | ||
| 299 | + Ok(Json(EnrollmentResponse::new(&enrollment))) | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +/// List a course's roster. Requires teacher+ — students see their own courses | ||
| 303 | +/// via `GET /courses/me`. | ||
| 304 | +#[utoipa::path( | ||
| 305 | + get, | ||
| 306 | + path = "/{id}/enrollments", | ||
| 307 | + tag = "courses", | ||
| 308 | + security(("session_cookie" = [])), | ||
| 309 | + params(("id" = String, Path, description = "Course id")), | ||
| 310 | + responses( | ||
| 311 | + (status = 200, description = "All enrollments", body = [EnrollmentResponse]), | ||
| 312 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 313 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 314 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 315 | + ), | ||
| 316 | +)] | ||
| 317 | +async fn list_roster( | ||
| 318 | + State(st): State<AppState>, | ||
| 319 | + _teacher: RequireTeacher, | ||
| 320 | + Path(id): Path<String>, | ||
| 321 | +) -> Result<Json<Vec<EnrollmentResponse>>, AppError> { | ||
| 322 | + let course_id = CourseId::from_key(&id); | ||
| 323 | + // Course must exist — a missing course is a 404, not an empty roster. | ||
| 324 | + Course::read(&course_id, &st.db) | ||
| 325 | + .await? | ||
| 326 | + .ok_or(AppError::NotFound)?; | ||
| 327 | + let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?; | ||
| 328 | + Ok(Json( | ||
| 329 | + enrollments.iter().map(EnrollmentResponse::new).collect(), | ||
| 330 | + )) | ||
| 331 | +} | ||
| 332 | + | ||
| 333 | +/// Unenroll a user from a course. Requires teacher+ and course management | ||
| 334 | +/// rights. Existing exam results are kept (they disappear from the user's marks | ||
| 335 | +/// report until re-enrolled). | ||
| 336 | +#[utoipa::path( | ||
| 337 | + delete, | ||
| 338 | + path = "/{id}/enrollments/{user}", | ||
| 339 | + tag = "courses", | ||
| 340 | + security(("session_cookie" = [])), | ||
| 341 | + params( | ||
| 342 | + ("id" = String, Path, description = "Course id"), | ||
| 343 | + ("user" = String, Path, description = "User id"), | ||
| 344 | + ), | ||
| 345 | + responses( | ||
| 346 | + (status = 204, description = "Unenrolled"), | ||
| 347 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 348 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 349 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 350 | + ), | ||
| 351 | +)] | ||
| 352 | +async fn unenroll( | ||
| 353 | + State(st): State<AppState>, | ||
| 354 | + RequireTeacher(user): RequireTeacher, | ||
| 355 | + Path((id, target)): Path<(String, String)>, | ||
| 356 | +) -> Result<StatusCode, AppError> { | ||
| 357 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 358 | + .await? | ||
| 359 | + .ok_or(AppError::NotFound)?; | ||
| 360 | + if !can_manage_course(&course, &user) { | ||
| 361 | + return Err(AppError::Forbidden( | ||
| 362 | + "only the course creator or a manager/admin can unenroll users", | ||
| 363 | + )); | ||
| 364 | + } | ||
| 365 | + let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; | ||
| 366 | + if removed.is_none() { | ||
| 367 | + return Err(AppError::NotFound); | ||
| 368 | + } | ||
| 369 | + Ok(StatusCode::NO_CONTENT) | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +// ---- exams in a course ---------------------------------------------------- | ||
| 373 | + | ||
| 374 | +/// Create an exam inside a course. Requires teacher+ and course management | ||
| 375 | +/// rights; the exam's marks count `weight` times into the course average. | ||
| 376 | +#[utoipa::path( | ||
| 377 | + post, | ||
| 378 | + path = "/{id}/exams", | ||
| 379 | + tag = "courses", | ||
| 380 | + security(("session_cookie" = [])), | ||
| 381 | + params(("id" = String, Path, description = "Course id")), | ||
| 382 | + request_body = CreateExamInCourse, | ||
| 383 | + responses( | ||
| 384 | + (status = 201, description = "Exam created", body = ExamResponse), | ||
| 385 | + (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse), | ||
| 386 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 387 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 388 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 389 | + ), | ||
| 390 | +)] | ||
| 391 | +async fn create_exam_in_course( | ||
| 392 | + State(st): State<AppState>, | ||
| 393 | + RequireTeacher(user): RequireTeacher, | ||
| 394 | + Path(id): Path<String>, | ||
| 395 | + Json(req): Json<CreateExamInCourse>, | ||
| 396 | +) -> Result<(StatusCode, Json<ExamResponse>), AppError> { | ||
| 397 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 398 | + .await? | ||
| 399 | + .ok_or(AppError::NotFound)?; | ||
| 400 | + if !can_manage_course(&course, &user) { | ||
| 401 | + return Err(AppError::Forbidden( | ||
| 402 | + "only the course creator or a manager/admin can add exams to this course", | ||
| 403 | + )); | ||
| 404 | + } | ||
| 405 | + | ||
| 406 | + let title = ExamTitle::try_new(&req.title)?; | ||
| 407 | + let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; | ||
| 408 | + let kind = ExamKind::try_new(&req.kind)?; | ||
| 409 | + let weight = ExamWeight::try_new(req.weight)?; | ||
| 410 | + let exam = Exam::create( | ||
| 411 | + user.get_id(), | ||
| 412 | + course.get_id(), | ||
| 413 | + title, | ||
| 414 | + description, | ||
| 415 | + kind, | ||
| 416 | + weight, | ||
| 417 | + &st.db, | ||
| 418 | + ) | ||
| 419 | + .await?; | ||
| 420 | + Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +/// List a course's exams. | ||
| 424 | +#[utoipa::path( | ||
| 425 | + get, | ||
| 426 | + path = "/{id}/exams", | ||
| 427 | + tag = "courses", | ||
| 428 | + security(("session_cookie" = [])), | ||
| 429 | + params(("id" = String, Path, description = "Course id")), | ||
| 430 | + responses( | ||
| 431 | + (status = 200, description = "The course's exams", body = [ExamResponse]), | ||
| 432 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 433 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 434 | + ), | ||
| 435 | +)] | ||
| 436 | +async fn list_course_exams( | ||
| 437 | + State(st): State<AppState>, | ||
| 438 | + _user: CurrentUser, | ||
| 439 | + Path(id): Path<String>, | ||
| 440 | +) -> Result<Json<Vec<ExamResponse>>, AppError> { | ||
| 441 | + let course_id = CourseId::from_key(&id); | ||
| 442 | + // Course must exist — a missing course is a 404, not an empty exam list. | ||
| 443 | + Course::read(&course_id, &st.db) | ||
| 444 | + .await? | ||
| 445 | + .ok_or(AppError::NotFound)?; | ||
| 446 | + let exams = Exam::list_for_course(&course_id, &st.db).await?; | ||
| 447 | + Ok(Json(exams.iter().map(ExamResponse::new).collect())) | ||
| 448 | +} | ||
src/web/dto.rsmodified+52 -0
| @@ -3,6 +3,8 @@ | |||
| 3 | use serde::Serialize; | 3 | use serde::Serialize; |
| 4 | use utoipa::ToSchema; | 4 | use utoipa::ToSchema; |
| 5 | 5 | ||
| 6 | +use crate::domain::course::Course; | ||
| 7 | +use crate::domain::exam::Exam; | ||
| 6 | use crate::domain::role::Role as DomainRole; | 8 | use crate::domain::role::Role as DomainRole; |
| 7 | use crate::domain::user::User; | 9 | use crate::domain::user::User; |
| 8 | 10 | ||
| @@ -66,3 +68,53 @@ impl UserResponse { | |||
| 66 | } | 68 | } |
| 67 | } | 69 | } |
| 68 | } | 70 | } |
| 71 | + | ||
| 72 | +/// Public shape of a course. Shared by `courses` (CRUD) and `marks` (report | ||
| 73 | +/// blocks embed the course they average). | ||
| 74 | +#[derive(Serialize, ToSchema)] | ||
| 75 | +pub struct CourseResponse { | ||
| 76 | + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] | ||
| 77 | + pub id: String, | ||
| 78 | + pub creator: String, | ||
| 79 | + #[schema(example = "Algebra")] | ||
| 80 | + pub title: String, | ||
| 81 | + pub description: String, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +impl CourseResponse { | ||
| 85 | + pub fn new(course: &Course) -> Self { | ||
| 86 | + Self { | ||
| 87 | + id: course.get_id().key().to_string(), | ||
| 88 | + creator: course.get_creator().key().to_string(), | ||
| 89 | + title: course.get_title().as_str().to_string(), | ||
| 90 | + description: course.get_description().as_str().to_string(), | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` | ||
| 96 | +/// (in-course creation and listing). | ||
| 97 | +#[derive(Serialize, ToSchema)] | ||
| 98 | +pub struct ExamResponse { | ||
| 99 | + pub id: String, | ||
| 100 | + pub creator: String, | ||
| 101 | + pub course: String, | ||
| 102 | + pub title: String, | ||
| 103 | + pub description: String, | ||
| 104 | + pub kind: String, | ||
| 105 | + pub weight: i64, | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +impl ExamResponse { | ||
| 109 | + pub fn new(exam: &Exam) -> Self { | ||
| 110 | + Self { | ||
| 111 | + id: exam.get_id().key().to_string(), | ||
| 112 | + creator: exam.get_creator().key().to_string(), | ||
| 113 | + course: exam.get_course().key().to_string(), | ||
| 114 | + title: exam.get_title().as_str().to_string(), | ||
| 115 | + description: exam.get_description().as_str().to_string(), | ||
| 116 | + kind: exam.get_kind().as_str().to_string(), | ||
| 117 | + weight: exam.get_weight().as_i64(), | ||
| 118 | + } | ||
| 119 | + } | ||
| 120 | +} | ||
src/web/exams.rsmodified+73 -87
| @@ -6,39 +6,33 @@ use utoipa::ToSchema; | |||
| 6 | use utoipa_axum::router::OpenApiRouter; | 6 | use utoipa_axum::router::OpenApiRouter; |
| 7 | use utoipa_axum::routes; | 7 | use utoipa_axum::routes; |
| 8 | 8 | ||
| 9 | -use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle}; | 9 | +use crate::database::Database; |
| 10 | +use crate::domain::course::Course; | ||
| 11 | +use crate::domain::enrollment::Enrollment; | ||
| 12 | +use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle, ExamWeight}; | ||
| 10 | use crate::domain::exam_result::{ExamResult, Mark}; | 13 | use crate::domain::exam_result::{ExamResult, Mark}; |
| 11 | -use crate::domain::role::Role; | ||
| 12 | use crate::domain::user::{User, UserId}; | 14 | use crate::domain::user::{User, UserId}; |
| 13 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 15 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 14 | use crate::state::AppState; | 16 | use crate::state::AppState; |
| 15 | 17 | ||
| 16 | -use super::{CurrentUser, RequireTeacher}; | 18 | +use super::courses::can_manage_course; |
| 19 | +use super::{CurrentUser, ExamResponse, RequireTeacher}; | ||
| 17 | 20 | ||
| 18 | pub fn routes() -> OpenApiRouter<AppState> { | 21 | pub fn routes() -> OpenApiRouter<AppState> { |
| 19 | OpenApiRouter::new() | 22 | OpenApiRouter::new() |
| 20 | - .routes(routes!(create_exam, list_exams)) | 23 | + .routes(routes!(list_exams)) |
| 21 | .routes(routes!(get_exam, update_exam, delete_exam)) | 24 | .routes(routes!(get_exam, update_exam, delete_exam)) |
| 22 | .routes(routes!(grade, list_results)) | 25 | .routes(routes!(grade, list_results)) |
| 23 | .routes(routes!(my_result)) | 26 | .routes(routes!(my_result)) |
| 24 | .routes(routes!(remove_result)) | 27 | .routes(routes!(remove_result)) |
| 25 | } | 28 | } |
| 26 | 29 | ||
| 27 | -#[derive(Deserialize, ToSchema)] | ||
| 28 | -struct CreateExam { | ||
| 29 | - #[schema(example = "Chapter 3 quiz")] | ||
| 30 | - title: String, | ||
| 31 | - description: Option<String>, | ||
| 32 | - /// The assessment form: `homework` or `quiz`. | ||
| 33 | - #[schema(example = "quiz")] | ||
| 34 | - kind: String, | ||
| 35 | -} | ||
| 36 | - | ||
| 37 | #[derive(Deserialize, ToSchema)] | 30 | #[derive(Deserialize, ToSchema)] |
| 38 | struct UpdateExam { | 31 | struct UpdateExam { |
| 39 | title: Option<String>, | 32 | title: Option<String>, |
| 40 | description: Option<String>, | 33 | description: Option<String>, |
| 41 | kind: Option<String>, | 34 | kind: Option<String>, |
| 35 | + weight: Option<i64>, | ||
| 42 | } | 36 | } |
| 43 | 37 | ||
| 44 | #[derive(Deserialize, ToSchema)] | 38 | #[derive(Deserialize, ToSchema)] |
| @@ -51,27 +45,6 @@ struct GradeResult { | |||
| 51 | user_id: String, | 45 | user_id: String, |
| 52 | } | 46 | } |
| 53 | 47 | ||
| 54 | -#[derive(Serialize, ToSchema)] | ||
| 55 | -struct ExamResponse { | ||
| 56 | - id: String, | ||
| 57 | - creator: String, | ||
| 58 | - title: String, | ||
| 59 | - description: String, | ||
| 60 | - kind: String, | ||
| 61 | -} | ||
| 62 | - | ||
| 63 | -impl ExamResponse { | ||
| 64 | - fn new(exam: &Exam) -> Self { | ||
| 65 | - Self { | ||
| 66 | - id: exam.get_id().key().to_string(), | ||
| 67 | - creator: exam.get_creator().key().to_string(), | ||
| 68 | - title: exam.get_title().as_str().to_string(), | ||
| 69 | - description: exam.get_description().as_str().to_string(), | ||
| 70 | - kind: exam.get_kind().as_str().to_string(), | ||
| 71 | - } | ||
| 72 | - } | ||
| 73 | -} | ||
| 74 | - | ||
| 75 | #[derive(Serialize, ToSchema)] | 48 | #[derive(Serialize, ToSchema)] |
| 76 | struct ExamResultResponse { | 49 | struct ExamResultResponse { |
| 77 | id: String, | 50 | id: String, |
| @@ -93,39 +66,16 @@ impl ExamResultResponse { | |||
| 93 | } | 66 | } |
| 94 | } | 67 | } |
| 95 | 68 | ||
| 96 | -/// Who may edit/delete a specific exam: its creator, or anyone `manager` and | 69 | +/// The course an exam belongs to. A dangling reference means the course-delete |
| 97 | -/// above. Callers have already cleared the `teacher` bar via `RequireTeacher`. | 70 | +/// cascade was violated — surface it loudly as a 500, not a user-facing 404. |
| 98 | -fn can_manage(exam: &Exam, user: &User) -> bool { | 71 | +async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { |
| 99 | - exam.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) | 72 | + Course::read(exam.get_course(), db) |
| 73 | + .await? | ||
| 74 | + .ok_or_else(|| AppError::Internal("exam references a missing course".into())) | ||
| 100 | } | 75 | } |
| 101 | 76 | ||
| 102 | // ---- exams -------------------------------------------------------------- | 77 | // ---- exams -------------------------------------------------------------- |
| 103 | - | 78 | +// Exams are created inside a course: `POST /courses/{id}/exams`. |
| 104 | -/// Create an exam owned by the current user. Requires the `teacher` role or higher. | ||
| 105 | -#[utoipa::path( | ||
| 106 | - post, | ||
| 107 | - path = "/", | ||
| 108 | - tag = "exams", | ||
| 109 | - security(("session_cookie" = [])), | ||
| 110 | - request_body = CreateExam, | ||
| 111 | - responses( | ||
| 112 | - (status = 201, description = "Exam created", body = ExamResponse), | ||
| 113 | - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), | ||
| 114 | - (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 115 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 116 | - ), | ||
| 117 | -)] | ||
| 118 | -async fn create_exam( | ||
| 119 | - State(st): State<AppState>, | ||
| 120 | - RequireTeacher(user): RequireTeacher, | ||
| 121 | - Json(req): Json<CreateExam>, | ||
| 122 | -) -> Result<(StatusCode, Json<ExamResponse>), AppError> { | ||
| 123 | - let title = ExamTitle::try_new(&req.title)?; | ||
| 124 | - let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; | ||
| 125 | - let kind = ExamKind::try_new(&req.kind)?; | ||
| 126 | - let exam = Exam::create(user.get_id(), title, description, kind, &st.db).await?; | ||
| 127 | - Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) | ||
| 128 | -} | ||
| 129 | 79 | ||
| 130 | /// List all exams. | 80 | /// List all exams. |
| 131 | #[utoipa::path( | 81 | #[utoipa::path( |
| @@ -170,8 +120,9 @@ async fn get_exam( | |||
| 170 | Ok(Json(ExamResponse::new(&exam))) | 120 | Ok(Json(ExamResponse::new(&exam))) |
| 171 | } | 121 | } |
| 172 | 122 | ||
| 173 | -/// Update an exam. Requires teacher+; the creator may edit their own exam and | 123 | +/// Update an exam. Requires teacher+ and management rights over the exam's |
| 174 | -/// managers/admins may edit anyone's. Omitted fields keep their value. | 124 | +/// course (its creator, or manager/admin). Omitted fields keep their value; the |
| 125 | +/// course itself is not updatable. | ||
| 175 | #[utoipa::path( | 126 | #[utoipa::path( |
| 176 | patch, | 127 | patch, |
| 177 | path = "/{id}", | 128 | path = "/{id}", |
| @@ -181,9 +132,9 @@ async fn get_exam( | |||
| 181 | request_body = UpdateExam, | 132 | request_body = UpdateExam, |
| 182 | responses( | 133 | responses( |
| 183 | (status = 200, description = "Updated exam", body = ExamResponse), | 134 | (status = 200, description = "Updated exam", body = ExamResponse), |
| 184 | - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), | 135 | + (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse), |
| 185 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 136 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 186 | - (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | 137 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 187 | (status = 404, description = "Not found", body = ErrorResponse), | 138 | (status = 404, description = "Not found", body = ErrorResponse), |
| 188 | ), | 139 | ), |
| 189 | )] | 140 | )] |
| @@ -196,9 +147,10 @@ async fn update_exam( | |||
| 196 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 147 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 197 | .await? | 148 | .await? |
| 198 | .ok_or(AppError::NotFound)?; | 149 | .ok_or(AppError::NotFound)?; |
| 199 | - if !can_manage(&exam, &user) { | 150 | + let course = course_of(&exam, &st.db).await?; |
| 151 | + if !can_manage_course(&course, &user) { | ||
| 200 | return Err(AppError::Forbidden( | 152 | return Err(AppError::Forbidden( |
| 201 | - "only the creator or a manager/admin can edit this exam", | 153 | + "only the course creator or a manager/admin can edit this exam", |
| 202 | )); | 154 | )); |
| 203 | } | 155 | } |
| 204 | 156 | ||
| @@ -214,13 +166,19 @@ async fn update_exam( | |||
| 214 | Some(ref kind) => ExamKind::try_new(kind)?, | 166 | Some(ref kind) => ExamKind::try_new(kind)?, |
| 215 | None => exam.get_kind().clone(), | 167 | None => exam.get_kind().clone(), |
| 216 | }; | 168 | }; |
| 169 | + let weight = match req.weight { | ||
| 170 | + Some(weight) => ExamWeight::try_new(weight)?, | ||
| 171 | + None => exam.get_weight(), | ||
| 172 | + }; | ||
| 217 | 173 | ||
| 218 | - let updated = exam.update(title, description, kind, &st.db).await?; | 174 | + let updated = exam |
| 175 | + .update(title, description, kind, weight, &st.db) | ||
| 176 | + .await?; | ||
| 219 | Ok(Json(ExamResponse::new(&updated))) | 177 | Ok(Json(ExamResponse::new(&updated))) |
| 220 | } | 178 | } |
| 221 | 179 | ||
| 222 | -/// Delete an exam. Requires teacher+; the creator may delete their own exam and | 180 | +/// Delete an exam. Requires teacher+ and management rights over the exam's |
| 223 | -/// managers/admins may delete anyone's. Cascades the exam's result rows. | 181 | +/// course (its creator, or manager/admin). Cascades the exam's result rows. |
| 224 | #[utoipa::path( | 182 | #[utoipa::path( |
| 225 | delete, | 183 | delete, |
| 226 | path = "/{id}", | 184 | path = "/{id}", |
| @@ -230,7 +188,7 @@ async fn update_exam( | |||
| 230 | responses( | 188 | responses( |
| 231 | (status = 204, description = "Deleted"), | 189 | (status = 204, description = "Deleted"), |
| 232 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 190 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 233 | - (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), | 191 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 234 | (status = 404, description = "Not found", body = ErrorResponse), | 192 | (status = 404, description = "Not found", body = ErrorResponse), |
| 235 | ), | 193 | ), |
| 236 | )] | 194 | )] |
| @@ -242,9 +200,10 @@ async fn delete_exam( | |||
| 242 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) | 200 | let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 243 | .await? | 201 | .await? |
| 244 | .ok_or(AppError::NotFound)?; | 202 | .ok_or(AppError::NotFound)?; |
| 245 | - if !can_manage(&exam, &user) { | 203 | + let course = course_of(&exam, &st.db).await?; |
| 204 | + if !can_manage_course(&course, &user) { | ||
| 246 | return Err(AppError::Forbidden( | 205 | return Err(AppError::Forbidden( |
| 247 | - "only the creator or a manager/admin can delete this exam", | 206 | + "only the course creator or a manager/admin can delete this exam", |
| 248 | )); | 207 | )); |
| 249 | } | 208 | } |
| 250 | exam.delete(&st.db).await?; | 209 | exam.delete(&st.db).await?; |
| @@ -253,8 +212,9 @@ async fn delete_exam( | |||
| 253 | 212 | ||
| 254 | // ---- results ------------------------------------------------------------ | 213 | // ---- results ------------------------------------------------------------ |
| 255 | 214 | ||
| 256 | -/// Record (or overwrite) a student's mark for an exam. Requires teacher+. | 215 | +/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and |
| 257 | -/// Students never grade — including themselves. | 216 | +/// management rights over the exam's course; the target must be enrolled. |
| 217 | +/// Students never grade — and nobody grades themselves. | ||
| 258 | #[utoipa::path( | 218 | #[utoipa::path( |
| 259 | post, | 219 | post, |
| 260 | path = "/{id}/results", | 220 | path = "/{id}/results", |
| @@ -264,9 +224,9 @@ async fn delete_exam( | |||
| 264 | request_body = GradeResult, | 224 | request_body = GradeResult, |
| 265 | responses( | 225 | responses( |
| 266 | (status = 200, description = "Result recorded", body = ExamResultResponse), | 226 | (status = 200, description = "Result recorded", body = ExamResultResponse), |
| 267 | - (status = 400, description = "Invalid mark or unknown user", body = ErrorResponse), | 227 | + (status = 400, description = "Invalid mark, unknown user, or user not enrolled", body = ErrorResponse), |
| 268 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 228 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 269 | - (status = 403, description = "Requires teacher role or higher, or attempted to grade yourself", body = ErrorResponse), | 229 | + (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 270 | (status = 404, description = "Exam not found", body = ErrorResponse), | 230 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 271 | ), | 231 | ), |
| 272 | )] | 232 | )] |
| @@ -278,9 +238,15 @@ async fn grade( | |||
| 278 | ) -> Result<Json<ExamResultResponse>, AppError> { | 238 | ) -> Result<Json<ExamResultResponse>, AppError> { |
| 279 | let exam_id = ExamId::from_key(&id); | 239 | let exam_id = ExamId::from_key(&id); |
| 280 | // Exam must exist. | 240 | // Exam must exist. |
| 281 | - Exam::read(&exam_id, &st.db) | 241 | + let exam = Exam::read(&exam_id, &st.db) |
| 282 | .await? | 242 | .await? |
| 283 | .ok_or(AppError::NotFound)?; | 243 | .ok_or(AppError::NotFound)?; |
| 244 | + let course = course_of(&exam, &st.db).await?; | ||
| 245 | + if !can_manage_course(&course, &teacher) { | ||
| 246 | + return Err(AppError::Forbidden( | ||
| 247 | + "only the course creator or a manager/admin can grade this exam", | ||
| 248 | + )); | ||
| 249 | + } | ||
| 284 | 250 | ||
| 285 | let mark = Mark::try_new(req.mark)?; | 251 | let mark = Mark::try_new(req.mark)?; |
| 286 | let target = UserId::from_key(&req.user_id); | 252 | let target = UserId::from_key(&req.user_id); |
| @@ -299,6 +265,17 @@ async fn grade( | |||
| 299 | })); | 265 | })); |
| 300 | } | 266 | } |
| 301 | 267 | ||
| 268 | + // ... and be enrolled in the exam's course. | ||
| 269 | + if Enrollment::read_for_user(exam.get_course(), &target, &st.db) | ||
| 270 | + .await? | ||
| 271 | + .is_none() | ||
| 272 | + { | ||
| 273 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 274 | + field: "user_id", | ||
| 275 | + reason: "target user is not enrolled in this course", | ||
| 276 | + })); | ||
| 277 | + } | ||
| 278 | + | ||
| 302 | let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?; | 279 | let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?; |
| 303 | Ok(Json(ExamResultResponse::new(&result))) | 280 | Ok(Json(ExamResultResponse::new(&result))) |
| 304 | } | 281 | } |
| @@ -357,7 +334,8 @@ async fn my_result( | |||
| 357 | Ok(Json(ExamResultResponse::new(&result))) | 334 | Ok(Json(ExamResultResponse::new(&result))) |
| 358 | } | 335 | } |
| 359 | 336 | ||
| 360 | -/// Remove a student's result from an exam. Requires teacher+. | 337 | +/// Remove a student's result from an exam. Requires teacher+ and management |
| 338 | +/// rights over the exam's course. | ||
| 361 | #[utoipa::path( | 339 | #[utoipa::path( |
| 362 | delete, | 340 | delete, |
| 363 | path = "/{id}/results/{user}", | 341 | path = "/{id}/results/{user}", |
| @@ -370,17 +348,25 @@ async fn my_result( | |||
| 370 | responses( | 348 | responses( |
| 371 | (status = 204, description = "Removed"), | 349 | (status = 204, description = "Removed"), |
| 372 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 350 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 373 | - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | 351 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 374 | (status = 404, description = "Not found", body = ErrorResponse), | 352 | (status = 404, description = "Not found", body = ErrorResponse), |
| 375 | ), | 353 | ), |
| 376 | )] | 354 | )] |
| 377 | async fn remove_result( | 355 | async fn remove_result( |
| 378 | State(st): State<AppState>, | 356 | State(st): State<AppState>, |
| 379 | - _teacher: RequireTeacher, | 357 | + RequireTeacher(user): RequireTeacher, |
| 380 | Path((id, target)): Path<(String, String)>, | 358 | Path((id, target)): Path<(String, String)>, |
| 381 | ) -> Result<StatusCode, AppError> { | 359 | ) -> Result<StatusCode, AppError> { |
| 382 | - let removed = | 360 | + let exam = Exam::read(&ExamId::from_key(&id), &st.db) |
| 383 | - ExamResult::remove(&ExamId::from_key(&id), &UserId::from_key(&target), &st.db).await?; | 361 | + .await? |
| 362 | + .ok_or(AppError::NotFound)?; | ||
| 363 | + let course = course_of(&exam, &st.db).await?; | ||
| 364 | + if !can_manage_course(&course, &user) { | ||
| 365 | + return Err(AppError::Forbidden( | ||
| 366 | + "only the course creator or a manager/admin can remove results", | ||
| 367 | + )); | ||
| 368 | + } | ||
| 369 | + let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?; | ||
| 384 | if removed.is_none() { | 370 | if removed.is_none() { |
| 385 | return Err(AppError::NotFound); | 371 | return Err(AppError::NotFound); |
| 386 | } | 372 | } |
src/web/mod.rsmodified+2 -1
| @@ -4,6 +4,7 @@ | |||
| 4 | //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. | 4 | //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. |
| 5 | 5 | ||
| 6 | pub mod auth; | 6 | pub mod auth; |
| 7 | +pub mod courses; | ||
| 7 | pub mod events; | 8 | pub mod events; |
| 8 | pub mod exams; | 9 | pub mod exams; |
| 9 | pub mod notes; | 10 | pub mod notes; |
| @@ -12,5 +13,5 @@ pub mod users; | |||
| 12 | mod dto; | 13 | mod dto; |
| 13 | mod extractor; | 14 | mod extractor; |
| 14 | 15 | ||
| 15 | -pub use dto::UserResponse; | 16 | +pub use dto::{CourseResponse, ExamResponse, UserResponse}; |
| 16 | pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; | 17 | pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; |