forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

homework.rs1751 lines, 76.7 KiBHistoryRawDownload
1//! Homework entity endpoints: the cross-instance "my homework" list, lookup,
2//! edit, and delete of one homework by id, the student's submission with its
3//! files, the teacher's grading and roster, and the observer report. Creation
4//! and the per-instance listing live under `/instances/{id}/homework` (see
5//! [`super::instances`]); everything shares the visibility rule
6//! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees))
7//! The freeze and the audience interlock are conditions of the writes
8//! themselves ([`crate::db::homework_submission`]), serialized on the
9//! homework row's lock inside each transaction.
10
11use crate::web::tenant_state::State;
12use axum::Json;
13use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
14use axum::http::header::{CONTENT_DISPOSITION, CONTENT_TYPE};
15use axum::http::{HeaderValue, StatusCode};
16use axum::response::{IntoResponse, Response};
17use serde::{Deserialize, Serialize};
18use utoipa::{IntoParams, ToSchema};
19use utoipa_axum::router::OpenApiRouter;
20use utoipa_axum::routes;
21
22use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
23use crate::database::Database;
24use crate::domain::class_course::{ClassCourse, ClassCourseId};
25
26use crate::domain::exam_result::Mark;
27use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle};
28use crate::domain::homework_file::{HomeworkFile, HomeworkFileId};
29use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
30use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText};
31use crate::domain::note_file::{FileContentType, FileName};
32use crate::domain::role::Role;
33use crate::domain::timestamp::Timestamp;
34use crate::domain::user::UserId;
35use crate::error::{AppError, ErrorResponse, ValidationError};
36use crate::service;
37use crate::service::instance::{can_manage_instance, visible_instances};
38use crate::service::parent_link::ensure_can_observe;
39use crate::state::AppState;
40
41use super::instances::can_view_instance;
42use super::notes::content_disposition;
43use super::{
44 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,
45 check_not_past, paginate, read_upload, remove_blob, set_or_clear,
46};
47
48pub fn routes() -> OpenApiRouter<AppState> {
49 // The file-upload route carries a larger HTTP body cap than axum's 2 MB
50 // default — the server-wide hard ceiling plus multipart framing headroom;
51 // the school's actual, usually smaller, limit is enforced while the stream
52 // is read. Same split as notes' file routes (the download/delete siblings
53 // ride along under the cap harmlessly, having no body).
54 let files = OpenApiRouter::new()
55 .routes(routes!(upload_submission_file))
56 .routes(routes!(download_submission_file, delete_submission_file))
57 .layer(DefaultBodyLimit::max(
58 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
59 ));
60 // `/report/{user}` and `/{id}` share a first segment; the router resolves
61 // the static `report` ahead of the `{id}` capture (matchit's
62 // static-beats-parameter rule), so the report never shadows a homework id —
63 // and ULID keys can't spell "report" anyway.
64 OpenApiRouter::new()
65 .routes(routes!(list_homework))
66 .routes(routes!(get_homework, update_homework, delete_homework))
67 .routes(routes!(submit, get_submission, delete_submission))
68 .routes(routes!(list_homework_submissions))
69 .routes(routes!(grade_homework))
70 .routes(routes!(remove_homework_result))
71 .routes(routes!(my_homework_result))
72 .routes(routes!(homework_report))
73 .merge(files)
74}
75
76/// Validate a request's `assigned` list into a stored student subset. `None`,
77/// an explicit `null`, and an empty list all mean "the whole enrolled roster"
78/// (stored as `None`); a non-empty list must name at most
79/// [`MAX_HOMEWORK_ASSIGNED`] students, each currently enrolled in `instance`.
80/// Deduped so a repeated id can't inflate the cap or double a roster row.
81/// Shared by the create ([`super::instances`]) and PATCH handlers.
82pub(crate) async fn resolve_assigned(
83 assigned: Option<Vec<String>>,
84 instance: &ClassCourseId,
85 db: &Database,
86) -> Result<Option<Vec<UserId>>, AppError> {
87 let Some(mut keys) = assigned.filter(|keys| !keys.is_empty()) else {
88 return Ok(None);
89 };
90 keys.sort();
91 keys.dedup();
92 if keys.len() > MAX_HOMEWORK_ASSIGNED {
93 return Err(AppError::Validation(ValidationError::Invalid {
94 field: "assigned",
95 reason: "may name at most 200 students",
96 }));
97 }
98 let mut users = Vec::with_capacity(keys.len());
99 for key in keys {
100 let user = UserId::from_key(&key);
101 if service::enrollment::read_for_user(db, instance, &user)
102 .await?
103 .is_none()
104 {
105 return Err(AppError::Validation(ValidationError::Invalid {
106 field: "assigned",
107 reason: "every assigned student must be enrolled in the instance",
108 }));
109 }
110 users.push(user);
111 }
112 Ok(Some(users))
113}
114
115/// A homework description off the wire: an empty string means "none", anything
116/// else is length-validated. Shared by create and PATCH so both treat `""` the
117/// same (a stored empty description would be a needless present-but-blank row).
118pub(crate) fn description_or_none(text: &str) -> Result<Option<HomeworkDescription>, AppError> {
119 if text.is_empty() {
120 Ok(None)
121 } else {
122 Ok(Some(HomeworkDescription::try_new(text)?))
123 }
124}
125
126/// The homework plus its instance, or a 404 — every entity handler here gates
127/// on the parent instance, so they always travel together.
128async fn homework_with_instance(
129 id: &str,
130 db: &Database,
131) -> Result<(Homework, ClassCourse), AppError> {
132 let homework = service::homework::read(db, &HomeworkId::from_key(id))
133 .await?
134 .ok_or(AppError::NotFound)?;
135 let instance = crate::service::class_course::read(db, homework.get_class_course())
136 .await?
137 .ok_or(AppError::NotFound)?;
138 Ok((homework, instance))
139}
140
141/// The optional `?due_after=&due_before=&class_course=` scoping of the list.
142/// `due_after` keeps homework due at or after an instant (the frontend's open
143/// tab), `due_before` keeps what is due before one (the past tab) — the two
144/// bounds share no instant and leave no gap — and `class_course` scopes the
145/// list to one instance. Absent, each field filters nothing.
146#[derive(Debug, Deserialize, IntoParams)]
147struct HomeworkListFilter {
148 /// Keep homework due at or after this instant (Unix ms).
149 due_after: Option<i64>,
150 /// Keep homework due before this instant (Unix ms).
151 due_before: Option<i64>,
152 /// Keep only this class×course instance's homework (an instance id).
153 #[param(example = "019732e3-7b00-7000-8000-00000000face")]
154 class_course: Option<String>,
155}
156
157impl HomeworkListFilter {
158 /// Validate the raw query into the service-layer scope. A negative due
159 /// bound, an empty instance key, and a key that is not a hyphenated uuid
160 /// (the nil id included — [`ClassCourseId::from_key`] lands there) are
161 /// refused with the field named; a well-formed id that names no row
162 /// simply matches nothing.
163 fn resolve(self) -> Result<service::homework::HomeworkListFilter, AppError> {
164 let invalid =
165 |field: &'static str, reason: &'static str| AppError::Validation(ValidationError::Invalid { field, reason });
166 let due_after = match self.due_after {
167 None => None,
168 Some(ms) if ms < 0 => return Err(invalid("due_after", "must not be negative")),
169 Some(ms) => Some(ms),
170 };
171 let due_before = match self.due_before {
172 None => None,
173 Some(ms) if ms < 0 => return Err(invalid("due_before", "must not be negative")),
174 Some(ms) => Some(ms),
175 };
176 let class_course = match self.class_course.as_deref().map(str::trim) {
177 None => None,
178 Some("") => return Err(invalid("class_course", "must not be empty")),
179 Some(key) => {
180 let instance = ClassCourseId::from_key(key);
181 if instance.uuid().is_nil() {
182 return Err(invalid("class_course", "must be a hyphenated uuid"));
183 }
184 Some(instance)
185 }
186 };
187 Ok(service::homework::HomeworkListFilter {
188 due_after,
189 due_before,
190 class_course,
191 })
192 }
193}
194
195/// List the homework across the caller's instances — their "my homework" view —
196/// paged via `?limit=&offset=` (omit `limit` for all of it). Manager+ see every
197/// instance's homework; a teacher sees the homework of instances they run; a
198/// student sees only the homework they are assigned (whole-roster ones plus any
199/// subset that names them, each with its `assigned` narrowed to themselves).
200/// Returns a `{items, total, limit, offset}` envelope.
201///
202/// `due_after` and `due_before` (Unix ms) carry the frontend's open and past
203/// tabs — due at or after an instant, due before one — and `class_course`
204/// scopes the list to a single instance, all before anything leaves the
205/// database. Omitted, the response is the caller's whole visible homework,
206/// unchanged.
207#[utoipa::path(
208 get,
209 path = "/",
210 tag = "homework",
211 security(("session_cookie" = [])),
212 params(PageParams, HomeworkListFilter),
213 responses(
214 (status = 200, description = "A page of the caller's visible homework (all of it when unpaged)", body = Page<HomeworkResponse>),
215 (status = 400, description = "Invalid limit, offset, or filter", body = ErrorResponse),
216 (status = 401, description = "Not authenticated", body = ErrorResponse),
217 ),
218)]
219async fn list_homework(
220 State(st): State<AppState>,
221 CurrentUser(user): CurrentUser,
222 Query(page): Query<PageParams>,
223 Query(filter): Query<HomeworkListFilter>,
224) -> Result<Json<Page<HomeworkResponse>>, AppError> {
225 let (limit, offset) = page.resolve()?;
226 let filter = filter.resolve()?;
227 // The instances this caller manages — empty for a manager+, who manages all
228 // of them, and who is told apart by this flag.
229 let manages_all = user.get_role().at_least(Role::Manager);
230 if manages_all {
231 // The SQL WHERE is the whole filter on this path: a manager retains
232 // nothing in Rust, so the window and the count both run in the
233 // database and `total` comes back with the page.
234 let (homework, total) =
235 service::homework::list_all(&st.db, &filter, limit, offset).await?;
236 let items = homework.iter().map(HomeworkResponse::new).collect();
237 return Ok(Json(Page::new(items, total, limit, offset)));
238 }
239 let instances = visible_instances(&user, &st.db).await?;
240 let ids: Vec<ClassCourseId> = instances
241 .iter()
242 .map(|(instance, _)| instance.get_id().clone())
243 .collect();
244 // A student sees only the homework they are assigned; a teacher who
245 // manages an instance sees all of its homework (the manager+ path above
246 // already saw everything).
247 let managed: Vec<ClassCourseId> = instances
248 .iter()
249 .filter(|(_, manages)| *manages)
250 .map(|(instance, _)| instance.get_id().clone())
251 .collect();
252 let mut homework = service::homework::list_for_class_courses(&st.db, &ids, &filter).await?;
253 // The audience retain stays after the SQL filter and before the window,
254 // so `total` is the post-retain length, never a page sliced before it.
255 homework
256 .retain(|hw| managed.contains(hw.get_class_course()) || hw.student_sees(user.get_id()));
257 let total = homework.len() as i64;
258 // Paged in the web layer: the audience filter above is per-row Rust. The
259 // subset roster rides along only for the rows the caller manages — to a
260 // student it is narrowed to themselves, as it is on the single-homework
261 // read.
262 let items = paginate(&homework, limit, offset)
263 .iter()
264 .map(|hw| {
265 if managed.contains(hw.get_class_course()) {
266 HomeworkResponse::new(hw)
267 } else {
268 HomeworkResponse::for_viewer(hw, user.get_id())
269 }
270 })
271 .collect();
272 Ok(Json(Page::new(items, total, limit, offset)))
273}
274
275/// Fetch a single homework by id. Visible to whoever can view its instance (its
276/// enrolled students, its teachers, its class section's homeroom teacher, and
277/// managers/admins). A student the homework is *not* assigned to gets a 404 —
278/// the same no-leak an unseen exam draft gets, so a subset assignment never
279/// reveals itself to the students left out of it. To a caller without
280/// instance-management rights the `assigned` subset comes back narrowed to their
281/// own id: being named is theirs to know, the rest of the roster is not.
282#[utoipa::path(
283 get,
284 path = "/{id}",
285 tag = "homework",
286 security(("session_cookie" = [])),
287 params(("id" = String, Path, description = "Homework id")),
288 responses(
289 (status = 200, description = "The homework", body = HomeworkResponse),
290 (status = 401, description = "Not authenticated", body = ErrorResponse),
291 (status = 403, description = "Not enrolled in the homework's instance, not one of its teachers, and not a manager/admin", body = ErrorResponse),
292 (status = 404, description = "Not found (or a subset assignment the caller is not part of)", body = ErrorResponse),
293 ),
294)]
295async fn get_homework(
296 State(st): State<AppState>,
297 CurrentUser(user): CurrentUser,
298 Path(id): Path<String>,
299) -> Result<Json<HomeworkResponse>, AppError> {
300 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
301 if !can_view_instance(&st.db, instance.get_id(), &user).await? {
302 return Err(AppError::Forbidden(
303 "only the instance's enrolled students, its teachers, its şube's homeroom teacher, or a manager/admin can view this homework",
304 ));
305 }
306 // A student the homework is not assigned to must not even learn it exists —
307 // 404, not 403, exactly like an exam draft hidden from non-managers.
308 let manages = can_manage_instance(&st.db, instance.get_id(), &user).await?;
309 if !manages && !homework.student_sees(user.get_id()) {
310 return Err(AppError::NotFound);
311 }
312 // ... and one it *is* assigned to must not hand them the rest of the
313 // subset: the same no-leak, one step further in.
314 Ok(Json(if manages {
315 HomeworkResponse::new(&homework)
316 } else {
317 HomeworkResponse::for_viewer(&homework, user.get_id())
318 }))
319}
320
321#[derive(Deserialize, ToSchema)]
322struct UpdateHomework {
323 /// Re-title. Omit to keep the current title.
324 #[schema(max_length = 200)]
325 title: Option<String>,
326 /// Re-describe. Omit to keep; send `null` (or `""`) to clear.
327 #[serde(default, deserialize_with = "set_or_clear")]
328 #[schema(value_type = Option<String>, max_length = 2_000)]
329 description: Option<Option<String>>,
330 /// New due date, UTC unix-milliseconds. Omit to keep; a newly set value
331 /// must not be in the past (a kept one may already be past).
332 #[schema(example = 1_900_000_000_000_i64)]
333 due_at: Option<i64>,
334 /// Re-tag with another of the course's subjects
335 /// (`GET /courses/{id}/subjects`). Omit to keep — a homework always has a
336 /// subject, so there is no clear.
337 subject_id: Option<String>,
338 /// Re-scope the audience: a list of enrolled student ids, or an empty list
339 /// / `null` for the whole course. Omit to keep. Narrowing is refused (409)
340 /// while it would orphan a student who already submitted or was graded.
341 #[serde(default, deserialize_with = "set_or_clear")]
342 #[schema(value_type = Option<Vec<String>>, max_items = 200)]
343 assigned: Option<Option<Vec<String>>>,
344}
345
346/// Edit a homework's title, description, due date, subject, or assigned subset.
347/// Requires teacher+ and management rights over its instance. Omitted fields
348/// keep their value; a newly set `due_at` is re-checked against now and a new
349/// `subject_id` re-checked against the instance's resolved subject set (the
350/// offering's selection, or the section's own while it overrides). Narrowing
351/// `assigned` is refused (409) while it would orphan an existing submission or
352/// result.
353#[utoipa::path(
354 patch,
355 path = "/{id}",
356 tag = "homework",
357 security(("session_cookie" = [])),
358 params(("id" = String, Path, description = "Homework id")),
359 request_body = UpdateHomework,
360 responses(
361 (status = 200, description = "Updated homework", body = HomeworkResponse),
362 (status = 400, description = "Invalid title, description, due date, subject (unknown, from another course, or outside the instance's resolved subject set), or assigned list", body = ErrorResponse),
363 (status = 401, description = "Not authenticated", body = ErrorResponse),
364 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
365 (status = 404, description = "Not found", body = ErrorResponse),
366 (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result, or the subject this update re-tags from changed since the caller read it — nothing was written, re-read and retry; or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
367 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
368 ),
369)]
370async fn update_homework(
371 State(st): State<AppState>,
372 RequireTeacher(user): RequireTeacher,
373 Path(id): Path<String>,
374 Json(req): Json<UpdateHomework>,
375) -> Result<Json<HomeworkResponse>, AppError> {
376 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
377 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
378 return Err(AppError::Forbidden(
379 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can edit this homework",
380 ));
381 }
382 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
383
384 // The orphan guard and the write are one unit in
385 // [`service::homework::update`]: the guard reads the live submissions and
386 // results inside the write's transaction, under the homework row's lock —
387 // a submission (which locks the same row before writing) cannot land
388 // between the check and the narrowing that just missed it.
389
390 // Only what the request carried: an omitted field stays `None` and is never
391 // written, so a concurrent PATCH of another field survives. The two
392 // nullable columns keep their double option — `Some(None)` still clears.
393 let title = req
394 .title
395 .as_deref()
396 .map(HomeworkTitle::try_new)
397 .transpose()?;
398 // `null` and `""` both mean "clear" here, as they always have.
399 let description = req
400 .description
401 .map(|text| description_or_none(text.as_deref().unwrap_or("")))
402 .transpose()?;
403 let due_at = req.due_at.map(Timestamp::from_millis);
404 // A kept (absent) due date may already be past; a newly set one may not be.
405 check_not_past("due_at", due_at)?;
406 let subject = match &req.subject_id {
407 Some(subject_id) => Some(
408 crate::service::subject::in_instance(&st.db, subject_id, &instance).await?,
409 ),
410 None => None,
411 };
412 // The orphan guard runs on exactly the requests that re-scope the audience.
413 // An absent `assigned` writes nothing, so the stored subset is untouched and
414 // no narrowing can happen behind the guard's back — which the old "carry the
415 // snapshot back" branch could do, re-narrowing over a concurrent widening.
416 let assigned = match req.assigned {
417 Some(assigned) => Some(resolve_assigned(assigned, instance.get_id(), &st.db).await?),
418 None => None,
419 };
420
421 let updated = service::homework::update(
422 &st.db,
423 homework,
424 subject,
425 title,
426 description,
427 due_at,
428 assigned,
429 )
430 .await?;
431 Ok(Json(HomeworkResponse::new(&updated)))
432}
433
434/// Delete a homework and everything under it — submissions, their files, and
435/// results — then unlink the file blobs from disk. Requires teacher+ and
436/// management rights over its instance. The cascade is one transaction whose
437/// homework-row lock keeps a submission from landing under the homework
438/// mid-delete; the blob names are collected inside that transaction, before
439/// the rows are wiped, and removed after, so a crash in between strands at
440/// worst an unreachable file.
441#[utoipa::path(
442 delete,
443 path = "/{id}",
444 tag = "homework",
445 security(("session_cookie" = [])),
446 params(("id" = String, Path, description = "Homework id")),
447 responses(
448 (status = 204, description = "Deleted"),
449 (status = 401, description = "Not authenticated", body = ErrorResponse),
450 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
451 (status = 404, description = "Not found", body = ErrorResponse),
452 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
453 ),
454)]
455async fn delete_homework(
456 State(st): State<AppState>,
457 RequireTeacher(user): RequireTeacher,
458 Path(id): Path<String>,
459) -> Result<StatusCode, AppError> {
460 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
461 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
462 return Err(AppError::Forbidden(
463 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can delete this homework",
464 ));
465 }
466 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
467 // The blob-key collection and the cascade are
468 // [`service::homework::delete`]'s; unlinking the blobs stays here because
469 // only the web layer knows `files_path`.
470 let blob_keys = service::homework::delete(&st.db, homework).await?;
471 for key in &blob_keys {
472 remove_blob(&st.files_path, key).await;
473 }
474 Ok(StatusCode::NO_CONTENT)
475}
476
477/// One file attached to a submission — metadata only; the bytes download
478/// separately from `GET /homework/{id}/submission/files/{fid}`.
479#[derive(Serialize, ToSchema)]
480struct HomeworkFileResponse {
481 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
482 id: String,
483 /// The uploader's original filename.
484 #[schema(example = "odev.pdf")]
485 name: String,
486 /// MIME type as declared on upload.
487 #[schema(example = "application/pdf")]
488 content_type: String,
489 /// File size in bytes.
490 #[schema(example = 24_576)]
491 size: i64,
492}
493
494impl HomeworkFileResponse {
495 fn new(file: &HomeworkFile) -> Self {
496 Self {
497 id: file.get_id().key().to_string(),
498 name: file.get_name().as_str().to_string(),
499 content_type: file.get_content_type().as_str().to_string(),
500 size: file.get_size(),
501 }
502 }
503}
504
505/// The grade on a submission as the student sees it — present only once the
506/// teacher has recorded one, which is also what freezes the submission.
507#[derive(Serialize, ToSchema)]
508struct HomeworkResultResponse {
509 /// `done`, `incomplete`, or `missing` (a teacher's deliberate verdict).
510 #[schema(example = "done")]
511 status: String,
512 /// The optional 0–100 mark; `null` when graded on status alone.
513 mark: Option<i64>,
514 /// Who graded it.
515 graded_by: String,
516 /// When it was graded, UTC unix-milliseconds.
517 created_at: i64,
518}
519
520impl HomeworkResultResponse {
521 fn new(result: &HomeworkResult) -> Self {
522 Self {
523 status: result.get_status().as_str().to_string(),
524 mark: result.get_mark().map(|mark| mark.as_i64()),
525 graded_by: result.get_graded_by().key().to_string(),
526 created_at: result.get_created_at().as_millis(),
527 }
528 }
529}
530
531/// A student's own submission: their text and stamps, the computed late flag,
532/// every attached file, and the grade once one exists. `late` is derived here,
533/// never stored — `updated_at` (the last text edit or file add/delete) falling
534/// after the homework's `due_at`.
535#[derive(Serialize, ToSchema)]
536struct SubmissionResponse {
537 /// The submitting student.
538 user: String,
539 /// The homework this answers.
540 homework: String,
541 /// The optional free-text note; `null` when none was given.
542 text: Option<String>,
543 /// First hand-in, UTC unix-milliseconds (immutable across re-submits).
544 submitted_at: i64,
545 /// Last touched — a text edit or a file add/delete — UTC unix-milliseconds.
546 updated_at: i64,
547 /// Whether the submission was last touched after the homework's `due_at`.
548 late: bool,
549 /// The attached files, newest first (metadata only).
550 files: Vec<HomeworkFileResponse>,
551 /// The grade, once the teacher has recorded one (freezes the submission).
552 result: Option<HomeworkResultResponse>,
553}
554
555impl SubmissionResponse {
556 fn new(
557 homework: &Homework,
558 submission: &HomeworkSubmission,
559 files: &[HomeworkFile],
560 result: Option<&HomeworkResult>,
561 ) -> Self {
562 Self {
563 user: submission.get_user().key().to_string(),
564 homework: homework.get_id().key().to_string(),
565 text: submission.get_text().map(|text| text.as_str().to_string()),
566 submitted_at: submission.get_submitted_at().as_millis(),
567 updated_at: submission.get_updated_at().as_millis(),
568 late: submission.get_updated_at() > homework.get_due_at(),
569 files: files.iter().map(HomeworkFileResponse::new).collect(),
570 result: result.map(HomeworkResultResponse::new),
571 }
572 }
573}
574
575#[derive(Deserialize, ToSchema)]
576struct SubmitHomework {
577 /// The submission's free-text note (optional). Sent in full each time: this
578 /// replaces any previous text, and omitting it (or sending `""`) clears it.
579 /// Files are managed separately via `.../submission/files` and are never
580 /// touched here.
581 #[schema(
582 example = "Answers to questions 1–4 are in the attached photo.",
583 max_length = 5_000
584 )]
585 text: Option<String>,
586}
587
588/// Submit (or re-submit) the caller's own work for a homework: optional text,
589/// files added separately. Requires the student role, enrollment in the instance,
590/// and that the homework is assigned to the caller (a subset it doesn't name
591/// 404s, never leaking the assignment). Text replaces the previous text; the
592/// first-submit stamp is pinned once and `updated_at` moves to now. `201` on the
593/// first submit, `200` on a later edit. Refused (409) once the work is graded —
594/// ask the teacher to remove the grade to reopen it.
595#[utoipa::path(
596 post,
597 path = "/{id}/submission",
598 tag = "homework",
599 security(("session_cookie" = [])),
600 params(("id" = String, Path, description = "Homework id")),
601 request_body = SubmitHomework,
602 responses(
603 (status = 200, description = "Submission updated", body = SubmissionResponse),
604 (status = 201, description = "Submission created", body = SubmissionResponse),
605 (status = 400, description = "Text exceeds its length limit", body = ErrorResponse),
606 (status = 401, description = "Not authenticated", body = ErrorResponse),
607 (status = 403, description = "Not a student, or not enrolled in the homework's instance", body = ErrorResponse),
608 (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse),
609 (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
610 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
611 ),
612)]
613async fn submit(
614 State(st): State<AppState>,
615 CurrentUser(user): CurrentUser,
616 Path(id): Path<String>,
617 Json(req): Json<SubmitHomework>,
618) -> Result<(StatusCode, Json<SubmissionResponse>), AppError> {
619 // Empty text stores as "no note", so a present-but-blank row is never left.
620 let text = match &req.text {
621 Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?),
622 _ => None,
623 };
624 // The gate, the year wall, the graded check, and the upsert are one
625 // unit in [`service::homework_submission::submit`] — the audience
626 // interlock, not the freeze (that is the stamp on the row).
627 let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?;
628 let files =
629 service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?;
630 let status = if landed.existed {
631 StatusCode::OK
632 } else {
633 StatusCode::CREATED
634 };
635 // A result can't exist here — the gate would have 409'd.
636 Ok((
637 status,
638 Json(SubmissionResponse::new(
639 &landed.homework,
640 &landed.submission,
641 &files,
642 None,
643 )),
644 ))
645}
646
647/// Read the caller's own submission to a homework: their text, files, the
648/// computed late flag, and the grade if one exists. Same visibility gates as
649/// submitting (student, enrolled, assigned). `404` until they have submitted.
650#[utoipa::path(
651 get,
652 path = "/{id}/submission",
653 tag = "homework",
654 security(("session_cookie" = [])),
655 params(("id" = String, Path, description = "Homework id")),
656 responses(
657 (status = 200, description = "The caller's submission", body = SubmissionResponse),
658 (status = 401, description = "Not authenticated", body = ErrorResponse),
659 (status = 403, description = "Not a student, or not enrolled in the homework's instance", body = ErrorResponse),
660 (status = 404, description = "No such homework, a subset assignment the caller is not part of, or nothing submitted yet", body = ErrorResponse),
661 ),
662)]
663async fn get_submission(
664 State(st): State<AppState>,
665 CurrentUser(user): CurrentUser,
666 Path(id): Path<String>,
667) -> Result<Json<SubmissionResponse>, AppError> {
668 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
669 let submission =
670 service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
671 .await?
672 .ok_or(AppError::NotFound)?;
673 let files = service::homework_file::list_for_submission(&st.db, submission.get_id()).await?;
674 let result =
675 service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()).await?;
676 Ok(Json(SubmissionResponse::new(
677 &homework,
678 &submission,
679 &files,
680 result.as_ref(),
681 )))
682}
683
684/// Withdraw the caller's own submission — its text, its file rows, and their
685/// blobs. Same visibility gates as submitting. Refused (409) once the work is
686/// graded. The file rows fall in one transaction with the submission (children
687/// first); their blob names are collected before the wipe and unlinked after.
688#[utoipa::path(
689 delete,
690 path = "/{id}/submission",
691 tag = "homework",
692 security(("session_cookie" = [])),
693 params(("id" = String, Path, description = "Homework id")),
694 responses(
695 (status = 204, description = "Deleted"),
696 (status = 401, description = "Not authenticated", body = ErrorResponse),
697 (status = 403, description = "Not a student, or not enrolled in the homework's instance", body = ErrorResponse),
698 (status = 404, description = "No such homework, a subset assignment the caller is not part of, or nothing submitted yet", body = ErrorResponse),
699 (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
700 ),
701)]
702async fn delete_submission(
703 State(st): State<AppState>,
704 CurrentUser(user): CurrentUser,
705 Path(id): Path<String>,
706) -> Result<StatusCode, AppError> {
707 // Gate, year wall, graded check, and the cascade are
708 // [`service::homework_submission::delete`]'s; the file rows it returns
709 // carry the blob names to unlink now that the rows are gone.
710 let files = service::homework_submission::delete(&st.db, &user, &id).await?;
711 for file in &files {
712 remove_blob(&st.files_path, file.get_file()).await;
713 }
714 Ok(StatusCode::NO_CONTENT)
715}
716
717/// Serve a submission file as a download — `Content-Disposition: attachment`,
718/// never inline. Homework files take *any* content type (documents, photos —
719/// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only,
720/// allowlisted exam images [`super::serve_inline_blob`] renders inline, they
721/// must download: an inline HTML/SVG upload would run as stored XSS in a
722/// viewer's session. This is exactly the note-file download idiom.
723async fn serve_download(st: &AppState, file: &HomeworkFile) -> Result<Response, AppError> {
724 let bytes = tokio::fs::read(blob_path(&st.files_path, file.get_file()))
725 .await
726 .map_err(|err| {
727 // The row exists but its blob doesn't — server-side damage (a lost
728 // volume path), not a client 404.
729 AppError::Internal(format!(
730 "missing blob for homework file {}: {err}",
731 file.get_id().key()
732 ))
733 })?;
734 // The stored content type is validated ASCII without control characters, so
735 // it always parses; the fallback is belt and braces.
736 let content_type = HeaderValue::from_str(file.get_content_type().as_str())
737 .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
738 let disposition = HeaderValue::from_str(&content_disposition(file.get_name().as_str()))
739 .unwrap_or_else(|_| HeaderValue::from_static("attachment"));
740 Ok((
741 [
742 (CONTENT_TYPE, content_type),
743 (CONTENT_DISPOSITION, disposition),
744 ],
745 bytes,
746 )
747 .into_response())
748}
749
750/// Attach a file to the caller's own submission. `multipart/form-data` with the
751/// bytes under a `file` field (its `filename` required); any content type, at
752/// most the school's `max_file_bytes`, up to 10 files per submission. Same
753/// visibility gates as submitting. A submission need not exist first — a
754/// photo-only homework never types text, so this auto-creates an empty
755/// submission to hang the file off (an existing one's text is preserved). Adding
756/// a file re-stamps the submission's `updated_at`. Refused (409) once graded, or
757/// once the 10-file cap is reached.
758#[utoipa::path(
759 post,
760 path = "/{id}/submission/files",
761 tag = "homework",
762 security(("session_cookie" = [])),
763 params(("id" = String, Path, description = "Homework id")),
764 request_body(content = UploadFileForm, content_type = "multipart/form-data"),
765 responses(
766 (status = 201, description = "File stored", body = HomeworkFileResponse),
767 (status = 400, description = "Missing file field, empty file, or an invalid filename or content type", body = ErrorResponse),
768 (status = 401, description = "Not authenticated", body = ErrorResponse),
769 (status = 403, description = "Not a student, or not enrolled in the homework's instance", body = ErrorResponse),
770 (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse),
771 (status = 409, description = "The homework has been graded, or the submission already holds the maximum of 10 files, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
772 (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse),
773 ),
774)]
775async fn upload_submission_file(
776 State(st): State<AppState>,
777 CurrentUser(user): CurrentUser,
778 Path(id): Path<String>,
779 mut multipart: Multipart,
780) -> Result<(StatusCode, Json<HomeworkFileResponse>), AppError> {
781 // Pre-flight, so a caller with no business here is refused before uploading
782 // 25 MiB; the gate that *licenses the write* is the one under the lease
783 // below, because this snapshot goes stale while the body streams.
784 let preflight = service::homework::gate_own_submission(&id, &user, &st.db).await?;
785 service::homework::require_open_instance(&preflight, &st.db).await?;
786 let limit = service::settings::load(&st.db).await?.get_max_file_bytes();
787 // Consume the body before taking the lock — a slow upload must not stall the
788 // homework subsystem (mirrors the exam/note image uploads).
789 let upload = read_upload(&mut multipart, limit).await?;
790 let name = FileName::try_new(&upload.name.unwrap_or_default())?;
791 let content_type = FileContentType::try_new(&upload.content_type.unwrap_or_default())?;
792
793 const GRADED: AppError = AppError::Conflict(
794 "this homework has been graded — ask the teacher to remove the grade before adding files",
795 );
796 // Re-read the homework. Streaming the body takes as long as the client
797 // wants it to, and a homework delete can commit inside that window — so
798 // the pre-flight snapshot can name a homework that no longer exists, and
799 // this handler would then auto-create a submission, credit the badge
800 // counters and write a file under it, all unreachable afterwards. A gate
801 // read before the body is a pre-flight; a gate read after it is the
802 // decision. The writes below are still ordered against a delete, a grade
803 // and a PATCH narrowing the audience — each contends on the homework
804 // row's lock inside its own transaction.
805 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
806 // Re-walled too: the year can be archived while the body streams.
807 service::homework::require_open_instance(&homework, &st.db).await?;
808 let submission = service::homework_file::ensure_can_attach(&st.db, &user, &homework).await?;
809
810 // Blob first, row second — a stored row always points at a real blob. The
811 // 10-file cap and the freeze are one conditional write on the submission row
812 // inside `insert`. Unlink the fresh blob if the row insert loses either.
813 let file = HomeworkFile::new(
814 submission.get_id(),
815 name,
816 content_type,
817 upload.data.len() as i64,
818 );
819 let path = blob_path(&st.files_path, file.get_file());
820 crate::web::ensure_files_dir(&st.files_path).await?;
821 tokio::fs::write(&path, &upload.data)
822 .await
823 .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?;
824 let stored = match service::homework_file::insert(&st.db, file).await {
825 Ok(Some(stored)) => stored,
826 // `None` is the freeze biting, an `Err` the file cap (or worse); either
827 // way the blob just written has no row and must go.
828 landed => {
829 let _ = tokio::fs::remove_file(&path).await;
830 return Err(landed.err().unwrap_or(GRADED));
831 }
832 };
833 // A landed file moves the submission's "last touched" clock (the late flag).
834 service::homework_submission::touch(&st.db, submission.get_id()).await?;
835 Ok((
836 StatusCode::CREATED,
837 Json(HomeworkFileResponse::new(&stored)),
838 ))
839}
840
841/// Download a submission file's bytes. Two callers, one handler: a student reads
842/// their own file (behind the submission gate), or a teacher who manages the
843/// homework's instance reads any file under it. A parent never reaches here —
844/// observers get the report, never the bytes. The file is scoped to the homework
845/// in the path, so a managed homework's id can't be used to pull a file from
846/// another one.
847#[utoipa::path(
848 get,
849 path = "/{id}/submission/files/{fid}",
850 tag = "homework",
851 security(("session_cookie" = [])),
852 params(
853 ("id" = String, Path, description = "Homework id"),
854 ("fid" = String, Path, description = "File id"),
855 ),
856 responses(
857 (status = 200, description = "The file bytes", content_type = "application/octet-stream"),
858 (status = 401, description = "Not authenticated", body = ErrorResponse),
859 (status = 403, description = "A student not enrolled, or a teacher without management rights over the instance", body = ErrorResponse),
860 (status = 404, description = "No such homework or file (or a subset assignment the caller is not part of)", body = ErrorResponse),
861 ),
862)]
863async fn download_submission_file(
864 State(st): State<AppState>,
865 CurrentUser(user): CurrentUser,
866 Path((id, fid)): Path<(String, String)>,
867) -> Result<Response, AppError> {
868 let file_id = HomeworkFileId::from_key(&fid);
869 let file = if user.get_role() == Role::Student {
870 // Student: only their own file, behind the full submission gate.
871 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
872 let submission =
873 service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
874 .await?
875 .ok_or(AppError::NotFound)?;
876 service::homework_file::read_for(&st.db, &file_id, submission.get_id())
877 .await?
878 .ok_or(AppError::NotFound)?
879 } else {
880 // Teacher+: any file under a homework they manage.
881 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
882 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
883 return Err(AppError::Forbidden(
884 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can read submission files",
885 ));
886 }
887 service::homework_file::read_in_homework(&st.db, &file_id, homework.get_id())
888 .await?
889 .ok_or(AppError::NotFound)?
890 };
891 serve_download(&st, &file).await
892}
893
894/// Remove a file from the caller's own submission — row first, then its blob.
895/// Same visibility gates as submitting. Refused (409) once graded. Removing a
896/// file re-stamps the submission's `updated_at`.
897#[utoipa::path(
898 delete,
899 path = "/{id}/submission/files/{fid}",
900 tag = "homework",
901 security(("session_cookie" = [])),
902 params(
903 ("id" = String, Path, description = "Homework id"),
904 ("fid" = String, Path, description = "File id"),
905 ),
906 responses(
907 (status = 204, description = "Deleted"),
908 (status = 401, description = "Not authenticated", body = ErrorResponse),
909 (status = 403, description = "Not a student, or not enrolled in the homework's instance", body = ErrorResponse),
910 (status = 404, description = "No such homework or file (or a subset assignment the caller is not part of)", body = ErrorResponse),
911 (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
912 ),
913)]
914async fn delete_submission_file(
915 State(st): State<AppState>,
916 CurrentUser(user): CurrentUser,
917 Path((id, fid)): Path<(String, String)>,
918) -> Result<StatusCode, AppError> {
919 let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?;
920 service::homework::require_open_instance(&homework, &st.db).await?;
921 const GRADED: AppError = AppError::Conflict(
922 "this homework has been graded — ask the teacher to remove the grade before deleting files",
923 );
924 if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id())
925 .await?
926 .is_some()
927 {
928 return Err(GRADED);
929 }
930 let submission =
931 service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id())
932 .await?
933 .ok_or(AppError::NotFound)?;
934 let file = service::homework_file::read_for(
935 &st.db,
936 &HomeworkFileId::from_key(&fid),
937 submission.get_id(),
938 )
939 .await?
940 .ok_or(AppError::NotFound)?;
941 let blob = file.get_file().to_string();
942 // The delete's own transaction re-stamps the submission's "last touched"
943 // clock (the late flag) as its freeze gate, so a refused delete moves
944 // nothing and no separate touch is owed here.
945 if service::homework_file::delete(&st.db, file)
946 .await?
947 .is_none()
948 {
949 return Err(GRADED);
950 }
951 remove_blob(&st.files_path, &blob).await;
952 Ok(StatusCode::NO_CONTENT)
953}
954
955// ---- grading, roster, report ------------------------------------------------
956
957#[derive(Deserialize, ToSchema)]
958struct GradeHomework {
959 /// The student being graded.
960 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
961 user: String,
962 /// The verdict: `done`, `incomplete`, or `missing`.
963 #[schema(example = "done")]
964 status: String,
965 /// An optional 0–100 mark on top of the status; omit to grade on status
966 /// alone.
967 #[schema(minimum = 0, maximum = 100)]
968 mark: Option<i64>,
969}
970
971/// Record (or overwrite) a student's grade for a homework: a status
972/// (`done`/`incomplete`/`missing`) plus an optional 0–100 mark. Requires
973/// teacher+ and management rights over the homework's instance; the target must
974/// be a live student, enrolled in the instance, and in the homework's audience.
975/// Nobody grades themselves. Grading before the due date, or before any
976/// submission exists (`missing` for work never handed in), is allowed. A stored
977/// grade freezes the student's submission until it is removed.
978#[utoipa::path(
979 post,
980 path = "/{id}/results",
981 tag = "homework",
982 security(("session_cookie" = [])),
983 params(("id" = String, Path, description = "Homework id")),
984 request_body = GradeHomework,
985 responses(
986 (status = 200, description = "Grade recorded", body = HomeworkResultResponse),
987 (status = 400, description = "Invalid status or mark, unknown user, user not a student, not enrolled, or not in the homework's audience", body = ErrorResponse),
988 (status = 401, description = "Not authenticated", body = ErrorResponse),
989 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin, or attempted to grade yourself", body = ErrorResponse),
990 (status = 404, description = "Homework not found", body = ErrorResponse),
991 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
992 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
993 ),
994)]
995async fn grade_homework(
996 State(st): State<AppState>,
997 RequireTeacher(teacher): RequireTeacher,
998 Path(id): Path<String>,
999 Json(req): Json<GradeHomework>,
1000) -> Result<Json<HomeworkResultResponse>, AppError> {
1001 // The grading gates live in [`service::homework_result::grade`]; the
1002 // grade transaction locks the homework row across the freeze stamp, which
1003 // orders it against every student-side write — and keeps a homework
1004 // delete from letting the upsert resurrect a result row under a vanished
1005 // homework (the vanished row answers 404).
1006 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
1007 if !can_manage_instance(&st.db, instance.get_id(), &teacher).await? {
1008 return Err(AppError::Forbidden(
1009 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can grade this homework",
1010 ));
1011 }
1012 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
1013
1014 let status = HomeworkStatus::try_new(&req.status)?;
1015 let mark = req.mark.map(Mark::try_new).transpose()?;
1016 let target = UserId::from_key(&req.user);
1017
1018 // The self-grade, target-exists, live-student, enrollment, and audience
1019 // gates run inside [`service::homework_result::grade`], under the lease.
1020 let result =
1021 service::homework_result::grade(&st.db, homework.get_id(), &teacher, status, mark, &target)
1022 .await?;
1023 Ok(Json(HomeworkResultResponse::new(&result)))
1024}
1025
1026/// Remove a student's grade from a homework — un-grading, which unfreezes the
1027/// student's submission and files for further edits. Requires teacher+ and
1028/// management rights over the homework's instance.
1029#[utoipa::path(
1030 delete,
1031 path = "/{id}/results/{user}",
1032 tag = "homework",
1033 security(("session_cookie" = [])),
1034 params(
1035 ("id" = String, Path, description = "Homework id"),
1036 ("user" = String, Path, description = "User id"),
1037 ),
1038 responses(
1039 (status = 204, description = "Removed"),
1040 (status = 401, description = "Not authenticated", body = ErrorResponse),
1041 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
1042 (status = 404, description = "No such homework, or no grade for this user", body = ErrorResponse),
1043 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
1044 ),
1045)]
1046async fn remove_homework_result(
1047 State(st): State<AppState>,
1048 RequireTeacher(user): RequireTeacher,
1049 Path((id, target)): Path<(String, String)>,
1050) -> Result<StatusCode, AppError> {
1051 // Removing the grade is what unfreezes the submission; the un-grade's
1052 // transaction takes the homework row's lock, so it cannot straddle a
1053 // student-side write either.
1054 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
1055 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
1056 return Err(AppError::Forbidden(
1057 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can remove grades",
1058 ));
1059 }
1060 crate::service::class_course::require_open(&st.db, instance.get_id()).await?;
1061 let removed =
1062 service::homework_result::ungrade(&st.db, homework.get_id(), &UserId::from_key(&target))
1063 .await?;
1064 if removed.is_none() {
1065 return Err(AppError::NotFound);
1066 }
1067 Ok(StatusCode::NO_CONTENT)
1068}
1069
1070/// The caller's own grade for a homework. Any authenticated user may read
1071/// their own; `404` while ungraded (or when the homework doesn't exist). This
1072/// is the one read a student graded `missing` *without* ever submitting has —
1073/// their submission endpoints 404 while nothing is submitted.
1074#[utoipa::path(
1075 get,
1076 path = "/{id}/result",
1077 tag = "homework",
1078 security(("session_cookie" = [])),
1079 params(("id" = String, Path, description = "Homework id")),
1080 responses(
1081 (status = 200, description = "The caller's grade", body = HomeworkResultResponse),
1082 (status = 401, description = "Not authenticated", body = ErrorResponse),
1083 (status = 404, description = "No such homework, or not graded yet", body = ErrorResponse),
1084 ),
1085)]
1086async fn my_homework_result(
1087 State(st): State<AppState>,
1088 CurrentUser(user): CurrentUser,
1089 Path(id): Path<String>,
1090) -> Result<Json<HomeworkResultResponse>, AppError> {
1091 let result =
1092 service::homework_result::read_for(&st.db, &HomeworkId::from_key(&id), user.get_id())
1093 .await?
1094 .ok_or(AppError::NotFound)?;
1095 Ok(Json(HomeworkResultResponse::new(&result)))
1096}
1097
1098/// The submission part of a roster row — the student's work without the grade,
1099/// which sits beside it on the row (a graded-but-never-submitted student
1100/// carries a grade and no submission).
1101#[derive(Serialize, ToSchema)]
1102struct HomeworkRosterSubmission {
1103 /// The optional free-text note; `null` when none was given.
1104 text: Option<String>,
1105 /// First hand-in, UTC unix-milliseconds (immutable across re-submits).
1106 submitted_at: i64,
1107 /// Last touched — a text edit or a file add/delete — UTC unix-milliseconds.
1108 updated_at: i64,
1109 /// Whether the submission was last touched after the homework's `due_at`.
1110 late: bool,
1111 /// The attached files, newest first (metadata only).
1112 files: Vec<HomeworkFileResponse>,
1113}
1114
1115/// One student's line in a homework's teacher roster.
1116#[derive(Serialize, ToSchema)]
1117struct HomeworkRosterEntry {
1118 /// The student.
1119 user: String,
1120 /// Their submission, if they handed anything in.
1121 submission: Option<HomeworkRosterSubmission>,
1122 /// Their grade, if the teacher recorded one.
1123 result: Option<HomeworkResultResponse>,
1124 /// Computed: nothing submitted and the due date has passed. Independent of
1125 /// the teacher-set `missing` status, which is a deliberate verdict.
1126 missing: bool,
1127 /// Computed: the student is no longer enrolled in the instance. Their stale
1128 /// rows stay readable here, but they can't submit and can't be graded.
1129 unenrolled: bool,
1130}
1131
1132/// The teacher's roster for a homework, paged via `?limit=&offset=` (omit
1133/// `limit` for all of it): one row per student in the audience — the assigned
1134/// subset, or every student currently enrolled in the instance when the
1135/// homework carries none —
1136/// plus any student outside it who still owns a submission or grade (an
1137/// unenrollment or an audience change leaves work behind; it stays visible
1138/// here, flagged). Each row carries the submission with its files and computed
1139/// late flag, the grade, a computed `missing`, and a computed `unenrolled`.
1140/// Requires teacher+ and management rights over the homework's instance. Returns
1141/// a `{items, total, limit, offset}` envelope.
1142#[utoipa::path(
1143 get,
1144 path = "/{id}/submissions",
1145 tag = "homework",
1146 security(("session_cookie" = [])),
1147 params(("id" = String, Path, description = "Homework id"), PageParams),
1148 responses(
1149 (status = 200, description = "A page of roster rows (all of them when unpaged)", body = Page<HomeworkRosterEntry>),
1150 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1151 (status = 401, description = "Not authenticated", body = ErrorResponse),
1152 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
1153 (status = 404, description = "Homework not found", body = ErrorResponse),
1154 ),
1155)]
1156async fn list_homework_submissions(
1157 State(st): State<AppState>,
1158 RequireTeacher(user): RequireTeacher,
1159 Path(id): Path<String>,
1160 Query(page): Query<PageParams>,
1161) -> Result<Json<Page<HomeworkRosterEntry>>, AppError> {
1162 let (limit, offset) = page.resolve()?;
1163 let (homework, instance) = homework_with_instance(&id, &st.db).await?;
1164 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
1165 return Err(AppError::Forbidden(
1166 "only the instance's teachers, its şube's homeroom teacher, or a manager/admin can list submissions",
1167 ));
1168 }
1169 let submissions =
1170 service::homework_submission::list_for_homework(&st.db, homework.get_id()).await?;
1171 let results = service::homework_result::list_for_homework(&st.db, homework.get_id()).await?;
1172 let enrolled: Vec<String> =
1173 service::enrollment::list_for_class_course(&st.db, instance.get_id(), None, 0)
1174 .await?
1175 .0
1176 .iter()
1177 .map(|enrollment| enrollment.get_user().key().to_string())
1178 .collect();
1179 // The audience: the assigned subset as stored, or — no subset — whoever
1180 // is enrolled right now. Anyone outside it who still owns a submission or
1181 // grade is appended rather than dropped: their stale rows are exactly what
1182 // a narrowing 409 names as blockers, so the teacher must be able to see
1183 // them. Sorted by student id for a stable page window.
1184 let mut users: Vec<String> = match homework.get_assigned() {
1185 Some(assigned) if !assigned.is_empty() => {
1186 assigned.iter().map(|user| user.key().to_string()).collect()
1187 }
1188 _ => enrolled.clone(),
1189 };
1190 for holder in submissions
1191 .iter()
1192 .map(HomeworkSubmission::get_user)
1193 .chain(results.iter().map(HomeworkResult::get_user))
1194 {
1195 let key = holder.key().to_string();
1196 if !users.contains(&key) {
1197 users.push(key);
1198 }
1199 }
1200 users.sort();
1201 users.dedup();
1202 let total = users.len() as i64;
1203 // Join the heavy parts (the file lists) onto the page alone.
1204 let mut items = Vec::new();
1205 // Paged in the web layer: the audience is resolved in Rust.
1206 for user_key in paginate(&users, limit, offset) {
1207 let submission = match submissions
1208 .iter()
1209 .find(|submission| &submission.get_user().key() == user_key)
1210 {
1211 Some(submission) => Some(HomeworkRosterSubmission {
1212 text: submission.get_text().map(|text| text.as_str().to_string()),
1213 submitted_at: submission.get_submitted_at().as_millis(),
1214 updated_at: submission.get_updated_at().as_millis(),
1215 late: submission.get_updated_at() > homework.get_due_at(),
1216 files: service::homework_file::list_for_submission(&st.db, submission.get_id())
1217 .await?
1218 .iter()
1219 .map(HomeworkFileResponse::new)
1220 .collect(),
1221 }),
1222 None => None,
1223 };
1224 items.push(HomeworkRosterEntry {
1225 user: user_key.clone(),
1226 missing: submission.is_none() && Timestamp::now() > homework.get_due_at(),
1227 unenrolled: !enrolled.contains(user_key),
1228 submission,
1229 result: results
1230 .iter()
1231 .find(|result| &result.get_user().key() == user_key)
1232 .map(HomeworkResultResponse::new),
1233 });
1234 }
1235 Ok(Json(Page::new(items, total, limit, offset)))
1236}
1237
1238/// One homework on a student's report: the assignment context plus what the
1239/// student did with it and how it was graded, if it was.
1240#[derive(Serialize, ToSchema)]
1241struct HomeworkReportEntry {
1242 /// The class×course instance the homework belongs to.
1243 class_course: String,
1244 /// The homework id.
1245 homework: String,
1246 title: String,
1247 /// The course subject the homework is tagged with.
1248 subject: String,
1249 /// When it was due, UTC unix-milliseconds.
1250 due_at: i64,
1251 /// Whether the student has submitted anything.
1252 submitted: bool,
1253 /// Whether the submission was last touched after `due_at`.
1254 late: bool,
1255 /// Computed: nothing submitted and the due date has passed — independent
1256 /// of a teacher-set `missing` status.
1257 missing: bool,
1258 /// The grade, once one exists.
1259 result: Option<HomeworkResultResponse>,
1260}
1261
1262/// A student's homework report across the instances their class section carries, paged
1263/// via `?limit=&offset=` (omit `limit` for all of it): one row per homework in
1264/// their audience — submitted/late/missing state plus the grade once one
1265/// exists. Statuses and marks, never the submitted files (observers get the
1266/// report, not the bytes). Requires teacher+, or a parent linked to the target
1267/// student. Managers, admins, and parents see every instance; a teacher sees
1268/// only the target's instances they manage. Returns a `{items, total, limit,
1269/// offset}` envelope.
1270#[utoipa::path(
1271 get,
1272 path = "/report/{user}",
1273 tag = "homework",
1274 security(("session_cookie" = [])),
1275 params(("user" = String, Path, description = "User id"), PageParams),
1276 responses(
1277 (status = 200, description = "A page of the user's homework report (all of it when unpaged)", body = Page<HomeworkReportEntry>),
1278 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1279 (status = 401, description = "Not authenticated", body = ErrorResponse),
1280 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
1281 (status = 404, description = "User not found", body = ErrorResponse),
1282 ),
1283)]
1284async fn homework_report(
1285 State(st): State<AppState>,
1286 CurrentUser(caller): CurrentUser,
1287 Path(user): Path<String>,
1288 Query(page): Query<PageParams>,
1289) -> Result<Json<Page<HomeworkReportEntry>>, AppError> {
1290 let (limit, offset) = page.resolve()?;
1291 let target = UserId::from_key(&user);
1292 ensure_can_observe(&caller, &target, &st.db).await?;
1293 // User must exist — a missing user is a 404, not an empty report. The row
1294 // itself is what `visible_instances` takes.
1295 let target_user = crate::service::user::read(&st.db, &target)
1296 .await?
1297 .ok_or(AppError::NotFound)?;
1298 // Only an exactly-teacher caller is narrowed to the instances they manage;
1299 // manager+ and a linked parent read the full report (the marks idiom).
1300 let mut instances: Vec<ClassCourse> = visible_instances(&target_user, &st.db)
1301 .await?
1302 .into_iter()
1303 .map(|(instance, _)| instance)
1304 .collect();
1305 if caller.get_role() == Role::Teacher {
1306 let mut managed = Vec::with_capacity(instances.len());
1307 for instance in instances {
1308 // The narrowing asks about the *caller's* rights, not the target's:
1309 // `visible_instances` answers for the user it was handed.
1310 if can_manage_instance(&st.db, instance.get_id(), &caller).await? {
1311 managed.push(instance);
1312 }
1313 }
1314 instances = managed;
1315 }
1316 let mut rows = Vec::new();
1317 for instance in &instances {
1318 rows.extend(
1319 service::homework::list_for_user_in_class_course(&st.db, instance.get_id(), &target)
1320 .await?,
1321 );
1322 }
1323 let total = rows.len() as i64;
1324 // Join submissions and grades onto the page alone.
1325 let mut items = Vec::new();
1326 // Paged in the web layer: the rows are gathered instance by instance.
1327 for homework in paginate(&rows, limit, offset) {
1328 let submission =
1329 service::homework_submission::read_for(&st.db, homework.get_id(), &target).await?;
1330 let result = service::homework_result::read_for(&st.db, homework.get_id(), &target).await?;
1331 items.push(HomeworkReportEntry {
1332 class_course: homework.get_class_course().key().to_string(),
1333 homework: homework.get_id().key().to_string(),
1334 title: homework.get_title().as_str().to_string(),
1335 subject: homework.get_subject().key().to_string(),
1336 due_at: homework.get_due_at().as_millis(),
1337 submitted: submission.is_some(),
1338 late: submission
1339 .as_ref()
1340 .is_some_and(|submission| submission.get_updated_at() > homework.get_due_at()),
1341 missing: submission.is_none() && Timestamp::now() > homework.get_due_at(),
1342 result: result.as_ref().map(HomeworkResultResponse::new),
1343 });
1344 }
1345 Ok(Json(Page::new(items, total, limit, offset)))
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350 use super::*;
1351 use axum::Router;
1352 use axum::body::Body;
1353 use axum::http::{Request, StatusCode};
1354 use tower::ServiceExt;
1355
1356 use crate::database::init_test_tenants;
1357 use crate::db::session;
1358 use crate::domain::homework::HomeworkTitle;
1359 use crate::domain::role::Role;
1360 use crate::domain::subject::{SubjectDescription, SubjectName};
1361 use crate::domain::user::Username;
1362 use crate::tenant::{DEMO_SCHOOL_ID, SchoolId};
1363
1364 const DAY: i64 = 86_400_000;
1365
1366 /// The app behind a live school cookie for `user`, plus the tenant
1367 /// registry handle. The router is the real one, so the cookie, the
1368 /// tenant resolution, and the published query params are all exercised.
1369 async fn app_for(username: &str, role: Role) -> (Router, String, crate::database::Database) {
1370 let tenants = init_test_tenants().await;
1371 let school = tenants
1372 .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
1373 .await
1374 .expect("the demo school");
1375 let user = crate::service::user::create(&school, Username::try_new(username).unwrap(), None)
1376 .await
1377 .unwrap();
1378 let user = crate::service::user::set_role(&school, user.get_id(), role)
1379 .await
1380 .unwrap()
1381 .0;
1382 let token = session::create(&school, user.get_id()).await.unwrap();
1383 let cookie = format!("session={DEMO_SCHOOL_ID}.{}", token.token().as_str());
1384 let state = AppState {
1385 db: tenants.control().clone(),
1386 tenants,
1387 files_path: std::env::temp_dir(),
1388 cookie_secure: false,
1389 rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
1390 chatbot_limit: Default::default(),
1391 rag_limit: Default::default(),
1392 exam_presence: Default::default(),
1393 board_hub: Default::default(),
1394 ai: None,
1395 metrics: crate::telemetry::Metrics::noop(),
1396 };
1397 (crate::build_router(state), cookie, school)
1398 }
1399
1400 /// One homework with a chosen due instant and audience on `instance`.
1401 async fn seed_homework_on(
1402 db: &crate::database::Database,
1403 instance: &ClassCourseId,
1404 course: &crate::domain::course::CourseId,
1405 due_at: i64,
1406 title: &str,
1407 assigned: Option<Vec<UserId>>,
1408 ) -> Homework {
1409 let subject = crate::db::subject::create(
1410 db,
1411 course,
1412 SubjectName::try_new(title).unwrap(),
1413 SubjectDescription::try_new("").unwrap(),
1414 )
1415 .await
1416 .unwrap();
1417 let teacher = crate::service::user::create(db, Username::try_new(title).unwrap(), None)
1418 .await
1419 .unwrap();
1420 crate::db::homework::create(
1421 db,
1422 instance,
1423 subject.get_id(),
1424 HomeworkTitle::try_new(title).unwrap(),
1425 None,
1426 Timestamp::from_millis(due_at),
1427 assigned,
1428 teacher.get_id(),
1429 )
1430 .await
1431 .unwrap()
1432 }
1433
1434 /// One homework with a chosen due instant and audience on a fresh
1435 /// instance; returns the instance and the row.
1436 async fn seed_homework(
1437 db: &crate::database::Database,
1438 due_at: i64,
1439 title: &str,
1440 assigned: Option<Vec<UserId>>,
1441 ) -> (ClassCourseId, Homework) {
1442 let (instance, course) = crate::db::course::a_test_instance(db).await;
1443 let homework =
1444 seed_homework_on(db, &instance, &course, due_at, title, assigned).await;
1445 (instance, homework)
1446 }
1447
1448 /// A student put on the live roster of the class `instance` belongs to —
1449 /// the membership `visible_instances` reads for a student.
1450 async fn join_class(
1451 db: &crate::database::Database,
1452 instance: &ClassCourseId,
1453 student: &UserId,
1454 ) {
1455 let instance = crate::service::class_course::read(db, instance)
1456 .await
1457 .unwrap()
1458 .unwrap();
1459 sqlx::query(
1460 "INSERT INTO class_member (id, class, app_user, added_by, joined_at) \
1461 VALUES ($1, $2, $3, $3, 0)",
1462 )
1463 .bind(crate::domain::class_group::ClassGroupId::generate().uuid())
1464 .bind(instance.get_class().uuid())
1465 .bind(student.uuid())
1466 .execute(db)
1467 .await
1468 .unwrap();
1469 }
1470
1471 async fn get(app: &Router, uri: &str, cookie: &str) -> (StatusCode, serde_json::Value) {
1472 let response = app
1473 .clone()
1474 .oneshot(
1475 Request::builder()
1476 .uri(uri)
1477 .header("cookie", cookie)
1478 .body(Body::empty())
1479 .unwrap(),
1480 )
1481 .await
1482 .unwrap();
1483 let status = response.status();
1484 let body = axum::body::to_bytes(response.into_body(), 1 << 20)
1485 .await
1486 .unwrap();
1487 let json = if body.is_empty() {
1488 serde_json::Value::Null
1489 } else {
1490 serde_json::from_slice(&body).unwrap()
1491 };
1492 (status, json)
1493 }
1494
1495 /// The manager path: the due window and the instance scope narrow in SQL,
1496 /// the page window applies after the filter, and `total` stays the
1497 /// filtered length. Absent params are exactly the old response.
1498 #[tokio::test]
1499 async fn manager_filters_open_past_and_instance_in_sql() {
1500 let now = Timestamp::now().as_millis();
1501 let (app, cookie, school) = app_for("mudur-filter", Role::Manager).await;
1502 let (_, past) = seed_homework(&school, now - DAY, "past-here", None).await;
1503 let (_, open) = seed_homework(&school, now + DAY, "open-here", None).await;
1504 let (there, open_there) = seed_homework(&school, now + 2 * DAY, "open-there", None).await;
1505
1506 // Absent params: every row, newest first — the old response.
1507 let (status, body) = get(&app, "/homework", &cookie).await;
1508 assert_eq!(status, StatusCode::OK);
1509 assert_eq!(body["total"], 3);
1510 let ids: Vec<String> = body["items"]
1511 .as_array()
1512 .unwrap()
1513 .iter()
1514 .map(|row| row["id"].as_str().unwrap().to_string())
1515 .collect();
1516 assert_eq!(
1517 ids,
1518 vec![
1519 open_there.get_id().key(),
1520 open.get_id().key(),
1521 past.get_id().key()
1522 ]
1523 );
1524
1525 // The open tab: due at or after the bound.
1526 let (status, body) = get(&app, &format!("/homework?due_after={now}"), &cookie).await;
1527 assert_eq!(status, StatusCode::OK);
1528 assert_eq!(body["total"], 2);
1529 assert!(
1530 body["items"]
1531 .as_array()
1532 .unwrap()
1533 .iter()
1534 .all(|row| row["due_at"].as_i64().unwrap() >= now)
1535 );
1536
1537 // The past tab: due strictly before the bound — no overlap, no gap.
1538 let (status, body) = get(&app, &format!("/homework?due_before={now}"), &cookie).await;
1539 assert_eq!(status, StatusCode::OK);
1540 assert_eq!(body["total"], 1);
1541 assert_eq!(body["items"][0]["id"], past.get_id().key().to_string());
1542
1543 // The instance scope: only `there`'s rows.
1544 let (status, body) = get(
1545 &app,
1546 &format!("/homework?class_course={}", there.key()),
1547 &cookie,
1548 )
1549 .await;
1550 assert_eq!(status, StatusCode::OK);
1551 assert_eq!(body["total"], 1);
1552 assert_eq!(body["items"][0]["id"], open_there.get_id().key().to_string());
1553
1554 // A well-formed id that names no row: an empty page, not a 404.
1555 let stranger = ClassCourseId::generate();
1556 let (status, body) = get(
1557 &app,
1558 &format!("/homework?class_course={}", stranger.key()),
1559 &cookie,
1560 )
1561 .await;
1562 assert_eq!(status, StatusCode::OK);
1563 assert_eq!(body["total"], 0);
1564 assert!(body["items"].as_array().unwrap().is_empty());
1565
1566 // The window applies after the filter; total is the filtered count.
1567 let (status, body) =
1568 get(&app, &format!("/homework?due_after={now}&limit=1"), &cookie).await;
1569 assert_eq!(status, StatusCode::OK);
1570 assert_eq!(body["total"], 2);
1571 assert_eq!(body["items"].as_array().unwrap().len(), 1);
1572 let (status, body) =
1573 get(&app, &format!("/homework?due_after={now}&offset=1"), &cookie).await;
1574 assert_eq!(status, StatusCode::OK);
1575 assert_eq!(body["total"], 2);
1576 assert_eq!(body["items"][0]["id"], open.get_id().key().to_string());
1577 }
1578
1579 /// A bad filter is a 400 naming the field: negative due bounds, and an
1580 /// instance key that is empty, not a uuid, or the nil uuid.
1581 #[tokio::test]
1582 async fn bad_filters_are_400_naming_the_field() {
1583 let (app, cookie, _school) = app_for("mudur-hata", Role::Manager).await;
1584 for (uri, field) in [
1585 ("/homework?due_after=-1", "due_after"),
1586 ("/homework?due_before=-5", "due_before"),
1587 ("/homework?class_course=", "class_course"),
1588 ("/homework?class_course=%20", "class_course"),
1589 ("/homework?class_course=not-a-uuid", "class_course"),
1590 (
1591 "/homework?class_course=00000000-0000-0000-0000-000000000000",
1592 "class_course",
1593 ),
1594 ] {
1595 let (status, body) = get(&app, uri, &cookie).await;
1596 assert_eq!(status, StatusCode::BAD_REQUEST, "{uri} must be a 400");
1597 assert!(
1598 body["error"]
1599 .as_str()
1600 .unwrap_or_default()
1601 .contains(field),
1602 "{uri} must name {field}: {body}"
1603 );
1604 }
1605 }
1606
1607 /// The audience wall survives the filter: a student still sees only the
1608 /// homework they are assigned, a teacher still sees their instances'
1609 /// homework, and the manager sees every instance — all narrowed by the
1610 /// same params.
1611 #[tokio::test]
1612 async fn audience_walls_survive_the_filter() {
1613 let now = Timestamp::now().as_millis();
1614 let (app, _, school) = app_for("ogretmen-seyirci", Role::Student).await;
1615 // The same registry also holds the actors; mint them directly.
1616 let ali = crate::service::user::create(&school, Username::try_new("ali-filter").unwrap(), None)
1617 .await
1618 .unwrap();
1619 let veli = crate::service::user::create(&school, Username::try_new("veli-filter").unwrap(), None)
1620 .await
1621 .unwrap();
1622 let teacher = crate::service::user::create(
1623 &school,
1624 Username::try_new("hocasi-filter").unwrap(),
1625 None,
1626 )
1627 .await
1628 .unwrap();
1629 let teacher = crate::service::user::set_role(&school, teacher.get_id(), Role::Teacher)
1630 .await
1631 .unwrap()
1632 .0;
1633 let manager = crate::service::user::create(
1634 &school,
1635 Username::try_new("mudur-seyirci").unwrap(),
1636 None,
1637 )
1638 .await
1639 .unwrap();
1640 let manager = crate::service::user::set_role(&school, manager.get_id(), Role::Manager)
1641 .await
1642 .unwrap()
1643 .0;
1644
1645 let (instance, course) = crate::db::course::a_test_instance(&school).await;
1646 let whole_open = seed_homework_on(&school, &instance, &course, now + DAY, "acik-genel", None).await;
1647 let subset_open = seed_homework_on(
1648 &school,
1649 &instance,
1650 &course,
1651 now + DAY,
1652 "acik-secili",
1653 Some(vec![*ali.get_id()]),
1654 )
1655 .await;
1656 let past = seed_homework_on(&school, &instance, &course, now - DAY, "gecmis-genel", None).await;
1657 join_class(&school, &instance, ali.get_id()).await;
1658 join_class(&school, &instance, veli.get_id()).await;
1659 crate::db::class_course_teacher::assign(&school, &instance, teacher.get_id())
1660 .await
1661 .unwrap();
1662
1663 let ali_cookie = format!(
1664 "session={DEMO_SCHOOL_ID}.{}",
1665 session::create(&school, ali.get_id())
1666 .await
1667 .unwrap()
1668 .token()
1669 .as_str()
1670 );
1671 let veli_cookie = format!(
1672 "session={DEMO_SCHOOL_ID}.{}",
1673 session::create(&school, veli.get_id())
1674 .await
1675 .unwrap()
1676 .token()
1677 .as_str()
1678 );
1679 let teacher_cookie = format!(
1680 "session={DEMO_SCHOOL_ID}.{}",
1681 session::create(&school, teacher.get_id())
1682 .await
1683 .unwrap()
1684 .token()
1685 .as_str()
1686 );
1687 let manager_cookie = format!(
1688 "session={DEMO_SCHOOL_ID}.{}",
1689 session::create(&school, manager.get_id())
1690 .await
1691 .unwrap()
1692 .token()
1693 .as_str()
1694 );
1695
1696 // Ali: open tab only, and the subset names him — narrowed to him.
1697 let (status, body) = get(&app, &format!("/homework?due_after={now}"), &ali_cookie).await;
1698 assert_eq!(status, StatusCode::OK);
1699 assert_eq!(body["total"], 2);
1700 let ids: Vec<String> = body["items"]
1701 .as_array()
1702 .unwrap()
1703 .iter()
1704 .map(|row| row["id"].as_str().unwrap().to_string())
1705 .collect();
1706 assert_eq!(
1707 ids,
1708 vec![
1709 subset_open.get_id().key(),
1710 whole_open.get_id().key()
1711 ]
1712 );
1713 let subset = body["items"]
1714 .as_array()
1715 .unwrap()
1716 .iter()
1717 .find(|row| row["id"] == subset_open.get_id().key())
1718 .unwrap();
1719 assert_eq!(
1720 subset["assigned"],
1721 serde_json::json!([ali.get_id().key().to_string()]),
1722 "a student's subset roster is narrowed to themselves"
1723 );
1724
1725 // Veli shares the class but not the subset: the open tab hides it.
1726 let (status, body) = get(&app, &format!("/homework?due_after={now}"), &veli_cookie).await;
1727 assert_eq!(status, StatusCode::OK);
1728 assert_eq!(body["total"], 1);
1729 assert_eq!(body["items"][0]["id"], whole_open.get_id().key().to_string());
1730
1731 // The teacher manages the instance: every open row of it, roster and
1732 // all — the past row stays behind the filter, not the audience.
1733 let (status, body) =
1734 get(&app, &format!("/homework?due_after={now}"), &teacher_cookie).await;
1735 assert_eq!(status, StatusCode::OK);
1736 assert_eq!(body["total"], 2);
1737 assert!(body["items"].as_array().unwrap().iter().any(|row| row["id"]
1738 == subset_open.get_id().key()
1739 && row["assigned"]
1740 .as_array()
1741 .unwrap()
1742 .len()
1743 == 1));
1744
1745 // The manager sees every instance's homework, narrowed by the params.
1746 let (status, body) = get(&app, &format!("/homework?due_before={now}"), &manager_cookie).await;
1747 assert_eq!(status, StatusCode::OK);
1748 assert_eq!(body["total"], 1);
1749 assert_eq!(body["items"][0]["id"], past.get_id().key().to_string());
1750 }
1751}