From eb282a08846f91620b0c8d7569574ece93fc4a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 02:21:37 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(exams):=20summary=20statistics?= =?UTF-8?q?=20for=20graded=20results?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /exams/{id}/statistics (teacher+) reports the graded count and the mean, min, and max of an exam's marks. Statistics are null while nothing is graded; a missing exam is a 404, not an empty report. --- src/web/exams.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/web/exams.rs b/src/web/exams.rs index 149195a..fb67c48 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -25,6 +25,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(grade, list_results)) .routes(routes!(my_result)) .routes(routes!(remove_result)) + .routes(routes!(exam_statistics)) } #[derive(Deserialize, ToSchema)] @@ -66,6 +67,17 @@ impl ExamResultResponse { } } +#[derive(Serialize, ToSchema)] +struct ExamStatisticsResponse { + exam: String, + /// Number of graded results. + graded: u64, + /// Plain mean of the graded marks; `null` while nothing is graded. + average: Option, + min: Option, + max: Option, +} + /// The course an exam belongs to. A dangling reference means the course-delete /// cascade was violated — surface it loudly as a 500, not a user-facing 404. async fn course_of(exam: &Exam, db: &Database) -> Result { @@ -372,3 +384,41 @@ async fn remove_result( } Ok(StatusCode::NO_CONTENT) } + +/// Summary statistics for an exam's graded results. Requires teacher+. +#[utoipa::path( + get, + path = "/{id}/statistics", + tag = "exams", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Exam id")), + responses( + (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "Exam not found", body = ErrorResponse), + ), +)] +async fn exam_statistics( + State(st): State, + _teacher: RequireTeacher, + Path(id): Path, +) -> Result, AppError> { + let exam_id = ExamId::from_key(&id); + // Exam must exist — a missing exam is a 404, not an empty statistic. + Exam::read(&exam_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let results = ExamResult::list_for_exam(&exam_id, &st.db).await?; + + let marks: Vec = results.iter().map(|r| r.get_mark().as_i64()).collect(); + let average = + (!marks.is_empty()).then(|| marks.iter().sum::() as f64 / marks.len() as f64); + Ok(Json(ExamStatisticsResponse { + exam: exam_id.key().to_string(), + graded: marks.len() as u64, + average, + min: marks.iter().min().copied(), + max: marks.iter().max().copied(), + })) +}