forge
Explore
Log in

Don't you dare go Hollow

Grading, roster, observer report, sweeps

Browse files at this commit

854c5fb70dc9d057fa543e2792148f09d7ac9169Ahmet Kaan GümüşParent: 330819f
  • feat
    • grading, roster, observer report, sweeps
Show full message
✨ feat(homework): grading, roster, observer report, sweeps
src/domain/course.rsmodified+8 -3
@@ -287,11 +287,12 @@ impl Course {
287 287
288 /// Delete the course and cascade-remove everything inside it: results,288 /// Delete the course and cascade-remove everything inside it: results,
289 /// attempts, answers, and question/answer images of its exams, its289 /// attempts, answers, and question/answer images of its exams, its
290+ /// homework with their submissions, submission files, and grades, its
290 /// enrollments, its sessions with their roll call, its subjects, and the291 /// enrollments, its sessions with their roll call, its subjects, and the
291 /// exams themselves. The children go in one transaction so a crash can't292 /// exams themselves. The children go in one transaction so a crash can't
292- /// leave an exam pointing at a deleted course. The image *blobs* (question293+ /// leave an exam pointing at a deleted course. The image and
293- /// and answer) are the web layer's to remove — it collects their names294+ /// homework-file *blobs* are the web layer's to remove — it collects
294- /// before calling this.295+ /// their names before calling this.
295 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {296 pub async fn delete(self, db: &Database) -> Result<Course, AppError> {
296 db.query(297 db.query(
297 "BEGIN TRANSACTION;298 "BEGIN TRANSACTION;
@@ -301,10 +302,14 @@ impl Course {
301 DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);302 DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
302 DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);303 DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
303 DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);304 DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course);
305+ DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course));
306+ DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
307+ DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course);
304 DELETE session_attendance WHERE course = $course;308 DELETE session_attendance WHERE course = $course;
305 DELETE course_session WHERE course = $course;309 DELETE course_session WHERE course = $course;
306 DELETE enrollment WHERE course = $course;310 DELETE enrollment WHERE course = $course;
307 DELETE subject WHERE course = $course;311 DELETE subject WHERE course = $course;
312+ DELETE homework WHERE course = $course;
308 DELETE exam WHERE course = $course;313 DELETE exam WHERE course = $course;
309 COMMIT TRANSACTION;",314 COMMIT TRANSACTION;",
310 )315 )
src/domain/homework.rsmodified+13 -0
@@ -241,6 +241,19 @@ impl Homework {
241 Ok(result.take::<Vec<Homework>>(0)?)241 Ok(result.take::<Vec<Homework>>(0)?)
242 }242 }
243 243
244+ /// Whether any homework still references `subject` — the subject delete
245+ /// guard's question: a subject with homework can't be deleted until the
246+ /// homework is re-tagged or removed. Mirrors
247+ /// [`crate::domain::exam_question::ExamQuestion::any_for_subject`].
248+ pub async fn any_for_subject(subject: &SubjectId, db: &Database) -> Result<bool, AppError> {
249+ let mut result = db
250+ .query("SELECT VALUE id FROM homework WHERE subject = $subject LIMIT 1")
251+ .bind(("subject", subject.record()))
252+ .await?
253+ .check()?;
254+ Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())
255+ }
256+
244 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.257 /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework.
245 /// `course`, `created_by`, and `created_at` are untouched — the write258 /// `course`, `created_by`, and `created_at` are untouched — the write
246 /// re-sends them unchanged, which the `READONLY` schema permits (only a259 /// re-sends them unchanged, which the `READONLY` schema permits (only a
src/web/courses.rsmodified+16 -4
@@ -18,6 +18,7 @@ use crate::domain::exam::{
18 ExamTitle,18 ExamTitle,
19 };19 };
20 use crate::domain::homework::{Homework, HomeworkTitle};20 use crate::domain::homework::{Homework, HomeworkTitle};
21+use crate::domain::homework_file::HomeworkFile;
21 use crate::domain::question_image::QuestionImage;22 use crate::domain::question_image::QuestionImage;
22 use crate::domain::role::Role;23 use crate::domain::role::Role;
23 use crate::domain::settings::Settings;24 use crate::domain::settings::Settings;
@@ -27,7 +28,7 @@ use crate::domain::user::{User, UserId};
27 use crate::error::{AppError, ErrorResponse, ValidationError};28 use crate::error::{AppError, ErrorResponse, ValidationError};
28 use crate::state::AppState;29 use crate::state::AppState;
29 30
30-use super::homework::{description_or_none, resolve_assigned};31+use super::homework::{HOMEWORK_LOCK, description_or_none, resolve_assigned};
31 use super::sessions::resolve_session_teacher;32 use super::sessions::resolve_session_teacher;
32 use super::subjects::subject_in_course;33 use super::subjects::subject_in_course;
33 use super::terms::resolve_term;34 use super::terms::resolve_term;
@@ -451,8 +452,9 @@ async fn update_course(
451 452
452 /// Delete a course. Requires teacher+; only its creator or a manager/admin may453 /// Delete a course. Requires teacher+; only its creator or a manager/admin may
453 /// delete it — an assigned teacher runs the course but does not own it. Cascades the course's exams (with454 /// delete it — an assigned teacher runs the course but does not own it. Cascades the course's exams (with
454-/// their results, questions, answers, and question images), its sessions and455+/// their results, questions, answers, and question images), its homework (with
455-/// roll call, its subjects, and all enrollments.456+/// submissions, submission files, and grades), its sessions and roll call, its
457+/// subjects, and all enrollments.
456 #[utoipa::path(458 #[utoipa::path(
457 delete,459 delete,
458 path = "/{id}",460 path = "/{id}",
@@ -483,8 +485,13 @@ async fn delete_course(
483 // between strands at worst an unreachable blob.485 // between strands at worst an unreachable blob.
484 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;486 let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?;
485 let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?;487 let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?;
488+ let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?;
486 course.delete(&st.db).await?;489 course.delete(&st.db).await?;
487- for file in image_files.iter().chain(&answer_image_files) {490+ for file in image_files
491+ .iter()
492+ .chain(&answer_image_files)
493+ .chain(&homework_files)
494+ {
488 remove_blob(&st.files_path, file).await;495 remove_blob(&st.files_path, file).await;
489 }496 }
490 Ok(StatusCode::NO_CONTENT)497 Ok(StatusCode::NO_CONTENT)
@@ -1014,6 +1021,11 @@ async fn create_homework_in_course(
1014 };1021 };
1015 let due_at = Timestamp::from_millis(req.due_at);1022 let due_at = Timestamp::from_millis(req.due_at);
1016 check_not_past("due_at", Some(due_at))?;1023 check_not_past("due_at", Some(due_at))?;
1024+ // Reader lease of [`HOMEWORK_LOCK`], held from the subject check through
1025+ // the create: a subject delete (a writer, which checks for homework) can't
1026+ // vanish the subject between its validation here and the row landing with
1027+ // it.
1028+ let _guard = HOMEWORK_LOCK.read().await;
1017 let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?;1029 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?;1030 let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?;
1019 let homework = Homework::create(1031 let homework = Homework::create(
src/web/homework.rsmodified+454 -12
@@ -1,9 +1,9 @@
1-//! Homework entity endpoints: the cross-course "my homework" list plus lookup,1+//! Homework entity endpoints: the cross-course "my homework" list, lookup,
2-//! edit, and delete of one homework by id. Creation and the per-course listing2+//! edit, and delete of one homework by id, the student's submission with its
3-//! live under `/courses/{id}/homework` (see [`super::courses`]); student3+//! files, the teacher's grading and roster, and the observer report. Creation
4-//! submissions, files, grading, the roster, and the observer report arrive in4+//! and the per-course listing live under `/courses/{id}/homework` (see
5-//! later steps and reuse the visibility rule ([`Homework::student_sees`]), the5+//! [`super::courses`]); everything shares the visibility rule
6-//! [`HOMEWORK_LOCK`], and [`resolve_assigned`] from here.6+//! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`].
7 7
8 use axum::Json;8 use axum::Json;
9 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};9 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State};
@@ -19,10 +19,13 @@ use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVE
19 use crate::database::Database;19 use crate::database::Database;
20 use crate::domain::course::{Course, CourseId};20 use crate::domain::course::{Course, CourseId};
21 use crate::domain::enrollment::Enrollment;21 use crate::domain::enrollment::Enrollment;
22+use crate::domain::exam_result::Mark;
22 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};23 use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
23 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};24 use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
24-use crate::domain::homework_result::HomeworkResult;25+use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
25-use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId, SubmissionText};26+use crate::domain::homework_submission::{
27+ HomeworkSubmission, HomeworkSubmissionId, SubmissionText,
28+};
26 use crate::domain::note_file::{FileContentType, FileName};29 use crate::domain::note_file::{FileContentType, FileName};
27 use crate::domain::role::Role;30 use crate::domain::role::Role;
28 use crate::domain::settings::Settings;31 use crate::domain::settings::Settings;
@@ -36,7 +39,7 @@ use super::notes::content_disposition;
36 use super::subjects::subject_in_course;39 use super::subjects::subject_in_course;
37 use super::{40 use super::{
38 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,41 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,
39- check_not_past, paginate, read_upload, remove_blob, set_or_clear,42+ check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear,
40 };43 };
41 44
42 /// Serializes the homework subsystem's cross-record check-then-writes, which45 /// Serializes the homework subsystem's cross-record check-then-writes, which
@@ -65,10 +68,19 @@ pub fn routes() -> OpenApiRouter<AppState> {
65 .layer(DefaultBodyLimit::max(68 .layer(DefaultBodyLimit::max(
66 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,69 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
67 ));70 ));
71+ // `/report/{user}` and `/{id}` share a first segment; the router resolves
72+ // the static `report` ahead of the `{id}` capture (matchit's
73+ // static-beats-parameter rule), so the report never shadows a homework id —
74+ // and ULID keys can't spell "report" anyway.
68 OpenApiRouter::new()75 OpenApiRouter::new()
69 .routes(routes!(list_homework))76 .routes(routes!(list_homework))
70 .routes(routes!(get_homework, update_homework, delete_homework))77 .routes(routes!(get_homework, update_homework, delete_homework))
71 .routes(routes!(submit, get_submission, delete_submission))78 .routes(routes!(submit, get_submission, delete_submission))
79+ .routes(routes!(list_homework_submissions))
80+ .routes(routes!(grade_homework))
81+ .routes(routes!(remove_homework_result))
82+ .routes(routes!(my_homework_result))
83+ .routes(routes!(homework_report))
72 .merge(files)84 .merge(files)
73 }85 }
74 86
@@ -97,7 +109,10 @@ pub(crate) async fn resolve_assigned(
97 let mut users = Vec::with_capacity(keys.len());109 let mut users = Vec::with_capacity(keys.len());
98 for key in keys {110 for key in keys {
99 let user = UserId::from_key(&key);111 let user = UserId::from_key(&key);
100- if Enrollment::read_for_user(course, &user, db).await?.is_none() {112+ if Enrollment::read_for_user(course, &user, db)
113+ .await?
114+ .is_none()
115+ {
101 return Err(AppError::Validation(ValidationError::Invalid {116 return Err(AppError::Validation(ValidationError::Invalid {
102 field: "assigned",117 field: "assigned",
103 reason: "every assigned student must be enrolled in the course",118 reason: "every assigned student must be enrolled in the course",
@@ -158,7 +173,10 @@ async fn list_homework(
158 Homework::list_all(&st.db).await?173 Homework::list_all(&st.db).await?
159 } else {174 } else {
160 let courses = visible_courses(&user, &st.db).await?;175 let courses = visible_courses(&user, &st.db).await?;
161- let ids: Vec<_> = courses.iter().map(|course| course.get_id().clone()).collect();176+ let ids: Vec<_> = courses
177+ .iter()
178+ .map(|course| course.get_id().clone())
179+ .collect();
162 // A student sees only the homework they are assigned; a teacher who180 // A student sees only the homework they are assigned; a teacher who
163 // manages a course sees all of its homework (the manager+ path above181 // manages a course sees all of its homework (the manager+ path above
164 // already saw everything).182 // already saw everything).
@@ -276,6 +294,13 @@ async fn update_homework(
276 ));294 ));
277 }295 }
278 296
297+ // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the
298+ // live submissions and results, and the row write depends on what it saw —
299+ // without the lease a submission (a reader) could land between the check
300+ // and the write, orphaned by the narrowing that just missed it. The lease
301+ // also pins the subject re-tag against a concurrent subject delete.
302+ let _guard = HOMEWORK_LOCK.write().await;
303+
279 let title = match req.title {304 let title = match req.title {
280 Some(ref title) => HomeworkTitle::try_new(title)?,305 Some(ref title) => HomeworkTitle::try_new(title)?,
281 None => homework.get_title().clone(),306 None => homework.get_title().clone(),
@@ -604,7 +629,12 @@ async fn submit(
604 // A result can't exist here — the gate above would have 409'd.629 // A result can't exist here — the gate above would have 409'd.
605 Ok((630 Ok((
606 status,631 status,
607- Json(SubmissionResponse::new(&homework, &submission, &files, None)),632+ Json(SubmissionResponse::new(
633+ &homework,
634+ &submission,
635+ &files,
636+ None,
637+ )),
608 ))638 ))
609 }639 }
610 640
@@ -905,3 +935,415 @@ async fn delete_submission_file(
905 HomeworkSubmission::touch(&submission, &st.db).await?;935 HomeworkSubmission::touch(&submission, &st.db).await?;
906 Ok(StatusCode::NO_CONTENT)936 Ok(StatusCode::NO_CONTENT)
907 }937 }
938+
939+// ---- grading, roster, report ------------------------------------------------
940+
941+#[derive(Deserialize, ToSchema)]
942+struct GradeHomework {
943+ /// The student being graded.
944+ #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")]
945+ user: String,
946+ /// The verdict: `done`, `incomplete`, or `missing`.
947+ #[schema(example = "done")]
948+ status: String,
949+ /// An optional 0–100 mark on top of the status; omit to grade on status
950+ /// alone.
951+ mark: Option<i64>,
952+}
953+
954+/// Record (or overwrite) a student's grade for a homework: a status
955+/// (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires
956+/// teacher+ and management rights over the homework's course; the target must
957+/// be a live student, enrolled in the course, and in the homework's audience.
958+/// Nobody grades themselves. Grading before the due date, or before any
959+/// submission exists (`missing` for work never handed in), is allowed. A stored
960+/// grade freezes the student's submission until it is removed.
961+#[utoipa::path(
962+ post,
963+ path = "/{id}/results",
964+ tag = "homework",
965+ security(("session_cookie" = [])),
966+ params(("id" = String, Path, description = "Homework id")),
967+ request_body = GradeHomework,
968+ responses(
969+ (status = 200, description = "Grade recorded", body = HomeworkResultResponse),
970+ (status = 400, description = "Invalid status or mark, unknown user, user not a student, not enrolled, or not in the homework's audience", body = ErrorResponse),
971+ (status = 401, description = "Not authenticated", body = ErrorResponse),
972+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
973+ (status = 404, description = "Homework not found", body = ErrorResponse),
974+ ),
975+)]
976+async fn grade_homework(
977+ State(st): State<AppState>,
978+ RequireTeacher(teacher): RequireTeacher,
979+ Path(id): Path<String>,
980+ Json(req): Json<GradeHomework>,
981+) -> Result<Json<HomeworkResultResponse>, AppError> {
982+ // Writer lease of [`HOMEWORK_LOCK`], taken before the homework read: a
983+ // grade is what freezes a submission, so it must not interleave with the
984+ // read side's gate-through-write submission edits — and reading the
985+ // homework under the lease keeps a homework delete (a fellow writer) from
986+ // letting this upsert resurrect a result row under a vanished homework.
987+ let _guard = HOMEWORK_LOCK.write().await;
988+ let (homework, course) = homework_with_course(&id, &st.db).await?;
989+ if !can_manage_course(&course, &teacher) {
990+ return Err(AppError::Forbidden(
991+ "only the course creator, an assigned teacher, or a manager/admin can grade this homework",
992+ ));
993+ }
994+
995+ let status = HomeworkStatus::try_new(&req.status)?;
996+ let mark = req.mark.map(Mark::try_new).transpose()?;
997+ let target = UserId::from_key(&req.user);
998+
999+ // Grading never targets oneself — no grader, whatever their role, may
1000+ // write their own grade.
1001+ if &target == teacher.get_id() {
1002+ return Err(AppError::Forbidden("grading yourself is not allowed"));
1003+ }
1004+
1005+ // Target user must exist.
1006+ let Some(target_user) = User::read(&target, &st.db).await? else {
1007+ return Err(AppError::Validation(ValidationError::Invalid {
1008+ field: "user",
1009+ reason: "target user does not exist",
1010+ }));
1011+ };
1012+
1013+ // Only students carry homework grades — the live role, so a stale
1014+ // enrollment left behind by a promotion can't reopen grading for staff.
1015+ if target_user.get_role() != Role::Student {
1016+ return Err(AppError::Validation(ValidationError::Invalid {
1017+ field: "user",
1018+ reason: "only students can be graded",
1019+ }));
1020+ }
1021+
1022+ // ... enrolled in the homework's course ...
1023+ if Enrollment::read_for_user(homework.get_course(), &target, &st.db)
1024+ .await?
1025+ .is_none()
1026+ {
1027+ return Err(AppError::Validation(ValidationError::Invalid {
1028+ field: "user",
1029+ reason: "target user is not enrolled in this course",
1030+ }));
1031+ }
1032+
1033+ // ... and in the homework's audience — a subset assignment is also the
1034+ // grading roster, so a grade can't land on a student the homework never
1035+ // named.
1036+ if !homework.student_sees(&target) {
1037+ return Err(AppError::Validation(ValidationError::Invalid {
1038+ field: "user",
1039+ reason: "target user is not in this homework's audience",
1040+ }));
1041+ }
1042+
1043+ let result = HomeworkResult::grade(
1044+ homework.get_id(),
1045+ &target,
1046+ status,
1047+ mark,
1048+ teacher.get_id(),
1049+ &st.db,
1050+ )
1051+ .await?;
1052+ Ok(Json(HomeworkResultResponse::new(&result)))
1053+}
1054+
1055+/// Remove a student's grade from a homework — un-grading, which unfreezes the
1056+/// student's submission and files for further edits. Requires teacher+ and
1057+/// management rights over the homework's course.
1058+#[utoipa::path(
1059+ delete,
1060+ path = "/{id}/results/{user}",
1061+ tag = "homework",
1062+ security(("session_cookie" = [])),
1063+ params(
1064+ ("id" = String, Path, description = "Homework id"),
1065+ ("user" = String, Path, description = "User id"),
1066+ ),
1067+ responses(
1068+ (status = 204, description = "Removed"),
1069+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1070+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1071+ (status = 404, description = "No such homework, or no grade for this user", body = ErrorResponse),
1072+ ),
1073+)]
1074+async fn remove_homework_result(
1075+ State(st): State<AppState>,
1076+ RequireTeacher(user): RequireTeacher,
1077+ Path((id, target)): Path<(String, String)>,
1078+) -> Result<StatusCode, AppError> {
1079+ // Writer lease, before the read — the twin of grading's: removing the
1080+ // grade is what unfreezes the submission, so it must not straddle the read
1081+ // side's gate-through-write edits either.
1082+ let _guard = HOMEWORK_LOCK.write().await;
1083+ let (homework, course) = homework_with_course(&id, &st.db).await?;
1084+ if !can_manage_course(&course, &user) {
1085+ return Err(AppError::Forbidden(
1086+ "only the course creator, an assigned teacher, or a manager/admin can remove grades",
1087+ ));
1088+ }
1089+ let removed =
1090+ HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?;
1091+ if removed.is_none() {
1092+ return Err(AppError::NotFound);
1093+ }
1094+ Ok(StatusCode::NO_CONTENT)
1095+}
1096+
1097+/// The caller's own grade for a homework. Any authenticated user may read
1098+/// their own; `404` while ungraded (or when the homework doesn't exist). This
1099+/// is the one read a student graded `missing` *without* ever submitting has —
1100+/// their submission endpoints 404 while nothing is submitted.
1101+#[utoipa::path(
1102+ get,
1103+ path = "/{id}/result",
1104+ tag = "homework",
1105+ security(("session_cookie" = [])),
1106+ params(("id" = String, Path, description = "Homework id")),
1107+ responses(
1108+ (status = 200, description = "The caller's grade", body = HomeworkResultResponse),
1109+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1110+ (status = 404, description = "No such homework, or not graded yet", body = ErrorResponse),
1111+ ),
1112+)]
1113+async fn my_homework_result(
1114+ State(st): State<AppState>,
1115+ CurrentUser(user): CurrentUser,
1116+ Path(id): Path<String>,
1117+) -> Result<Json<HomeworkResultResponse>, AppError> {
1118+ let result = HomeworkResult::read_for(&HomeworkId::from_key(&id), user.get_id(), &st.db)
1119+ .await?
1120+ .ok_or(AppError::NotFound)?;
1121+ Ok(Json(HomeworkResultResponse::new(&result)))
1122+}
1123+
1124+/// The submission part of a roster row — the student's work without the grade,
1125+/// which sits beside it on the row (a graded-but-never-submitted student
1126+/// carries a grade and no submission).
1127+#[derive(Serialize, ToSchema)]
1128+struct HomeworkRosterSubmission {
1129+ /// The optional free-text note; `null` when none was given.
1130+ text: Option<String>,
1131+ /// First hand-in, UTC unix-milliseconds (immutable across re-submits).
1132+ submitted_at: i64,
1133+ /// Last touched — a text edit or a file add/delete — UTC unix-milliseconds.
1134+ updated_at: i64,
1135+ /// Whether the submission was last touched after the homework's `due_at`.
1136+ late: bool,
1137+ /// The attached files, newest first (metadata only).
1138+ files: Vec<HomeworkFileResponse>,
1139+}
1140+
1141+/// One student's line in a homework's teacher roster.
1142+#[derive(Serialize, ToSchema)]
1143+struct HomeworkRosterEntry {
1144+ /// The student.
1145+ user: String,
1146+ /// Their submission, if they handed anything in.
1147+ submission: Option<HomeworkRosterSubmission>,
1148+ /// Their grade, if the teacher recorded one.
1149+ result: Option<HomeworkResultResponse>,
1150+ /// Computed: nothing submitted and the due date has passed. Independent of
1151+ /// the teacher-set `missing` status, which is a deliberate verdict.
1152+ missing: bool,
1153+ /// Computed: the student is no longer enrolled in the course. Their stale
1154+ /// rows stay readable here, but they can't submit and can't be graded.
1155+ unenrolled: bool,
1156+}
1157+
1158+/// The teacher's roster for a homework, paged via `?limit=&offset=` (omit
1159+/// `limit` for all of it): one row per student in the audience — the assigned
1160+/// subset, or every currently enrolled student for a whole-course homework —
1161+/// plus any student outside it who still owns a submission or grade (an
1162+/// unenrollment or an audience change leaves work behind; it stays visible
1163+/// here, flagged). Each row carries the submission with its files and computed
1164+/// late flag, the grade, a computed `missing`, and a computed `unenrolled`.
1165+/// Requires teacher+ and management rights over the homework's course. Returns
1166+/// a `{items, total, limit, offset}` envelope.
1167+#[utoipa::path(
1168+ get,
1169+ path = "/{id}/submissions",
1170+ tag = "homework",
1171+ security(("session_cookie" = [])),
1172+ params(("id" = String, Path, description = "Homework id"), PageParams),
1173+ responses(
1174+ (status = 200, description = "A page of roster rows (all of them when unpaged)", body = Page<HomeworkRosterEntry>),
1175+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1176+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1177+ (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
1178+ (status = 404, description = "Homework not found", body = ErrorResponse),
1179+ ),
1180+)]
1181+async fn list_homework_submissions(
1182+ State(st): State<AppState>,
1183+ RequireTeacher(user): RequireTeacher,
1184+ Path(id): Path<String>,
1185+ Query(page): Query<PageParams>,
1186+) -> Result<Json<Page<HomeworkRosterEntry>>, AppError> {
1187+ let (limit, offset) = page.resolve()?;
1188+ let (homework, course) = homework_with_course(&id, &st.db).await?;
1189+ if !can_manage_course(&course, &user) {
1190+ return Err(AppError::Forbidden(
1191+ "only the course creator, an assigned teacher, or a manager/admin can list submissions",
1192+ ));
1193+ }
1194+ let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?;
1195+ let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?;
1196+ let enrolled: Vec<String> = Enrollment::list_for_course(course.get_id(), &st.db)
1197+ .await?
1198+ .iter()
1199+ .map(|enrollment| enrollment.get_user().key().to_string())
1200+ .collect();
1201+ // The audience: the assigned subset as stored, or — whole-course — whoever
1202+ // is enrolled right now. Anyone outside it who still owns a submission or
1203+ // grade is appended rather than dropped: their stale rows are exactly what
1204+ // a narrowing 409 names as blockers, so the teacher must be able to see
1205+ // them. Sorted by student id for a stable page window.
1206+ let mut users: Vec<String> = match homework.get_assigned() {
1207+ Some(assigned) if !assigned.is_empty() => {
1208+ assigned.iter().map(|user| user.key().to_string()).collect()
1209+ }
1210+ _ => enrolled.clone(),
1211+ };
1212+ for holder in submissions
1213+ .iter()
1214+ .map(HomeworkSubmission::get_user)
1215+ .chain(results.iter().map(HomeworkResult::get_user))
1216+ {
1217+ let key = holder.key().to_string();
1218+ if !users.contains(&key) {
1219+ users.push(key);
1220+ }
1221+ }
1222+ users.sort();
1223+ users.dedup();
1224+ let total = users.len() as i64;
1225+ // Join the heavy parts (the file lists) onto the page alone.
1226+ let mut items = Vec::new();
1227+ for user_key in paginate(&users, limit, offset) {
1228+ let submission = match submissions
1229+ .iter()
1230+ .find(|submission| submission.get_user().key() == user_key)
1231+ {
1232+ Some(submission) => Some(HomeworkRosterSubmission {
1233+ text: submission.get_text().map(|text| text.as_str().to_string()),
1234+ submitted_at: submission.get_submitted_at().as_millis(),
1235+ updated_at: submission.get_updated_at().as_millis(),
1236+ late: submission.get_updated_at() > homework.get_due_at(),
1237+ files: HomeworkFile::list_for_submission(submission.get_id(), &st.db)
1238+ .await?
1239+ .iter()
1240+ .map(HomeworkFileResponse::new)
1241+ .collect(),
1242+ }),
1243+ None => None,
1244+ };
1245+ items.push(HomeworkRosterEntry {
1246+ user: user_key.clone(),
1247+ missing: submission.is_none() && Timestamp::now() > homework.get_due_at(),
1248+ unenrolled: !enrolled.contains(user_key),
1249+ submission,
1250+ result: results
1251+ .iter()
1252+ .find(|result| result.get_user().key() == user_key)
1253+ .map(HomeworkResultResponse::new),
1254+ });
1255+ }
1256+ Ok(Json(Page::new(items, total, limit, offset)))
1257+}
1258+
1259+/// One homework on a student's report: the assignment context plus what the
1260+/// student did with it and how it was graded, if it was.
1261+#[derive(Serialize, ToSchema)]
1262+struct HomeworkReportEntry {
1263+ /// The course the homework belongs to.
1264+ course: String,
1265+ /// The homework id.
1266+ homework: String,
1267+ title: String,
1268+ /// The course subject the homework is tagged with.
1269+ subject: String,
1270+ /// When it was due, UTC unix-milliseconds.
1271+ due_at: i64,
1272+ /// Whether the student has submitted anything.
1273+ submitted: bool,
1274+ /// Whether the submission was last touched after `due_at`.
1275+ late: bool,
1276+ /// Computed: nothing submitted and the due date has passed — independent
1277+ /// of a teacher-set `missing` status.
1278+ missing: bool,
1279+ /// The grade, once one exists.
1280+ result: Option<HomeworkResultResponse>,
1281+}
1282+
1283+/// A student's homework report across their enrolled courses, paged via
1284+/// `?limit=&offset=` (omit `limit` for all of it): one row per homework in
1285+/// their audience — submitted/late/missing state plus the grade once one
1286+/// exists. Statuses and marks, never the submitted files (observers get the
1287+/// report, not the bytes). Requires teacher+, or a parent linked to the target
1288+/// student. Managers, admins, and parents see every course; a teacher sees only
1289+/// the target's courses they manage. Returns a `{items, total, limit, offset}`
1290+/// envelope.
1291+#[utoipa::path(
1292+ get,
1293+ path = "/report/{user}",
1294+ tag = "homework",
1295+ security(("session_cookie" = [])),
1296+ params(("user" = String, Path, description = "User id"), PageParams),
1297+ responses(
1298+ (status = 200, description = "A page of the user's homework report (all of it when unpaged)", body = Page<HomeworkReportEntry>),
1299+ (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1300+ (status = 401, description = "Not authenticated", body = ErrorResponse),
1301+ (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
1302+ (status = 404, description = "User not found", body = ErrorResponse),
1303+ ),
1304+)]
1305+async fn homework_report(
1306+ State(st): State<AppState>,
1307+ CurrentUser(caller): CurrentUser,
1308+ Path(user): Path<String>,
1309+ Query(page): Query<PageParams>,
1310+) -> Result<Json<Page<HomeworkReportEntry>>, AppError> {
1311+ let (limit, offset) = page.resolve()?;
1312+ let target = UserId::from_key(&user);
1313+ ensure_can_observe(&caller, &target, &st.db).await?;
1314+ // User must exist — a missing user is a 404, not an empty report.
1315+ User::read(&target, &st.db)
1316+ .await?
1317+ .ok_or(AppError::NotFound)?;
1318+ // Only an exactly-teacher caller is narrowed to their managed courses;
1319+ // manager+ and a linked parent read the full report (the marks idiom).
1320+ let mut courses = Course::list_enrolled(&target, &st.db).await?;
1321+ if caller.get_role() == Role::Teacher {
1322+ courses.retain(|course| can_manage_course(course, &caller));
1323+ }
1324+ let mut rows = Vec::new();
1325+ for course in &courses {
1326+ rows.extend(Homework::list_for_user_in_course(course.get_id(), &target, &st.db).await?);
1327+ }
1328+ let total = rows.len() as i64;
1329+ // Join submissions and grades onto the page alone.
1330+ let mut items = Vec::new();
1331+ for homework in paginate(&rows, limit, offset) {
1332+ let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?;
1333+ let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?;
1334+ items.push(HomeworkReportEntry {
1335+ course: homework.get_course().key().to_string(),
1336+ homework: homework.get_id().key().to_string(),
1337+ title: homework.get_title().as_str().to_string(),
1338+ subject: homework.get_subject().key().to_string(),
1339+ due_at: homework.get_due_at().as_millis(),
1340+ submitted: submission.is_some(),
1341+ late: submission
1342+ .as_ref()
1343+ .is_some_and(|submission| submission.get_updated_at() > homework.get_due_at()),
1344+ missing: submission.is_none() && Timestamp::now() > homework.get_due_at(),
1345+ result: result.as_ref().map(HomeworkResultResponse::new),
1346+ });
1347+ }
1348+ Ok(Json(Page::new(items, total, limit, offset)))
1349+}
src/web/subjects.rsmodified+18 -3
@@ -9,12 +9,14 @@ use utoipa_axum::routes;
9 use crate::database::Database;9 use crate::database::Database;
10 use crate::domain::course::{Course, CourseId};10 use crate::domain::course::{Course, CourseId};
11 use crate::domain::exam_question::ExamQuestion;11 use crate::domain::exam_question::ExamQuestion;
12+use crate::domain::homework::Homework;
12 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};13 use crate::domain::subject::{Subject, SubjectDescription, SubjectId, SubjectName};
13 use crate::error::{AppError, ErrorResponse, ValidationError};14 use crate::error::{AppError, ErrorResponse, ValidationError};
14 use crate::state::AppState;15 use crate::state::AppState;
15 16
16 use super::courses::{can_manage_course, can_view_course};17 use super::courses::{can_manage_course, can_view_course};
17 use super::exams::EXAM_LOCK;18 use super::exams::EXAM_LOCK;
19+use super::homework::HOMEWORK_LOCK;
18 use super::{CurrentUser, RequireTeacher, SubjectResponse};20 use super::{CurrentUser, RequireTeacher, SubjectResponse};
19 21
20 pub fn routes() -> OpenApiRouter<AppState> {22 pub fn routes() -> OpenApiRouter<AppState> {
@@ -139,8 +141,9 @@ async fn update_subject(
139 }141 }
140 142
141 /// Delete a subject. Requires teacher+ and management rights over its course.143 /// Delete a subject. Requires teacher+ and management rights over its course.
142-/// Refused with a 409 while any exam question still references it — re-tag or144+/// Refused with a 409 while any exam question or homework still references it —
143-/// delete those questions first, so no question is left without a real subject.145+/// re-tag or delete those first, so nothing is left pointing at a subject that
146+/// no longer exists.
144 #[utoipa::path(147 #[utoipa::path(
145 delete,148 delete,
146 path = "/{id}",149 path = "/{id}",
@@ -152,7 +155,7 @@ async fn update_subject(
152 (status = 401, description = "Not authenticated", body = ErrorResponse),155 (status = 401, description = "Not authenticated", body = ErrorResponse),
153 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),156 (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse),
154 (status = 404, description = "Not found", body = ErrorResponse),157 (status = 404, description = "Not found", body = ErrorResponse),
155- (status = 409, description = "Exam questions still reference this subject", body = ErrorResponse),158+ (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse),
156 ),159 ),
157 )]160 )]
158 async fn delete_subject(161 async fn delete_subject(
@@ -175,6 +178,18 @@ async fn delete_subject(
175 "exam questions still reference this subject — re-tag or delete them first",178 "exam questions still reference this subject — re-tag or delete them first",
176 ));179 ));
177 }180 }
181+ // The homework twin of the guard above, under [`HOMEWORK_LOCK`]'s writer
182+ // lease: homework create validates its subject under the read side and the
183+ // PATCH re-tag under the write side, so the no-homework check and the
184+ // delete can't straddle a row that just adopted this subject. This is the
185+ // only place both locks are held; the order is EXAM_LOCK, then
186+ // HOMEWORK_LOCK.
187+ let _homework_guard = HOMEWORK_LOCK.write().await;
188+ if Homework::any_for_subject(subject.get_id(), &st.db).await? {
189+ return Err(AppError::Conflict(
190+ "homework still references this subject — re-tag or delete it first",
191+ ));
192+ }
178 subject.delete(&st.db).await?;193 subject.delete(&st.db).await?;
179 Ok(StatusCode::NO_CONTENT)194 Ok(StatusCode::NO_CONTENT)
180 }195 }