forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

marks.rs511 lines, 20.9 KiBHistoryRawDownload
1//! Mark reports: the per-instance weighted average a student carries, and the
2//! report card — the same numbers rolled up per term.
3//!
4//! Both read through the *instance* (`class_course`): a student's marks are
5//! grouped by the course their section is taught, so two sections teaching the
6//! same catalog course are two lines. A block's marks are the exams *addressed
7//! to* its instance (`exam_audience`), not only the ones it owns — a shared
8//! exam is each of its audiences' exam, so its mark appears in every one of
9//! their blocks. The roll-up, the term average and the verdict live in
10//! [`crate::service::karne`]; this module is the HTTP shape and the teacher
11//! narrowing.
12
13use std::collections::{HashMap, HashSet};
14
15use crate::web::tenant_state::State;
16use axum::Json;
17use axum::extract::{Path, Query};
18use serde::{Deserialize, Serialize};
19use utoipa::{IntoParams, ToSchema};
20use utoipa_axum::router::OpenApiRouter;
21use utoipa_axum::routes;
22
23use crate::database::Database;
24
25use crate::domain::class_course::{ClassCourse, ClassCourseId};
26use crate::domain::class_group::ClassGroupId;
27use crate::domain::exam::Exam;
28use crate::domain::role::Role;
29use crate::domain::term::TermId;
30use crate::domain::user::{User, UserId};
31use crate::error::{AppError, ErrorResponse};
32use crate::service;
33use crate::service::instance::can_manage_instance;
34use crate::service::karne::KarneReport;
35use crate::service::parent_link::ensure_can_observe;
36use crate::state::AppState;
37
38use super::{CourseResponse, CurrentUser, course_people, person_map};
39
40pub fn routes() -> OpenApiRouter<AppState> {
41 OpenApiRouter::new()
42 .routes(routes!(my_marks))
43 .routes(routes!(user_marks))
44 .routes(routes!(my_karne))
45 .routes(routes!(user_karne))
46}
47
48/// One graded exam inside a course block of the report.
49#[derive(Serialize, ToSchema)]
50struct MarkEntry {
51 /// Exam id.
52 exam: String,
53 title: String,
54 kind: String,
55 /// The kind's weight from the school settings, resolved at request time —
56 /// how many times this mark counts into the instance average. `1` when the
57 /// school no longer lists the kind.
58 weight: i64,
59 mark: i64,
60 /// The mark's label from the school's grade bands (`GET /settings`);
61 /// `null` when no bands are configured.
62 #[schema(example = "5")]
63 grade: Option<String>,
64 graded_by: String,
65}
66
67/// A student's marks in one instance — one catalog course as one section teaches
68/// it.
69#[derive(Serialize, ToSchema)]
70struct CourseMarks {
71 /// The instance these marks belong to (`GET /instances/{id}`). Two sections
72 /// teaching the same course are two blocks.
73 instance: String,
74 course: CourseResponse,
75 /// Graded results only — ungraded exams don't appear.
76 results: Vec<MarkEntry>,
77 /// `Σ(mark×weight) / Σ(weight)` over the graded exams; `null` while
78 /// nothing is graded.
79 average: Option<f64>,
80 /// The average's label from the school's grade bands; `null` when there
81 /// is no average or no bands are configured.
82 average_grade: Option<String>,
83}
84
85/// A student's full mark report across the instances they sit.
86#[derive(Serialize, ToSchema)]
87struct MarksReport {
88 /// The student's user id.
89 user: String,
90 courses: Vec<CourseMarks>,
91 /// Plain mean of the non-null block averages; `null` while no block has a
92 /// graded exam.
93 overall_average: Option<f64>,
94 /// The overall average's label from the school's grade bands; `null` when
95 /// there is no average or no bands are configured.
96 overall_grade: Option<String>,
97}
98
99/// `Σ(mark×weight) / Σ(weight)`; `None` when there is nothing to average. The
100/// zero-denominator guard is structural — kind weights are 1–100 and retired
101/// kinds resolve to 1, so a weight is never 0.
102fn weighted_average(pairs: &[(i64, i64)]) -> Option<f64> {
103 let total_weight: i64 = pairs.iter().map(|(_, weight)| weight).sum();
104 if total_weight == 0 {
105 return None;
106 }
107 let total: i64 = pairs.iter().map(|(mark, weight)| mark * weight).sum();
108 Some(total as f64 / total_weight as f64)
109}
110
111/// The instances a student's report is built from: the sections they are a live
112/// member of, and the instances those sections carry — the same path the report
113/// card walks, so the two can never disagree about which blocks a student has.
114///
115/// A hand-placed enrollment outside their sections is deliberately not a source
116/// here: a student's academic identity is their section, and adding an
117/// instance to it is what the office does with `POST /classes/{id}/instances`.
118async fn enrolled_instances(user: &UserId, db: &Database) -> Result<Vec<ClassCourse>, AppError> {
119 let (members, _) = crate::db::class_member::list_for_user(db, user, None, 0).await?;
120 let classes: Vec<ClassGroupId> = members
121 .iter()
122 .map(|member| member.get_class().clone())
123 .collect();
124 crate::db::class_course::list_for_class_ids(db, &classes).await
125}
126
127/// Assemble the report: for each instance the student sits, join its exams with
128/// the student's graded results, weigh each mark by its kind's weight *in that
129/// section* ([`service::exam_weight::resolve`]: the section's override, else
130/// the offering's, else the settings weight, else 1), then average. A `viewer`
131/// narrows the report to the instances that viewer manages (self-reports and
132/// manager+ reports pass `None` and see everything); the overall average
133/// follows the narrowed set.
134async fn build_report(
135 user: &UserId,
136 viewer: Option<&User>,
137 db: &Database,
138) -> Result<MarksReport, AppError> {
139 let mut instances = enrolled_instances(user, db).await?;
140 if let Some(viewer) = viewer {
141 let mut kept = Vec::with_capacity(instances.len());
142 for instance in instances {
143 if can_manage_instance(db, instance.get_id(), viewer).await? {
144 kept.push(instance);
145 }
146 }
147 instances = kept;
148 }
149
150 // One settings read grades (bands/labels) the whole report — the weights
151 // ride each section's own chain now — and one batch read resolves every
152 // block's catalog row (its title and kind).
153 let school = service::settings::load(db).await?;
154 let course_ids: Vec<crate::domain::course::CourseId> =
155 instances.iter().map(|i| i.get_course().clone()).collect();
156 let courses = service::course::list_by_ids(db, &course_ids).await?;
157 let by_key: HashMap<String, &crate::domain::course::Course> = courses
158 .iter()
159 .map(|course| (course.get_id().key(), course))
160 .collect();
161 let people = person_map(courses.iter().flat_map(course_people), db).await?;
162 // The blocks display the sections' **resolved** titles/descriptions
163 // (override → offering → catalog), batched — the `/courses` catalog list
164 // is the deliberate exception that keeps the catalog row's own values,
165 // because that surface IS the catalog.
166 let instance_refs: Vec<&ClassCourse> = instances.iter().collect();
167 let content = service::instance_resolve::resolved_content(db, &instance_refs).await?;
168
169 let mut blocks = Vec::with_capacity(instances.len());
170 let mut seen: HashSet<String> = HashSet::new();
171 for instance in &instances {
172 // The section's weight chain answer per kind, computed once — every
173 // mark of a kind weighs the same inside one block.
174 let mut line_weights: HashMap<String, i64> = HashMap::new();
175 let exams = crate::service::exam::list_for_class_course(db, instance.get_id()).await?;
176 let by_exam: HashMap<String, &Exam> = exams.iter().map(|e| (e.get_id().key(), e)).collect();
177 let results =
178 crate::service::exam_result::list_for_user_in_course(db, instance.get_id(), user)
179 .await?;
180
181 let mut entries = Vec::with_capacity(results.len());
182 let mut pairs = Vec::with_capacity(results.len());
183 for result in &results {
184 // A result whose exam is gone cannot happen given the delete
185 // cascade — skip defensively rather than corrupt the average.
186 let Some(exam) = by_exam.get(result.get_exam().key().as_str()) else {
187 continue;
188 };
189 // The kind's weight *in this section*: the section's own
190 // override, else the offering's, else the settings weight, else 1
191 // — a retired kind keeps counting once, an own set in force is
192 // the whole answer, empty included.
193 let kind = exam.get_kind().as_str();
194 let weight = match line_weights.get(kind) {
195 Some(weight) => *weight,
196 None => {
197 let weight = service::exam_weight::resolve(db, instance, kind).await?;
198 line_weights.insert(kind.to_string(), weight);
199 weight
200 }
201 };
202 entries.push(MarkEntry {
203 exam: exam.get_id().key().to_string(),
204 title: exam.get_title().as_str().to_string(),
205 kind: exam.get_kind().as_str().to_string(),
206 weight,
207 mark: result.get_mark().as_i64(),
208 grade: school
209 .grade_label(result.get_mark().as_i64() as f64)
210 .map(str::to_string),
211 graded_by: result.get_graded_by().key().to_string(),
212 });
213 pairs.push((result.get_mark().as_i64(), weight));
214 }
215
216 let Some(course) = by_key.get(instance.get_course().key().as_str()) else {
217 // An instance whose catalog row is gone is unreachable (the delete
218 // is refused while instances exist) — skip rather than fabricate.
219 continue;
220 };
221 seen.insert(instance.get_id().key());
222 let average = weighted_average(&pairs);
223 // The instance-scoped display: resolved title/description over the
224 // catalog row's (which stays the id/kind/counters source).
225 let resolved = content
226 .get(instance.get_id().key().as_str())
227 .expect("resolved_content covers every instance it is given");
228 let mut course = CourseResponse::new(course, &people);
229 course.title = resolved.title.clone();
230 course.description = resolved.description.clone();
231 blocks.push(CourseMarks {
232 instance: instance.get_id().key(),
233 course,
234 average,
235 average_grade: average.and_then(|a| school.grade_label(a).map(str::to_string)),
236 results: entries,
237 });
238 }
239
240 let averages: Vec<f64> = blocks.iter().filter_map(|block| block.average).collect();
241 let overall_average =
242 (!averages.is_empty()).then(|| averages.iter().sum::<f64>() / averages.len() as f64);
243
244 Ok(MarksReport {
245 user: user.key().to_string(),
246 courses: blocks,
247 overall_average,
248 overall_grade: overall_average.and_then(|a| school.grade_label(a).map(str::to_string)),
249 })
250}
251
252/// The current user's mark report: every instance they sit, with its graded
253/// exams, weighted instance averages, and the overall average.
254#[utoipa::path(
255 get,
256 path = "/me",
257 tag = "marks",
258 security(("session_cookie" = [])),
259 responses(
260 (status = 200, description = "The caller's mark report", body = MarksReport),
261 (status = 401, description = "Not authenticated", body = ErrorResponse),
262 ),
263)]
264async fn my_marks(
265 State(st): State<AppState>,
266 CurrentUser(user): CurrentUser,
267) -> Result<Json<MarksReport>, AppError> {
268 Ok(Json(build_report(user.get_id(), None, &st.db).await?))
269}
270
271/// Any user's mark report. Requires teacher+, or a parent tied to the target
272/// student. Managers, admins, and parents see every instance; a teacher sees
273/// only the target's instances they run — the rest of the report (other
274/// sections) stays out of reach.
275#[utoipa::path(
276 get,
277 path = "/{user}",
278 tag = "marks",
279 security(("session_cookie" = [])),
280 params(("user" = String, Path, description = "User id")),
281 responses(
282 (status = 200, description = "The user's mark report, narrowed to the caller's instances", body = MarksReport),
283 (status = 401, description = "Not authenticated", body = ErrorResponse),
284 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
285 (status = 404, description = "User not found", body = ErrorResponse),
286 ),
287)]
288async fn user_marks(
289 State(st): State<AppState>,
290 CurrentUser(caller): CurrentUser,
291 Path(user): Path<String>,
292) -> Result<Json<MarksReport>, AppError> {
293 let target = UserId::from_key(&user);
294 ensure_can_observe(&caller, &target, &st.db).await?;
295 // User must exist — a missing user is a 404, not an empty report.
296 crate::service::user::read(&st.db, &target)
297 .await?
298 .ok_or(AppError::NotFound)?;
299 // Only an exactly-teacher caller is narrowed to the instances they run;
300 // manager+ and a linked parent read the full report.
301 let viewer = (caller.get_role() == Role::Teacher).then_some(&caller);
302 Ok(Json(build_report(&target, viewer, &st.db).await?))
303}
304
305/// The `?term=` selector both report-card routes share. Omitted, it means the
306/// newest term on the calendar — the one a family is reading about now.
307#[derive(Deserialize, IntoParams)]
308struct KarneQuery {
309 /// The term to report on (`GET /terms`). Omit for the newest one.
310 #[param(example = "019732e3-7b00-7000-8000-00000000dead")]
311 term: Option<String>,
312}
313
314/// The term the request names, resolved *without* the archive gate: an
315/// archived term's report card is exactly what a family asks for, and the
316/// service serves its frozen snapshot. A term that does not exist is a 404, as
317/// is an empty calendar.
318async fn resolve_term(query: &KarneQuery, db: &Database) -> Result<TermId, AppError> {
319 match query.term.as_deref() {
320 Some(id) => Ok(*service::term::read(db, &TermId::from_key(id))
321 .await?
322 .ok_or(AppError::NotFound)?
323 .get_id()),
324 None => {
325 let (terms, _) = service::term::list_all(db, Some(1), 0).await?;
326 terms
327 .first()
328 .map(|term| *term.get_id())
329 .ok_or(AppError::NotFound)
330 }
331 }
332}
333
334/// Narrow a report card to the instances `viewer` runs: the lines stay, the
335/// term average is recomputed over them (each weighted by its `ders_saati`,
336/// the report card's own rule), and the verdict is dropped.
337///
338/// Dropping it is the honest half: the verdict is a judgement over the whole
339/// report card against the school's passing floor, and the floor's rule lives
340/// in [`crate::service::karne`] — a partially-seen report card states no
341/// verdict rather than one computed from a subset. A caller who runs every
342/// instance in the report sees it, because nothing is filtered.
343async fn narrow_karne(
344 mut report: KarneReport,
345 viewer: &User,
346 db: &Database,
347) -> Result<KarneReport, AppError> {
348 let lines_seen = report.instances.len();
349 let mut kept = Vec::with_capacity(lines_seen);
350 for line in std::mem::take(&mut report.instances) {
351 if can_manage_instance(db, &ClassCourseId::from_key(&line.class_course), viewer).await? {
352 kept.push(line);
353 }
354 }
355 // Nothing was filtered: the report is the whole report card, verdict included.
356 if kept.len() == lines_seen {
357 report.instances = kept;
358 return Ok(report);
359 }
360 let mut total_weight = 0i64;
361 let mut total = 0f64;
362 for line in &kept {
363 if let Some(average) = line.average {
364 total_weight += line.ders_saati;
365 total += average * line.ders_saati as f64;
366 }
367 }
368 report.instances = kept;
369 report.year_average = (total_weight > 0).then(|| total / total_weight as f64);
370 report.verdict = None;
371 Ok(report)
372}
373
374/// The current user's report card for one term: every instance of their
375/// sections that counts toward the report card, the `ders_saati`-weighted
376/// average across them, and the verdict. An archived term serves the snapshot
377/// the school froze when it was closed; an open one computes live.
378#[utoipa::path(
379 get,
380 path = "/karne",
381 tag = "marks",
382 security(("session_cookie" = [])),
383 params(KarneQuery),
384 responses(
385 (status = 200, description = "The caller's karne for that dönem", body = KarneReport),
386 (status = 401, description = "Not authenticated", body = ErrorResponse),
387 (status = 404, description = "No such term (or an empty calendar)", body = ErrorResponse),
388 ),
389)]
390async fn my_karne(
391 State(st): State<AppState>,
392 CurrentUser(user): CurrentUser,
393 Query(query): Query<KarneQuery>,
394) -> Result<Json<KarneReport>, AppError> {
395 let term = resolve_term(&query, &st.db).await?;
396 Ok(Json(
397 service::karne::build(&st.db, user.get_id(), &term).await?,
398 ))
399}
400
401/// Any user's report card for one term. Requires teacher+, or a parent tied to
402/// the target student. A linked parent and manager+ read the whole report card;
403/// an exactly-teacher caller sees only the lines of the instances they run,
404/// with the term average recomputed over those and no verdict (see
405/// [`narrow_karne`]).
406#[utoipa::path(
407 get,
408 path = "/karne/{user}",
409 tag = "marks",
410 security(("session_cookie" = [])),
411 params(("user" = String, Path, description = "User id"), KarneQuery),
412 responses(
413 (status = 200, description = "The user's karne, narrowed to the caller's instances", body = KarneReport),
414 (status = 401, description = "Not authenticated", body = ErrorResponse),
415 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
416 (status = 404, description = "User not found, or no such term", body = ErrorResponse),
417 ),
418)]
419async fn user_karne(
420 State(st): State<AppState>,
421 CurrentUser(caller): CurrentUser,
422 Path(user): Path<String>,
423 Query(query): Query<KarneQuery>,
424) -> Result<Json<KarneReport>, AppError> {
425 let target = UserId::from_key(&user);
426 ensure_can_observe(&caller, &target, &st.db).await?;
427 crate::service::user::read(&st.db, &target)
428 .await?
429 .ok_or(AppError::NotFound)?;
430 let term = resolve_term(&query, &st.db).await?;
431 let report = service::karne::build(&st.db, &target, &term).await?;
432 let report = if caller.get_role() == Role::Teacher {
433 narrow_karne(report, &caller, &st.db).await?
434 } else {
435 report
436 };
437 Ok(Json(report))
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 /// The term's own number, each instance weighted by its `ders_saati`: the
445 /// report card's arithmetic, checked here against the report shape this
446 /// module serves.
447 #[test]
448 fn the_report_shape_carries_the_instance_it_grouped_by() {
449 let pairs = [(85, 1), (70, 2)];
450 assert_eq!(weighted_average(&pairs), Some(75.0));
451 assert_eq!(weighted_average(&[]), None);
452 }
453
454 /// The shared-exam rule on the marks report: an exam addressed to a second
455 /// instance stands in *its* block too, while the exam addressed to its
456 /// owner alone stays out of it. Read through `exam.class_course` the second
457 /// block would have held no results.
458 #[tokio::test]
459 async fn an_ortak_exam_stands_in_every_block_it_is_addressed_to() {
460 let (db, _leases) = crate::database::init_test_db().await;
461 let fixture = crate::db::exam_result::tests::an_ortak_exam_karne(&db).await;
462 let ortak_mark = crate::db::exam_result::tests::ORTAK_MARK;
463 let owner_mark = crate::db::exam_result::tests::OWNER_MARK;
464
465 let report = build_report(&fixture.student, None, &db).await.unwrap();
466 assert_eq!(report.courses.len(), 2, "a block per şube's instance");
467
468 let block = |instance: &ClassCourseId| {
469 report
470 .courses
471 .iter()
472 .find(|block| block.instance == instance.key())
473 .unwrap_or_else(|| panic!("no block for {}", instance.key()))
474 };
475
476 let owner = block(&fixture.owner);
477 let owned_marks: Vec<(&str, i64)> = owner
478 .results
479 .iter()
480 .map(|entry| (entry.title.as_str(), entry.mark))
481 .collect();
482 assert_eq!(
483 owned_marks.len(),
484 2,
485 "the owner sits both exams, its own line"
486 );
487 assert!(owned_marks.contains(&("ortak", ortak_mark)));
488 assert!(owned_marks.contains(&("tek", owner_mark)));
489 assert_eq!(
490 owner.average,
491 Some((ortak_mark + owner_mark) as f64 / 2.0),
492 "both marks weigh 1 each"
493 );
494
495 let addressed = block(&fixture.addressed);
496 let marks: Vec<(&str, i64)> = addressed
497 .results
498 .iter()
499 .map(|entry| (entry.title.as_str(), entry.mark))
500 .collect();
501 assert_eq!(
502 marks,
503 vec![("ortak", ortak_mark)],
504 "the ortak exam is the second instance's own, the owner's one is not"
505 );
506 assert_eq!(addressed.average, Some(ortak_mark as f64));
507
508 // Each block weighs once, so the report is their plain mean.
509 assert_eq!(report.overall_average, Some(75.0));
510 }
511}