From cd56c5b413414e49bb4283297c66047f2acad586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 02:21:02 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(courses):=20courses,=20enrollm?= =?UTF-8?q?ent,=20and=20course-scoped=20weighted=20exams?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Courses become the unit exams and enrollments hang off. Teachers create them; editing, deleting, enrolling, and adding exams require course management rights (creator, or manager/admin). Enrollment rows use a deterministic composite (course, user) id, so enrolling is one atomic idempotent UPSERT with no find-then-insert race. Deleting a course cascades its exams, their results, and enrollments in one transaction. Exams move inside a course (POST /courses/{id}/exams) and gain a weight (1-100) that says how many times they count into the course average; kinds grow to homework, quiz, midterm, final, project, and oral — informational only, weight drives the math. Grading now demands course management rights and an enrolled target; moving an exam between courses is deliberately impossible so results can't be stranded. Routes: courses CRUD, GET /courses/me for the caller's enrollments, roster listing, enroll/unenroll, and per-course exam creation/listing. --- src/constant.rs | 13 +- src/database.rs | 17 ++ src/domain/course.rs | 183 ++++++++++++++++ src/domain/enrollment.rs | 125 +++++++++++ src/domain/exam.rs | 63 +++++- src/domain/mod.rs | 2 + src/lib.rs | 4 +- src/validate.rs | 32 ++- src/web/courses.rs | 448 +++++++++++++++++++++++++++++++++++++++ src/web/dto.rs | 52 +++++ src/web/exams.rs | 160 +++++++------- src/web/mod.rs | 3 +- 12 files changed, 1001 insertions(+), 101 deletions(-) create mode 100644 src/domain/course.rs create mode 100644 src/domain/enrollment.rs create mode 100644 src/web/courses.rs diff --git a/src/constant.rs b/src/constant.rs index df8010b..4b953d9 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -24,14 +24,23 @@ pub const MAX_EVENT_DESCRIPTION_LEN: usize = 2_000; pub const MAX_EXAM_TITLE_LEN: usize = 200; pub const MAX_EXAM_DESCRIPTION_LEN: usize = 2_000; +pub const MAX_COURSE_TITLE_LEN: usize = 200; +pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; + /// The only accepted attendance states. pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; -/// The only accepted exam kinds — an exam is a homework or a quiz, nothing else. -pub const EXAM_KINDS: [&str; 2] = ["homework", "quiz"]; +/// The only accepted exam kinds. Informational metadata only — `weight` drives +/// the course average. +pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; /// Inclusive bounds for an exam mark. pub const MIN_MARK: i64 = 0; pub const MAX_MARK: i64 = 100; +/// Inclusive bounds for an exam's weight in the course average. The minimum of +/// 1 keeps every graded exam counted and the average's denominator non-zero. +pub const MIN_EXAM_WEIGHT: i64 = 1; +pub const MAX_EXAM_WEIGHT: i64 = 100; + pub const SESSION_DURATION_DAYS: i64 = 7; diff --git a/src/database.rs b/src/database.rs index ace23f6..0b7e70f 100644 --- a/src/database.rs +++ b/src/database.rs @@ -15,6 +15,8 @@ pub const EVENT_TABLE: &str = "event"; pub const ATTENDANCE_TABLE: &str = "attendance"; pub const EXAM_TABLE: &str = "exam"; pub const EXAM_RESULT_TABLE: &str = "exam_result"; +pub const COURSE_TABLE: &str = "course"; +pub const ENROLLMENT_TABLE: &str = "enrollment"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot. @@ -58,11 +60,26 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record; DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; + DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; + DEFINE FIELD IF NOT EXISTS title ON course TYPE string; + DEFINE FIELD IF NOT EXISTS description ON course TYPE string; + + DEFINE TABLE IF NOT EXISTS enrollment SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON enrollment TYPE record; + DEFINE FIELD IF NOT EXISTS user ON enrollment TYPE record; + DEFINE FIELD IF NOT EXISTS enrolled_by ON enrollment TYPE record; + DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; + DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; + DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; + DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; DEFINE FIELD IF NOT EXISTS title ON exam TYPE string; DEFINE FIELD IF NOT EXISTS description ON exam TYPE string; DEFINE FIELD IF NOT EXISTS kind ON exam TYPE string; + DEFINE FIELD IF NOT EXISTS weight ON exam TYPE int; + DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course; DEFINE TABLE IF NOT EXISTS exam_result SCHEMAFULL; DEFINE FIELD IF NOT EXISTS exam ON exam_result TYPE record; diff --git a/src/domain/course.rs b/src/domain/course.rs new file mode 100644 index 0000000..2123006 --- /dev/null +++ b/src/domain/course.rs @@ -0,0 +1,183 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::{MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; +use crate::database::{COURSE_TABLE, Database}; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::{validate_optional, validate_required}; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct CourseId(RecordId); + +impl CourseId { + pub fn generate() -> Self { + Self(RecordId::new(COURSE_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(COURSE_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct CourseTitle(String); + +impl CourseTitle { + pub fn try_new(value: &str) -> Result { + validate_required("title", value, MAX_COURSE_TITLE_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct CourseDescription(String); + +impl CourseDescription { + pub fn try_new(value: &str) -> Result { + validate_optional("description", value, MAX_COURSE_DESCRIPTION_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// A course: the unit exams and enrollments hang off. Marks are computed per +/// course from its exams' weights. +#[derive(Debug, Clone, SurrealValue)] +pub struct Course { + id: CourseId, + creator: UserId, + title: CourseTitle, + description: CourseDescription, +} + +impl Course { + pub fn get_id(&self) -> &CourseId { + &self.id + } + + pub fn get_creator(&self) -> &UserId { + &self.creator + } + + pub fn get_title(&self) -> &CourseTitle { + &self.title + } + + pub fn get_description(&self) -> &CourseDescription { + &self.description + } + + pub fn is_creator(&self, user: &UserId) -> bool { + &self.creator == user + } + + pub async fn create( + creator: &UserId, + title: CourseTitle, + description: CourseDescription, + db: &Database, + ) -> Result { + let course = Course { + id: CourseId::generate(), + creator: creator.clone(), + title, + description, + }; + let created: Option = db.create(course.id.record()).content(course).await?; + created.ok_or_else(|| AppError::Internal("failed to create course".into())) + } + + pub async fn read(id: &CourseId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM course ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// The courses `user` is enrolled in — the spine of `/courses/me` and the + /// marks report. + pub async fn list_enrolled(user: &UserId, db: &Database) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM course + WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr) + ORDER BY id DESC", + ) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + title: CourseTitle, + description: CourseDescription, + db: &Database, + ) -> Result { + self.title = title; + self.description = description; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the course and cascade-remove everything inside it: results of + /// its exams, its enrollments, and the exams themselves. The children go in + /// one transaction so a crash can't leave an exam pointing at a deleted + /// course. + pub async fn delete(self, db: &Database) -> Result { + db.query( + "BEGIN TRANSACTION; + DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE enrollment WHERE course = $course; + DELETE exam WHERE course = $course; + COMMIT TRANSACTION;", + ) + .bind(("course", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn title_is_required() { + assert!(CourseTitle::try_new("algebra").is_ok()); + assert!(CourseTitle::try_new("").is_err()); + assert!(CourseTitle::try_new(" ").is_err()); + } + + #[tokio::test] + async fn description_is_optional() { + assert!(CourseDescription::try_new("").is_ok()); + } +} diff --git a/src/domain/enrollment.rs b/src/domain/enrollment.rs new file mode 100644 index 0000000..7a0641a --- /dev/null +++ b/src/domain/enrollment.rs @@ -0,0 +1,125 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, ENROLLMENT_TABLE}; +use crate::domain::course::CourseId; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct EnrollmentId(RecordId); + +impl EnrollmentId { + /// A deterministic id for the (course, user) pair. The same pair always + /// maps to the same record id, so enrolling is a single atomic UPSERT with + /// no find-then-insert race and one-row-per-pair by construction. ULID keys + /// are alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(course: &CourseId, user: &UserId) -> Self { + Self(RecordId::new( + ENROLLMENT_TABLE, + format!("{}_{}", course.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// A user's membership in a course. Grading requires it; removing it hides the +/// user's marks from the report but never deletes result rows. +#[derive(Debug, Clone, SurrealValue)] +pub struct Enrollment { + id: EnrollmentId, + course: CourseId, + user: UserId, + enrolled_by: UserId, +} + +impl Enrollment { + pub fn get_id(&self) -> &EnrollmentId { + &self.id + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_enrolled_by(&self) -> &UserId { + &self.enrolled_by + } + + /// Enroll (idempotently) `user` into `course`. One row per (course, user), + /// keyed by a deterministic composite id so this is a single atomic UPSERT — + /// concurrent enrolls for the same pair converge on one row instead of + /// racing the unique index into a 500. + pub async fn enroll( + course: &CourseId, + user: &UserId, + enrolled_by: &UserId, + db: &Database, + ) -> Result { + let enrollment = Enrollment { + id: EnrollmentId::composite(course, user), + course: course.clone(), + user: user.clone(), + enrolled_by: enrolled_by.clone(), + }; + let saved: Option = db + .upsert(enrollment.id.record()) + .content(enrollment) + .await?; + saved.ok_or_else(|| AppError::Internal("failed to enroll user".into())) + } + + /// Some(_) iff `user` is enrolled in `course` — the grading gate. + pub async fn read_for_user( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM enrollment WHERE course = $course AND user = $usr LIMIT 1") + .bind(("course", course.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } + + pub async fn list_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM enrollment WHERE course = $course ORDER BY id DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn remove( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE enrollment WHERE course = $course AND user = $usr RETURN BEFORE") + .bind(("course", course.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 09e1710..24112a4 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -3,9 +3,10 @@ use ulid::Ulid; use crate::constant::{MAX_EXAM_DESCRIPTION_LEN, MAX_EXAM_TITLE_LEN}; use crate::database::{Database, EXAM_TABLE}; +use crate::domain::course::CourseId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -use crate::validate::{validate_exam_kind, validate_optional, validate_required}; +use crate::validate::{validate_exam_kind, validate_optional, validate_required, validate_weight}; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamId(RecordId); @@ -59,8 +60,9 @@ impl ExamDescription { } } -/// A validated exam kind: `homework` | `quiz`. An exam is never a graded course -/// mark — only one of these two assessment forms. +/// A validated exam kind: `homework` | `quiz` | `midterm` | `final` | +/// `project` | `oral`. Informational metadata only — `weight` drives the +/// course average. #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct ExamKind(String); @@ -75,13 +77,31 @@ impl ExamKind { } } +/// A validated exam weight, held to `[MIN_EXAM_WEIGHT, MAX_EXAM_WEIGHT]`. The +/// exam counts `weight` times into its course's average. +#[derive(Debug, Clone, Copy, PartialEq, Eq, SurrealValue)] +pub struct ExamWeight(i64); + +impl ExamWeight { + pub fn try_new(value: i64) -> Result { + validate_weight(value)?; + Ok(Self(value)) + } + + pub fn as_i64(&self) -> i64 { + self.0 + } +} + #[derive(Debug, Clone, SurrealValue)] pub struct Exam { id: ExamId, creator: UserId, + course: CourseId, title: ExamTitle, description: ExamDescription, kind: ExamKind, + weight: ExamWeight, } impl Exam { @@ -93,6 +113,10 @@ impl Exam { &self.creator } + pub fn get_course(&self) -> &CourseId { + &self.course + } + pub fn get_title(&self) -> &ExamTitle { &self.title } @@ -105,23 +129,31 @@ impl Exam { &self.kind } + pub fn get_weight(&self) -> ExamWeight { + self.weight + } + pub fn is_creator(&self, user: &UserId) -> bool { &self.creator == user } pub async fn create( creator: &UserId, + course: &CourseId, title: ExamTitle, description: ExamDescription, kind: ExamKind, + weight: ExamWeight, db: &Database, ) -> Result { let exam = Exam { id: ExamId::generate(), creator: creator.clone(), + course: course.clone(), title, description, kind, + weight, }; let created: Option = db.create(exam.id.record()).content(exam).await?; created.ok_or_else(|| AppError::Internal("failed to create exam".into())) @@ -139,16 +171,29 @@ impl Exam { Ok(result.take::>(0)?) } + pub async fn list_for_course(course: &CourseId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM exam WHERE course = $course ORDER BY id DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + // `course` is deliberately not updatable — moving an exam between courses + // would strand results of students not enrolled in the target course. pub async fn update( mut self, title: ExamTitle, description: ExamDescription, kind: ExamKind, + weight: ExamWeight, db: &Database, ) -> Result { self.title = title; self.description = description; self.kind = kind; + self.weight = weight; let updated: Option = db.update(self.id.record()).content(self).await?; updated.ok_or(AppError::NotFound) } @@ -182,10 +227,18 @@ mod tests { #[tokio::test] async fn kind_must_be_known() { - for kind in ["homework", "quiz"] { + for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { assert_eq!(ExamKind::try_new(kind).unwrap().as_str(), kind); } - assert!(ExamKind::try_new("final").is_err()); + assert!(ExamKind::try_new("essay").is_err()); assert!(ExamKind::try_new("").is_err()); } + + #[tokio::test] + async fn weight_range_is_enforced() { + assert_eq!(ExamWeight::try_new(1).unwrap().as_i64(), 1); + assert_eq!(ExamWeight::try_new(100).unwrap().as_i64(), 100); + assert!(ExamWeight::try_new(0).is_err()); + assert!(ExamWeight::try_new(101).is_err()); + } } diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 23e00ca..38ca4a3 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -3,6 +3,8 @@ //! same typed value flows from HTTP input all the way into the database. pub mod attendance; +pub mod course; +pub mod enrollment; pub mod event; pub mod exam; pub mod exam_result; diff --git a/src/lib.rs b/src/lib.rs index e38d5eb..a9c85de 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,8 @@ use crate::state::AppState; (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), (name = "notes", description = "Per-user notes CRUD"), (name = "events", description = "Events and attendance"), - (name = "exams", description = "Exams (homework/quiz) and student results"), + (name = "courses", description = "Courses, enrollment, and course exams"), + (name = "exams", description = "Exams (per course, weighted) and student results"), ), )] struct ApiDoc; @@ -73,6 +74,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/users", web::users::routes()) .nest("/notes", web::notes::routes()) .nest("/events", web::events::routes()) + .nest("/courses", web::courses::routes()) .nest("/exams", web::exams::routes()) .split_for_parts(); diff --git a/src/validate.rs b/src/validate.rs index f88022e..2d9de5b 100644 --- a/src/validate.rs +++ b/src/validate.rs @@ -2,8 +2,9 @@ //! the value, so an existing newtype is always valid (parse, don't validate). use crate::constant::{ - ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_MARK, MAX_PASSWORD_LEN, MAX_PHONE_DIGITS, - MAX_USERNAME_LEN, MIN_MARK, MIN_PASSWORD_LEN, MIN_PHONE_DIGITS, MIN_USERNAME_LEN, + ATTENDANCE_STATUSES, EXAM_KINDS, MAX_EMAIL_LEN, MAX_EXAM_WEIGHT, MAX_MARK, MAX_PASSWORD_LEN, + MAX_PHONE_DIGITS, MAX_USERNAME_LEN, MIN_EXAM_WEIGHT, MIN_MARK, MIN_PASSWORD_LEN, + MIN_PHONE_DIGITS, MIN_USERNAME_LEN, }; use crate::error::ValidationError; @@ -173,7 +174,7 @@ pub fn validate_exam_kind(value: &str) -> Result<(), ValidationError> { } else { Err(ValidationError::Invalid { field: "kind", - reason: "must be one of: homework, quiz", + reason: "must be one of: homework, quiz, midterm, final, project, oral", }) } } @@ -189,6 +190,17 @@ pub fn validate_mark(value: i64) -> Result<(), ValidationError> { } } +pub fn validate_weight(value: i64) -> Result<(), ValidationError> { + if (MIN_EXAM_WEIGHT..=MAX_EXAM_WEIGHT).contains(&value) { + Ok(()) + } else { + Err(ValidationError::Invalid { + field: "weight", + reason: "must be between 1 and 100", + }) + } +} + #[cfg(test)] mod tests { use super::*; @@ -275,10 +287,10 @@ mod tests { #[tokio::test] async fn exam_kind_rules() { - for kind in ["homework", "quiz"] { + for kind in ["homework", "quiz", "midterm", "final", "project", "oral"] { assert!(validate_exam_kind(kind).is_ok()); } - assert!(validate_exam_kind("final").is_err()); + assert!(validate_exam_kind("essay").is_err()); assert!(validate_exam_kind("").is_err()); } @@ -290,4 +302,14 @@ mod tests { assert!(validate_mark(-1).is_err()); assert!(validate_mark(101).is_err()); } + + #[tokio::test] + async fn weight_rules() { + for weight in [1, 50, 100] { + assert!(validate_weight(weight).is_ok()); + } + assert!(validate_weight(0).is_err()); + assert!(validate_weight(-1).is_err()); + assert!(validate_weight(101).is_err()); + } } diff --git a/src/web/courses.rs b/src/web/courses.rs new file mode 100644 index 0000000..91677e8 --- /dev/null +++ b/src/web/courses.rs @@ -0,0 +1,448 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; +use crate::domain::enrollment::Enrollment; +use crate::domain::exam::{Exam, ExamDescription, ExamKind, ExamTitle, ExamWeight}; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{CourseResponse, CurrentUser, ExamResponse, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(create_course, list_courses)) + .routes(routes!(my_courses)) + .routes(routes!(get_course, update_course, delete_course)) + .routes(routes!(enroll, list_roster)) + .routes(routes!(unenroll)) + .routes(routes!(create_exam_in_course, list_course_exams)) +} + +#[derive(Deserialize, ToSchema)] +struct CreateCourse { + #[schema(example = "Algebra")] + title: String, + description: Option, +} + +#[derive(Deserialize, ToSchema)] +struct UpdateCourse { + title: Option, + description: Option, +} + +#[derive(Deserialize, ToSchema)] +struct EnrollUser { + /// The user to enroll. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + user_id: String, +} + +#[derive(Deserialize, ToSchema)] +struct CreateExamInCourse { + #[schema(example = "Midterm")] + title: String, + description: Option, + /// The assessment form: `homework`, `quiz`, `midterm`, `final`, `project`, + /// or `oral`. Informational — `weight` drives the course average. + #[schema(example = "midterm")] + kind: String, + /// How many times this exam counts into the course average, `1`–`100`. + #[schema(example = 3)] + weight: i64, +} + +#[derive(Serialize, ToSchema)] +struct EnrollmentResponse { + id: String, + course: String, + user: String, + enrolled_by: String, +} + +impl EnrollmentResponse { + fn new(enrollment: &Enrollment) -> Self { + Self { + id: enrollment.get_id().key().to_string(), + course: enrollment.get_course().key().to_string(), + user: enrollment.get_user().key().to_string(), + enrolled_by: enrollment.get_enrolled_by().key().to_string(), + } + } +} + +/// Who may write inside a specific course (edit/delete it, enroll, add exams, +/// grade): its creator, or anyone `manager` and above. Callers have already +/// cleared the `teacher` bar via `RequireTeacher`. +pub(crate) fn can_manage_course(course: &Course, user: &User) -> bool { + course.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) +} + +// ---- courses ------------------------------------------------------------ + +/// Create a course owned by the current user. Requires the `teacher` role or higher. +#[utoipa::path( + post, + path = "/", + tag = "courses", + security(("session_cookie" = [])), + request_body = CreateCourse, + responses( + (status = 201, description = "Course created", body = CourseResponse), + (status = 400, description = "Invalid fields", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn create_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let title = CourseTitle::try_new(&req.title)?; + let description = CourseDescription::try_new(&req.description.unwrap_or_default())?; + let course = Course::create(user.get_id(), title, description, &st.db).await?; + Ok((StatusCode::CREATED, Json(CourseResponse::new(&course)))) +} + +/// List all courses. +#[utoipa::path( + get, + path = "/", + tag = "courses", + security(("session_cookie" = [])), + responses( + (status = 200, description = "All courses", body = [CourseResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_courses( + State(st): State, + _user: CurrentUser, +) -> Result>, AppError> { + let courses = Course::list_all(&st.db).await?; + Ok(Json(courses.iter().map(CourseResponse::new).collect())) +} + +/// The courses the current user is enrolled in. +#[utoipa::path( + get, + path = "/me", + tag = "courses", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's enrolled courses", body = [CourseResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_courses( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result>, AppError> { + let courses = Course::list_enrolled(user.get_id(), &st.db).await?; + Ok(Json(courses.iter().map(CourseResponse::new).collect())) +} + +/// Fetch a single course by id. +#[utoipa::path( + get, + path = "/{id}", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + responses( + (status = 200, description = "The course", body = CourseResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_course( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(CourseResponse::new(&course))) +} + +/// Update a course. Requires teacher+; the creator may edit their own course +/// and managers/admins may edit anyone's. Omitted fields keep their value. +#[utoipa::path( + patch, + path = "/{id}", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = UpdateCourse, + responses( + (status = 200, description = "Updated course", body = CourseResponse), + (status = 400, description = "Invalid fields", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can edit this course", + )); + } + + let title = match req.title { + Some(ref title) => CourseTitle::try_new(title)?, + None => course.get_title().clone(), + }; + let description = match req.description { + Some(ref description) => CourseDescription::try_new(description)?, + None => course.get_description().clone(), + }; + + let updated = course.update(title, description, &st.db).await?; + Ok(Json(CourseResponse::new(&updated))) +} + +/// Delete a course. Requires teacher+; the creator may delete their own course +/// and managers/admins may delete anyone's. Cascades the course's exams, their +/// results, and all enrollments. +#[utoipa::path( + delete, + path = "/{id}", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can delete this course", + )); + } + course.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- enrollments ---------------------------------------------------------- + +/// Enroll a user into a course (idempotent upsert). Requires teacher+ and +/// course management rights. +#[utoipa::path( + post, + path = "/{id}/enrollments", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = EnrollUser, + responses( + (status = 200, description = "Enrolled (or already enrolled)", body = EnrollmentResponse), + (status = 400, description = "Unknown user", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn enroll( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can enroll users", + )); + } + + let target = UserId::from_key(&req.user_id); + if User::read(&target, &st.db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + } + + let enrollment = Enrollment::enroll(course.get_id(), &target, user.get_id(), &st.db).await?; + Ok(Json(EnrollmentResponse::new(&enrollment))) +} + +/// List a course's roster. Requires teacher+ — students see their own courses +/// via `GET /courses/me`. +#[utoipa::path( + get, + path = "/{id}/enrollments", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + responses( + (status = 200, description = "All enrollments", body = [EnrollmentResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn list_roster( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, +) -> Result>, AppError> { + let course_id = CourseId::from_key(&id); + // Course must exist — a missing course is a 404, not an empty roster. + Course::read(&course_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let enrollments = Enrollment::list_for_course(&course_id, &st.db).await?; + Ok(Json( + enrollments.iter().map(EnrollmentResponse::new).collect(), + )) +} + +/// Unenroll a user from a course. Requires teacher+ and course management +/// rights. Existing exam results are kept (they disappear from the user's marks +/// report until re-enrolled). +#[utoipa::path( + delete, + path = "/{id}/enrollments/{user}", + tag = "courses", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Course id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Unenrolled"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn unenroll( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can unenroll users", + )); + } + let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} + +// ---- exams in a course ---------------------------------------------------- + +/// Create an exam inside a course. Requires teacher+ and course management +/// rights; the exam's marks count `weight` times into the course average. +#[utoipa::path( + post, + path = "/{id}/exams", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = CreateExamInCourse, + responses( + (status = 201, description = "Exam created", body = ExamResponse), + (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn create_exam_in_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can add exams to this course", + )); + } + + let title = ExamTitle::try_new(&req.title)?; + let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; + let kind = ExamKind::try_new(&req.kind)?; + let weight = ExamWeight::try_new(req.weight)?; + let exam = Exam::create( + user.get_id(), + course.get_id(), + title, + description, + kind, + weight, + &st.db, + ) + .await?; + Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) +} + +/// List a course's exams. +#[utoipa::path( + get, + path = "/{id}/exams", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + responses( + (status = 200, description = "The course's exams", body = [ExamResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn list_course_exams( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let course_id = CourseId::from_key(&id); + // Course must exist — a missing course is a 404, not an empty exam list. + Course::read(&course_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let exams = Exam::list_for_course(&course_id, &st.db).await?; + Ok(Json(exams.iter().map(ExamResponse::new).collect())) +} diff --git a/src/web/dto.rs b/src/web/dto.rs index 70181ea..40e3463 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -3,6 +3,8 @@ use serde::Serialize; use utoipa::ToSchema; +use crate::domain::course::Course; +use crate::domain::exam::Exam; use crate::domain::role::Role as DomainRole; use crate::domain::user::User; @@ -66,3 +68,53 @@ impl UserResponse { } } } + +/// Public shape of a course. Shared by `courses` (CRUD) and `marks` (report +/// blocks embed the course they average). +#[derive(Serialize, ToSchema)] +pub struct CourseResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + pub id: String, + pub creator: String, + #[schema(example = "Algebra")] + pub title: String, + pub description: String, +} + +impl CourseResponse { + pub fn new(course: &Course) -> Self { + Self { + id: course.get_id().key().to_string(), + creator: course.get_creator().key().to_string(), + title: course.get_title().as_str().to_string(), + description: course.get_description().as_str().to_string(), + } + } +} + +/// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` +/// (in-course creation and listing). +#[derive(Serialize, ToSchema)] +pub struct ExamResponse { + pub id: String, + pub creator: String, + pub course: String, + pub title: String, + pub description: String, + pub kind: String, + pub weight: i64, +} + +impl ExamResponse { + pub fn new(exam: &Exam) -> Self { + Self { + id: exam.get_id().key().to_string(), + creator: exam.get_creator().key().to_string(), + course: exam.get_course().key().to_string(), + title: exam.get_title().as_str().to_string(), + description: exam.get_description().as_str().to_string(), + kind: exam.get_kind().as_str().to_string(), + weight: exam.get_weight().as_i64(), + } + } +} diff --git a/src/web/exams.rs b/src/web/exams.rs index 137a578..149195a 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -6,39 +6,33 @@ use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle}; +use crate::database::Database; +use crate::domain::course::Course; +use crate::domain::enrollment::Enrollment; +use crate::domain::exam::{Exam, ExamDescription, ExamId, ExamKind, ExamTitle, ExamWeight}; use crate::domain::exam_result::{ExamResult, Mark}; -use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, RequireTeacher}; +use super::courses::can_manage_course; +use super::{CurrentUser, ExamResponse, RequireTeacher}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() - .routes(routes!(create_exam, list_exams)) + .routes(routes!(list_exams)) .routes(routes!(get_exam, update_exam, delete_exam)) .routes(routes!(grade, list_results)) .routes(routes!(my_result)) .routes(routes!(remove_result)) } -#[derive(Deserialize, ToSchema)] -struct CreateExam { - #[schema(example = "Chapter 3 quiz")] - title: String, - description: Option, - /// The assessment form: `homework` or `quiz`. - #[schema(example = "quiz")] - kind: String, -} - #[derive(Deserialize, ToSchema)] struct UpdateExam { title: Option, description: Option, kind: Option, + weight: Option, } #[derive(Deserialize, ToSchema)] @@ -51,27 +45,6 @@ struct GradeResult { user_id: String, } -#[derive(Serialize, ToSchema)] -struct ExamResponse { - id: String, - creator: String, - title: String, - description: String, - kind: String, -} - -impl ExamResponse { - fn new(exam: &Exam) -> Self { - Self { - id: exam.get_id().key().to_string(), - creator: exam.get_creator().key().to_string(), - title: exam.get_title().as_str().to_string(), - description: exam.get_description().as_str().to_string(), - kind: exam.get_kind().as_str().to_string(), - } - } -} - #[derive(Serialize, ToSchema)] struct ExamResultResponse { id: String, @@ -93,39 +66,16 @@ impl ExamResultResponse { } } -/// Who may edit/delete a specific exam: its creator, or anyone `manager` and -/// above. Callers have already cleared the `teacher` bar via `RequireTeacher`. -fn can_manage(exam: &Exam, user: &User) -> bool { - exam.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) +/// The course an exam belongs to. A dangling reference means the course-delete +/// cascade was violated — surface it loudly as a 500, not a user-facing 404. +async fn course_of(exam: &Exam, db: &Database) -> Result { + Course::read(exam.get_course(), db) + .await? + .ok_or_else(|| AppError::Internal("exam references a missing course".into())) } // ---- exams -------------------------------------------------------------- - -/// Create an exam owned by the current user. Requires the `teacher` role or higher. -#[utoipa::path( - post, - path = "/", - tag = "exams", - security(("session_cookie" = [])), - request_body = CreateExam, - responses( - (status = 201, description = "Exam created", body = ExamResponse), - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), - (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), - ), -)] -async fn create_exam( - State(st): State, - RequireTeacher(user): RequireTeacher, - Json(req): Json, -) -> Result<(StatusCode, Json), AppError> { - let title = ExamTitle::try_new(&req.title)?; - let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; - let kind = ExamKind::try_new(&req.kind)?; - let exam = Exam::create(user.get_id(), title, description, kind, &st.db).await?; - Ok((StatusCode::CREATED, Json(ExamResponse::new(&exam)))) -} +// Exams are created inside a course: `POST /courses/{id}/exams`. /// List all exams. #[utoipa::path( @@ -170,8 +120,9 @@ async fn get_exam( Ok(Json(ExamResponse::new(&exam))) } -/// Update an exam. Requires teacher+; the creator may edit their own exam and -/// managers/admins may edit anyone's. Omitted fields keep their value. +/// Update an exam. Requires teacher+ and management rights over the exam's +/// course (its creator, or manager/admin). Omitted fields keep their value; the +/// course itself is not updatable. #[utoipa::path( patch, path = "/{id}", @@ -181,9 +132,9 @@ async fn get_exam( request_body = UpdateExam, responses( (status = 200, description = "Updated exam", body = ExamResponse), - (status = 400, description = "Invalid fields or kind", body = ErrorResponse), + (status = 400, description = "Invalid fields, kind, or weight", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] @@ -196,9 +147,10 @@ async fn update_exam( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - if !can_manage(&exam, &user) { + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( - "only the creator or a manager/admin can edit this exam", + "only the course creator or a manager/admin can edit this exam", )); } @@ -214,13 +166,19 @@ async fn update_exam( Some(ref kind) => ExamKind::try_new(kind)?, None => exam.get_kind().clone(), }; + let weight = match req.weight { + Some(weight) => ExamWeight::try_new(weight)?, + None => exam.get_weight(), + }; - let updated = exam.update(title, description, kind, &st.db).await?; + let updated = exam + .update(title, description, kind, weight, &st.db) + .await?; Ok(Json(ExamResponse::new(&updated))) } -/// Delete an exam. Requires teacher+; the creator may delete their own exam and -/// managers/admins may delete anyone's. Cascades the exam's result rows. +/// Delete an exam. Requires teacher+ and management rights over the exam's +/// course (its creator, or manager/admin). Cascades the exam's result rows. #[utoipa::path( delete, path = "/{id}", @@ -230,7 +188,7 @@ async fn update_exam( responses( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Not the creator (and not a manager/admin)", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] @@ -242,9 +200,10 @@ async fn delete_exam( let exam = Exam::read(&ExamId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; - if !can_manage(&exam, &user) { + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { return Err(AppError::Forbidden( - "only the creator or a manager/admin can delete this exam", + "only the course creator or a manager/admin can delete this exam", )); } exam.delete(&st.db).await?; @@ -253,8 +212,9 @@ async fn delete_exam( // ---- results ------------------------------------------------------------ -/// Record (or overwrite) a student's mark for an exam. Requires teacher+. -/// Students never grade — including themselves. +/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and +/// management rights over the exam's course; the target must be enrolled. +/// Students never grade — and nobody grades themselves. #[utoipa::path( post, path = "/{id}/results", @@ -264,9 +224,9 @@ async fn delete_exam( request_body = GradeResult, responses( (status = 200, description = "Result recorded", body = ExamResultResponse), - (status = 400, description = "Invalid mark or unknown user", body = ErrorResponse), + (status = 400, description = "Invalid mark, unknown user, or user not enrolled", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher, or attempted to grade yourself", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), ), )] @@ -278,9 +238,15 @@ async fn grade( ) -> Result, AppError> { let exam_id = ExamId::from_key(&id); // Exam must exist. - Exam::read(&exam_id, &st.db) + let exam = Exam::read(&exam_id, &st.db) .await? .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &teacher) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can grade this exam", + )); + } let mark = Mark::try_new(req.mark)?; let target = UserId::from_key(&req.user_id); @@ -299,6 +265,17 @@ async fn grade( })); } + // ... and be enrolled in the exam's course. + if Enrollment::read_for_user(exam.get_course(), &target, &st.db) + .await? + .is_none() + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } + let result = ExamResult::grade(&exam_id, &target, mark, teacher.get_id(), &st.db).await?; Ok(Json(ExamResultResponse::new(&result))) } @@ -357,7 +334,8 @@ async fn my_result( Ok(Json(ExamResultResponse::new(&result))) } -/// Remove a student's result from an exam. Requires teacher+. +/// Remove a student's result from an exam. Requires teacher+ and management +/// rights over the exam's course. #[utoipa::path( delete, path = "/{id}/results/{user}", @@ -370,17 +348,25 @@ async fn my_result( responses( (status = 204, description = "Removed"), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), ), )] async fn remove_result( State(st): State, - _teacher: RequireTeacher, + RequireTeacher(user): RequireTeacher, Path((id, target)): Path<(String, String)>, ) -> Result { - let removed = - ExamResult::remove(&ExamId::from_key(&id), &UserId::from_key(&target), &st.db).await?; + let exam = Exam::read(&ExamId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let course = course_of(&exam, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can remove results", + )); + } + let removed = ExamResult::remove(exam.get_id(), &UserId::from_key(&target), &st.db).await?; if removed.is_none() { return Err(AppError::NotFound); } diff --git a/src/web/mod.rs b/src/web/mod.rs index 19ceb54..d174b23 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -4,6 +4,7 @@ //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. pub mod auth; +pub mod courses; pub mod events; pub mod exams; pub mod notes; @@ -12,5 +13,5 @@ pub mod users; mod dto; mod extractor; -pub use dto::UserResponse; +pub use dto::{CourseResponse, ExamResponse, UserResponse}; pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher};