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

attempts.rs825 lines, 34.7 KiBHistoryRawDownload
1use super::*;
2
3use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt};
4use crate::service::exam_attempt;
5
6// ---- attempts -------------------------------------------------------------
7// A sittable exam (sync, async, or open mode) is *sat*: starting an attempt
8// is the live-attendance signal, finishing is the submission. The exam's
9// `max_attempts` (0 = unlimited) says how many sittings each student gets;
10// re-posting resumes a running attempt and mints the next sitting once the
11// last one is over. Deadlines are judged only by the server clock — clients
12// sync via `GET /time`.
13
14/// A student's view of their (latest) attempt. `now` is echoed so clients can
15/// render countdowns without trusting the device clock.
16#[derive(Serialize, ToSchema)]
17pub(crate) struct AttemptResponse {
18 id: String,
19 exam: String,
20 user: PersonRef,
21 /// Which sitting this is — 1 for the first attempt, counting up.
22 attempt: i64,
23 /// How many sittings the caller has used, this one included.
24 attempts_used: u64,
25 /// The exam's attempt limit; `0` means unlimited.
26 max_attempts: i64,
27 /// When the attempt started, UTC unix-milliseconds.
28 started_at: i64,
29 /// Submission instant; `null` while running (or expired unsubmitted).
30 finished_at: Option<i64>,
31 /// When the student left the exam room mid-attempt; `null` while inside
32 /// (or if they never used the room). With `allow_rejoin` off, a set
33 /// `left_at` locks further answering until the teacher reopens the door.
34 left_at: Option<i64>,
35 /// `in_progress` | `submitted` | `expired`.
36 #[schema(example = "in_progress")]
37 status: String,
38 /// When the attempt closes: the earlier of the window's `ends_at` and
39 /// `started_at + duration_ms` (whichever exists). Recomputed live from
40 /// the exam's current schedule; `null` for an open exam without a
41 /// duration — such an attempt only ends by submission.
42 deadline: Option<i64>,
43 /// `deadline - now`, floored at 0; `null` unless in progress with a
44 /// deadline.
45 remaining_ms: Option<i64>,
46 /// The caller's mark, once graded.
47 mark: Option<i64>,
48 /// How many questions the caller has answered so far.
49 answered: u64,
50 /// How many questions the exam has.
51 question_count: u64,
52 /// Server clock at response time, UTC unix-milliseconds.
53 now: i64,
54}
55
56impl AttemptResponse {
57 #[expect(
58 clippy::too_many_arguments,
59 reason = "a flat view over attempt + exam + progress; a builder would obscure it"
60 )]
61 pub(crate) fn new(
62 attempt: &ExamAttempt,
63 exam: &Exam,
64 mark: Option<Mark>,
65 people: &HashMap<String, PersonRef>,
66 answered: u64,
67 question_count: u64,
68 attempts_used: u64,
69 now: Timestamp,
70 ) -> Self {
71 let status = attempt.status(exam, now);
72 let deadline = attempt.deadline(exam);
73 let remaining_ms = (status == AttemptStatus::InProgress)
74 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
75 .flatten();
76 Self {
77 id: attempt.get_id().key().to_string(),
78 exam: attempt.get_exam().key().to_string(),
79 user: PersonRef::resolve(people, attempt.get_user()),
80 attempt: attempt.get_seq(),
81 attempts_used,
82 max_attempts: exam.get_max_attempts().as_i64(),
83 started_at: attempt.get_started_at().as_millis(),
84 finished_at: attempt.get_finished_at().map(|t| t.as_millis()),
85 left_at: attempt.get_left_at().map(|t| t.as_millis()),
86 status: status.as_str().to_string(),
87 deadline: deadline.map(|t| t.as_millis()),
88 remaining_ms,
89 mark: mark.map(|m| m.as_i64()),
90 answered,
91 question_count,
92 now: now.as_millis(),
93 }
94 }
95}
96
97/// The (answered, question_count) pair behind an attempt view — how far one
98/// student has come through the exam's question list.
99pub(crate) async fn attempt_progress(
100 exam: &ExamId,
101 user: &UserId,
102 seq: i64,
103 db: &Database,
104) -> Result<(u64, u64), AppError> {
105 let answered = crate::service::exam_answer::list_for_exam_user(db, exam, user, seq)
106 .await?
107 .len() as u64;
108 let question_count = crate::service::exam_question::list_for_exam(db, exam, None, 0)
109 .await?
110 .0
111 .len() as u64;
112 Ok((answered, question_count))
113}
114
115/// Start, resume, or retake the caller's attempt. Requires the student role
116/// (staff run exams, they don't sit them), enrollment in the exam's instance, a
117/// sittable exam (`sync`/`async`/`open` mode), and — when a window exists — the
118/// window to be open. A still-running attempt is returned
119/// as-is (`200` instead of `201`), so a reconnecting client gets its original
120/// clock back — re-starting never resets the time. Once the latest attempt is
121/// submitted or expired, re-posting starts the next sitting (`201`, blank
122/// answer sheet) while the exam's `max_attempts` (0 = unlimited) allows it.
123#[utoipa::path(
124 post,
125 path = "/{id}/attempt",
126 tag = "exams",
127 security(("session_cookie" = [])),
128 params(("id" = String, Path, description = "Exam id")),
129 responses(
130 (status = 201, description = "Attempt started (first sitting or a retake)", body = AttemptResponse),
131 (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),
132 (status = 401, description = "Not authenticated", body = ErrorResponse),
133 (status = 403, description = "Not a student, or not enrolled in the exam's instance", body = ErrorResponse),
134 (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse),
135 (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, no attempts remaining, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
136 ),
137)]
138pub(crate) async fn start_attempt(
139 State(st): State<AppState>,
140 CurrentUser(user): CurrentUser,
141 Path(id): Path<String>,
142) -> Result<(StatusCode, Json<AttemptResponse>), AppError> {
143 let (exam, attempt, created) =
144 exam_attempt::start_attempt(&st.db, &ExamId::from_key(&id), &user).await?;
145 let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id())
146 .await?
147 .map(|r| r.get_mark());
148 let (answered, question_count) =
149 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
150 let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
151 let people = PersonRef::map_of(&[&user]);
152 let status = if created {
153 StatusCode::CREATED
154 } else {
155 StatusCode::OK
156 };
157 Ok((
158 status,
159 Json(AttemptResponse::new(
160 &attempt,
161 &exam,
162 mark,
163 &people,
164 answered,
165 question_count,
166 used,
167 Timestamp::now(),
168 )),
169 ))
170}
171
172/// The caller's own (latest) attempt: status, deadline, remaining time, and
173/// mark once graded — everything a student's live exam screen needs, judged
174/// by the server clock. `404` until an attempt is started.
175#[utoipa::path(
176 get,
177 path = "/{id}/attempt",
178 tag = "exams",
179 security(("session_cookie" = [])),
180 params(("id" = String, Path, description = "Exam id")),
181 responses(
182 (status = 200, description = "The caller's latest attempt", body = AttemptResponse),
183 (status = 401, description = "Not authenticated", body = ErrorResponse),
184 (status = 404, description = "No such exam, or no attempt yet", body = ErrorResponse),
185 ),
186)]
187pub(crate) async fn my_attempt(
188 State(st): State<AppState>,
189 CurrentUser(user): CurrentUser,
190 Path(id): Path<String>,
191) -> Result<Json<AttemptResponse>, AppError> {
192 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
193 .await?
194 .ok_or(AppError::NotFound)?;
195 let attempt = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
196 .await?
197 .ok_or(AppError::NotFound)?;
198 let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id())
199 .await?
200 .map(|r| r.get_mark());
201 let (answered, question_count) =
202 attempt_progress(exam.get_id(), user.get_id(), attempt.get_seq(), &st.db).await?;
203 let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
204 let people = PersonRef::map_of(&[&user]);
205 Ok(Json(AttemptResponse::new(
206 &attempt,
207 &exam,
208 mark,
209 &people,
210 answered,
211 question_count,
212 used,
213 Timestamp::now(),
214 )))
215}
216
217/// Submit the caller's attempt. Allowed while the deadline hasn't passed;
218/// after it, the attempt is already `expired` (a valid terminal state — the
219/// student used their full time) and submitting is a `409`.
220#[utoipa::path(
221 post,
222 path = "/{id}/attempt/finish",
223 tag = "exams",
224 security(("session_cookie" = [])),
225 params(("id" = String, Path, description = "Exam id")),
226 responses(
227 (status = 200, description = "Attempt submitted", body = AttemptResponse),
228 (status = 401, description = "Not authenticated", body = ErrorResponse),
229 (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse),
230 (status = 409, description = "Already submitted, the deadline passed, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
231 ),
232)]
233pub(crate) async fn finish_attempt(
234 State(st): State<AppState>,
235 CurrentUser(user): CurrentUser,
236 Path(id): Path<String>,
237) -> Result<Json<AttemptResponse>, AppError> {
238 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
239 .await?
240 .ok_or(AppError::NotFound)?;
241 let finished = exam_attempt::finish_attempt(&st.db, &exam, user.get_id()).await?;
242 let mark = crate::service::exam_result::read_for_user(&st.db, exam.get_id(), user.get_id())
243 .await?
244 .map(|r| r.get_mark());
245 let (answered, question_count) =
246 attempt_progress(exam.get_id(), user.get_id(), finished.get_seq(), &st.db).await?;
247 let used = exam_attempt::attempts_used(&st.db, exam.get_id(), user.get_id()).await?;
248 let people = PersonRef::map_of(&[&user]);
249 Ok(Json(AttemptResponse::new(
250 &finished,
251 &exam,
252 mark,
253 &people,
254 answered,
255 question_count,
256 used,
257 Timestamp::now(),
258 )))
259}
260
261// ---- live monitor ---------------------------------------------------------
262
263/// One roster row of the live exam monitor. The attempt fields describe the
264/// student's *latest* sitting.
265#[derive(Serialize, ToSchema)]
266pub(crate) struct LiveStudentResponse {
267 user: PersonRef,
268 /// `not_started` | `absent` | `in_progress` | `submitted` | `expired`.
269 /// `absent` is `not_started` after the window closed: the student never
270 /// sat and no longer can. Open exams have no window, so nobody is ever
271 /// absent from one.
272 #[schema(example = "in_progress")]
273 status: String,
274 /// Which sitting the shown attempt is (1, 2, …); `null` before the first.
275 attempt: Option<i64>,
276 /// How many sittings this student has used.
277 attempts_used: u64,
278 started_at: Option<i64>,
279 finished_at: Option<i64>,
280 /// When this student left the exam room mid-attempt; `null` while inside.
281 left_at: Option<i64>,
282 /// When this student's attempt closes (server-authoritative).
283 deadline: Option<i64>,
284 /// Time this student has left, floored at 0; `null` unless in progress.
285 remaining_ms: Option<i64>,
286 /// The student's mark, once graded.
287 mark: Option<i64>,
288 /// How many questions this student has answered so far.
289 answered: u64,
290 /// When this student last saved an answer, UTC unix-milliseconds; `null`
291 /// before the first save.
292 last_activity: Option<i64>,
293}
294
295#[derive(Serialize, ToSchema)]
296pub(crate) struct LiveCountsResponse {
297 enrolled: u64,
298 /// Enrolled with no attempt while the window is still open (or the exam
299 /// has no window).
300 not_started: u64,
301 /// Enrolled with no attempt and the window closed — the no-shows.
302 absent: u64,
303 in_progress: u64,
304 submitted: u64,
305 expired: u64,
306 graded: u64,
307}
308
309/// A live snapshot of an exam: the enrolled roster with per-student attempt
310/// state, remaining time, and marks, all judged by one server-clock read.
311#[derive(Serialize, ToSchema)]
312pub(crate) struct ExamLiveResponse {
313 exam: ExamResponse,
314 /// Server clock the snapshot was judged at, UTC unix-milliseconds.
315 now: i64,
316 /// How many questions the exam has.
317 question_count: u64,
318 counts: LiveCountsResponse,
319 students: Vec<LiveStudentResponse>,
320}
321
322/// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.
323/// Students unenrolled mid-exam drop off the roster view (their attempt and
324/// mark rows survive, exactly like the marks report). The roster is the
325/// exam's whole audience (D2), so an announced-to section's sitters appear
326/// here exactly like the owner's — deduped by student, one row per person.
327pub(crate) async fn live_snapshot(
328 exam: &Exam,
329 db: &Database,
330) -> Result<ExamLiveResponse, AppError> {
331 let now = Timestamp::now();
332 let roster = crate::db::enrollment::list_for_exam_audience(db, exam.get_id()).await?;
333 // Per student: their latest sitting (the one the monitor shows) plus how
334 // many they've used.
335 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
336 let mut used: HashMap<String, u64> = HashMap::new();
337 for attempt in exam_attempt::list_for_exam(db, exam.get_id()).await? {
338 let key = attempt.get_user().key().to_string();
339 *used.entry(key.clone()).or_insert(0) += 1;
340 match attempts.entry(key) {
341 std::collections::hash_map::Entry::Vacant(slot) => {
342 slot.insert(attempt);
343 }
344 std::collections::hash_map::Entry::Occupied(mut slot) => {
345 if attempt.get_seq() > slot.get().get_seq() {
346 slot.insert(attempt);
347 }
348 }
349 }
350 }
351 let marks: HashMap<String, i64> = crate::service::exam_result::list_for_exam(db, exam.get_id())
352 .await?
353 .iter()
354 .map(|result| {
355 (
356 result.get_user().key().to_string(),
357 result.get_mark().as_i64(),
358 )
359 })
360 .collect();
361 let question_count = crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0)
362 .await?
363 .0
364 .len() as u64;
365 // Per-student progress: answer count and the latest save instant. The
366 // per-exam read now returns every sitting's rows across all students, so
367 // each answer is scoped to that student's *current* sitting — matching its
368 // seq to their latest attempt — or a re-sitting student's count would
369 // double up their prior attempts.
370 let mut progress: HashMap<String, (u64, i64)> = HashMap::new();
371 for answer in crate::service::exam_answer::list_for_exam(db, exam.get_id()).await? {
372 let key = answer.get_user().key().to_string();
373 if attempts.get(&key).map(ExamAttempt::get_seq) != Some(answer.get_seq()) {
374 continue;
375 }
376 let entry = progress.entry(key).or_insert((0, i64::MIN));
377 entry.0 += 1;
378 entry.1 = entry.1.max(answer.get_updated_at().as_millis());
379 }
380 let people = person_map(roster.iter().map(|e| *e.get_user()), db).await?;
381
382 // Once the window closes the door is shut for good (starting answers
383 // 409), so "hasn't started" hardens into "was absent". Open exams have
384 // no window and never make that call.
385 let window_over = exam.get_ends_at().is_some_and(|ends| now >= ends);
386 let mut students: Vec<LiveStudentResponse> = roster
387 .iter()
388 .map(|enrollment| {
389 let key = enrollment.get_user().key();
390 let attempt = attempts.get(&key);
391 let status = attempt.map(|a| a.status(exam, now));
392 let deadline = attempt.and_then(|a| a.deadline(exam));
393 LiveStudentResponse {
394 user: PersonRef::resolve(&people, enrollment.get_user()),
395 status: match status {
396 Some(status) => status.as_str(),
397 None if window_over => "absent",
398 None => "not_started",
399 }
400 .to_string(),
401 attempt: attempt.map(ExamAttempt::get_seq),
402 attempts_used: used.get(&key).copied().unwrap_or(0),
403 started_at: attempt.map(|a| a.get_started_at().as_millis()),
404 finished_at: attempt
405 .and_then(|a| a.get_finished_at())
406 .map(|t| t.as_millis()),
407 left_at: attempt.and_then(|a| a.get_left_at()).map(|t| t.as_millis()),
408 deadline: deadline.map(|t| t.as_millis()),
409 remaining_ms: (status == Some(AttemptStatus::InProgress))
410 .then(|| deadline.map(|d| (d.as_millis() - now.as_millis()).max(0)))
411 .flatten(),
412 mark: marks.get(&key).copied(),
413 answered: progress.get(&key).map_or(0, |p| p.0),
414 last_activity: progress.get(&key).map(|p| p.1),
415 }
416 })
417 .collect();
418 students.sort_by(|a, b| a.user.username.cmp(&b.user.username));
419
420 let count = |status: &str| students.iter().filter(|s| s.status == status).count() as u64;
421 let counts = LiveCountsResponse {
422 enrolled: students.len() as u64,
423 not_started: count("not_started"),
424 absent: count("absent"),
425 in_progress: count("in_progress"),
426 submitted: count("submitted"),
427 expired: count("expired"),
428 graded: students.iter().filter(|s| s.mark.is_some()).count() as u64,
429 };
430 Ok(ExamLiveResponse {
431 exam: ExamResponse::new(exam),
432 now: now.as_millis(),
433 question_count,
434 counts,
435 students,
436 })
437}
438
439/// A one-shot live snapshot of the exam: who's in, who's still writing (and
440/// on which sitting), who walked out of the room (`left_at`), who never
441/// showed at all (`absent`, once the window is over), time each student has
442/// left, and marks as they land — the roster of every instance the exam is
443/// addressed to, so an announced-to section's sitters are here too. Requires
444/// teacher+ and management rights over the exam's instance. Poll it to keep a
445/// monitor up to date.
446#[utoipa::path(
447 get,
448 path = "/{id}/live",
449 tag = "exams",
450 security(("session_cookie" = [])),
451 params(("id" = String, Path, description = "Exam id")),
452 responses(
453 (status = 200, description = "Live snapshot", body = ExamLiveResponse),
454 (status = 401, description = "Not authenticated", body = ErrorResponse),
455 (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),
456 (status = 404, description = "Exam not found", body = ErrorResponse),
457 ),
458)]
459pub(crate) async fn exam_live(
460 State(st): State<AppState>,
461 RequireTeacher(user): RequireTeacher,
462 Path(id): Path<String>,
463) -> Result<Json<ExamLiveResponse>, AppError> {
464 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
465 .await?
466 .ok_or(AppError::NotFound)?;
467 let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
468 if !manages {
469 return Err(AppError::Forbidden(
470 "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can monitor this exam",
471 ));
472 }
473 Ok(Json(live_snapshot(&exam, &st.db).await?))
474}
475
476// ---- answers ----------------------------------------------------------------
477// Students answer inside their attempt; every save is an upsert stamped with
478// the server clock. The WebSocket room (`/exams/{id}/attempt/ws`) drives the
479// same paths below.
480
481/// A student's own saved answer, embedded in their question view.
482#[derive(Serialize, ToSchema)]
483pub(crate) struct AnswerStateResponse {
484 /// The picked option's id (`choice` questions).
485 selected: Option<String>,
486 /// The typed answer (`text` questions).
487 text: Option<String>,
488 /// When this answer was last saved, UTC unix-milliseconds.
489 updated_at: i64,
490 /// The student's own drawn answer, if any — bytes at
491 /// `GET /exams/{id}/attempt/answers/{qid}/image`.
492 answer_image: Option<ImageMetaResponse>,
493}
494
495impl AnswerStateResponse {
496 pub(crate) fn new(answer: &ExamAnswer, answer_image: Option<ImageMetaResponse>) -> Self {
497 Self {
498 selected: answer.get_selected().map(|id| id.as_str().to_string()),
499 text: answer.get_text().map(|t| t.as_str().to_string()),
500 updated_at: answer.get_updated_at().as_millis(),
501 answer_image,
502 }
503 }
504}
505
506/// A question as the sitting student sees it: no `correct` choice id, their own
507/// saved answer embedded.
508#[derive(Serialize, ToSchema)]
509pub(crate) struct AttemptQuestionResponse {
510 id: String,
511 /// The subject this question belongs to (`GET /subjects/{id}`).
512 subject: String,
513 text: String,
514 /// `choice` or `text`.
515 #[schema(example = "choice")]
516 kind: String,
517 points: i64,
518 /// The options with their ids — and deliberately *not* `correct`: this DTO
519 /// leaks no answer key because it has no field to carry one, and
520 /// `ChoiceResponse` carries none either.
521 choices: Option<Vec<ChoiceResponse>>,
522 /// The question's illustration, if any — bytes at
523 /// `GET /exams/{id}/questions/{qid}/image`.
524 image: Option<ImageMetaResponse>,
525 /// Per-option pictures aligned with `choices`, if any — bytes at
526 /// `GET /exams/{id}/questions/{qid}/choices/{choice_id}/image`.
527 choice_images: Option<Vec<Option<ImageMetaResponse>>>,
528 /// The caller's saved answer; `null` while unanswered.
529 answer: Option<AnswerStateResponse>,
530}
531
532#[derive(Deserialize, ToSchema)]
533pub(crate) struct SaveAnswer {
534 /// The question being answered.
535 question_id: String,
536 /// The picked option's `id` — required for `choice` questions.
537 selected: Option<String>,
538 /// The typed answer — required for `text` questions (empty clears the draft).
539 #[schema(max_length = 10000)]
540 text: Option<String>,
541}
542
543#[derive(Serialize, ToSchema)]
544pub(crate) struct AnswerSavedResponse {
545 question: String,
546 /// The picked option's id.
547 selected: Option<String>,
548 text: Option<String>,
549 /// Save instant by the server clock, UTC unix-milliseconds.
550 updated_at: i64,
551}
552
553/// The exam's questions as the sitting student sees them: `correct` stripped,
554/// their own saved answers embedded — the latest sitting's, since a retake
555/// starts from a blank sheet. Requires enrollment in the exam's instance (the
556/// questions are the instance's content — leaving it closes them) and an
557/// attempt — start one with `POST /exams/{id}/attempt` first (404 until
558/// then). Readable in every attempt state, so a submitted student can still
559/// review what they wrote.
560#[utoipa::path(
561 get,
562 path = "/{id}/attempt/questions",
563 tag = "exams",
564 security(("session_cookie" = [])),
565 params(("id" = String, Path, description = "Exam id")),
566 responses(
567 (status = 200, description = "Questions with the caller's answers embedded", body = [AttemptQuestionResponse]),
568 (status = 401, description = "Not authenticated", body = ErrorResponse),
569 (status = 403, description = "Not enrolled in the exam's instance", body = ErrorResponse),
570 (status = 404, description = "No such exam, or no attempt yet — start the attempt first", body = ErrorResponse),
571 ),
572)]
573pub(crate) async fn attempt_questions(
574 State(st): State<AppState>,
575 CurrentUser(user): CurrentUser,
576 Path(id): Path<String>,
577) -> Result<Json<Vec<AttemptQuestionResponse>>, AppError> {
578 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
579 .await?
580 .ok_or(AppError::NotFound)?;
581 exam_attempt::ensure_enrolled(&exam, user.get_id(), &st.db).await?;
582 // The question list is for sitting students; without an attempt there is
583 // nothing to sit behind — and no early peek at the questions. The embedded
584 // answers are the *current* sitting's only, so the seq scopes the reads.
585 let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), user.get_id())
586 .await?
587 .ok_or(AppError::NotFound)?
588 .get_seq();
589
590 let (questions, _) =
591 crate::service::exam_question::list_for_exam(&st.db, exam.get_id(), None, 0).await?;
592 let images = images_by_question(exam.get_id(), &st.db).await?;
593 let answers: HashMap<String, ExamAnswer> =
594 crate::service::exam_answer::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq)
595 .await?
596 .into_iter()
597 .map(|answer| (answer.get_question().key().to_string(), answer))
598 .collect();
599 let answer_images: HashMap<String, AnswerImage> =
600 crate::service::answer_image::list_for_exam_user(&st.db, exam.get_id(), user.get_id(), seq)
601 .await?
602 .into_iter()
603 .map(|image| (image.get_question().key().to_string(), image))
604 .collect();
605 Ok(Json(
606 questions
607 .iter()
608 .map(|question| {
609 let question_images = images
610 .get(question.get_id().key().as_str())
611 .map_or(&[][..], Vec::as_slice);
612 AttemptQuestionResponse {
613 id: question.get_id().key().to_string(),
614 subject: question.get_subject().key().to_string(),
615 text: question.get_text().as_str().to_string(),
616 kind: question.get_kind().as_str().to_string(),
617 points: question.get_points().as_i64(),
618 choices: ChoiceResponse::list(question.get_choices()),
619 image: image_meta(question_images, None),
620 choice_images: choice_image_metas(question, question_images),
621 answer: answers.get(question.get_id().key().as_str()).map(|answer| {
622 AnswerStateResponse::new(
623 answer,
624 answer_images
625 .get(question.get_id().key().as_str())
626 .map(ImageMetaResponse::from_answer),
627 )
628 }),
629 }
630 })
631 .collect(),
632 ))
633}
634
635/// Save (or overwrite) one answer in the caller's in-progress attempt.
636/// `choice` questions take `selected`; `text` questions take `text`. Requires
637/// the student role and enrollment in the exam's instance — an unenrollment (or a
638/// promotion out of `student`) mid-exam closes the sheet. Rejected once the
639/// attempt is submitted or its deadline has passed —
640/// the server clock, not the client's, is the judge — and rejected while the
641/// student has left the exam room with the rejoin door closed.
642#[utoipa::path(
643 post,
644 path = "/{id}/attempt/answers",
645 tag = "exams",
646 security(("session_cookie" = [])),
647 params(("id" = String, Path, description = "Exam id")),
648 request_body = SaveAnswer,
649 responses(
650 (status = 200, description = "Answer saved", body = AnswerSavedResponse),
651 (status = 400, description = "Payload doesn't match the question's kind", body = ErrorResponse),
652 (status = 401, description = "Not authenticated", body = ErrorResponse),
653 (status = 403, description = "Not a student, or not enrolled in the exam's instance", body = ErrorResponse),
654 (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse),
655 (status = 409, description = "Attempt already submitted, time is up, rejoin is closed, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
656 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
657 ),
658)]
659pub(crate) async fn save_answer(
660 State(st): State<AppState>,
661 CurrentUser(user): CurrentUser,
662 Path(id): Path<String>,
663 Json(req): Json<SaveAnswer>,
664) -> Result<Json<AnswerSavedResponse>, AppError> {
665 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
666 .await?
667 .ok_or(AppError::NotFound)?;
668 let answer = exam_attempt::save_answer_checked(
669 &st.db,
670 &exam,
671 &user,
672 &req.question_id,
673 req.selected,
674 req.text,
675 )
676 .await?;
677 Ok(Json(AnswerSavedResponse {
678 question: answer.get_question().key().to_string(),
679 selected: answer.get_selected().map(|id| id.as_str().to_string()),
680 text: answer.get_text().map(|t| t.as_str().to_string()),
681 updated_at: answer.get_updated_at().as_millis(),
682 }))
683}
684
685/// One student's answer sheet with correctness flags — always the *latest*
686/// sitting's answers (a retake starts from a blank sheet). Every row carries
687/// the saved answer plus `is_correct` (`null` for text questions — those are
688/// the grader's call), and the machine's `auto_score` over the choice
689/// questions is attached as a *suggestion*: the final mark stays human, via
690/// `POST /exams/{id}/results`. Requires teacher+ and management rights over
691/// the exam's instance.
692#[utoipa::path(
693 get,
694 path = "/{id}/attempts/{user}/answers",
695 tag = "exams",
696 security(("session_cookie" = [])),
697 params(
698 ("id" = String, Path, description = "Exam id"),
699 ("user" = String, Path, description = "User id"),
700 ),
701 responses(
702 (status = 200, description = "The student's answers, judged", body = AttemptAnswersResponse),
703 (status = 401, description = "Not authenticated", body = ErrorResponse),
704 (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
705 (status = 404, description = "No such exam, or the student has no attempt", body = ErrorResponse),
706 ),
707)]
708pub(crate) async fn attempt_answers(
709 State(st): State<AppState>,
710 RequireTeacher(user): RequireTeacher,
711 Path((id, target)): Path<(String, String)>,
712) -> Result<Json<AttemptAnswersResponse>, AppError> {
713 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
714 .await?
715 .ok_or(AppError::NotFound)?;
716 let instance = exam_attempt::class_course_of(&exam, &st.db).await?;
717 if !can_manage_instance(&st.db, instance.get_id(), &user).await? {
718 return Err(AppError::Forbidden(
719 "only this instance's teachers, its class's homeroom teacher, or a manager/admin can read answer sheets",
720 ));
721 }
722 let target = UserId::from_key(&target);
723 // No attempt means no answer sheet — a 404, not an empty one. This grading
724 // view shows the *latest* sitting; prior sittings live under the
725 // per-attempt history endpoints.
726 let seq = exam_attempt::read_latest_for_user(&st.db, exam.get_id(), &target)
727 .await?
728 .ok_or(AppError::NotFound)?
729 .get_seq();
730 Ok(Json(
731 answer_sheet(&exam, &target, seq, &HashSet::new(), &st.db).await?,
732 ))
733}
734
735/// One sitting's judged answer sheet: the `seq`th attempt's answers, drawing
736/// refs, correctness flags, and auto-score suggestion. Shared by the latest-
737/// sitting grading view and the per-attempt history endpoint.
738///
739/// `hidden` names the questions whose answer key must not leak out of this
740/// sheet (empty for a teacher). Dropping them from the question list is the
741/// whole redaction: their `is_correct` falls to `null` for want of a question,
742/// and they leave `auto_score` entirely — a per-question score still standing
743/// in the total is the same bit, arrived at by subtraction.
744pub(crate) async fn answer_sheet(
745 exam: &Exam,
746 target: &UserId,
747 seq: i64,
748 hidden: &HashSet<String>,
749 db: &Database,
750) -> Result<AttemptAnswersResponse, AppError> {
751 let (mut questions, _) =
752 crate::service::exam_question::list_for_exam(db, exam.get_id(), None, 0).await?;
753 questions.retain(|question| !hidden.contains(question.get_id().key().as_str()));
754 let answers =
755 crate::service::exam_answer::list_for_exam_user(db, exam.get_id(), target, seq).await?;
756 let answer_images: HashMap<String, AnswerImage> =
757 crate::service::answer_image::list_for_exam_user(db, exam.get_id(), target, seq)
758 .await?
759 .into_iter()
760 .map(|image| (image.get_question().key().to_string(), image))
761 .collect();
762 let by_question: HashMap<String, &ExamQuestion> = questions
763 .iter()
764 .map(|question| (question.get_id().key(), question))
765 .collect();
766 let (earned, possible) = auto_score(&questions, &answers);
767 let people = person_map([*target], db).await?;
768 Ok(AttemptAnswersResponse {
769 exam: exam.get_id().key().to_string(),
770 user: PersonRef::resolve(&people, target),
771 answers: answers
772 .iter()
773 .map(|answer| StudentAnswerResponse {
774 question: answer.get_question().key().to_string(),
775 selected: answer.get_selected().map(|id| id.as_str().to_string()),
776 text: answer.get_text().map(|t| t.as_str().to_string()),
777 updated_at: answer.get_updated_at().as_millis(),
778 is_correct: by_question
779 .get(answer.get_question().key().as_str())
780 .and_then(|question| answer.is_correct(question)),
781 answer_image: answer_images
782 .get(answer.get_question().key().as_str())
783 .map(ImageMetaResponse::from_answer),
784 })
785 .collect(),
786 auto_score: AutoScoreResponse { earned, possible },
787 })
788}
789
790/// One row of a student's answer sheet, as the grader sees it.
791#[derive(Serialize, ToSchema)]
792pub(crate) struct StudentAnswerResponse {
793 question: String,
794 /// The picked option's id.
795 selected: Option<String>,
796 text: Option<String>,
797 /// When the answer was last saved, UTC unix-milliseconds.
798 updated_at: i64,
799 /// Whether `selected` hits the question's `correct`; `null` for text
800 /// questions (the grader judges those).
801 is_correct: Option<bool>,
802 /// The student's drawn answer, if any — bytes at
803 /// `GET /exams/{id}/attempts/{user}/answers/{qid}/image`.
804 answer_image: Option<ImageMetaResponse>,
805}
806
807/// The machine's scoring suggestion over the choice questions.
808#[derive(Serialize, ToSchema)]
809pub(crate) struct AutoScoreResponse {
810 /// Points earned where `selected == correct`.
811 earned: i64,
812 /// Total points across the exam's choice questions.
813 possible: i64,
814}
815
816/// A student's full answer sheet for grading.
817#[derive(Serialize, ToSchema)]
818pub(crate) struct AttemptAnswersResponse {
819 exam: String,
820 /// The student whose sheet this is.
821 user: PersonRef,
822 answers: Vec<StudentAnswerResponse>,
823 /// The suggested score over choice questions — never the final mark.
824 auto_score: AutoScoreResponse,
825}