From fcf8ff70508c0e26821c9ac8282d8f80ba2d2019 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 22 Jul 2026 17:29:50 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(homework):=20course=20homework?= =?UTF-8?q?=20CRUD=20endpoints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/domain/homework.rs | 30 ++++ src/error.rs | 7 + src/lib.rs | 2 + src/web/courses.rs | 140 ++++++++++++++- src/web/dto.rs | 47 ++++++ src/web/exam_ws.rs | 1 + src/web/homework.rs | 374 +++++++++++++++++++++++++++++++++++++++++ src/web/mod.rs | 5 +- 8 files changed, 601 insertions(+), 5 deletions(-) create mode 100644 src/web/homework.rs diff --git a/src/domain/homework.rs b/src/domain/homework.rs index f49e162..8de0aba 100644 --- a/src/domain/homework.rs +++ b/src/domain/homework.rs @@ -188,6 +188,36 @@ impl Homework { Ok(result.take::>(0)?) } + /// Every homework in the system, newest first — the manager+ view of the + /// cross-course "my homework" list. + pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM homework ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Every homework of every course in `courses`, newest first (one query) — + /// the cross-course list over a caller's visible courses. The web layer + /// still trims each course's rows to what the caller may see (a student to + /// the ones they `student_sees`). + pub async fn list_for_courses( + courses: &[CourseId], + db: &Database, + ) -> Result, AppError> { + if courses.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = courses.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") + .bind(("courses", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + /// The homework of `course` that `user` is meant to see — whole-course ones /// plus any subset that names them — newest first. Backs a student's (or an /// observer's) per-course homework report; mirrors [`Homework::student_sees`] diff --git a/src/error.rs b/src/error.rs index eb672bd..5157739 100644 --- a/src/error.rs +++ b/src/error.rs @@ -51,6 +51,12 @@ pub enum AppError { Forbidden(&'static str), #[error("conflict: {0}")] Conflict(&'static str), + /// A 409 whose message is only known at runtime — e.g. the specific + /// students a homework's narrowed `assigned` list would orphan. Owned + /// string, like [`AppError::PayloadTooLarge`]; static conflicts use + /// [`AppError::Conflict`]. + #[error("conflict: {0}")] + ConflictOwned(String), /// A request body (file upload) over the allowed size. Owned string: the /// school-configured limit is only known at runtime. #[error("payload too large: {0}")] @@ -147,6 +153,7 @@ impl IntoResponse for AppError { AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()), AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()), AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()), + AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()), AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()), AppError::Db(e) => { tracing::error!("database error: {e}"); diff --git a/src/lib.rs b/src/lib.rs index 18599b5..3df324e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,7 @@ use crate::state::AppState; (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), + (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files (photos/documents); a submission touched after `due_at` is flagged late (computed, never stored) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed, and beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"), ), )] @@ -98,6 +99,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/attendance", web::attendance::routes()) .nest("/settings", web::settings::routes()) .nest("/subjects", web::subjects::routes()) + .nest("/homework", web::homework::routes()) .nest("/terms", web::terms::routes()) .split_for_parts(); diff --git a/src/web/courses.rs b/src/web/courses.rs index ef642a5..e43b48d 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -17,6 +17,7 @@ use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, }; +use crate::domain::homework::{Homework, HomeworkTitle}; use crate::domain::question_image::QuestionImage; use crate::domain::role::Role; use crate::domain::settings::Settings; @@ -26,12 +27,14 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; +use super::homework::{description_or_none, resolve_assigned}; use super::sessions::resolve_session_teacher; +use super::subjects::subject_in_course; use super::terms::resolve_term; use super::{ - CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireManager, - RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range, - course_people, paginate, person_map, remove_blob, set_or_clear, + CourseResponse, CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef, + RequireManager, RequireTeacher, SessionResponse, SubjectResponse, check_not_past, + check_time_range, course_people, paginate, person_map, remove_blob, set_or_clear, }; pub fn routes() -> OpenApiRouter { @@ -46,6 +49,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(create_exam_in_course, list_course_exams)) .routes(routes!(create_session_in_course, list_course_sessions)) .routes(routes!(create_subject_in_course, list_course_subjects)) + .routes(routes!(create_homework_in_course, list_course_homework)) } #[derive(Deserialize, ToSchema)] @@ -944,6 +948,136 @@ async fn list_course_subjects( Ok(Json(Page::new(items, total, limit, offset))) } +// ---- homework in a course -------------------------------------------------- +// A teacher assigns homework per course, tagged with one of the course's +// subjects and due at a future time. `assigned` optionally narrows it to a +// subset of the enrolled students; omit it for the whole course. + +#[derive(Deserialize, ToSchema)] +struct CreateHomework { + #[schema(example = "Read chapter 3 and answer Q1-Q5")] + title: String, + description: Option, + /// The course subject this homework belongs to + /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with + /// one of its course's subjects. + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + subject_id: String, + /// When the homework is due, UTC unix-milliseconds. Required; must not be + /// in the past. Late submissions are still accepted, just flagged late. + #[schema(example = 1_900_000_000_000_i64)] + due_at: i64, + /// The students this homework is for: a list of enrolled student ids. Omit, + /// send `null`, or send `[]` to assign the whole enrolled course (whoever is + /// enrolled when they submit); a subset caps at 200 named students. + assigned: Option>, +} + +/// Assign a homework inside a course. Requires teacher+ and course management +/// rights. The homework is tagged with one of the course's subjects and given a +/// future `due_at`; `assigned` optionally narrows it to a subset of the enrolled +/// students (omit or empty = the whole course). +#[utoipa::path( + post, + path = "/{id}/homework", + tag = "homework", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = CreateHomework, + responses( + (status = 201, description = "Homework created", body = HomeworkResponse), + (status = 400, description = "Invalid fields, a due date in the past, an unknown subject (or one from another course), or an assigned student not enrolled / over the cap", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn create_homework_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, an assigned teacher, or a manager/admin can add homework to this course", + )); + } + + let title = HomeworkTitle::try_new(&req.title)?; + let description = match req.description.as_deref() { + Some(text) => description_or_none(text)?, + None => None, + }; + let due_at = Timestamp::from_millis(req.due_at); + check_not_past("due_at", Some(due_at))?; + let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; + let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; + let homework = Homework::create( + course.get_id(), + &subject, + title, + description, + due_at, + assigned, + user.get_id(), + &st.db, + ) + .await?; + Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework)))) +} + +/// List a course's homework, newest first, paged via `?limit=&offset=` (omit +/// `limit` for all of it). Visible to the course's enrolled users, its creator, +/// its assigned teachers, and managers/admins — but a student sees only the +/// homework they are assigned (whole-course ones plus subsets that name them). +/// Returns a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/{id}/homework", + tag = "homework", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id"), PageParams), + responses( + (status = 200, description = "A page of the course's homework (all of it when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn list_course_homework( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + // Course must exist — a missing course is a 404, not an empty homework list. + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", + )); + } + let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?; + // A student sees only the homework they are assigned; managers see all. + if !can_manage_course(&course, &user) { + homework.retain(|hw| hw.student_sees(user.get_id())); + } + let total = homework.len() as i64; + let items = paginate(&homework, limit, offset) + .iter() + .map(HomeworkResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + // ---- sessions in a course -------------------------------------------------- #[derive(Deserialize, ToSchema)] diff --git a/src/web/dto.rs b/src/web/dto.rs index 34fd271..641e475 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -9,6 +9,7 @@ use crate::database::Database; use crate::domain::course::Course; use crate::domain::course_session::CourseSession; use crate::domain::exam::Exam; +use crate::domain::homework::Homework; use crate::domain::role::Role as DomainRole; use crate::domain::subject::Subject; use crate::domain::user::{User, UserId}; @@ -234,6 +235,52 @@ impl SubjectResponse { } } +/// Public shape of a homework assignment. Shared by `courses` (in-course +/// creation and listing) and `homework` (cross-course list, lookup, edit). +/// `assigned` is the student subset — `null` means the whole enrolled course +/// (whoever is enrolled at submit time); a subset lists the named students' ids. +/// `due_at`/`created_at` are UTC unix-milliseconds; lateness is judged per +/// submission (against `due_at`), never stored on the homework itself. +#[derive(Serialize, ToSchema)] +pub struct HomeworkResponse { + #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] + pub id: String, + /// The course this homework belongs to. + pub course: String, + /// The course subject this homework is tagged with. + pub subject: String, + #[schema(example = "Read chapter 3")] + pub title: String, + pub description: Option, + /// When the homework is due, UTC unix-milliseconds. + #[schema(example = 1_900_000_000_000_i64)] + pub due_at: i64, + /// The assigned student ids, or `null` for the whole enrolled course. + pub assigned: Option>, + /// Who assigned the homework. + pub created_by: String, + /// When it was assigned, UTC unix-milliseconds. + pub created_at: i64, +} + +impl HomeworkResponse { + pub fn new(homework: &Homework) -> Self { + Self { + id: homework.get_id().key().to_string(), + course: homework.get_course().key().to_string(), + subject: homework.get_subject().key().to_string(), + title: homework.get_title().as_str().to_string(), + description: homework.get_description().map(|d| d.as_str().to_string()), + due_at: homework.get_due_at().as_millis(), + assigned: homework + .get_assigned() + .map(|users| users.iter().map(|user| user.key().to_string()).collect()), + created_by: homework.get_created_by().key().to_string(), + created_at: homework.get_created_at().as_millis(), + } + } +} + /// Public shape of a course session (one lesson). Shared by `courses` /// (in-course creation and listing) and `sessions` (CRUD + roll call). #[derive(Serialize, ToSchema)] diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 1134d0e..ae8da8c 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -434,6 +434,7 @@ fn error_frame(err: &AppError) -> Value { AppError::Unauthorized => "unauthorized".to_string(), AppError::Forbidden(message) => (*message).to_string(), AppError::Conflict(message) => (*message).to_string(), + AppError::ConflictOwned(message) => message.clone(), AppError::PayloadTooLarge(message) => message.clone(), AppError::TooManyRequests { .. } => "too many requests".to_string(), AppError::DbUnavailable => { diff --git a/src/web/homework.rs b/src/web/homework.rs new file mode 100644 index 0000000..9f6cd73 --- /dev/null +++ b/src/web/homework.rs @@ -0,0 +1,374 @@ +//! Homework entity endpoints: the cross-course "my homework" list plus lookup, +//! edit, and delete of one homework by id. Creation and the per-course listing +//! live under `/courses/{id}/homework` (see [`super::courses`]); student +//! submissions, files, grading, the roster, and the observer report arrive in +//! later steps and reuse the visibility rule ([`Homework::student_sees`]), the +//! [`HOMEWORK_LOCK`], and [`resolve_assigned`] from here. + +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use serde::Deserialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::constant::MAX_HOMEWORK_ASSIGNED; +use crate::database::Database; +use crate::domain::course::{Course, CourseId}; +use crate::domain::enrollment::Enrollment; +use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; +use crate::domain::homework_file::HomeworkFile; +use crate::domain::homework_result::HomeworkResult; +use crate::domain::homework_submission::HomeworkSubmission; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::courses::{can_manage_course, can_view_course, visible_courses}; +use super::subjects::subject_in_course; +use super::{ + CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, check_not_past, paginate, + remove_blob, set_or_clear, +}; + +/// Serializes the homework subsystem's cross-record check-then-writes, which +/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as +/// [`crate::web::exams::EXAM_LOCK`]. The class of bug: a submission stays +/// editable only *until a result exists*, so the "no grade yet" read and the +/// submission write that depends on it must not straddle a concurrent grade, +/// and a homework delete must not race a submission landing under it. Read side +/// (steps 3/4): the student's submission and file writes, held from the +/// ungraded gate through the upsert, concurrent with each other. Write side: +/// grade/ungrade (steps 3/4) and the homework-delete cascade here. Lock order, +/// where both are taken: `HOMEWORK_LOCK` before the file-cap `Mutex`, never the +/// reverse. +// ponytail: global RwLock, shard per-homework if write latency ever matters. +pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(list_homework)) + .routes(routes!(get_homework, update_homework, delete_homework)) +} + +/// Validate a request's `assigned` list into a stored student subset. `None`, +/// an explicit `null`, and an empty list all mean "the whole enrolled course" +/// (stored as `None`); a non-empty list must name at most +/// [`MAX_HOMEWORK_ASSIGNED`] students, each currently enrolled in `course`. +/// Deduped so a repeated id can't inflate the cap or double a roster row. +/// Shared by the create ([`super::courses`]) and PATCH handlers. +pub(crate) async fn resolve_assigned( + assigned: Option>, + course: &CourseId, + db: &Database, +) -> Result>, AppError> { + let Some(mut keys) = assigned.filter(|keys| !keys.is_empty()) else { + return Ok(None); + }; + keys.sort(); + keys.dedup(); + if keys.len() > MAX_HOMEWORK_ASSIGNED { + return Err(AppError::Validation(ValidationError::Invalid { + field: "assigned", + reason: "may name at most 200 students", + })); + } + let mut users = Vec::with_capacity(keys.len()); + for key in keys { + let user = UserId::from_key(&key); + if Enrollment::read_for_user(course, &user, db).await?.is_none() { + return Err(AppError::Validation(ValidationError::Invalid { + field: "assigned", + reason: "every assigned student must be enrolled in the course", + })); + } + users.push(user); + } + Ok(Some(users)) +} + +/// A homework description off the wire: an empty string means "none", anything +/// else is length-validated. Shared by create and PATCH so both treat `""` the +/// same (a stored empty description would be a needless present-but-blank row). +pub(crate) fn description_or_none(text: &str) -> Result, AppError> { + if text.is_empty() { + Ok(None) + } else { + Ok(Some(HomeworkDescription::try_new(text)?)) + } +} + +/// The homework plus its course, or a 404 — every entity handler here gates on +/// the parent course, so they always travel together. +async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Course), AppError> { + let homework = Homework::read(&HomeworkId::from_key(id), db) + .await? + .ok_or(AppError::NotFound)?; + let course = Course::read(homework.get_course(), db) + .await? + .ok_or(AppError::NotFound)?; + Ok((homework, course)) +} + +/// List the homework across the caller's courses — their "my homework" view — +/// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every +/// course's homework; a teacher sees the homework of courses they run; a +/// student sees only the homework they are assigned (whole-course ones plus any +/// subset that names them). Returns a `{items, total, limit, offset}` envelope. +#[utoipa::path( + get, + path = "/", + tag = "homework", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of the caller's visible homework (all of it when unpaged)", body = Page), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn list_homework( + State(st): State, + CurrentUser(user): CurrentUser, + Query(page): Query, +) -> Result>, AppError> { + let (limit, offset) = page.resolve()?; + let homework = if user.get_role().at_least(Role::Manager) { + Homework::list_all(&st.db).await? + } else { + let courses = visible_courses(&user, &st.db).await?; + let ids: Vec<_> = courses.iter().map(|course| course.get_id().clone()).collect(); + // A student sees only the homework they are assigned; a teacher who + // manages a course sees all of its homework (the manager+ path above + // already saw everything). + let managed: Vec<&str> = courses + .iter() + .filter(|course| can_manage_course(course, &user)) + .map(|course| course.get_id().key()) + .collect(); + let mut homework = Homework::list_for_courses(&ids, &st.db).await?; + homework.retain(|hw| { + managed.contains(&hw.get_course().key()) || hw.student_sees(user.get_id()) + }); + homework + }; + let total = homework.len() as i64; + let items = paginate(&homework, limit, offset) + .iter() + .map(HomeworkResponse::new) + .collect(); + Ok(Json(Page::new(items, total, limit, offset))) +} + +/// Fetch a single homework by id. Visible to whoever can view its course (its +/// enrolled users, creator, assigned teachers, and managers/admins). A student +/// the homework is *not* assigned to gets a 404 — the same no-leak an unseen +/// exam draft gets, so a subset assignment never reveals itself to the students +/// left out of it. +#[utoipa::path( + get, + path = "/{id}", + tag = "homework", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Homework id")), + responses( + (status = 200, description = "The homework", body = HomeworkResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not enrolled in the homework's course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse), + (status = 404, description = "Not found (or a subset assignment the caller is not part of)", body = ErrorResponse), + ), +)] +async fn get_homework( + State(st): State, + CurrentUser(user): CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let (homework, course) = homework_with_course(&id, &st.db).await?; + if !can_view_course(&course, &user, &st.db).await? { + return Err(AppError::Forbidden( + "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this homework", + )); + } + // A student the homework is not assigned to must not even learn it exists — + // 404, not 403, exactly like an exam draft hidden from non-managers. + if !can_manage_course(&course, &user) && !homework.student_sees(user.get_id()) { + return Err(AppError::NotFound); + } + Ok(Json(HomeworkResponse::new(&homework))) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateHomework { + /// Re-title. Omit to keep the current title. + title: Option, + /// Re-describe. Omit to keep; send `null` (or `""`) to clear. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + description: Option>, + /// New due date, UTC unix-milliseconds. Omit to keep; a newly set value + /// must not be in the past (a kept one may already be past). + #[schema(example = 1_900_000_000_000_i64)] + due_at: Option, + /// Re-tag with another of the course's subjects + /// (`GET /courses/{id}/subjects`). Omit to keep — a homework always has a + /// subject, so there is no clear. + subject_id: Option, + /// Re-scope the audience: a list of enrolled student ids, or an empty list + /// / `null` for the whole course. Omit to keep. Narrowing is refused (409) + /// while it would orphan a student who already submitted or was graded. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option>)] + assigned: Option>>, +} + +/// Edit a homework's title, description, due date, subject, or assigned subset. +/// Requires teacher+ and management rights over its course. Omitted fields keep +/// their value; a newly set `due_at` is re-checked against now and a new +/// `subject_id` re-checked against the course. Narrowing `assigned` is refused +/// (409) while it would orphan an existing submission or result. +#[utoipa::path( + patch, + path = "/{id}", + tag = "homework", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Homework id")), + request_body = UpdateHomework, + responses( + (status = 200, description = "Updated homework", body = HomeworkResponse), + (status = 400, description = "Invalid title, description, due date, subject (unknown or from another course), or assigned list", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result", body = ErrorResponse), + ), +)] +async fn update_homework( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let (homework, course) = homework_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can edit this homework", + )); + } + + let title = match req.title { + Some(ref title) => HomeworkTitle::try_new(title)?, + None => homework.get_title().clone(), + }; + let description = match req.description { + Some(Some(ref text)) => description_or_none(text)?, + Some(None) => None, + None => homework.get_description().cloned(), + }; + let due_at = match req.due_at { + Some(millis) => { + let due_at = Timestamp::from_millis(millis); + check_not_past("due_at", Some(due_at))?; + due_at + } + None => homework.get_due_at(), + }; + let subject = match req.subject_id { + Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?, + None => homework.get_subject().clone(), + }; + let assigned = match req.assigned { + Some(assigned) => { + let resolved = resolve_assigned(assigned, course.get_id(), &st.db).await?; + ensure_no_orphans(&homework, resolved.as_deref(), &st.db).await?; + resolved + } + None => homework.get_assigned().map(<[UserId]>::to_vec), + }; + + let updated = homework + .update(&subject, title, description, due_at, assigned, &st.db) + .await?; + Ok(Json(HomeworkResponse::new(&updated))) +} + +/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student +/// who already submitted or was graded falls outside it — their work would be +/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in +/// which case no one can be orphaned). The blocking students are named in the +/// message so the teacher knows whose work to clear (or whom to keep assigned) +/// first. +async fn ensure_no_orphans( + homework: &Homework, + new_assigned: Option<&[UserId]>, + db: &Database, +) -> Result<(), AppError> { + // Whole-course covers everyone — no narrowing, no orphans. + let Some(subset) = new_assigned else { + return Ok(()); + }; + let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), db).await?; + let results = HomeworkResult::list_for_homework(homework.get_id(), db).await?; + let mut blocked: Vec = Vec::new(); + for user in submissions + .iter() + .map(HomeworkSubmission::get_user) + .chain(results.iter().map(HomeworkResult::get_user)) + { + let key = user.key().to_string(); + if !subset.contains(user) && !blocked.contains(&key) { + blocked.push(key); + } + } + if blocked.is_empty() { + Ok(()) + } else { + Err(AppError::ConflictOwned(format!( + "narrowing the assigned list would orphan existing work by {} student(s): {}", + blocked.len(), + blocked.join(", ") + ))) + } +} + +/// Delete a homework and everything under it — submissions, their files, and +/// results — then unlink the file blobs from disk. Requires teacher+ and +/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease +/// so no submission can land under the homework mid-delete; the blob names are +/// collected before the rows are wiped (the cascade is one transaction, children +/// first) and removed after, so a crash in between strands at worst an +/// unreachable file. +#[utoipa::path( + delete, + path = "/{id}", + tag = "homework", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Homework id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_homework( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let (homework, course) = homework_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator, an assigned teacher, or a manager/admin can delete this homework", + )); + } + let _guard = HOMEWORK_LOCK.write().await; + let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; + homework.delete(&st.db).await?; + for key in &blob_keys { + remove_blob(&st.files_path, key).await; + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/mod.rs b/src/web/mod.rs index 66bf15d..45a9421 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -9,6 +9,7 @@ pub mod courses; pub mod events; pub mod exam_ws; pub mod exams; +pub mod homework; pub mod marks; pub mod messages; pub mod notes; @@ -26,8 +27,8 @@ mod extractor; mod page; pub use dto::{ - CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse, - course_people, person_map, + CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse, + UserResponse, course_people, person_map, }; pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher}; pub use page::{Page, PageParams, paginate};