forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 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::role::Role;
15use crate::domain::user::{User, UserId};
16use crate::error::{AppError, ErrorResponse};
17use crate::service;
18use crate::service::parent_link::ensure_can_observe;
19use crate::state::AppState;
20
21use super::courses::can_manage_course;
22use super::{CourseResponse, CurrentUser, course_people, person_map};
23
24pub fn routes() -> OpenApiRouter<AppState> {
25 OpenApiRouter::new()
26 .routes(routes!(my_marks))
27 .routes(routes!(user_marks))
28}
29
30/// One graded exam inside a course block of the report.
31#[derive(Serialize, ToSchema)]
32struct MarkEntry {
33 /// Exam id.
34 exam: String,
35 title: String,
36 kind: String,
37 /// The kind's weight from the school settings, resolved at request time —
38 /// how many times this mark counts into the course average. `1` when the
39 /// school no longer lists the kind.
40 weight: i64,
41 mark: i64,
42 /// The mark's label from the school's grade bands (`GET /settings`);
43 /// `null` when no bands are configured.
44 #[schema(example = "AA")]
45 grade: Option<String>,
46 graded_by: String,
47}
48
49/// A student's marks in one enrolled course.
50#[derive(Serialize, ToSchema)]
51struct CourseMarks {
52 course: CourseResponse,
53 /// Graded results only — ungraded exams don't appear.
54 results: Vec<MarkEntry>,
55 /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while
56 /// nothing is graded.
57 average: Option<f64>,
58 /// The average's label from the school's grade bands; `null` when there
59 /// is no average or no bands are configured.
60 average_grade: Option<String>,
61}
62
63/// A student's full mark report across their enrolled courses.
64#[derive(Serialize, ToSchema)]
65struct MarksReport {
66 /// The student's user id.
67 user: String,
68 courses: Vec<CourseMarks>,
69 /// Plain mean of the non-null course averages; `null` while no course has
70 /// a graded exam.
71 overall_average: Option<f64>,
72 /// The overall average's label from the school's grade bands; `null` when
73 /// there is no average or no bands are configured.
74 overall_grade: Option<String>,
75}
76
77/// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The
78/// zero-denominator guard is structural — kind weights are 1–100 and retired
79/// kinds resolve to 1, so a weight is never 0.
80fn 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/// Assemble the report: for each enrolled course, join the course's exams
90/// with the user's graded results, weigh each mark by its exam kind's
91/// settings weight, then average. A `viewer` narrows the report to the
92/// courses that viewer manages (self-reports and manager+ reports pass `None`
93/// and see everything); the overall average follows the narrowed set.
94async 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 // One settings read weighs and labels the whole report.
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 // 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().as_str()) 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}