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

mod.rs721 lines, 31.6 KiBHistoryRawDownload
1use std::collections::{HashMap, HashSet};
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
6use axum::http::StatusCode;
7use axum::response::Response;
8use serde::{Deserialize, Serialize};
9use utoipa::ToSchema;
10use utoipa_axum::router::OpenApiRouter;
11use utoipa_axum::routes;
12
13use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
14use crate::database::Database;
15use crate::domain::answer_image::AnswerImage;
16
17use crate::domain::exam::{
18 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle,
19};
20use crate::domain::exam_answer::{ExamAnswer, auto_score};
21use crate::domain::exam_question::{
22 Choice, ChoiceId, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText,
23};
24use crate::domain::exam_result::{ExamResult, Mark};
25use crate::domain::note_file::FileContentType;
26use crate::domain::question_image::QuestionImage;
27use crate::domain::role::Role;
28use crate::domain::timestamp::Timestamp;
29use crate::domain::user::{User, UserId};
30use crate::error::{AppError, ErrorResponse, ValidationError};
31use crate::service;
32use crate::service::instance::{can_manage_instance, visible_instances};
33use crate::state::AppState;
34
35use super::bank_questions::BankQuestionResponse;
36use super::instances::can_view_instance;
37use super::{
38 ChoiceBody, CurrentUser, ExamResponse, ImageUpload, Page, PageParams, PersonRef,
39 RequireTeacher, UploadFileForm, WindowParams, blob_path, check_not_past, paginate,
40 person_map, read_image_upload, remove_blob, set_or_clear, store_blob,
41};
42
43pub(crate) mod attempts;
44pub(crate) mod audience;
45pub(crate) mod images;
46pub(crate) mod questions;
47pub(crate) mod review;
48
49pub(crate) use attempts::*;
50pub(crate) use audience::*;
51pub(crate) use images::*;
52pub(crate) use questions::*;
53pub(crate) use review::*;
54
55pub fn routes() -> OpenApiRouter<AppState> {
56 OpenApiRouter::new()
57 // Plain route: OpenApiRouter can't describe a WebSocket upgrade, so
58 // the exam room lives outside the generated spec (see the `exams` tag
59 // description and README for the protocol).
60 .route(
61 "/{id}/attempt/ws",
62 axum::routing::get(super::exam_ws::attempt_ws),
63 )
64 .routes(routes!(list_exams))
65 .routes(routes!(get_exam, update_exam, delete_exam))
66 .routes(routes!(add_audience, list_audience, remove_audience))
67 .routes(routes!(grade, list_results))
68 .routes(routes!(my_result))
69 .routes(routes!(remove_result))
70 .routes(routes!(exam_statistics))
71 .routes(routes!(start_attempt, my_attempt))
72 .routes(routes!(finish_attempt))
73 .routes(routes!(exam_live))
74 .routes(routes!(create_question, list_questions))
75 .routes(routes!(update_question, delete_question))
76 .routes(routes!(question_from_bank))
77 .routes(routes!(question_to_bank))
78 .routes(routes!(question_refresh_from_bank))
79 .routes(routes!(attempt_questions))
80 .routes(routes!(save_answer))
81 .routes(routes!(attempt_answers))
82 .routes(routes!(student_attempts))
83 .routes(routes!(student_attempt_answers))
84 .routes(routes!(student_marks_history))
85 .routes(routes!(review_questions))
86 .routes(routes!(review_attempts))
87 .routes(routes!(review_attempt_answers))
88 // The image routes get their own HTTP body cap, like the note-file
89 // ones: the server-wide hard ceiling plus multipart framing headroom.
90 .merge(
91 OpenApiRouter::new()
92 .routes(routes!(
93 upload_question_image,
94 get_question_image,
95 delete_question_image
96 ))
97 .routes(routes!(
98 upload_choice_image,
99 get_choice_image,
100 delete_choice_image
101 ))
102 .routes(routes!(
103 upload_answer_image,
104 get_answer_image,
105 delete_answer_image
106 ))
107 .routes(routes!(get_student_answer_image))
108 .routes(routes!(student_attempt_answer_image))
109 .routes(routes!(review_attempt_answer_image))
110 .layer(DefaultBodyLimit::max(
111 MAX_MAX_FILE_BYTES as usize + UPLOAD_BODY_OVERHEAD_BYTES,
112 )),
113 )
114}
115
116#[derive(Deserialize, ToSchema)]
117struct UpdateExam {
118 #[schema(max_length = 200)]
119 title: Option<String>,
120 #[schema(max_length = 2000)]
121 description: Option<String>,
122 /// The assessment form — one of the school's exam kinds (`GET /settings`).
123 /// Changing it re-weights the exam: the instance average uses the kind's
124 /// settings-configured weight. For that reason an exam that already carries
125 /// marks keeps its kind (`409`) — those marks would silently re-weight,
126 /// exactly what the settings' kind-removal guard refuses.
127 kind: Option<String>,
128 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
129 /// to turn the exam back into an offline-graded one. Frozen once anyone
130 /// has started an attempt. Switching to `open` requires clearing
131 /// `starts_at`/`ends_at` in the same request.
132 #[serde(default, deserialize_with = "set_or_clear")]
133 #[schema(value_type = Option<String>)]
134 mode: Option<Option<String>>,
135 /// Window open, UTC unix-milliseconds. Omit to keep; `null` to clear.
136 /// A newly set value must not be in the past.
137 #[serde(default, deserialize_with = "set_or_clear")]
138 #[schema(value_type = Option<i64>)]
139 starts_at: Option<Option<i64>>,
140 /// Window close, UTC unix-milliseconds. Omit to keep; `null` to clear.
141 /// Moving it while a sync exam runs extends (or cuts) everyone's deadline;
142 /// a newly set value must not be in the past.
143 #[serde(default, deserialize_with = "set_or_clear")]
144 #[schema(value_type = Option<i64>)]
145 ends_at: Option<Option<i64>>,
146 /// Per-attempt budget, milliseconds (`async`, or optionally `open`). Omit
147 /// to keep; `null` to clear. Changing it mid-exam moves every running
148 /// attempt's deadline.
149 #[serde(default, deserialize_with = "set_or_clear")]
150 #[schema(value_type = Option<i64>, minimum = 60000, maximum = 86400000)]
151 duration_ms: Option<Option<i64>>,
152 /// Attempt limit: `1`–`100`, or `0` for unlimited. Omit to keep. Editable
153 /// live — raising it grants retakes on the spot; lowering it only blocks
154 /// future starts.
155 #[schema(minimum = 0, maximum = 100)]
156 max_attempts: Option<i64>,
157 /// Whether students who left the exam room may come back in. Omit to
158 /// keep. Editable live — the teacher's door handle for the running room.
159 allow_rejoin: Option<bool>,
160 /// Whether students may review their graded attempt once results are out.
161 /// Omit to keep. Editable live.
162 allow_review: Option<bool>,
163 /// `false` publishes a draft (students can now see and sit it); `true`
164 /// pulls a published exam back into hiding — allowed only while nobody
165 /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.
166 draft: Option<bool>,
167}
168
169#[derive(Deserialize, ToSchema)]
170struct GradeResult {
171 /// The mark to record, `0`–`100`.
172 #[schema(example = 85, minimum = 0, maximum = 100)]
173 mark: i64,
174 /// The student being graded.
175 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
176 user_id: String,
177}
178
179#[derive(Serialize, ToSchema)]
180pub(crate) struct ExamResultResponse {
181 id: String,
182 exam: String,
183 /// The graded student.
184 user: PersonRef,
185 /// Which sitting this mark belongs to (1 = first attempt). Lets the grader
186 /// jump from a mark to that sitting's answer sheet
187 /// (`GET /exams/{id}/students/{user}/attempts/{seq}/answers`) — without it
188 /// a marked retake's answers are unreachable from the mark.
189 seq: i64,
190 mark: i64,
191 /// Who recorded the mark.
192 graded_by: PersonRef,
193}
194
195impl ExamResultResponse {
196 fn new(result: &ExamResult, people: &HashMap<String, PersonRef>) -> Self {
197 Self {
198 id: result.get_id().key().to_string(),
199 exam: result.get_exam().key().to_string(),
200 user: PersonRef::resolve(people, result.get_user()),
201 seq: result.get_seq(),
202 mark: result.get_mark().as_i64(),
203 graded_by: PersonRef::resolve(people, result.get_graded_by()),
204 }
205 }
206}
207
208#[derive(Serialize, ToSchema)]
209struct ExamStatisticsResponse {
210 exam: String,
211 /// Number of graded results.
212 graded: u64,
213 /// Plain mean of the graded marks; `null` while nothing is graded.
214 average: Option<f64>,
215 min: Option<i64>,
216 max: Option<i64>,
217}
218
219// ---- exams --------------------------------------------------------------
220// Exams are created inside an instance: `POST /instances/{id}/exams`.
221
222/// List the exams visible to the caller: every exam for manager+, otherwise
223/// the exams of the instances they teach or are enrolled in — minus other
224/// people's drafts (a draft shows only to its instance's managers). Paged via
225/// `?limit=&offset=` (omit `limit` for the full list); returns a
226/// `{items, total, limit, offset}` envelope.
227///
228/// The optional `?starts_after=&ends_after=` schedule window (unix
229/// milliseconds) applies *after* the visibility and draft filtering, narrows
230/// the list to upcoming/unfinished exams and flips the order to ascending by
231/// schedule — so `?ends_after=<now>&limit=20` returns the twenty *soonest*
232/// exams rather than the twenty newest-created. Exams without a window
233/// (no `mode`, or `open`) are excluded by either parameter.
234/// `?starts_before=` / `?ends_before=` are the mirror bounds (strictly
235/// before). Visibility, the draft rule, the window, the page, and the count
236/// share one SQL `WHERE`, so a filtered page never decodes the exams it
237/// skips.
238#[utoipa::path(
239 get,
240 path = "/",
241 tag = "exams",
242 security(("session_cookie" = [])),
243 params(WindowParams, PageParams),
244 responses(
245 (status = 200, description = "A page of the caller's visible exams (all of them when unpaged)", body = Page<ExamResponse>),
246 (status = 400, description = "Invalid window, limit, or offset", body = ErrorResponse),
247 (status = 401, description = "Not authenticated", body = ErrorResponse),
248 ),
249)]
250async fn list_exams(
251 State(st): State<AppState>,
252 CurrentUser(user): CurrentUser,
253 Query(window): Query<WindowParams>,
254 Query(page): Query<PageParams>,
255) -> Result<Json<Page<ExamResponse>>, AppError> {
256 let (limit, offset) = page.resolve()?;
257 window.validate()?;
258 let params = service::exam::WindowedListParams {
259 starts_after: window.starts_after,
260 ends_after: window.ends_after,
261 starts_before: window.starts_before,
262 ends_before: window.ends_before,
263 limit,
264 offset,
265 };
266 // Visibility and the draft rule ride the same WHERE as the page and the
267 // count: a manager+ reads the whole table, everyone else the exams of
268 // their visible instances — a draft only where they manage the instance.
269 let (exams, total) = if user.get_role().at_least(Role::Manager) {
270 service::exam::list_windowed(&st.db, None, None, params).await?
271 } else {
272 let instances = visible_instances(&user, &st.db).await?;
273 let visible: Vec<_> = instances.iter().map(|(i, _)| i.get_id().clone()).collect();
274 // Drafts show only where the caller manages the instance (as one of
275 // its teachers — the manager+ path above already saw everything).
276 let managed: Vec<_> = instances
277 .iter()
278 .filter(|(_, manages)| *manages)
279 .map(|(instance, _)| instance.get_id().clone())
280 .collect();
281 service::exam::list_windowed(&st.db, Some(&visible), Some(&managed), params).await?
282 };
283 let items = exams.iter().map(ExamResponse::new).collect();
284 Ok(Json(Page::new(items, total, limit, offset)))
285}
286
287/// Fetch a single exam by id. Visible to **any instance the exam is addressed
288/// to** — its owner's enrolled students and teachers, and, for an announced
289/// exam (a shared exam), each addressed section's alike — plus managers/admins;
290/// drafts only show to the managers of an addressed instance (everyone else
291/// gets a `404`, as if the exam doesn't exist yet — because it doesn't,
292/// officially).
293///
294/// Gate order is deliberate and must stay as written: a caller with no view of
295/// any addressed instance is refused by the *view* gate (`403`) before the
296/// draft gate is reached, so the `404` rule covers only callers who can see an
297/// instance the exam reaches — a teacher since removed from it, for instance,
298/// gets the `403` unless they are enrolled. Moving the draft check above the
299/// view check to "make the 404 universal" would hand every unenrolled caller a
300/// probe for which exams exist.
301#[utoipa::path(
302 get,
303 path = "/{id}",
304 tag = "exams",
305 security(("session_cookie" = [])),
306 params(("id" = String, Path, description = "Exam id")),
307 responses(
308 (status = 200, description = "The exam", body = ExamResponse),
309 (status = 401, description = "Not authenticated", body = ErrorResponse),
310 (status = 403, description = "Not enrolled and not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
311 (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
312 ),
313)]
314async fn get_exam(
315 State(st): State<AppState>,
316 CurrentUser(user): CurrentUser,
317 Path(id): Path<String>,
318) -> Result<Json<ExamResponse>, AppError> {
319 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
320 .await?
321 .ok_or(AppError::NotFound)?;
322 let (may_view, may_manage) = audience_rights(&st.db, &exam, &user).await?;
323 if !may_view {
324 return Err(AppError::Forbidden(
325 "only an addressed instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view this exam",
326 ));
327 }
328 // A draft doesn't exist for anyone but an addressed instance's managers —
329 // 404, not 403, so its existence never leaks to the students it's hidden
330 // from.
331 if exam.is_draft() && !may_manage {
332 return Err(AppError::NotFound);
333 }
334 Ok(Json(ExamResponse::new(&exam)))
335}
336
337/// Update an exam. Requires teacher+ and management rights over the exam's
338/// instance (an assigned teacher, its class's homeroom teacher, or a
339/// manager/admin). Omitted fields keep their value; an explicit `null` clears a
340/// schedule field; the instance an exam hangs off is not updatable here.
341/// The schedule must stay consistent as a whole (see the create endpoint), and
342/// `mode` is frozen once anyone has started an attempt — times, duration,
343/// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be
344/// extended, granted retakes, or have its rejoin door opened live.
345/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only
346/// while it has no attempts and no results (`409` otherwise) — students never
347/// lose sight of an exam they've already sat or been graded on.
348#[utoipa::path(
349 patch,
350 path = "/{id}",
351 tag = "exams",
352 security(("session_cookie" = [])),
353 params(("id" = String, Path, description = "Exam id")),
354 request_body = UpdateExam,
355 responses(
356 (status = 200, description = "Updated exam", body = ExamResponse),
357 (status = 400, description = "Invalid fields, kind, attempt limit, or schedule (malformed window, duration exceeding the window, or newly set times in the past)", body = ErrorResponse),
358 (status = 401, description = "Not authenticated", body = ErrorResponse),
359 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
360 (status = 404, description = "Not found", body = ErrorResponse),
361 (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, the exam kept changing under concurrent edits, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
362 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
363 ),
364)]
365async fn update_exam(
366 State(st): State<AppState>,
367 RequireTeacher(user): RequireTeacher,
368 Path(id): Path<String>,
369 Json(req): Json<UpdateExam>,
370) -> Result<Json<ExamResponse>, AppError> {
371 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
372 .await?
373 .ok_or(AppError::NotFound)?;
374 let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;
375 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
376 return Err(AppError::Forbidden(
377 "only this instance's teachers, its class's homeroom teacher, or a manager/admin can edit this exam",
378 ));
379 }
380 service::exam_attempt::require_open(&st.db, &exam).await?;
381
382 // Field validation, in the order the request is judged — only values this
383 // request sets are held to the rules (a stored kind survives list edits,
384 // kept times may legitimately be past). The merge against the stored row,
385 // the schedule re-validation as a unit, and the mode-freeze / re-draft /
386 // kind gates are the workflow's own steps:
387 // [`crate::service::exam::update`] re-derives them per retry round behind
388 // the compare-and-set.
389 let title = req.title.as_deref().map(ExamTitle::try_new).transpose()?;
390 let description = req
391 .description
392 .as_deref()
393 .map(ExamDescription::try_new)
394 .transpose()?;
395 let kind = match &req.kind {
396 // Only a kind this request sets is held to the current settings list —
397 // a stored kind survives later list edits, like past times survive
398 // the no-past rule.
399 Some(kind) => Some(ExamKind::try_new(
400 kind,
401 service::settings::load(&st.db).await?.get_exam_kinds(),
402 )?),
403 None => None,
404 };
405 let mode = match &req.mode {
406 Some(update) => Some(update.as_deref().map(ExamMode::try_new).transpose()?),
407 None => None,
408 };
409 let starts_at = match req.starts_at {
410 Some(update) => {
411 let starts_at = update.map(Timestamp::from_millis);
412 check_not_past("starts_at", starts_at)?;
413 Some(starts_at)
414 }
415 None => None,
416 };
417 let ends_at = match req.ends_at {
418 Some(update) => {
419 let ends_at = update.map(Timestamp::from_millis);
420 check_not_past("ends_at", ends_at)?;
421 Some(ends_at)
422 }
423 None => None,
424 };
425 let duration_ms = match req.duration_ms {
426 Some(update) => Some(update.map(ExamDuration::try_new).transpose()?),
427 None => None,
428 };
429 let max_attempts = req
430 .max_attempts
431 .map(ExamAttemptLimit::try_new)
432 .transpose()?;
433 let patch = service::exam::ExamPatch {
434 title,
435 description,
436 kind,
437 mode,
438 starts_at,
439 ends_at,
440 duration_ms,
441 max_attempts,
442 allow_rejoin: req.allow_rejoin,
443 allow_review: req.allow_review,
444 draft: req.draft,
445 };
446 let exam = service::exam::update(&st.db, exam.get_id(), &patch).await?;
447 Ok(Json(ExamResponse::new(&exam)))
448}
449
450/// Delete an exam. Requires teacher+ and management rights over the exam's
451/// instance (an assigned teacher, its class's homeroom teacher, or a
452/// manager/admin). Cascades the exam's results,
453/// attempts, questions, answers, and question + answer images (blobs included).
454#[utoipa::path(
455 delete,
456 path = "/{id}",
457 tag = "exams",
458 security(("session_cookie" = [])),
459 params(("id" = String, Path, description = "Exam id")),
460 responses(
461 (status = 204, description = "Deleted"),
462 (status = 401, description = "Not authenticated", body = ErrorResponse),
463 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
464 (status = 404, description = "Not found", body = ErrorResponse),
465 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
466 ),
467)]
468async fn delete_exam(
469 State(st): State<AppState>,
470 RequireTeacher(user): RequireTeacher,
471 Path(id): Path<String>,
472) -> Result<StatusCode, AppError> {
473 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
474 .await?
475 .ok_or(AppError::NotFound)?;
476 let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;
477 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
478 return Err(AppError::Forbidden(
479 "only this instance's teachers, its class's homeroom teacher, or a manager/admin can delete this exam",
480 ));
481 }
482 // The workflow — the archived-term gate, the exam-row lock and the
483 // cascade with its in-transaction blob-key collection, the delete — is
484 // [`crate::service::exam::delete`]'s. Blob unlinking stays here because
485 // only the web layer knows `files_path`.
486 let outcome = service::exam::delete(&st.db, &exam).await?;
487 for file in &outcome.image_files {
488 remove_blob(&st.files_path, file).await;
489 }
490 for file in &outcome.answer_image_files {
491 remove_blob(&st.files_path, file).await;
492 }
493 Ok(StatusCode::NO_CONTENT)
494}
495
496// ---- results ------------------------------------------------------------
497
498/// Record (or overwrite) a student's mark for an exam. Requires teacher+ and
499/// management rights over **an instance the exam is addressed to** (the
500/// announced-to section's teacher grades its own students on a shared exam);
501/// the target must be a student enrolled in one of them. Only students carry
502/// marks; students never grade — and nobody
503/// grades themselves. A draft can't be graded (`409`) — a mark would point at
504/// an exam its student can't see.
505#[utoipa::path(
506 post,
507 path = "/{id}/results",
508 tag = "exams",
509 security(("session_cookie" = [])),
510 params(("id" = String, Path, description = "Exam id")),
511 request_body = GradeResult,
512 responses(
513 (status = 200, description = "Result recorded", body = ExamResultResponse),
514 (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),
515 (status = 401, description = "Not authenticated", body = ErrorResponse),
516 (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin, or attempted to grade yourself", body = ErrorResponse),
517 (status = 404, description = "Exam not found", body = ErrorResponse),
518 (status = 409, description = "The exam is a draft, its kind has been removed from the school's settings, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
519 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
520 ),
521)]
522async fn grade(
523 State(st): State<AppState>,
524 RequireTeacher(teacher): RequireTeacher,
525 Path(id): Path<String>,
526 Json(req): Json<GradeResult>,
527) -> Result<Json<ExamResultResponse>, AppError> {
528 let exam_id = ExamId::from_key(&id);
529 // Exam must exist, and only someone with a right over its instance may
530 // grade it.
531 let exam = service::exam::read(&st.db, &exam_id)
532 .await?
533 .ok_or(AppError::NotFound)?;
534 let (_, manages) = audience_rights(&st.db, &exam, &teacher).await?;
535 if !manages {
536 return Err(AppError::Forbidden(
537 "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can grade this exam",
538 ));
539 }
540 let target = UserId::from_key(&req.user_id);
541 // The workflow — the draft and kind pre-flights (the draft one re-made
542 // on the locked exam row inside the mark's own transaction, so a
543 // concurrent re-draft cannot slip a mark onto a hidden exam), the
544 // grader/target walls, the sitting resolution, the mark's own
545 // transaction, and the badge sync — is
546 // [`crate::service::exam_result::grade`]'s.
547 let result =
548 service::exam_result::grade(&st.db, &exam_id, teacher.get_id(), &target, req.mark).await?;
549 let target_user = service::user::read(&st.db, &target)
550 .await?
551 .ok_or(AppError::NotFound)?;
552 let people = PersonRef::map_of(&[&target_user, &teacher]);
553 Ok(Json(ExamResultResponse::new(&result, &people)))
554}
555
556/// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all
557/// of them). Requires teacher+ and management rights over an instance the
558/// exam is addressed to — students read only their own via
559/// `GET /exams/{id}/result`. Returns a
560/// `{items, total, limit, offset}` envelope.
561#[utoipa::path(
562 get,
563 path = "/{id}/results",
564 tag = "exams",
565 security(("session_cookie" = [])),
566 params(("id" = String, Path, description = "Exam id"), PageParams),
567 responses(
568 (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
569 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
570 (status = 401, description = "Not authenticated", body = ErrorResponse),
571 (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
572 (status = 404, description = "Exam not found", body = ErrorResponse),
573 ),
574)]
575async fn list_results(
576 State(st): State<AppState>,
577 RequireTeacher(user): RequireTeacher,
578 Path(id): Path<String>,
579 Query(page): Query<PageParams>,
580) -> Result<Json<Page<ExamResultResponse>>, AppError> {
581 let (limit, offset) = page.resolve()?;
582 // Exam must exist — a missing exam is a 404, not an empty result list.
583 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
584 .await?
585 .ok_or(AppError::NotFound)?;
586 let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
587 if !manages {
588 return Err(AppError::Forbidden(
589 "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can list results",
590 ));
591 }
592 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;
593 let total = results.len() as i64;
594 // Join people onto the page alone — the lookup shrinks with the window.
595 // Paged in the web layer: the list is deduped to the latest mark per
596 // sitting pair in Rust.
597 let rows = paginate(&results, limit, offset);
598 let people = person_map(
599 rows.iter()
600 .flat_map(|r| [*r.get_user(), *r.get_graded_by()]),
601 &st.db,
602 )
603 .await?;
604 let items = rows
605 .iter()
606 .map(|r| ExamResultResponse::new(r, &people))
607 .collect();
608 Ok(Json(Page::new(items, total, limit, offset)))
609}
610
611/// The current user's own result for an exam. Any authenticated user may read
612/// their own mark; `404` while ungraded (or when the exam doesn't exist).
613#[utoipa::path(
614 get,
615 path = "/{id}/result",
616 tag = "exams",
617 security(("session_cookie" = [])),
618 params(("id" = String, Path, description = "Exam id")),
619 responses(
620 (status = 200, description = "The caller's result", body = ExamResultResponse),
621 (status = 401, description = "Not authenticated", body = ErrorResponse),
622 (status = 404, description = "No such exam, or not graded yet", body = ErrorResponse),
623 ),
624)]
625async fn my_result(
626 State(st): State<AppState>,
627 CurrentUser(user): CurrentUser,
628 Path(id): Path<String>,
629) -> Result<Json<ExamResultResponse>, AppError> {
630 let result = service::exam_result::read_for_user(&st.db, &ExamId::from_key(&id), user.get_id())
631 .await?
632 .ok_or(AppError::NotFound)?;
633 let people = person_map([*result.get_user(), *result.get_graded_by()], &st.db).await?;
634 Ok(Json(ExamResultResponse::new(&result, &people)))
635}
636
637/// Remove a student's result from an exam. Requires teacher+ and management
638/// rights over an instance the exam is addressed to.
639#[utoipa::path(
640 delete,
641 path = "/{id}/results/{user}",
642 tag = "exams",
643 security(("session_cookie" = [])),
644 params(
645 ("id" = String, Path, description = "Exam id"),
646 ("user" = String, Path, description = "User id"),
647 ),
648 responses(
649 (status = 204, description = "Removed"),
650 (status = 401, description = "Not authenticated", body = ErrorResponse),
651 (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
652 (status = 404, description = "Not found", body = ErrorResponse),
653 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
654 ),
655)]
656async fn remove_result(
657 State(st): State<AppState>,
658 RequireTeacher(user): RequireTeacher,
659 Path((id, target)): Path<(String, String)>,
660) -> Result<StatusCode, AppError> {
661 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
662 .await?
663 .ok_or(AppError::NotFound)?;
664 let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
665 if !manages {
666 return Err(AppError::Forbidden(
667 "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can remove results",
668 ));
669 }
670 // The archived-term gate and the refunding delete are
671 // [`crate::service::exam_result::remove`]'s.
672 let removed = service::exam_result::remove(&st.db, &exam, &UserId::from_key(&target)).await?;
673 if removed.is_none() {
674 return Err(AppError::NotFound);
675 }
676 Ok(StatusCode::NO_CONTENT)
677}
678
679/// Summary statistics for an exam's graded results. Requires teacher+ and
680/// management rights over an instance the exam is addressed to.
681#[utoipa::path(
682 get,
683 path = "/{id}/statistics",
684 tag = "exams",
685 security(("session_cookie" = [])),
686 params(("id" = String, Path, description = "Exam id")),
687 responses(
688 (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),
689 (status = 401, description = "Not authenticated", body = ErrorResponse),
690 (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
691 (status = 404, description = "Exam not found", body = ErrorResponse),
692 ),
693)]
694async fn exam_statistics(
695 State(st): State<AppState>,
696 RequireTeacher(user): RequireTeacher,
697 Path(id): Path<String>,
698) -> Result<Json<ExamStatisticsResponse>, AppError> {
699 // Exam must exist — a missing exam is a 404, not an empty statistic.
700 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
701 .await?
702 .ok_or(AppError::NotFound)?;
703 let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
704 if !manages {
705 return Err(AppError::Forbidden(
706 "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can view statistics",
707 ));
708 }
709 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;
710
711 let marks: Vec<i64> = results.iter().map(|r| r.get_mark().as_i64()).collect();
712 let average =
713 (!marks.is_empty()).then(|| marks.iter().sum::<i64>() as f64 / marks.len() as f64);
714 Ok(Json(ExamStatisticsResponse {
715 exam: exam.get_id().key().to_string(),
716 graded: marks.len() as u64,
717 average,
718 min: marks.iter().min().copied(),
719 max: marks.iter().max().copied(),
720 }))
721}