forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

marks.rs227 lines, 8.5 KiBHistoryRawDownload
1use std::collections::HashMap;
2
3use crate::web::tenant_state::State;
4use axum::Json;
5use axum::extract::Path;
6use serde::Serialize;
7use utoipa::ToSchema;
8use utoipa_axum::router::OpenApiRouter;
9use utoipa_axum::routes;
10
11use crate::database::Database;
12
13use crate::domain::exam::Exam;
14use crate::domain::exam_result::ExamResult;
15use crate::domain::role::Role;
16use crate::domain::user::{User, UserId};
17use crate::error::{AppError, ErrorResponse};
18use crate::service;
19use crate::service::parent_link::ensure_can_observe;
20use crate::state::AppState;
21
22use super::courses::can_manage_course;
23use super::{CourseResponse, CurrentUser, course_people, person_map};
24
25pub fn routes() -> OpenApiRouter<AppState> {
26 OpenApiRouter::new()
27 .routes(routes!(my_marks))
28 .routes(routes!(user_marks))
29}
30
31/// One graded exam inside a course block of the report.
32#[derive(Serialize, ToSchema)]
33struct MarkEntry {
34 /// Exam id.
35 exam: String,
36 title: String,
37 kind: String,
38 /// The kind's weight from the school settings, resolved at request time —
39 /// how many times this mark counts into the course average. `1` when the
40 /// school no longer lists the kind.
41 weight: i64,
42 mark: i64,
43 /// The mark's label from the school's grade bands (`GET /settings`);
44 /// `null` when no bands are configured.
45 #[schema(example = "AA")]
46 grade: Option<String>,
47 graded_by: String,
48}
49
50/// A student's marks in one enrolled course.
51#[derive(Serialize, ToSchema)]
52struct CourseMarks {
53 course: CourseResponse,
54 /// Graded results only — ungraded exams don't appear.
55 results: Vec<MarkEntry>,
56 /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while
57 /// nothing is graded.
58 average: Option<f64>,
59 /// The average's label from the school's grade bands; `null` when there
60 /// is no average or no bands are configured.
61 average_grade: Option<String>,
62}
63
64/// A student's full mark report across their enrolled courses.
65#[derive(Serialize, ToSchema)]
66struct MarksReport {
67 /// The student's user id.
68 user: String,
69 courses: Vec<CourseMarks>,
70 /// Plain mean of the non-null course averages; `null` while no course has
71 /// a graded exam.
72 overall_average: Option<f64>,
73 /// The overall average's label from the school's grade bands; `null` when
74 /// there is no average or no bands are configured.
75 overall_grade: Option<String>,
76}
77
78/// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The
79/// zero-denominator guard is structural — kind weights are 1–100 and retired
80/// kinds resolve to 1, so a weight is never 0.
81fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {
82 let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum();
83 if total_weight == 0 {
84 return None;
85 }
86 let total: i64 = pairs.iter().map(|(mark, weight)| mark * weight).sum();
87 Some(total as f64 / total_weight as f64)
88}
89
90/// Assemble the report: for each enrolled course, join the course's exams
91/// with the user's graded results, weigh each mark by its exam kind's
92/// settings weight, then average. A `viewer` narrows the report to the
93/// courses that viewer manages (self-reports and manager+ reports pass `None`
94/// and see everything); the overall average follows the narrowed set.
95async fn build_report(
96 user: &UserId,
97 viewer: Option<&User>,
98 db: &Database,
99) -> Result<MarksReport, AppError> {
100 let (mut courses, _) = crate::service::course::list_enrolled(db, user, None, 0).await?;
101 if let Some(viewer) = viewer {
102 courses.retain(|course| can_manage_course(course, viewer));
103 }
104
105 // One settings read weighs and labels the whole report.
106 let school = service::settings::load(db).await?;
107 let people = person_map(courses.iter().flat_map(course_people), db).await?;
108
109 let mut blocks = Vec::with_capacity(courses.len());
110 for course in &courses {
111 let exams = crate::service::exam::list_for_course(db, course.get_id()).await?;
112 let by_key: HashMap<&str, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();
113
114 let results = ExamResult::list_for_user_in_course(course.get_id(), user, db).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 // A result whose exam is gone cannot happen given the delete
119 // cascade — skip defensively rather than corrupt the average.
120 let Some(exam) = by_key.get(result.get_exam().key()) else {
121 continue;
122 };
123 // The kind's current settings weight; an exam keeps a retired
124 // kind, and its marks then count once.
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/// The current user's mark report: every enrolled course with its graded
164/// exams, weighted course averages, and the overall average.
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)]
175async 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/// Any user's mark report. Requires teacher+, or a parent tied to the target
183/// student. Managers, admins, and parents see every course; a teacher sees
184/// only the target's courses they manage — the rest of the report (other
185/// teachers' courses) stays out of reach.
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)]
199async 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 // User must exist — a missing user is a 404, not an empty report.
207 crate::service::user::read(&st.db, &target)
208 .await?
209 .ok_or(AppError::NotFound)?;
210 // Only an exactly-teacher caller is narrowed to their managed courses;
211 // manager+ and a linked parent read the full report.
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)]
217mod 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 // (50×1 + 90×3) / 4 = 80
225 assert_eq!(weighted_average(&[(50, 1), (90, 3)]), Some(80.0));
226 }
227}