| 1 | use std::collections::HashMap; |
| 2 | |
| 3 | use crate::web::tenant_state::State; |
| 4 | use axum::Json; |
| 5 | use axum::extract::Path; |
| 6 | use serde::Serialize; |
| 7 | use utoipa::ToSchema; |
| 8 | use utoipa_axum::router::OpenApiRouter; |
| 9 | use utoipa_axum::routes; |
| 10 | |
| 11 | use crate::database::Database; |
| 12 | |
| 13 | use crate::domain::exam::Exam; |
| 14 | use crate::domain::role::Role; |
| 15 | use crate::domain::user::{User, UserId}; |
| 16 | use crate::error::{AppError, ErrorResponse}; |
| 17 | use crate::service; |
| 18 | use crate::service::parent_link::ensure_can_observe; |
| 19 | use crate::state::AppState; |
| 20 | |
| 21 | use super::courses::can_manage_course; |
| 22 | use super::{CourseResponse, CurrentUser, course_people, person_map}; |
| 23 | |
| 24 | pub fn routes() -> OpenApiRouter<AppState> { |
| 25 | OpenApiRouter::new() |
| 26 | .routes(routes!(my_marks)) |
| 27 | .routes(routes!(user_marks)) |
| 28 | } |
| 29 | |
| 30 | |
| 31 | #[derive(Serialize, ToSchema)] |
| 32 | struct MarkEntry { |
| 33 | |
| 34 | exam: String, |
| 35 | title: String, |
| 36 | kind: String, |
| 37 | |
| 38 | |
| 39 | |
| 40 | weight: i64, |
| 41 | mark: i64, |
| 42 | |
| 43 | |
| 44 | #[schema(example = "AA")] |
| 45 | grade: Option<String>, |
| 46 | graded_by: String, |
| 47 | } |
| 48 | |
| 49 | |
| 50 | #[derive(Serialize, ToSchema)] |
| 51 | struct CourseMarks { |
| 52 | course: CourseResponse, |
| 53 | |
| 54 | results: Vec<MarkEntry>, |
| 55 | |
| 56 | |
| 57 | average: Option<f64>, |
| 58 | |
| 59 | |
| 60 | average_grade: Option<String>, |
| 61 | } |
| 62 | |
| 63 | |
| 64 | #[derive(Serialize, ToSchema)] |
| 65 | struct MarksReport { |
| 66 | |
| 67 | user: String, |
| 68 | courses: Vec<CourseMarks>, |
| 69 | |
| 70 | |
| 71 | overall_average: Option<f64>, |
| 72 | |
| 73 | |
| 74 | overall_grade: Option<String>, |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> { |
| 81 | let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum(); |
| 82 | if total_weight == 0 { |
| 83 | return None; |
| 84 | } |
| 85 | let total: i64 = pairs.iter().map(|(mark, weight)| mark * weight).sum(); |
| 86 | Some(total as f64 / total_weight as f64) |
| 87 | } |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | async fn build_report( |
| 95 | user: &UserId, |
| 96 | viewer: Option<&User>, |
| 97 | db: &Database, |
| 98 | ) -> Result<MarksReport, AppError> { |
| 99 | let (mut courses, _) = crate::service::course::list_enrolled(db, user, None, 0).await?; |
| 100 | if let Some(viewer) = viewer { |
| 101 | courses.retain(|course| can_manage_course(course, viewer)); |
| 102 | } |
| 103 | |
| 104 | |
| 105 | let school = service::settings::load(db).await?; |
| 106 | let people = person_map(courses.iter().flat_map(course_people), db).await?; |
| 107 | |
| 108 | let mut blocks = Vec::with_capacity(courses.len()); |
| 109 | for course in &courses { |
| 110 | let exams = crate::service::exam::list_for_course(db, course.get_id()).await?; |
| 111 | let by_key: HashMap<String, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect(); |
| 112 | |
| 113 | let results = |
| 114 | crate::service::exam_result::list_for_user_in_course(db, course.get_id(), user).await?; |
| 115 | let mut entries = Vec::with_capacity(results.len()); |
| 116 | let mut pairs = Vec::with_capacity(results.len()); |
| 117 | for result in &results { |
| 118 | |
| 119 | |
| 120 | let Some(exam) = by_key.get(result.get_exam().key().as_str()) else { |
| 121 | continue; |
| 122 | }; |
| 123 | |
| 124 | |
| 125 | let weight = school |
| 126 | .exam_kind_weight(exam.get_kind().as_str()) |
| 127 | .unwrap_or(1); |
| 128 | entries.push(MarkEntry { |
| 129 | exam: exam.get_id().key().to_string(), |
| 130 | title: exam.get_title().as_str().to_string(), |
| 131 | kind: exam.get_kind().as_str().to_string(), |
| 132 | weight, |
| 133 | mark: result.get_mark().as_i64(), |
| 134 | grade: school |
| 135 | .grade_label(result.get_mark().as_i64() as f64) |
| 136 | .map(str::to_string), |
| 137 | graded_by: result.get_graded_by().key().to_string(), |
| 138 | }); |
| 139 | pairs.push((result.get_mark().as_i64(), weight)); |
| 140 | } |
| 141 | |
| 142 | let average = weighted_average(&pairs); |
| 143 | blocks.push(CourseMarks { |
| 144 | course: CourseResponse::new(course, &people), |
| 145 | average, |
| 146 | average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)), |
| 147 | results: entries, |
| 148 | }); |
| 149 | } |
| 150 | |
| 151 | let averages: Vec<f64> = blocks.iter().filter_map(|block| block.average).collect(); |
| 152 | let overall_average = |
| 153 | (!averages.is_empty()).then(|| averages.iter().sum::<f64>() / averages.len() as f64); |
| 154 | |
| 155 | Ok(MarksReport { |
| 156 | user: user.key().to_string(), |
| 157 | courses: blocks, |
| 158 | overall_average, |
| 159 | overall_grade: overall_average.and_then(|a| school.grade_label(a).map(str::to_string)), |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | |
| 164 | |
| 165 | #[utoipa::path( |
| 166 | get, |
| 167 | path = "/me", |
| 168 | tag = "marks", |
| 169 | security(("session_cookie" = [])), |
| 170 | responses( |
| 171 | (status = 200, description = "The caller's mark report", body = MarksReport), |
| 172 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 173 | ), |
| 174 | )] |
| 175 | async fn my_marks( |
| 176 | State(st): State<AppState>, |
| 177 | CurrentUser(user): CurrentUser, |
| 178 | ) -> Result<Json<MarksReport>, AppError> { |
| 179 | Ok(Json(build_report(user.get_id(), None, &st.db).await?)) |
| 180 | } |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | #[utoipa::path( |
| 187 | get, |
| 188 | path = "/{user}", |
| 189 | tag = "marks", |
| 190 | security(("session_cookie" = [])), |
| 191 | params(("user" = String, Path, description = "User id")), |
| 192 | responses( |
| 193 | (status = 200, description = "The user's mark report, narrowed to the caller's courses", body = MarksReport), |
| 194 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 195 | (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse), |
| 196 | (status = 404, description = "User not found", body = ErrorResponse), |
| 197 | ), |
| 198 | )] |
| 199 | async fn user_marks( |
| 200 | State(st): State<AppState>, |
| 201 | CurrentUser(caller): CurrentUser, |
| 202 | Path(user): Path<String>, |
| 203 | ) -> Result<Json<MarksReport>, AppError> { |
| 204 | let target = UserId::from_key(&user); |
| 205 | ensure_can_observe(&caller, &target, &st.db).await?; |
| 206 | |
| 207 | crate::service::user::read(&st.db, &target) |
| 208 | .await? |
| 209 | .ok_or(AppError::NotFound)?; |
| 210 | |
| 211 | |
| 212 | let viewer = (caller.get_role() == Role::Teacher).then_some(&caller); |
| 213 | Ok(Json(build_report(&target, viewer, &st.db).await?)) |
| 214 | } |
| 215 | |
| 216 | #[cfg(test)] |
| 217 | mod tests { |
| 218 | use super::*; |
| 219 | |
| 220 | #[tokio::test] |
| 221 | async fn weighted_average_handles_empty_and_weights() { |
| 222 | assert_eq!(weighted_average(&[]), None); |
| 223 | assert_eq!(weighted_average(&[(70, 1)]), Some(70.0)); |
| 224 | |
| 225 | assert_eq!(weighted_average(&[(50, 1), (90, 3)]), Some(80.0)); |
| 226 | } |
| 227 | } |