forge
Explore
Log in

Don't you dare go Hollow

Course homework CRUD endpoints

Browse files at this commit

fcf8ff70508c0e26821c9ac8282d8f80ba2d2019Ahmet Kaan GümüşParent: 7425b19
  • feat
    • course homework CRUD endpoints
Show full message
✨ feat(homework): course homework CRUD endpoints
src/domain/homework.rsmodified+30 -0
@@ -188,6 +188,36 @@ impl Homework {
188188 Ok(result.take::<Vec<Homework>>(0)?)
189189 }
190190
191+ /// Every homework in the system, newest first — the manager+ view of the
192+ /// cross-course "my homework" list.
193+ pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
194+ let mut result = db
195+ .query("SELECT * FROM homework ORDER BY id DESC")
196+ .await?
197+ .check()?;
198+ Ok(result.take::<Vec<Homework>>(0)?)
199+ }
200+
201+ /// Every homework of every course in `courses`, newest first (one query) —
202+ /// the cross-course list over a caller's visible courses. The web layer
203+ /// still trims each course's rows to what the caller may see (a student to
204+ /// the ones they `student_sees`).
205+ pub async fn list_for_courses(
206+ courses: &[CourseId],
207+ db: &Database,
208+ ) -> Result<Vec<Homework>, AppError> {
209+ if courses.is_empty() {
210+ return Ok(Vec::new());
211+ }
212+ let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect();
213+ let mut result = db
214+ .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC")
215+ .bind(("courses", records))
216+ .await?
217+ .check()?;
218+ Ok(result.take::<Vec<Homework>>(0)?)
219+ }
220+
191221 /// The homework of `course` that `user` is meant to see — whole-course ones
192222 /// plus any subset that names them — newest first. Backs a student's (or an
193223 /// observer's) per-course homework report; mirrors [`Homework::student_sees`]
src/error.rsmodified+7 -0
@@ -51,6 +51,12 @@ pub enum AppError {
5151 Forbidden(&'static str),
5252 #[error("conflict: {0}")]
5353 Conflict(&'static str),
54+ /// A 409 whose message is only known at runtime — e.g. the specific
55+ /// students a homework's narrowed `assigned` list would orphan. Owned
56+ /// string, like [`AppError::PayloadTooLarge`]; static conflicts use
57+ /// [`AppError::Conflict`].
58+ #[error("conflict: {0}")]
59+ ConflictOwned(String),
5460 /// A request body (file upload) over the allowed size. Owned string: the
5561 /// school-configured limit is only known at runtime.
5662 #[error("payload too large: {0}")]
@@ -147,6 +153,7 @@ impl IntoResponse for AppError {
147153 AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized".to_string()),
148154 AppError::Forbidden(m) => (StatusCode::FORBIDDEN, m.to_string()),
149155 AppError::Conflict(m) => (StatusCode::CONFLICT, m.to_string()),
156+ AppError::ConflictOwned(m) => (StatusCode::CONFLICT, m.clone()),
150157 AppError::PayloadTooLarge(m) => (StatusCode::PAYLOAD_TOO_LARGE, m.clone()),
151158 AppError::Db(e) => {
152159 tracing::error!("database error: {e}");
src/lib.rsmodified+2 -0
@@ -54,6 +54,7 @@ use crate::state::AppState;
5454 (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"),
5555 (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+"),
5656 (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"),
57+ (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"),
5758 (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses may link to one. Read: any authenticated user; edit: manager+"),
5859 ),
5960 )]
@@ -98,6 +99,7 @@ pub fn build_router(state: AppState) -> Router {
9899 .nest("/attendance", web::attendance::routes())
99100 .nest("/settings", web::settings::routes())
100101 .nest("/subjects", web::subjects::routes())
102+ .nest("/homework", web::homework::routes())
101103 .nest("/terms", web::terms::routes())
102104 .split_for_parts();
103105
src/web/courses.rsmodified+137 -3
@@ -17,6 +17,7 @@ use crate::domain::exam::{
1717 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
1818 ExamTitle,
1919 };
20+use crate::domain::homework::{Homework, HomeworkTitle};
2021 use crate::domain::question_image::QuestionImage;
2122 use crate::domain::role::Role;
2223 use crate::domain::settings::Settings;
@@ -26,12 +27,14 @@ use crate::domain::user::{User, UserId};
2627 use crate::error::{AppError, ErrorResponse, ValidationError};
2728 use crate::state::AppState;
2829
30+use super::homework::{description_or_none, resolve_assigned};
2931 use super::sessions::resolve_session_teacher;
32+use super::subjects::subject_in_course;
3033 use super::terms::resolve_term;
3134 use super::{
32- CourseResponse, CurrentUser, ExamResponse, Page, PageParams, PersonRef, RequireManager,
33- RequireTeacher, SessionResponse, SubjectResponse, check_not_past, check_time_range,
34- course_people, paginate, person_map, remove_blob, set_or_clear,
35+ CourseResponse, CurrentUser, ExamResponse, HomeworkResponse, Page, PageParams, PersonRef,
36+ RequireManager, RequireTeacher, SessionResponse, SubjectResponse, check_not_past,
37+ check_time_range, course_people, paginate, person_map, remove_blob, set_or_clear,
3538 };
3639
3740 pub fn routes() -> OpenApiRouter<AppState> {
@@ -46,6 +49,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
4649 .routes(routes!(create_exam_in_course, list_course_exams))
4750 .routes(routes!(create_session_in_course, list_course_sessions))
4851 .routes(routes!(create_subject_in_course, list_course_subjects))
52+ .routes(routes!(create_homework_in_course, list_course_homework))
4953 }
5054
5155 #[derive(Deserialize, ToSchema)]
@@ -944,6 +948,136 @@ async fn list_course_subjects(
944948 Ok(Json(Page::new(items, total, limit, offset)))
945949 }
946950
951+// ---- homework in a course --------------------------------------------------
952+// A teacher assigns homework per course, tagged with one of the course's
953+// subjects and due at a future time. `assigned` optionally narrows it to a
954+// subset of the enrolled students; omit it for the whole course.
955+
956+#[derive(Deserialize, ToSchema)]
957+struct CreateHomework {
958+ #[schema(example = "Read chapter 3 and answer Q1-Q5")]
959+ title: String,
960+ description: Option<String>,
961+ /// The course subject this homework belongs to
962+ /// (`GET /courses/{id}/subjects`). Required — every homework is tagged with
963+ /// one of its course's subjects.
964+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
965+ subject_id: String,
966+ /// When the homework is due, UTC unix-milliseconds. Required; must not be
967+ /// in the past. Late submissions are still accepted, just flagged late.
968+ #[schema(example = 1_900_000_000_000_i64)]
969+ due_at: i64,
970+ /// The students this homework is for: a list of enrolled student ids. Omit,
971+ /// send `null`, or send `[]` to assign the whole enrolled course (whoever is
972+ /// enrolled when they submit); a subset caps at 200 named students.
973+ assigned: Option<Vec<String>>,
974+}
975+
976+/// Assign a homework inside a course. Requires teacher+ and course management
977+/// rights. The homework is tagged with one of the course's subjects and given a
978+/// future `due_at`; `assigned` optionally narrows it to a subset of the enrolled
979+/// students (omit or empty = the whole course).
980+#[utoipa::path(
981+ post,
982+ path = "/{id}/homework",
983+ tag = "homework",
984+ security(("session_cookie" = [])),
985+ params(("id" = String, Path, description = "Course id")),
986+ request_body = CreateHomework,
987+ responses(
988+ (status = 201, description = "Homework created", body = HomeworkResponse),
989+ (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),
990+ (status = 401, description = "Not authenticated", body = ErrorResponse),
991+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
992+ (status = 404, description = "Course not found", body = ErrorResponse),
993+ ),
994+)]
995+async fn create_homework_in_course(
996+ State(st): State<AppState>,
997+ RequireTeacher(user): RequireTeacher,
998+ Path(id): Path<String>,
999+ Json(req): Json<CreateHomework>,
1000+) -> Result<(StatusCode, Json<HomeworkResponse>), AppError> {
1001+ let course = Course::read(&CourseId::from_key(&id), &st.db)
1002+ .await?
1003+ .ok_or(AppError::NotFound)?;
1004+ if !can_manage_course(&course, &user) {
1005+ return Err(AppError::Forbidden(
1006+ "only the course creator, an assigned teacher, or a manager/admin can add homework to this course",
1007+ ));
1008+ }
1009+
1010+ let title = HomeworkTitle::try_new(&req.title)?;
1011+ let description = match req.description.as_deref() {
1012+ Some(text) => description_or_none(text)?,
1013+ None => None,
1014+ };
1015+ let due_at = Timestamp::from_millis(req.due_at);
1016+ check_not_past("due_at", Some(due_at))?;
1017+ let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;
1018+ let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?;
1019+ let homework = Homework::create(
1020+ course.get_id(),
1021+ &subject,
1022+ title,
1023+ description,
1024+ due_at,
1025+ assigned,
1026+ user.get_id(),
1027+ &st.db,
1028+ )
1029+ .await?;
1030+ Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework))))
1031+}
1032+
1033+/// List a course's homework, newest first, paged via `?limit=&offset=` (omit
1034+/// `limit` for all of it). Visible to the course's enrolled users, its creator,
1035+/// its assigned teachers, and managers/admins — but a student sees only the
1036+/// homework they are assigned (whole-course ones plus subsets that name them).
1037+/// Returns a `{items, total, limit, offset}` envelope.
1038+#[utoipa::path(
1039+ get,
1040+ path = "/{id}/homework",
1041+ tag = "homework",
1042+ security(("session_cookie" = [])),
1043+ params(("id" = String, Path, description = "Course id"), PageParams),
1044+ responses(
1045+ (status = 200, description = "A page of the course's homework (all of it when unpaged)", body = Page<HomeworkResponse>),
1046+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1047+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1048+ (status = 403, description = "Not enrolled, not the course creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
1049+ (status = 404, description = "Course not found", body = ErrorResponse),
1050+ ),
1051+)]
1052+async fn list_course_homework(
1053+ State(st): State<AppState>,
1054+ CurrentUser(user): CurrentUser,
1055+ Path(id): Path<String>,
1056+ Query(page): Query<PageParams>,
1057+) -> Result<Json<Page<HomeworkResponse>>, AppError> {
1058+ let (limit, offset) = page.resolve()?;
1059+ // Course must exist — a missing course is a 404, not an empty homework list.
1060+ let course = Course::read(&CourseId::from_key(&id), &st.db)
1061+ .await?
1062+ .ok_or(AppError::NotFound)?;
1063+ if !can_view_course(&course, &user, &st.db).await? {
1064+ return Err(AppError::Forbidden(
1065+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course",
1066+ ));
1067+ }
1068+ let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?;
1069+ // A student sees only the homework they are assigned; managers see all.
1070+ if !can_manage_course(&course, &user) {
1071+ homework.retain(|hw| hw.student_sees(user.get_id()));
1072+ }
1073+ let total = homework.len() as i64;
1074+ let items = paginate(&homework, limit, offset)
1075+ .iter()
1076+ .map(HomeworkResponse::new)
1077+ .collect();
1078+ Ok(Json(Page::new(items, total, limit, offset)))
1079+}
1080+
9471081 // ---- sessions in a course --------------------------------------------------
9481082
9491083 #[derive(Deserialize, ToSchema)]
src/web/dto.rsmodified+47 -0
@@ -9,6 +9,7 @@ use crate::database::Database;
99 use crate::domain::course::Course;
1010 use crate::domain::course_session::CourseSession;
1111 use crate::domain::exam::Exam;
12+use crate::domain::homework::Homework;
1213 use crate::domain::role::Role as DomainRole;
1314 use crate::domain::subject::Subject;
1415 use crate::domain::user::{User, UserId};
@@ -234,6 +235,52 @@ impl SubjectResponse {
234235 }
235236 }
236237
238+/// Public shape of a homework assignment. Shared by `courses` (in-course
239+/// creation and listing) and `homework` (cross-course list, lookup, edit).
240+/// `assigned` is the student subset — `null` means the whole enrolled course
241+/// (whoever is enrolled at submit time); a subset lists the named students' ids.
242+/// `due_at`/`created_at` are UTC unix-milliseconds; lateness is judged per
243+/// submission (against `due_at`), never stored on the homework itself.
244+#[derive(Serialize, ToSchema)]
245+pub struct HomeworkResponse {
246+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
247+ pub id: String,
248+ /// The course this homework belongs to.
249+ pub course: String,
250+ /// The course subject this homework is tagged with.
251+ pub subject: String,
252+ #[schema(example = "Read chapter 3")]
253+ pub title: String,
254+ pub description: Option<String>,
255+ /// When the homework is due, UTC unix-milliseconds.
256+ #[schema(example = 1_900_000_000_000_i64)]
257+ pub due_at: i64,
258+ /// The assigned student ids, or `null` for the whole enrolled course.
259+ pub assigned: Option<Vec<String>>,
260+ /// Who assigned the homework.
261+ pub created_by: String,
262+ /// When it was assigned, UTC unix-milliseconds.
263+ pub created_at: i64,
264+}
265+
266+impl HomeworkResponse {
267+ pub fn new(homework: &Homework) -> Self {
268+ Self {
269+ id: homework.get_id().key().to_string(),
270+ course: homework.get_course().key().to_string(),
271+ subject: homework.get_subject().key().to_string(),
272+ title: homework.get_title().as_str().to_string(),
273+ description: homework.get_description().map(|d| d.as_str().to_string()),
274+ due_at: homework.get_due_at().as_millis(),
275+ assigned: homework
276+ .get_assigned()
277+ .map(|users| users.iter().map(|user| user.key().to_string()).collect()),
278+ created_by: homework.get_created_by().key().to_string(),
279+ created_at: homework.get_created_at().as_millis(),
280+ }
281+ }
282+}
283+
237284 /// Public shape of a course session (one lesson). Shared by `courses`
238285 /// (in-course creation and listing) and `sessions` (CRUD + roll call).
239286 #[derive(Serialize, ToSchema)]
src/web/exam_ws.rsmodified+1 -0
@@ -434,6 +434,7 @@ fn error_frame(err: &AppError) -> Value {
434434 AppError::Unauthorized => "unauthorized".to_string(),
435435 AppError::Forbidden(message) => (*message).to_string(),
436436 AppError::Conflict(message) => (*message).to_string(),
437+ AppError::ConflictOwned(message) => message.clone(),
437438 AppError::PayloadTooLarge(message) => message.clone(),
438439 AppError::TooManyRequests { .. } => "too many requests".to_string(),
439440 AppError::DbUnavailable => {
src/web/homework.rsadded+374 -0
@@ -0,0 +1,374 @@
1+//! Homework entity endpoints: the cross-course "my homework" list plus lookup,
2+//! edit, and delete of one homework by id. Creation and the per-course listing
3+//! live under `/courses/{id}/homework` (see [`super::courses`]); student
4+//! submissions, files, grading, the roster, and the observer report arrive in
5+//! later steps and reuse the visibility rule ([`Homework::student_sees`]), the
6+//! [`HOMEWORK_LOCK`], and [`resolve_assigned`] from here.
7+
8+use axum::Json;
9+use axum::extract::{Path, Query, State};
10+use axum::http::StatusCode;
11+use serde::Deserialize;
12+use utoipa::ToSchema;
13+use utoipa_axum::router::OpenApiRouter;
14+use utoipa_axum::routes;
15+
16+use crate::constant::MAX_HOMEWORK_ASSIGNED;
17+use crate::database::Database;
18+use crate::domain::course::{Course, CourseId};
19+use crate::domain::enrollment::Enrollment;
20+use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
21+use crate::domain::homework_file::HomeworkFile;
22+use crate::domain::homework_result::HomeworkResult;
23+use crate::domain::homework_submission::HomeworkSubmission;
24+use crate::domain::role::Role;
25+use crate::domain::timestamp::Timestamp;
26+use crate::domain::user::UserId;
27+use crate::error::{AppError, ErrorResponse, ValidationError};
28+use crate::state::AppState;
29+
30+use super::courses::{can_manage_course, can_view_course, visible_courses};
31+use super::subjects::subject_in_course;
32+use super::{
33+ CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, check_not_past, paginate,
34+ remove_blob, set_or_clear,
35+};
36+
37+/// Serializes the homework subsystem's cross-record check-then-writes, which
38+/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as
39+/// [`crate::web::exams::EXAM_LOCK`]. The class of bug: a submission stays
40+/// editable only *until a result exists*, so the "no grade yet" read and the
41+/// submission write that depends on it must not straddle a concurrent grade,
42+/// and a homework delete must not race a submission landing under it. Read side
43+/// (steps 3/4): the student's submission and file writes, held from the
44+/// ungraded gate through the upsert, concurrent with each other. Write side:
45+/// grade/ungrade (steps 3/4) and the homework-delete cascade here. Lock order,
46+/// where both are taken: `HOMEWORK_LOCK` before the file-cap `Mutex`, never the
47+/// reverse.
48+// ponytail: global RwLock, shard per-homework if write latency ever matters.
49+pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
50+
51+pub fn routes() -> OpenApiRouter<AppState> {
52+ OpenApiRouter::new()
53+ .routes(routes!(list_homework))
54+ .routes(routes!(get_homework, update_homework, delete_homework))
55+}
56+
57+/// Validate a request's `assigned` list into a stored student subset. `None`,
58+/// an explicit `null`, and an empty list all mean "the whole enrolled course"
59+/// (stored as `None`); a non-empty list must name at most
60+/// [`MAX_HOMEWORK_ASSIGNED`] students, each currently enrolled in `course`.
61+/// Deduped so a repeated id can't inflate the cap or double a roster row.
62+/// Shared by the create ([`super::courses`]) and PATCH handlers.
63+pub(crate) async fn resolve_assigned(
64+ assigned: Option<Vec<String>>,
65+ course: &CourseId,
66+ db: &Database,
67+) -> Result<Option<Vec<UserId>>, AppError> {
68+ let Some(mut keys) = assigned.filter(|keys| !keys.is_empty()) else {
69+ return Ok(None);
70+ };
71+ keys.sort();
72+ keys.dedup();
73+ if keys.len() > MAX_HOMEWORK_ASSIGNED {
74+ return Err(AppError::Validation(ValidationError::Invalid {
75+ field: "assigned",
76+ reason: "may name at most 200 students",
77+ }));
78+ }
79+ let mut users = Vec::with_capacity(keys.len());
80+ for key in keys {
81+ let user = UserId::from_key(&key);
82+ if Enrollment::read_for_user(course, &user, db).await?.is_none() {
83+ return Err(AppError::Validation(ValidationError::Invalid {
84+ field: "assigned",
85+ reason: "every assigned student must be enrolled in the course",
86+ }));
87+ }
88+ users.push(user);
89+ }
90+ Ok(Some(users))
91+}
92+
93+/// A homework description off the wire: an empty string means "none", anything
94+/// else is length-validated. Shared by create and PATCH so both treat `""` the
95+/// same (a stored empty description would be a needless present-but-blank row).
96+pub(crate) fn description_or_none(text: &str) -> Result<Option<HomeworkDescription>, AppError> {
97+ if text.is_empty() {
98+ Ok(None)
99+ } else {
100+ Ok(Some(HomeworkDescription::try_new(text)?))
101+ }
102+}
103+
104+/// The homework plus its course, or a 404 — every entity handler here gates on
105+/// the parent course, so they always travel together.
106+async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Course), AppError> {
107+ let homework = Homework::read(&HomeworkId::from_key(id), db)
108+ .await?
109+ .ok_or(AppError::NotFound)?;
110+ let course = Course::read(homework.get_course(), db)
111+ .await?
112+ .ok_or(AppError::NotFound)?;
113+ Ok((homework, course))
114+}
115+
116+/// List the homework across the caller's courses — their "my homework" view —
117+/// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every
118+/// course's homework; a teacher sees the homework of courses they run; a
119+/// student sees only the homework they are assigned (whole-course ones plus any
120+/// subset that names them). Returns a `{items, total, limit, offset}` envelope.
121+#[utoipa::path(
122+ get,
123+ path = "/",
124+ tag = "homework",
125+ security(("session_cookie" = [])),
126+ params(PageParams),
127+ responses(
128+ (status = 200, description = "A page of the caller's visible homework (all of it when unpaged)", body = Page<HomeworkResponse>),
129+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
130+ (status = 401, description = "Not authenticated", body = ErrorResponse),
131+ ),
132+)]
133+async fn list_homework(
134+ State(st): State<AppState>,
135+ CurrentUser(user): CurrentUser,
136+ Query(page): Query<PageParams>,
137+) -> Result<Json<Page<HomeworkResponse>>, AppError> {
138+ let (limit, offset) = page.resolve()?;
139+ let homework = if user.get_role().at_least(Role::Manager) {
140+ Homework::list_all(&st.db).await?
141+ } else {
142+ let courses = visible_courses(&user, &st.db).await?;
143+ let ids: Vec<_> = courses.iter().map(|course| course.get_id().clone()).collect();
144+ // A student sees only the homework they are assigned; a teacher who
145+ // manages a course sees all of its homework (the manager+ path above
146+ // already saw everything).
147+ let managed: Vec<&str> = courses
148+ .iter()
149+ .filter(|course| can_manage_course(course, &user))
150+ .map(|course| course.get_id().key())
151+ .collect();
152+ let mut homework = Homework::list_for_courses(&ids, &st.db).await?;
153+ homework.retain(|hw| {
154+ managed.contains(&hw.get_course().key()) || hw.student_sees(user.get_id())
155+ });
156+ homework
157+ };
158+ let total = homework.len() as i64;
159+ let items = paginate(&homework, limit, offset)
160+ .iter()
161+ .map(HomeworkResponse::new)
162+ .collect();
163+ Ok(Json(Page::new(items, total, limit, offset)))
164+}
165+
166+/// Fetch a single homework by id. Visible to whoever can view its course (its
167+/// enrolled users, creator, assigned teachers, and managers/admins). A student
168+/// the homework is *not* assigned to gets a 404 — the same no-leak an unseen
169+/// exam draft gets, so a subset assignment never reveals itself to the students
170+/// left out of it.
171+#[utoipa::path(
172+ get,
173+ path = "/{id}",
174+ tag = "homework",
175+ security(("session_cookie" = [])),
176+ params(("id" = String, Path, description = "Homework id")),
177+ responses(
178+ (status = 200, description = "The homework", body = HomeworkResponse),
179+ (status = 401, description = "Not authenticated", body = ErrorResponse),
180+ (status = 403, description = "Not enrolled in the homework's course, not its creator or an assigned teacher, and not a manager/admin", body = ErrorResponse),
181+ (status = 404, description = "Not found (or a subset assignment the caller is not part of)", body = ErrorResponse),
182+ ),
183+)]
184+async fn get_homework(
185+ State(st): State<AppState>,
186+ CurrentUser(user): CurrentUser,
187+ Path(id): Path<String>,
188+) -> Result<Json<HomeworkResponse>, AppError> {
189+ let (homework, course) = homework_with_course(&id, &st.db).await?;
190+ if !can_view_course(&course, &user, &st.db).await? {
191+ return Err(AppError::Forbidden(
192+ "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this homework",
193+ ));
194+ }
195+ // A student the homework is not assigned to must not even learn it exists —
196+ // 404, not 403, exactly like an exam draft hidden from non-managers.
197+ if !can_manage_course(&course, &user) && !homework.student_sees(user.get_id()) {
198+ return Err(AppError::NotFound);
199+ }
200+ Ok(Json(HomeworkResponse::new(&homework)))
201+}
202+
203+#[derive(Deserialize, ToSchema)]
204+struct UpdateHomework {
205+ /// Re-title. Omit to keep the current title.
206+ title: Option<String>,
207+ /// Re-describe. Omit to keep; send `null` (or `""`) to clear.
208+ #[serde(default, deserialize_with = "set_or_clear")]
209+ #[schema(value_type = Option<String>)]
210+ description: Option<Option<String>>,
211+ /// New due date, UTC unix-milliseconds. Omit to keep; a newly set value
212+ /// must not be in the past (a kept one may already be past).
213+ #[schema(example = 1_900_000_000_000_i64)]
214+ due_at: Option<i64>,
215+ /// Re-tag with another of the course's subjects
216+ /// (`GET /courses/{id}/subjects`). Omit to keep — a homework always has a
217+ /// subject, so there is no clear.
218+ subject_id: Option<String>,
219+ /// Re-scope the audience: a list of enrolled student ids, or an empty list
220+ /// / `null` for the whole course. Omit to keep. Narrowing is refused (409)
221+ /// while it would orphan a student who already submitted or was graded.
222+ #[serde(default, deserialize_with = "set_or_clear")]
223+ #[schema(value_type = Option<Vec<String>>)]
224+ assigned: Option<Option<Vec<String>>>,
225+}
226+
227+/// Edit a homework's title, description, due date, subject, or assigned subset.
228+/// Requires teacher+ and management rights over its course. Omitted fields keep
229+/// their value; a newly set `due_at` is re-checked against now and a new
230+/// `subject_id` re-checked against the course. Narrowing `assigned` is refused
231+/// (409) while it would orphan an existing submission or result.
232+#[utoipa::path(
233+ patch,
234+ path = "/{id}",
235+ tag = "homework",
236+ security(("session_cookie" = [])),
237+ params(("id" = String, Path, description = "Homework id")),
238+ request_body = UpdateHomework,
239+ responses(
240+ (status = 200, description = "Updated homework", body = HomeworkResponse),
241+ (status = 400, description = "Invalid title, description, due date, subject (unknown or from another course), or assigned list", body = ErrorResponse),
242+ (status = 401, description = "Not authenticated", body = ErrorResponse),
243+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
244+ (status = 404, description = "Not found", body = ErrorResponse),
245+ (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result", body = ErrorResponse),
246+ ),
247+)]
248+async fn update_homework(
249+ State(st): State<AppState>,
250+ RequireTeacher(user): RequireTeacher,
251+ Path(id): Path<String>,
252+ Json(req): Json<UpdateHomework>,
253+) -> Result<Json<HomeworkResponse>, AppError> {
254+ let (homework, course) = homework_with_course(&id, &st.db).await?;
255+ if !can_manage_course(&course, &user) {
256+ return Err(AppError::Forbidden(
257+ "only the course creator, an assigned teacher, or a manager/admin can edit this homework",
258+ ));
259+ }
260+
261+ let title = match req.title {
262+ Some(ref title) => HomeworkTitle::try_new(title)?,
263+ None => homework.get_title().clone(),
264+ };
265+ let description = match req.description {
266+ Some(Some(ref text)) => description_or_none(text)?,
267+ Some(None) => None,
268+ None => homework.get_description().cloned(),
269+ };
270+ let due_at = match req.due_at {
271+ Some(millis) => {
272+ let due_at = Timestamp::from_millis(millis);
273+ check_not_past("due_at", Some(due_at))?;
274+ due_at
275+ }
276+ None => homework.get_due_at(),
277+ };
278+ let subject = match req.subject_id {
279+ Some(ref subject_id) => subject_in_course(subject_id, course.get_id(), &st.db).await?,
280+ None => homework.get_subject().clone(),
281+ };
282+ let assigned = match req.assigned {
283+ Some(assigned) => {
284+ let resolved = resolve_assigned(assigned, course.get_id(), &st.db).await?;
285+ ensure_no_orphans(&homework, resolved.as_deref(), &st.db).await?;
286+ resolved
287+ }
288+ None => homework.get_assigned().map(<[UserId]>::to_vec),
289+ };
290+
291+ let updated = homework
292+ .update(&subject, title, description, due_at, assigned, &st.db)
293+ .await?;
294+ Ok(Json(HomeworkResponse::new(&updated)))
295+}
296+
297+/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student
298+/// who already submitted or was graded falls outside it — their work would be
299+/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in
300+/// which case no one can be orphaned). The blocking students are named in the
301+/// message so the teacher knows whose work to clear (or whom to keep assigned)
302+/// first.
303+async fn ensure_no_orphans(
304+ homework: &Homework,
305+ new_assigned: Option<&[UserId]>,
306+ db: &Database,
307+) -> Result<(), AppError> {
308+ // Whole-course covers everyone — no narrowing, no orphans.
309+ let Some(subset) = new_assigned else {
310+ return Ok(());
311+ };
312+ let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), db).await?;
313+ let results = HomeworkResult::list_for_homework(homework.get_id(), db).await?;
314+ let mut blocked: Vec<String> = Vec::new();
315+ for user in submissions
316+ .iter()
317+ .map(HomeworkSubmission::get_user)
318+ .chain(results.iter().map(HomeworkResult::get_user))
319+ {
320+ let key = user.key().to_string();
321+ if !subset.contains(user) && !blocked.contains(&key) {
322+ blocked.push(key);
323+ }
324+ }
325+ if blocked.is_empty() {
326+ Ok(())
327+ } else {
328+ Err(AppError::ConflictOwned(format!(
329+ "narrowing the assigned list would orphan existing work by {} student(s): {}",
330+ blocked.len(),
331+ blocked.join(", ")
332+ )))
333+ }
334+}
335+
336+/// Delete a homework and everything under it — submissions, their files, and
337+/// results — then unlink the file blobs from disk. Requires teacher+ and
338+/// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease
339+/// so no submission can land under the homework mid-delete; the blob names are
340+/// collected before the rows are wiped (the cascade is one transaction, children
341+/// first) and removed after, so a crash in between strands at worst an
342+/// unreachable file.
343+#[utoipa::path(
344+ delete,
345+ path = "/{id}",
346+ tag = "homework",
347+ security(("session_cookie" = [])),
348+ params(("id" = String, Path, description = "Homework id")),
349+ responses(
350+ (status = 204, description = "Deleted"),
351+ (status = 401, description = "Not authenticated", body = ErrorResponse),
352+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
353+ (status = 404, description = "Not found", body = ErrorResponse),
354+ ),
355+)]
356+async fn delete_homework(
357+ State(st): State<AppState>,
358+ RequireTeacher(user): RequireTeacher,
359+ Path(id): Path<String>,
360+) -> Result<StatusCode, AppError> {
361+ let (homework, course) = homework_with_course(&id, &st.db).await?;
362+ if !can_manage_course(&course, &user) {
363+ return Err(AppError::Forbidden(
364+ "only the course creator, an assigned teacher, or a manager/admin can delete this homework",
365+ ));
366+ }
367+ let _guard = HOMEWORK_LOCK.write().await;
368+ let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?;
369+ homework.delete(&st.db).await?;
370+ for key in &blob_keys {
371+ remove_blob(&st.files_path, key).await;
372+ }
373+ Ok(StatusCode::NO_CONTENT)
374+}
src/web/mod.rsmodified+3 -2
@@ -9,6 +9,7 @@ pub mod courses;
99 pub mod events;
1010 pub mod exam_ws;
1111 pub mod exams;
12+pub mod homework;
1213 pub mod marks;
1314 pub mod messages;
1415 pub mod notes;
@@ -26,8 +27,8 @@ mod extractor;
2627 mod page;
2728
2829 pub use dto::{
29- CourseResponse, ExamResponse, PersonRef, SessionResponse, SubjectResponse, UserResponse,
30- course_people, person_map,
30+ CourseResponse, ExamResponse, HomeworkResponse, PersonRef, SessionResponse, SubjectResponse,
31+ UserResponse, course_people, person_map,
3132 };
3233 pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireStudent, RequireTeacher};
3334 pub use page::{Page, PageParams, paginate};