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

attendance.rs417 lines, 16.5 KiBHistoryRawDownload
1//! Attendance reports: the event tallies, the lesson roll call per instance,
2//! and the absence block a Turkish school actually reads — how many
3//! *days* a student was away in each term, and whether that is over the
4//! configured limit.
5//!
6//! The day counts are bucketed in the school's timezone
7//! ([`Settings::get_timezone`](crate::domain::settings::Settings::get_timezone)),
8//! because "a day of absence" is a calendar day at the school, not a UTC one:
9//! a lesson at 00:30 local is the same school day as one at 23:00 the evening
10//! before, and a UTC bucket would split it in two.
11
12use std::collections::{HashMap, HashSet};
13
14use crate::web::tenant_state::State;
15use axum::Json;
16use axum::extract::Path;
17use serde::Serialize;
18use utoipa::ToSchema;
19use utoipa_axum::router::OpenApiRouter;
20use utoipa_axum::routes;
21
22use crate::database::Database;
23use crate::domain::attendance::AttendanceStatus;
24use crate::domain::calendar::{zone_offset_minutes, zoned_day};
25use crate::domain::class_course::{ClassCourse, ClassCourseId};
26use crate::domain::course::{Course, CourseId};
27use crate::domain::role::Role;
28use crate::domain::session_attendance::SessionAttendance;
29use crate::domain::term::Term;
30use crate::domain::user::{User, UserId};
31use crate::error::{AppError, ErrorResponse};
32use crate::service::instance::can_manage_instance;
33use crate::service::parent_link::ensure_can_observe;
34use crate::state::AppState;
35
36use super::{CourseResponse, CurrentUser, course_people, person_map};
37
38pub fn routes() -> OpenApiRouter<AppState> {
39 OpenApiRouter::new()
40 .routes(routes!(my_report))
41 .routes(routes!(user_report))
42}
43
44/// Per-status tallies over a set of attendance rows, plus the attendance rate.
45#[derive(Serialize, ToSchema, Default)]
46struct StatusCounts {
47 present: u64,
48 absent: u64,
49 late: u64,
50 excused: u64,
51 /// Tallies of the school-added statuses (`GET /settings`), keyed by
52 /// status. Rate-neutral like `excused`: their semantics are the school's,
53 /// so they count into `total` only.
54 custom: HashMap<String, u64>,
55 /// All rows, `excused` and custom statuses included.
56 total: u64,
57 /// `(present + late) / (present + absent + late)` — being late is still
58 /// attending, and an excused absence counts against no one. `null` when
59 /// every row is excused/custom (or there are none).
60 rate: Option<f64>,
61}
62
63impl StatusCounts {
64 fn tally<'a>(statuses: impl Iterator<Item = &'a AttendanceStatus>) -> Self {
65 let mut counts = StatusCounts::default();
66 for status in statuses {
67 counts.total += 1;
68 match status.as_str() {
69 "present" => counts.present += 1,
70 "absent" => counts.absent += 1,
71 "late" => counts.late += 1,
72 "excused" => counts.excused += 1,
73 custom => *counts.custom.entry(custom.to_string()).or_default() += 1,
74 }
75 }
76 counts.rate = attendance_rate(counts.present, counts.absent, counts.late);
77 counts
78 }
79}
80
81/// `(present + late) / (present + absent + late)`; `None` when the denominator
82/// is zero.
83fn attendance_rate(present: u64, absent: u64, late: u64) -> Option<f64> {
84 let counted = present + absent + late;
85 (counted > 0).then(|| (present + late) as f64 / counted as f64)
86}
87
88/// A user's roll-call tallies in one instance.
89#[derive(Serialize, ToSchema)]
90struct CourseAttendance {
91 /// The instance these tallies belong to (`GET /instances/{id}`) — the
92 /// course as one class section teaches it.
93 instance: String,
94 course: CourseResponse,
95 counts: StatusCounts,
96}
97
98/// The configured per-term absence limits, or `null` per limit when the
99/// school set none.
100#[derive(Serialize, ToSchema)]
101struct AbsenceLimits {
102 max_excused_days: Option<i64>,
103 max_unexcused_days: Option<i64>,
104}
105
106/// One term's absence: how many days the student was away, split the way
107/// a Turkish school splits it.
108///
109/// A *day* is a calendar day at the school on which at least one lesson was
110/// missed — two absences in the same day count once, which is what the
111/// regulation counts. `unexcused_days` is the `absent` count and
112/// `excused_days` the `excused` one; a status the school added counts into
113/// neither (its semantics are the school's own).
114#[derive(Serialize, ToSchema)]
115struct TermAbsence {
116 /// The term (`GET /terms/{id}`).
117 term: String,
118 name: String,
119 #[schema(example = 3)]
120 absent_days: i64,
121 #[schema(example = 1)]
122 excused_days: i64,
123 /// The unexcused absence days — the count the unexcused limit watches.
124 /// Equal to `absent_days`; both are published because a client should not
125 /// have to know that.
126 #[schema(example = 3)]
127 unexcused_days: i64,
128 limits: AbsenceLimits,
129 /// Whether either configured limit is exceeded. `false` when no limit is
130 /// configured.
131 over_limit: bool,
132}
133
134/// A user's full attendance report: generic events, lesson roll call overall,
135/// the roll call broken down per instance, and the per-term absence breakdown.
136#[derive(Serialize, ToSchema)]
137struct AttendanceReport {
138 /// The user's id.
139 user: String,
140 /// Tallies over event attendance (`/events/{id}/attendance`).
141 events: StatusCounts,
142 /// Tallies over every lesson roll-call row, all instances combined.
143 sessions: StatusCounts,
144 /// The session tallies split per instance. An instance appears as long as
145 /// the user has roll-call rows in it — attendance is a historical record,
146 /// so unenrolling never hides an absence.
147 courses: Vec<CourseAttendance>,
148 /// The per-term absent-day counts, oldest term first. A lesson that falls
149 /// in no term's range is not counted here (it still counts in the
150 /// tallies).
151 devamsizlik: Vec<TermAbsence>,
152}
153
154/// The term an instant falls in: the containing term with the latest start,
155/// or `None` when the calendar does not cover it.
156fn term_of(instant: i64, terms: &[Term]) -> Option<&Term> {
157 terms
158 .iter()
159 .filter(|term| {
160 term.get_starts_at().as_millis() <= instant && instant <= term.get_ends_at().as_millis()
161 })
162 .max_by_key(|term| term.get_starts_at().as_millis())
163}
164
165/// Assemble the report: tally the user's event rows, then their session rows
166/// grouped by the (denormalized) instance. A `viewer` narrows the per-instance
167/// blocks — and the overall session tally, and the absence block — to the
168/// instances that viewer runs (self-reports and manager+ reports pass `None`).
169/// Event tallies are school-wide, not course data, so they stay in either case.
170async fn build_report(
171 user: &UserId,
172 viewer: Option<&User>,
173 db: &Database,
174) -> Result<AttendanceReport, AppError> {
175 let events = crate::service::attendance::list_for_user(db, user).await?;
176 let sessions = crate::service::session_attendance::list_for_user(db, user).await?;
177
178 // Group session rows by instance, preserving first-seen (newest-first)
179 // order.
180 let mut instance_ids: Vec<ClassCourseId> = Vec::new();
181 let mut by_instance: HashMap<String, Vec<&SessionAttendance>> = HashMap::new();
182 for row in &sessions {
183 let key = row.get_class_course().key();
184 if !by_instance.contains_key(&key) {
185 instance_ids.push(row.get_class_course().clone());
186 }
187 by_instance.entry(key).or_default().push(row);
188 }
189
190 let instances = crate::db::class_course::list_by_ids(db, &instance_ids).await?;
191 let instance_by_key: HashMap<String, &ClassCourse> = instances
192 .iter()
193 .map(|instance| (instance.get_id().key(), instance))
194 .collect();
195 let course_ids: Vec<CourseId> = instances
196 .iter()
197 .map(|instance| instance.get_course().clone())
198 .collect();
199 let courses = crate::service::course::list_by_ids(db, &course_ids).await?;
200 let course_by_key: HashMap<String, &Course> =
201 courses.iter().map(|c| (c.get_id().key(), c)).collect();
202 let people = person_map(courses.iter().flat_map(course_people), db).await?;
203 // The per-instance blocks display the sections' **resolved**
204 // titles/descriptions (override → offering → catalog), batched — the
205 // `/courses` catalog list is the deliberate exception that keeps the
206 // catalog row's own values, because that surface IS the catalog.
207 let instance_refs: Vec<&ClassCourse> = instances.iter().collect();
208 let content = crate::service::instance_resolve::resolved_content(db, &instance_refs).await?;
209
210 let mut blocks = Vec::with_capacity(instance_ids.len());
211 let mut visible_rows: Vec<&SessionAttendance> = Vec::with_capacity(sessions.len());
212 for instance_id in &instance_ids {
213 // A row whose instance is gone cannot happen given the delete cascade —
214 // skip defensively rather than fabricate a block.
215 let Some(instance) = instance_by_key.get(instance_id.key().as_str()) else {
216 continue;
217 };
218 if let Some(viewer) = viewer
219 && !can_manage_instance(db, instance.get_id(), viewer).await?
220 {
221 continue;
222 }
223 let Some(course) = course_by_key.get(instance.get_course().key().as_str()) else {
224 continue;
225 };
226 let rows = &by_instance[instance_id.key().as_str()];
227 visible_rows.extend(rows.iter().copied());
228 // The instance-scoped display: resolved title/description over the
229 // catalog row's (which stays the id/kind/counters source).
230 let resolved = content
231 .get(instance.get_id().key().as_str())
232 .expect("resolved_content covers every instance it is given");
233 let mut course = CourseResponse::new(course, &people);
234 course.title = resolved.title.clone();
235 course.description = resolved.description.clone();
236 blocks.push(CourseAttendance {
237 instance: instance.get_id().key(),
238 course,
239 counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())),
240 });
241 }
242
243 // A narrowed viewer's overall tally follows the visible blocks; a full
244 // report keeps the historical every-row tally.
245 let session_counts = match viewer {
246 Some(_) => StatusCounts::tally(visible_rows.iter().map(|r| r.get_status())),
247 None => StatusCounts::tally(sessions.iter().map(|a| a.get_status())),
248 };
249
250 let devamsizlik = absence_by_term(&visible_rows, &blocks, db).await?;
251
252 Ok(AttendanceReport {
253 user: user.key().to_string(),
254 events: StatusCounts::tally(events.iter().map(|a| a.get_status())),
255 sessions: session_counts,
256 courses: blocks,
257 devamsizlik,
258 })
259}
260
261/// The absence block: for every term the visible rows reach, the count of
262/// distinct school-days on which the student was `absent` (unexcused) and on
263/// which they were `excused`.
264///
265/// The day is the *lesson's* day (`course_session.starts_at`), never when the
266/// teacher got round to marking: a roll call taken a week late must not move an
267/// absence into another term. The lessons are read one instance at a time
268/// (they are the same instances the blocks are built from), and the terms once.
269async fn absence_by_term(
270 rows: &[&SessionAttendance],
271 blocks: &[CourseAttendance],
272 db: &Database,
273) -> Result<Vec<TermAbsence>, AppError> {
274 if rows.is_empty() || blocks.is_empty() {
275 return Ok(Vec::new());
276 }
277 // One read per visible instance: every session it ever held, keyed by id.
278 let mut starts_at: HashMap<String, i64> = HashMap::new();
279 for block in blocks {
280 let (held, _) = crate::service::course_session::list_for_class_course(
281 db,
282 &ClassCourseId::from_key(&block.instance),
283 None,
284 0,
285 )
286 .await?;
287 for session in held {
288 starts_at.insert(session.get_id().key(), session.get_starts_at().as_millis());
289 }
290 }
291
292 let school = crate::service::settings::load(db).await?;
293 let offset = zone_offset_minutes(school.get_timezone());
294 let (terms, _) = crate::service::term::list_all(db, None, 0).await?;
295
296 // A day counts once per (term, status class), which is what the
297 // regulation counts.
298 let mut unexcused: HashSet<(String, chrono::NaiveDate)> = HashSet::new();
299 let mut excused: HashSet<(String, chrono::NaiveDate)> = HashSet::new();
300 let mut order: Vec<String> = Vec::new();
301 let mut by_term: HashMap<String, &Term> = HashMap::new();
302 for row in rows {
303 let class = match row.get_status().as_str() {
304 "absent" => &mut unexcused,
305 "excused" => &mut excused,
306 // Every other status is the school's own semantics; it is not a
307 // day away.
308 _ => continue,
309 };
310 let Some(start) = starts_at.get(row.get_session().key().as_str()) else {
311 continue;
312 };
313 let Some(term) = term_of(*start, &terms) else {
314 // A lesson outside every term's range is not this block's.
315 continue;
316 };
317 let key = term.get_id().key();
318 if !by_term.contains_key(&key) {
319 by_term.insert(key.clone(), term);
320 order.push(key.clone());
321 }
322 class.insert((key, zoned_day(*start, offset)));
323 }
324
325 let mut blocks_out = Vec::with_capacity(order.len());
326 for key in order {
327 let Some(term) = by_term.get(&key) else {
328 continue;
329 };
330 let absent_days = unexcused
331 .iter()
332 .filter(|(term_id, _)| term_id == &key)
333 .count() as i64;
334 let excused_days = excused
335 .iter()
336 .filter(|(term_id, _)| term_id == &key)
337 .count() as i64;
338 let limits = AbsenceLimits {
339 max_excused_days: school.get_max_excused_absent_days(),
340 max_unexcused_days: school.get_max_unexcused_absent_days(),
341 };
342 let over_limit = limits
343 .max_excused_days
344 .is_some_and(|max| excused_days > max)
345 || limits
346 .max_unexcused_days
347 .is_some_and(|max| absent_days > max);
348 blocks_out.push(TermAbsence {
349 term: key,
350 name: term.get_name().as_str().to_string(),
351 absent_days,
352 excused_days,
353 unexcused_days: absent_days,
354 limits,
355 over_limit,
356 });
357 }
358 blocks_out.sort_by_key(|block| block.term.clone());
359 Ok(blocks_out)
360}
361
362/// The current user's attendance report: event tallies, lesson roll-call
363/// tallies, a per-instance breakdown with attendance rates, and the per-term
364/// absence breakdown.
365#[utoipa::path(
366 get,
367 path = "/me",
368 tag = "attendance",
369 security(("session_cookie" = [])),
370 responses(
371 (status = 200, description = "The caller's attendance report", body = AttendanceReport),
372 (status = 401, description = "Not authenticated", body = ErrorResponse),
373 ),
374)]
375async fn my_report(
376 State(st): State<AppState>,
377 CurrentUser(user): CurrentUser,
378) -> Result<Json<AttendanceReport>, AppError> {
379 Ok(Json(build_report(user.get_id(), None, &st.db).await?))
380}
381
382/// Any user's attendance report. Requires teacher+, or a parent tied to the
383/// target student. Managers, admins, and parents see every instance; a teacher
384/// sees the event tallies plus only the roll-call blocks — and the absence
385/// days — of the instances they run.
386#[utoipa::path(
387 get,
388 path = "/{user}",
389 tag = "attendance",
390 security(("session_cookie" = [])),
391 params(("user" = String, Path, description = "User id")),
392 responses(
393 (status = 200, description = "The user's attendance report, narrowed to the caller's instances", body = AttendanceReport),
394 (status = 401, description = "Not authenticated", body = ErrorResponse),
395 (status = 403, description = "Requires teacher role or higher, or a parent link to this student", body = ErrorResponse),
396 (status = 404, description = "User not found", body = ErrorResponse),
397 ),
398)]
399async fn user_report(
400 State(st): State<AppState>,
401 CurrentUser(caller): CurrentUser,
402 Path(user): Path<String>,
403) -> Result<Json<AttendanceReport>, AppError> {
404 let target = UserId::from_key(&user);
405 ensure_can_observe(&caller, &target, &st.db).await?;
406 // User must exist — a missing user is a 404, not an empty report.
407 crate::service::user::read(&st.db, &target)
408 .await?
409 .ok_or(AppError::NotFound)?;
410 // Only an exactly-teacher caller is narrowed to the instances they run;
411 // manager+ and a linked parent read the full report.
412 let viewer = (caller.get_role() == Role::Teacher).then_some(&caller);
413 Ok(Json(build_report(&target, viewer, &st.db).await?))
414}
415
416// The day-bucketing unit test moved with its arithmetic to
417// `src/domain/calendar.rs` (`the_day_bucket_follows_the_school_zone`).