diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index 03d09fc..f47b4a3 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -1,6 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::database::{Database, EXAM_RESULT_TABLE}; +use crate::domain::course::CourseId; use crate::domain::exam::ExamId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -124,6 +125,26 @@ impl ExamResult { saved.ok_or_else(|| AppError::Internal("failed to record exam result".into())) } + /// The user's graded results restricted to one course's exams — the raw + /// rows behind the per-course block of the marks report. + pub async fn list_for_user_in_course( + course: &CourseId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM exam_result WHERE user = $usr + AND exam IN (SELECT VALUE id FROM exam WHERE course = $course) + ORDER BY id DESC", + ) + .bind(("usr", user.record())) + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + pub async fn list_for_exam(exam: &ExamId, db: &Database) -> Result, AppError> { let mut result = db .query("SELECT * FROM exam_result WHERE exam = $ex ORDER BY id DESC") diff --git a/src/lib.rs b/src/lib.rs index a9c85de..b37522d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, and exams behind cookie-session auth.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth.", ), modifiers(&SecurityAddon), tags( @@ -43,6 +43,7 @@ use crate::state::AppState; (name = "events", description = "Events and attendance"), (name = "courses", description = "Courses, enrollment, and course exams"), (name = "exams", description = "Exams (per course, weighted) and student results"), + (name = "marks", description = "Weighted mark reports per course and overall"), ), )] struct ApiDoc; @@ -76,6 +77,7 @@ pub fn build_router(state: AppState) -> Router { .nest("/events", web::events::routes()) .nest("/courses", web::courses::routes()) .nest("/exams", web::exams::routes()) + .nest("/marks", web::marks::routes()) .split_for_parts(); // Catch-all per-IP limit over every route (Swagger included). Kept inside diff --git a/src/web/marks.rs b/src/web/marks.rs new file mode 100644 index 0000000..6a6dcc4 --- /dev/null +++ b/src/web/marks.rs @@ -0,0 +1,176 @@ +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{Path, State}; +use serde::Serialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::course::Course; +use crate::domain::exam::Exam; +use crate::domain::exam_result::ExamResult; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::{CourseResponse, CurrentUser, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(my_marks)) + .routes(routes!(user_marks)) +} + +/// One graded exam inside a course block of the report. +#[derive(Serialize, ToSchema)] +struct MarkEntry { + /// Exam id. + exam: String, + title: String, + kind: String, + weight: i64, + mark: i64, + graded_by: String, +} + +/// A student's marks in one enrolled course. +#[derive(Serialize, ToSchema)] +struct CourseMarks { + course: CourseResponse, + /// Graded results only — ungraded exams don't appear. + results: Vec, + /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while + /// nothing is graded. + average: Option, +} + +/// A student's full mark report across their enrolled courses. +#[derive(Serialize, ToSchema)] +struct MarksReport { + /// The student's user id. + user: String, + courses: Vec, + /// Plain mean of the non-null course averages; `null` while no course has + /// a graded exam. + overall_average: Option, +} + +/// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The +/// zero-denominator guard is structural — `ExamWeight` already forbids 0. +fn weighted_average(pairs: &[(i64, i64)]) -> Option { + let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum(); + if total_weight == 0 { + return None; + } + let total: i64 = pairs.iter().map(|(mark, weight)| mark * weight).sum(); + Some(total as f64 / total_weight as f64) +} + +/// Assemble the report: for each enrolled course, join the course's exams +/// (weights) with the user's graded results, then average. +async fn build_report(user: &UserId, db: &Database) -> Result { + let courses = Course::list_enrolled(user, db).await?; + + let mut blocks = Vec::with_capacity(courses.len()); + for course in &courses { + let exams = Exam::list_for_course(course.get_id(), db).await?; + let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); + + let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).await?; + let mut entries = Vec::with_capacity(results.len()); + let mut pairs = Vec::with_capacity(results.len()); + for result in &results { + // A result whose exam is gone cannot happen given the delete + // cascade — skip defensively rather than corrupt the average. + let Some(exam) = by_key.get(result.get_exam().key()) else { + continue; + }; + entries.push(MarkEntry { + exam: exam.get_id().key().to_string(), + title: exam.get_title().as_str().to_string(), + kind: exam.get_kind().as_str().to_string(), + weight: exam.get_weight().as_i64(), + mark: result.get_mark().as_i64(), + graded_by: result.get_graded_by().key().to_string(), + }); + pairs.push((result.get_mark().as_i64(), exam.get_weight().as_i64())); + } + + blocks.push(CourseMarks { + course: CourseResponse::new(course), + average: weighted_average(&pairs), + results: entries, + }); + } + + let averages: Vec = blocks.iter().filter_map(|block| block.average).collect(); + let overall_average = + (!averages.is_empty()).then(|| averages.iter().sum::() / averages.len() as f64); + + Ok(MarksReport { + user: user.key().to_string(), + courses: blocks, + overall_average, + }) +} + +/// The current user's mark report: every enrolled course with its graded +/// exams, weighted course averages, and the overall average. +#[utoipa::path( + get, + path = "/me", + tag = "marks", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's mark report", body = MarksReport), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_marks( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + Ok(Json(build_report(user.get_id(), &st.db).await?)) +} + +/// Any user's mark report. Requires teacher+. +#[utoipa::path( + get, + path = "/{user}", + tag = "marks", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id")), + responses( + (status = 200, description = "The user's mark report", body = MarksReport), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn user_marks( + State(st): State, + _teacher: RequireTeacher, + Path(user): Path, +) -> Result, AppError> { + let target = UserId::from_key(&user); + // User must exist — a missing user is a 404, not an empty report. + User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(build_report(&target, &st.db).await?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn weighted_average_handles_empty_and_weights() { + assert_eq!(weighted_average(&[]), None); + assert_eq!(weighted_average(&[(70, 1)]), Some(70.0)); + // (50×1 + 90×3) / 4 = 80 + assert_eq!(weighted_average(&[(50, 1), (90, 3)]), Some(80.0)); + } +} diff --git a/src/web/mod.rs b/src/web/mod.rs index d174b23..1c22d3d 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -7,6 +7,7 @@ pub mod auth; pub mod courses; pub mod events; pub mod exams; +pub mod marks; pub mod notes; pub mod users;