| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use crate::web::tenant_state::State; |
| 4 | use axum::Json; |
| 5 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 6 | use axum::http::StatusCode; |
| 7 | use axum::response::Response; |
| 8 | use serde::{Deserialize, Serialize}; |
| 9 | use utoipa::ToSchema; |
| 10 | use utoipa_axum::router::OpenApiRouter; |
| 11 | use utoipa_axum::routes; |
| 12 | |
| 13 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 14 | use crate::database::Database; |
| 15 | use crate::domain::answer_image::AnswerImage; |
| 16 | |
| 17 | use crate::domain::exam::{ |
| 18 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle, |
| 19 | }; |
| 20 | use crate::domain::exam_answer::{ExamAnswer, auto_score}; |
| 21 | use crate::domain::exam_question::{ |
| 22 | Choice, ChoiceId, ExamQuestion, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 23 | }; |
| 24 | use crate::domain::exam_result::{ExamResult, Mark}; |
| 25 | use crate::domain::note_file::FileContentType; |
| 26 | use crate::domain::question_image::QuestionImage; |
| 27 | use crate::domain::role::Role; |
| 28 | use crate::domain::timestamp::Timestamp; |
| 29 | use crate::domain::user::{User, UserId}; |
| 30 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 31 | use crate::service; |
| 32 | use crate::service::instance::{can_manage_instance, visible_instances}; |
| 33 | use crate::state::AppState; |
| 34 | |
| 35 | use super::bank_questions::BankQuestionResponse; |
| 36 | use super::instances::can_view_instance; |
| 37 | use 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 | |
| 43 | pub(crate) mod attempts; |
| 44 | pub(crate) mod audience; |
| 45 | pub(crate) mod images; |
| 46 | pub(crate) mod questions; |
| 47 | pub(crate) mod review; |
| 48 | |
| 49 | pub(crate) use attempts::*; |
| 50 | pub(crate) use audience::*; |
| 51 | pub(crate) use images::*; |
| 52 | pub(crate) use questions::*; |
| 53 | pub(crate) use review::*; |
| 54 | |
| 55 | pub fn routes() -> OpenApiRouter<AppState> { |
| 56 | OpenApiRouter::new() |
| 57 | |
| 58 | |
| 59 | |
| 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 | |
| 89 | |
| 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)] |
| 117 | struct UpdateExam { |
| 118 | #[schema(max_length = 200)] |
| 119 | title: Option<String>, |
| 120 | #[schema(max_length = 2000)] |
| 121 | description: Option<String>, |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | kind: Option<String>, |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | #[serde(default, deserialize_with = "set_or_clear")] |
| 133 | #[schema(value_type = Option<String>)] |
| 134 | mode: Option<Option<String>>, |
| 135 | |
| 136 | |
| 137 | #[serde(default, deserialize_with = "set_or_clear")] |
| 138 | #[schema(value_type = Option<i64>)] |
| 139 | starts_at: Option<Option<i64>>, |
| 140 | |
| 141 | |
| 142 | |
| 143 | #[serde(default, deserialize_with = "set_or_clear")] |
| 144 | #[schema(value_type = Option<i64>)] |
| 145 | ends_at: Option<Option<i64>>, |
| 146 | |
| 147 | |
| 148 | |
| 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 | |
| 153 | |
| 154 | |
| 155 | #[schema(minimum = 0, maximum = 100)] |
| 156 | max_attempts: Option<i64>, |
| 157 | |
| 158 | |
| 159 | allow_rejoin: Option<bool>, |
| 160 | |
| 161 | |
| 162 | allow_review: Option<bool>, |
| 163 | |
| 164 | |
| 165 | |
| 166 | draft: Option<bool>, |
| 167 | } |
| 168 | |
| 169 | #[derive(Deserialize, ToSchema)] |
| 170 | struct GradeResult { |
| 171 | |
| 172 | #[schema(example = 85, minimum = 0, maximum = 100)] |
| 173 | mark: i64, |
| 174 | |
| 175 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| 176 | user_id: String, |
| 177 | } |
| 178 | |
| 179 | #[derive(Serialize, ToSchema)] |
| 180 | pub(crate) struct ExamResultResponse { |
| 181 | id: String, |
| 182 | exam: String, |
| 183 | |
| 184 | user: PersonRef, |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | seq: i64, |
| 190 | mark: i64, |
| 191 | |
| 192 | graded_by: PersonRef, |
| 193 | } |
| 194 | |
| 195 | impl 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)] |
| 209 | struct ExamStatisticsResponse { |
| 210 | exam: String, |
| 211 | |
| 212 | graded: u64, |
| 213 | |
| 214 | average: Option<f64>, |
| 215 | min: Option<i64>, |
| 216 | max: Option<i64>, |
| 217 | } |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 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 | )] |
| 250 | async 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 | |
| 267 | |
| 268 | |
| 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 | |
| 275 | |
| 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 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 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 | )] |
| 314 | async 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 | |
| 329 | |
| 330 | |
| 331 | if exam.is_draft() && !may_manage { |
| 332 | return Err(AppError::NotFound); |
| 333 | } |
| 334 | Ok(Json(ExamResponse::new(&exam))) |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 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 | )] |
| 365 | async 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 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 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 | |
| 397 | |
| 398 | |
| 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 | |
| 451 | |
| 452 | |
| 453 | |
| 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 | )] |
| 468 | async 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 | |
| 483 | |
| 484 | |
| 485 | |
| 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 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 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 | )] |
| 522 | async 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 | |
| 530 | |
| 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 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | |
| 546 | |
| 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 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 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 | )] |
| 575 | async 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 | |
| 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 | |
| 595 | |
| 596 | |
| 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 | |
| 612 | |
| 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 | )] |
| 625 | async 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 | |
| 638 | |
| 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 | )] |
| 656 | async 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 | |
| 671 | |
| 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 | |
| 680 | |
| 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 | )] |
| 694 | async fn exam_statistics( |
| 695 | State(st): State<AppState>, |
| 696 | RequireTeacher(user): RequireTeacher, |
| 697 | Path(id): Path<String>, |
| 698 | ) -> Result<Json<ExamStatisticsResponse>, AppError> { |
| 699 | |
| 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 | } |