| 1 | use super::*; |
| 2 | |
| 3 | use crate::domain::exam_attempt::{AttemptStatus, ExamAttempt}; |
| 4 | use crate::service::exam_attempt; |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | #[derive(Serialize, ToSchema)] |
| 17 | pub(crate) struct AttemptResponse { |
| 18 | id: String, |
| 19 | exam: String, |
| 20 | user: PersonRef, |
| 21 | |
| 22 | attempt: i64, |
| 23 | |
| 24 | attempts_used: u64, |
| 25 | |
| 26 | max_attempts: i64, |
| 27 | |
| 28 | started_at: i64, |
| 29 | |
| 30 | finished_at: Option<i64>, |
| 31 | |
| 32 | |
| 33 | |
| 34 | left_at: Option<i64>, |
| 35 | |
| 36 | #[schema(example = "in_progress")] |
| 37 | status: String, |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | deadline: Option<i64>, |
| 43 | |
| 44 | |
| 45 | remaining_ms: Option<i64>, |
| 46 | |
| 47 | mark: Option<i64>, |
| 48 | |
| 49 | answered: u64, |
| 50 | |
| 51 | question_count: u64, |
| 52 | |
| 53 | now: i64, |
| 54 | } |
| 55 | |
| 56 | impl 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 | |
| 98 | |
| 99 | pub(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 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 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 | )] |
| 138 | pub(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 | |
| 173 | |
| 174 | |
| 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 | )] |
| 187 | pub(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 | |
| 218 | |
| 219 | |
| 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 | )] |
| 233 | pub(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 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | #[derive(Serialize, ToSchema)] |
| 266 | pub(crate) struct LiveStudentResponse { |
| 267 | user: PersonRef, |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | #[schema(example = "in_progress")] |
| 273 | status: String, |
| 274 | |
| 275 | attempt: Option<i64>, |
| 276 | |
| 277 | attempts_used: u64, |
| 278 | started_at: Option<i64>, |
| 279 | finished_at: Option<i64>, |
| 280 | |
| 281 | left_at: Option<i64>, |
| 282 | |
| 283 | deadline: Option<i64>, |
| 284 | |
| 285 | remaining_ms: Option<i64>, |
| 286 | |
| 287 | mark: Option<i64>, |
| 288 | |
| 289 | answered: u64, |
| 290 | |
| 291 | |
| 292 | last_activity: Option<i64>, |
| 293 | } |
| 294 | |
| 295 | #[derive(Serialize, ToSchema)] |
| 296 | pub(crate) struct LiveCountsResponse { |
| 297 | enrolled: u64, |
| 298 | |
| 299 | |
| 300 | not_started: u64, |
| 301 | |
| 302 | absent: u64, |
| 303 | in_progress: u64, |
| 304 | submitted: u64, |
| 305 | expired: u64, |
| 306 | graded: u64, |
| 307 | } |
| 308 | |
| 309 | |
| 310 | |
| 311 | #[derive(Serialize, ToSchema)] |
| 312 | pub(crate) struct ExamLiveResponse { |
| 313 | exam: ExamResponse, |
| 314 | |
| 315 | now: i64, |
| 316 | |
| 317 | question_count: u64, |
| 318 | counts: LiveCountsResponse, |
| 319 | students: Vec<LiveStudentResponse>, |
| 320 | } |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | pub(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 | |
| 334 | |
| 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 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 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 | |
| 383 | |
| 384 | |
| 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 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | |
| 445 | |
| 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 | )] |
| 459 | pub(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 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | #[derive(Serialize, ToSchema)] |
| 483 | pub(crate) struct AnswerStateResponse { |
| 484 | |
| 485 | selected: Option<String>, |
| 486 | |
| 487 | text: Option<String>, |
| 488 | |
| 489 | updated_at: i64, |
| 490 | |
| 491 | |
| 492 | answer_image: Option<ImageMetaResponse>, |
| 493 | } |
| 494 | |
| 495 | impl 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 | |
| 507 | |
| 508 | #[derive(Serialize, ToSchema)] |
| 509 | pub(crate) struct AttemptQuestionResponse { |
| 510 | id: String, |
| 511 | |
| 512 | subject: String, |
| 513 | text: String, |
| 514 | |
| 515 | #[schema(example = "choice")] |
| 516 | kind: String, |
| 517 | points: i64, |
| 518 | |
| 519 | |
| 520 | |
| 521 | choices: Option<Vec<ChoiceResponse>>, |
| 522 | |
| 523 | |
| 524 | image: Option<ImageMetaResponse>, |
| 525 | |
| 526 | |
| 527 | choice_images: Option<Vec<Option<ImageMetaResponse>>>, |
| 528 | |
| 529 | answer: Option<AnswerStateResponse>, |
| 530 | } |
| 531 | |
| 532 | #[derive(Deserialize, ToSchema)] |
| 533 | pub(crate) struct SaveAnswer { |
| 534 | |
| 535 | question_id: String, |
| 536 | |
| 537 | selected: Option<String>, |
| 538 | |
| 539 | #[schema(max_length = 10000)] |
| 540 | text: Option<String>, |
| 541 | } |
| 542 | |
| 543 | #[derive(Serialize, ToSchema)] |
| 544 | pub(crate) struct AnswerSavedResponse { |
| 545 | question: String, |
| 546 | |
| 547 | selected: Option<String>, |
| 548 | text: Option<String>, |
| 549 | |
| 550 | updated_at: i64, |
| 551 | } |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 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 | )] |
| 573 | pub(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 | |
| 583 | |
| 584 | |
| 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 | |
| 636 | |
| 637 | |
| 638 | |
| 639 | |
| 640 | |
| 641 | |
| 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 | )] |
| 659 | pub(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 | |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | |
| 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 | )] |
| 708 | pub(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 | |
| 724 | |
| 725 | |
| 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 | |
| 736 | |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | pub(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 | |
| 791 | #[derive(Serialize, ToSchema)] |
| 792 | pub(crate) struct StudentAnswerResponse { |
| 793 | question: String, |
| 794 | |
| 795 | selected: Option<String>, |
| 796 | text: Option<String>, |
| 797 | |
| 798 | updated_at: i64, |
| 799 | |
| 800 | |
| 801 | is_correct: Option<bool>, |
| 802 | |
| 803 | |
| 804 | answer_image: Option<ImageMetaResponse>, |
| 805 | } |
| 806 | |
| 807 | |
| 808 | #[derive(Serialize, ToSchema)] |
| 809 | pub(crate) struct AutoScoreResponse { |
| 810 | |
| 811 | earned: i64, |
| 812 | |
| 813 | possible: i64, |
| 814 | } |
| 815 | |
| 816 | |
| 817 | #[derive(Serialize, ToSchema)] |
| 818 | pub(crate) struct AttemptAnswersResponse { |
| 819 | exam: String, |
| 820 | |
| 821 | user: PersonRef, |
| 822 | answers: Vec<StudentAnswerResponse>, |
| 823 | |
| 824 | auto_score: AutoScoreResponse, |
| 825 | } |