From 5b6aac1695d4720c60e99d74f68169efcf1d4d60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 12 Jul 2026 22:01:53 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(attendance):=20course=20sessio?= =?UTF-8?q?ns,=20roll=20call,=20work=20log,=20reports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - course_session: a course's lesson (teacher, topic, required starts_at, optional ends_at); managed under course rights like exams; explicit teacher_id must hold teacher+; lists ordered by starts_at (timetable) - session_attendance roll call: one row per session+user by composite id, course denormalized so reports need no join; students never self-mark — the session's teacher or a course manager marks enrolled students, and the teacher's own presence row is manager+ only (no self-declared presence); session/course deletes cascade roll-call rows - work_entry staff timesheet (teacher+): check-in/out stamped by the server clock only, so a client clock or crafted request can't forge presence; one open stint per user held atomically — INSERT IGNORE on the deterministic open_{user} id, check-out takes it via DELETE RETURN BEFORE and re-files under a ULID; manager+ reads any log, corrects closed stints (ordered instants), deletes entries - attendance reports at /attendance/me and /attendance/{user} (teacher+), mirroring the marks report: event tallies + session tallies + per-course breakdown; rate = (present+late)/(present+absent+late) — late attends, excused counts against no one; unenrolling hides marks but never absences (attendance is a historical record) - RequireManager extractor; check_time_range shared by events/sessions --- src/constant.rs | 2 + src/database.rs | 29 +++ src/domain/attendance.rs | 11 + src/domain/course.rs | 23 +- src/domain/course_session.rs | 175 ++++++++++++++ src/domain/mod.rs | 3 + src/domain/session_attendance.rs | 141 +++++++++++ src/domain/work_entry.rs | 199 ++++++++++++++++ src/lib.rs | 8 +- src/web/attendance.rs | 207 ++++++++++++++++ src/web/courses.rs | 112 ++++++++- src/web/dto.rs | 30 +++ src/web/events.rs | 18 +- src/web/extractor.rs | 20 ++ src/web/mod.rs | 27 ++- src/web/sessions.rs | 395 +++++++++++++++++++++++++++++++ src/web/work.rs | 230 ++++++++++++++++++ 17 files changed, 1606 insertions(+), 24 deletions(-) create mode 100644 src/domain/course_session.rs create mode 100644 src/domain/session_attendance.rs create mode 100644 src/domain/work_entry.rs create mode 100644 src/web/attendance.rs create mode 100644 src/web/sessions.rs create mode 100644 src/web/work.rs diff --git a/src/constant.rs b/src/constant.rs index a487d8a..12fd2e8 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -30,6 +30,8 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; /// The only accepted attendance states. pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; +pub const MAX_SESSION_TOPIC_LEN: usize = 200; + /// The only accepted exam kinds. Informational metadata only — `weight` drives /// the course average. pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; diff --git a/src/database.rs b/src/database.rs index 86e77a0..a838fab 100644 --- a/src/database.rs +++ b/src/database.rs @@ -20,6 +20,9 @@ pub const EXAM_QUESTION_TABLE: &str = "exam_question"; pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; pub const COURSE_TABLE: &str = "course"; pub const ENROLLMENT_TABLE: &str = "enrollment"; +pub const COURSE_SESSION_TABLE: &str = "course_session"; +pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; +pub const WORK_ENTRY_TABLE: &str = "work_entry"; /// SCHEMAFULL schema: every column is typed, references use `record<..>`. /// Idempotent — safe to run on every boot. @@ -62,6 +65,7 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record; DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; + DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON course TYPE record; @@ -75,6 +79,31 @@ const MIGRATION: &str = " DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; + DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record; + DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record; + DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; + DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; + DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option; + DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; + + DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record; + DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; + DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record; + DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; + DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; + DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; + DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; + + DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record; + DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; + DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option; + DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; + DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 42a78e8..4173b27 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -115,6 +115,17 @@ impl Attendance { Ok(result.take::>(0)?) } + /// Every event-attendance row recorded for `user` — the events half of the + /// attendance report. + pub async fn list_for_user(user: &UserId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + pub async fn remove( event: &EventId, user: &UserId, diff --git a/src/domain/course.rs b/src/domain/course.rs index 02214c2..98f843a 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -133,6 +133,21 @@ impl Course { Ok(result.take::>(0)?) } + /// Load every course behind `ids` (one query) — the join half of the + /// attendance report's per-course blocks. + pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result, AppError> { + if ids.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = ids.iter().map(CourseId::record).collect(); + let mut result = db + .query("SELECT * FROM course WHERE id IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) + } + pub async fn update( mut self, title: CourseTitle, @@ -146,9 +161,9 @@ impl Course { } /// Delete the course and cascade-remove everything inside it: results and - /// attempts of its exams, its enrollments, and the exams themselves. The - /// children go in one transaction so a crash can't leave an exam pointing - /// at a deleted course. + /// attempts of its exams, its enrollments, its sessions with their roll + /// call, and the exams themselves. The children go in one transaction so a + /// crash can't leave an exam pointing at a deleted course. pub async fn delete(self, db: &Database) -> Result { db.query( "BEGIN TRANSACTION; @@ -156,6 +171,8 @@ impl Course { DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); + DELETE session_attendance WHERE course = $course; + DELETE course_session WHERE course = $course; DELETE enrollment WHERE course = $course; DELETE exam WHERE course = $course; COMMIT TRANSACTION;", diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs new file mode 100644 index 0000000..fe0c22c --- /dev/null +++ b/src/domain/course_session.rs @@ -0,0 +1,175 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::constant::MAX_SESSION_TOPIC_LEN; +use crate::database::{COURSE_SESSION_TABLE, Database}; +use crate::domain::course::CourseId; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; +use crate::validate::validate_optional; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct CourseSessionId(RecordId); + +impl CourseSessionId { + pub fn generate() -> Self { + Self(RecordId::new(COURSE_SESSION_TABLE, Ulid::new().to_string())) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(COURSE_SESSION_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SessionTopic(String); + +impl SessionTopic { + pub fn try_new(value: &str) -> Result { + validate_optional("topic", value, MAX_SESSION_TOPIC_LEN)?; + Ok(Self(value.to_string())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// One scheduled lesson of a course: the unit roll call is taken on. Unlike a +/// generic event, a session always has a start instant and belongs to a course, +/// so its roster is the course's enrollment plus the assigned teacher. +#[derive(Debug, Clone, SurrealValue)] +pub struct CourseSession { + id: CourseSessionId, + course: CourseId, + /// Who teaches this session. Must hold the `teacher` role or higher — + /// enforced at the web layer, where the target user row is at hand. + teacher: UserId, + topic: SessionTopic, + starts_at: Timestamp, + ends_at: Option, +} + +impl CourseSession { + pub fn get_id(&self) -> &CourseSessionId { + &self.id + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_teacher(&self) -> &UserId { + &self.teacher + } + + pub fn get_topic(&self) -> &SessionTopic { + &self.topic + } + + pub fn get_starts_at(&self) -> Timestamp { + self.starts_at + } + + pub fn get_ends_at(&self) -> Option { + self.ends_at + } + + pub fn is_teacher(&self, user: &UserId) -> bool { + &self.teacher == user + } + + pub async fn create( + course: &CourseId, + teacher: &UserId, + topic: SessionTopic, + starts_at: Timestamp, + ends_at: Option, + db: &Database, + ) -> Result { + let session = CourseSession { + id: CourseSessionId::generate(), + course: course.clone(), + teacher: teacher.clone(), + topic, + starts_at, + ends_at, + }; + let created: Option = + db.create(session.id.record()).content(session).await?; + created.ok_or_else(|| AppError::Internal("failed to create session".into())) + } + + pub async fn read( + id: &CourseSessionId, + db: &Database, + ) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// A course's sessions, most recent lesson first. Ordered by `starts_at` + /// (not id): a timetable is read by when the lesson happens, not by when + /// the row was created. + pub async fn list_for_course( + course: &CourseId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM course_session WHERE course = $course ORDER BY starts_at DESC") + .bind(("course", course.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn update( + mut self, + teacher: UserId, + topic: SessionTopic, + starts_at: Timestamp, + ends_at: Option, + db: &Database, + ) -> Result { + self.teacher = teacher; + self.topic = topic; + self.starts_at = starts_at; + self.ends_at = ends_at; + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + /// Delete the session and cascade-remove its roll-call rows. + pub async fn delete(self, db: &Database) -> Result { + db.query("DELETE session_attendance WHERE session = $s") + .bind(("s", self.id.record())) + .await? + .check()?; + let deleted: Option = db.delete(self.id.record()).await?; + deleted.ok_or(AppError::NotFound) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn topic_is_optional_but_bounded() { + assert!(SessionTopic::try_new("").is_ok()); + assert!(SessionTopic::try_new("limits and continuity").is_ok()); + assert!(SessionTopic::try_new(&"x".repeat(MAX_SESSION_TOPIC_LEN)).is_ok()); + assert!(SessionTopic::try_new(&"x".repeat(MAX_SESSION_TOPIC_LEN + 1)).is_err()); + } +} diff --git a/src/domain/mod.rs b/src/domain/mod.rs index aeef724..5d35a60 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -4,6 +4,7 @@ pub mod attendance; pub mod course; +pub mod course_session; pub mod enrollment; pub mod event; pub mod exam; @@ -15,5 +16,7 @@ pub mod note; pub mod profile; pub mod role; pub mod session; +pub mod session_attendance; pub mod timestamp; pub mod user; +pub mod work_entry; diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs new file mode 100644 index 0000000..7870a66 --- /dev/null +++ b/src/domain/session_attendance.rs @@ -0,0 +1,141 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; + +use crate::database::{Database, SESSION_ATTENDANCE_TABLE}; +use crate::domain::attendance::AttendanceStatus; +use crate::domain::course::CourseId; +use crate::domain::course_session::{CourseSession, CourseSessionId}; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct SessionAttendanceId(RecordId); + +impl SessionAttendanceId { + /// A deterministic id for the (session, user) pair. Because the same pair + /// always maps to the same record id, marking is a single atomic UPSERT with + /// no find-then-insert race, and one-row-per-pair holds by construction. + /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. + pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { + Self(RecordId::new( + SESSION_ATTENDANCE_TABLE, + format!("{}_{}", session.key(), user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One person's roll-call state for one lesson. `course` is denormalized from +/// the session so the per-course attendance report is a single indexed query +/// (`WHERE user = $u`) with no join. +#[derive(Debug, Clone, SurrealValue)] +pub struct SessionAttendance { + id: SessionAttendanceId, + session: CourseSessionId, + course: CourseId, + user: UserId, + status: AttendanceStatus, + marked_by: UserId, +} + +impl SessionAttendance { + pub fn get_id(&self) -> &SessionAttendanceId { + &self.id + } + + pub fn get_session(&self) -> &CourseSessionId { + &self.session + } + + pub fn get_course(&self) -> &CourseId { + &self.course + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_status(&self) -> &AttendanceStatus { + &self.status + } + + pub fn get_marked_by(&self) -> &UserId { + &self.marked_by + } + + /// Record (or overwrite) `user`'s status for the session. One row per + /// (session, user), keyed by a deterministic composite id so this is a + /// single atomic UPSERT — concurrent marks converge on the one row. + pub async fn mark( + session: &CourseSession, + user: &UserId, + status: AttendanceStatus, + marked_by: &UserId, + db: &Database, + ) -> Result { + let attendance = SessionAttendance { + id: SessionAttendanceId::composite(session.get_id(), user), + session: session.get_id().clone(), + course: session.get_course().clone(), + user: user.clone(), + status, + marked_by: marked_by.clone(), + }; + let saved: Option = db + .upsert(attendance.id.record()) + .content(attendance) + .await?; + saved.ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) + } + + pub async fn list_for_session( + session: &CourseSessionId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM session_attendance WHERE session = $s ORDER BY id DESC") + .bind(("s", session.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Every roll-call row ever recorded for `user` — the session half of the + /// attendance report. Deliberately not filtered by current enrollment: + /// attendance is a historical record, so unenrolling hides marks (report + /// semantics) but never absences. + pub async fn list_for_user( + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + pub async fn remove( + session: &CourseSessionId, + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("DELETE session_attendance WHERE session = $s AND user = $usr RETURN BEFORE") + .bind(("s", session.record())) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) + } +} diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs new file mode 100644 index 0000000..97d849d --- /dev/null +++ b/src/domain/work_entry.rs @@ -0,0 +1,199 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{Database, WORK_ENTRY_TABLE}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct WorkEntryId(RecordId); + +impl WorkEntryId { + pub fn generate() -> Self { + Self(RecordId::new(WORK_ENTRY_TABLE, Ulid::new().to_string())) + } + + /// The deterministic id of `user`'s *open* entry. At most one open stint + /// per user holds by construction: checking in is a single `INSERT IGNORE` + /// on this id (atomic — a second check-in changes nothing), and checking + /// out atomically takes the row and re-files it under a ULID id. + /// `open_` cannot collide with a ULID key (ULIDs are bare alphanumerics). + pub fn open_for(user: &UserId) -> Self { + Self(RecordId::new( + WORK_ENTRY_TABLE, + format!("open_{}", user.key()), + )) + } + + pub fn from_key(key: &str) -> Self { + Self(RecordId::new(WORK_ENTRY_TABLE, key)) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One work stint of a staff member: server-stamped `check_in`, and +/// `check_out` once closed. The wall clock is read server-side only — a +/// client can never supply its own instants (managers correct closed entries +/// through an explicit endpoint instead). +#[derive(Debug, Clone, SurrealValue)] +pub struct WorkEntry { + id: WorkEntryId, + user: UserId, + check_in: Timestamp, + check_out: Option, +} + +impl WorkEntry { + pub fn get_id(&self) -> &WorkEntryId { + &self.id + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_check_in(&self) -> Timestamp { + self.check_in + } + + pub fn get_check_out(&self) -> Option { + self.check_out + } + + pub fn is_open(&self) -> bool { + self.check_out.is_none() + } + + /// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE` + /// on the deterministic open id makes this atomic: if an open entry + /// already exists the insert is skipped (empty result) and the caller gets + /// a conflict — two racing check-ins can never create two open rows or + /// reset a running clock. + pub async fn check_in(user: &UserId, db: &Database) -> Result { + let entry = WorkEntry { + id: WorkEntryId::open_for(user), + user: user.clone(), + check_in: Timestamp::now(), + check_out: None, + }; + let mut result = db + .query("INSERT IGNORE INTO work_entry $entry") + .bind(("entry", entry)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::Conflict("already checked in — check out first")) + } + + /// Close `user`'s open stint. The `DELETE .. RETURN BEFORE` is an atomic + /// take: of two racing check-outs exactly one receives the row (the other + /// gets the conflict). The closed stint is then re-filed under a ULID id, + /// freeing the open slot for the next check-in. + pub async fn check_out(user: &UserId, db: &Database) -> Result { + let mut result = db + .query("DELETE $open RETURN BEFORE") + .bind(("open", WorkEntryId::open_for(user).record())) + .await? + .check()?; + let open = result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::Conflict("not checked in"))?; + + let closed = WorkEntry { + id: WorkEntryId::generate(), + user: open.user, + check_in: open.check_in, + check_out: Some(Timestamp::now()), + }; + let saved: Option = db.create(closed.id.record()).content(closed).await?; + saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) + } + + pub async fn read(id: &WorkEntryId, db: &Database) -> Result, AppError> { + Ok(db.select(id.record()).await?) + } + + /// Every stint of `user`, newest first — the open one (if any) included. + /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with + /// the ULIDs, so id order would misplace it. + pub async fn list_for_user(user: &UserId, db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM work_entry WHERE user = $usr ORDER BY check_in DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } + + /// Persist corrected instants (manager fix-ups on closed entries; the web + /// layer validates ordering and rejects open entries). + pub async fn update( + mut self, + check_in: Timestamp, + check_out: Timestamp, + db: &Database, + ) -> Result { + self.check_in = check_in; + self.check_out = Some(check_out); + let updated: Option = db.update(self.id.record()).content(self).await?; + updated.ok_or(AppError::NotFound) + } + + pub async fn remove(id: &WorkEntryId, db: &Database) -> Result, AppError> { + Ok(db.delete(id.record()).await?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database; + + #[tokio::test] + async fn check_in_is_exclusive_until_check_out() { + let db = database::init_mem().await.unwrap(); + // A `record` column checks the table of the id, not row + // existence — a fabricated id keeps this test free of user ceremony. + let user = UserId::from_key(&Ulid::new().to_string()); + + let open = WorkEntry::check_in(&user, &db).await.unwrap(); + assert!(open.is_open()); + assert_eq!(open.get_id().key(), format!("open_{}", user.key())); + + // Second check-in must not create a second stint or reset the clock. + let dup = WorkEntry::check_in(&user, &db).await; + assert!(matches!(dup, Err(AppError::Conflict(_)))); + let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].get_check_in(), open.get_check_in()); + + let closed = WorkEntry::check_out(&user, &db).await.unwrap(); + assert!(!closed.is_open()); + assert!(closed.get_check_out().unwrap() >= closed.get_check_in()); + + // The open slot is free again; a stray second check-out conflicts. + assert!(matches!( + WorkEntry::check_out(&user, &db).await, + Err(AppError::Conflict(_)) + )); + WorkEntry::check_in(&user, &db).await.unwrap(); + let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); + assert_eq!(entries.len(), 2); + } +} diff --git a/src/lib.rs b/src/lib.rs index 3ce688b..309c389 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,10 @@ use crate::state::AppState; (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), (name = "notes", description = "Per-user notes CRUD"), (name = "events", description = "Events and attendance"), - (name = "courses", description = "Courses, enrollment, and course exams"), + (name = "courses", description = "Courses, enrollment, course exams, and course sessions"), + (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), + (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), + (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), (name = "exams", description = "Exams (per course, weighted): results, sync/async scheduling, attempts, questions/answers, and live monitoring. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames, see the README's \"Taking an exam\" section for the protocol"), (name = "marks", description = "Weighted mark reports per course and overall"), ), @@ -77,8 +80,11 @@ pub fn build_router(state: AppState) -> Router { .nest("/notes", web::notes::routes()) .nest("/events", web::events::routes()) .nest("/courses", web::courses::routes()) + .nest("/sessions", web::sessions::routes()) .nest("/exams", web::exams::routes()) .nest("/marks", web::marks::routes()) + .nest("/work", web::work::routes()) + .nest("/attendance", web::attendance::routes()) .split_for_parts(); // Catch-all per-IP limit over every route (Swagger included). Kept inside diff --git a/src/web/attendance.rs b/src/web/attendance.rs new file mode 100644 index 0000000..f0110ab --- /dev/null +++ b/src/web/attendance.rs @@ -0,0 +1,207 @@ +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{Path, State}; +use serde::Serialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::attendance::{Attendance, AttendanceStatus}; +use crate::domain::course::{Course, CourseId}; +use crate::domain::session_attendance::SessionAttendance; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::{CourseResponse, CurrentUser, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(my_report)) + .routes(routes!(user_report)) +} + +/// Per-status tallies over a set of attendance rows, plus the attendance rate. +#[derive(Serialize, ToSchema, Default)] +struct StatusCounts { + present: u64, + absent: u64, + late: u64, + excused: u64, + /// All rows, `excused` included. + total: u64, + /// `(present + late) / (present + absent + late)` — being late is still + /// attending, and an excused absence counts against no one. `null` when + /// every row is excused (or there are none). + rate: Option, +} + +impl StatusCounts { + fn tally<'a>(statuses: impl Iterator) -> Self { + let mut counts = StatusCounts::default(); + for status in statuses { + counts.total += 1; + match status.as_str() { + "present" => counts.present += 1, + "absent" => counts.absent += 1, + "late" => counts.late += 1, + // `AttendanceStatus` admits exactly four values. + _ => counts.excused += 1, + } + } + counts.rate = attendance_rate(counts.present, counts.absent, counts.late); + counts + } +} + +/// `(present + late) / (present + absent + late)`; `None` when the denominator +/// is zero. +fn attendance_rate(present: u64, absent: u64, late: u64) -> Option { + let counted = present + absent + late; + (counted > 0).then(|| (present + late) as f64 / counted as f64) +} + +/// A user's roll-call tallies in one course. +#[derive(Serialize, ToSchema)] +struct CourseAttendance { + course: CourseResponse, + counts: StatusCounts, +} + +/// A user's full attendance report: generic events, lesson roll call overall, +/// and the roll call broken down per course. +#[derive(Serialize, ToSchema)] +struct AttendanceReport { + /// The user's id. + user: String, + /// Tallies over event attendance (`/events/{id}/attendance`). + events: StatusCounts, + /// Tallies over every lesson roll-call row, all courses combined. + sessions: StatusCounts, + /// The session tallies split per course. Courses appear as long as the + /// user has roll-call rows in them — attendance is a historical record, + /// so unenrolling never hides an absence. + courses: Vec, +} + +/// Assemble the report: tally the user's event rows, then their session rows +/// grouped by the (denormalized) course reference. +async fn build_report(user: &UserId, db: &Database) -> Result { + let events = Attendance::list_for_user(user, db).await?; + let sessions = SessionAttendance::list_for_user(user, db).await?; + + // Group session rows by course, preserving first-seen (newest-first) order. + let mut course_ids: Vec = Vec::new(); + let mut by_course: HashMap> = HashMap::new(); + for row in &sessions { + let key = row.get_course().key().to_string(); + if !by_course.contains_key(&key) { + course_ids.push(row.get_course().clone()); + } + by_course.entry(key).or_default().push(row); + } + + let courses = Course::list_by_ids(&course_ids, db).await?; + let course_by_key: HashMap<&str, &Course> = + courses.iter().map(|c| (c.get_id().key(), c)).collect(); + + let mut blocks = Vec::with_capacity(course_ids.len()); + for course_id in &course_ids { + // A row whose course is gone cannot happen given the delete cascade — + // skip defensively rather than fabricate a course block. + let Some(course) = course_by_key.get(course_id.key()) else { + continue; + }; + let rows = &by_course[course_id.key()]; + blocks.push(CourseAttendance { + course: CourseResponse::new(course), + counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), + }); + } + + Ok(AttendanceReport { + user: user.key().to_string(), + events: StatusCounts::tally(events.iter().map(|a| a.get_status())), + sessions: StatusCounts::tally(sessions.iter().map(|a| a.get_status())), + courses: blocks, + }) +} + +/// The current user's attendance report: event tallies, lesson roll-call +/// tallies, and a per-course breakdown with attendance rates. +#[utoipa::path( + get, + path = "/me", + tag = "attendance", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's attendance report", body = AttendanceReport), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_report( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + Ok(Json(build_report(user.get_id(), &st.db).await?)) +} + +/// Any user's attendance report. Requires teacher+. +#[utoipa::path( + get, + path = "/{user}", + tag = "attendance", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id")), + responses( + (status = 200, description = "The user's attendance report", body = AttendanceReport), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn user_report( + State(st): State, + _teacher: RequireTeacher, + Path(user): Path, +) -> Result, AppError> { + let target = UserId::from_key(&user); + // User must exist — a missing user is a 404, not an empty report. + User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + Ok(Json(build_report(&target, &st.db).await?)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn rate_counts_late_as_attended_and_ignores_excused() { + // 3 present + 1 late out of 5 unexcused rows. + assert_eq!(attendance_rate(3, 1, 1), Some(0.8)); + // Excused rows are outside both sides of the division. + assert_eq!(attendance_rate(0, 0, 0), None); + assert_eq!(attendance_rate(2, 0, 0), Some(1.0)); + assert_eq!(attendance_rate(0, 2, 0), Some(0.0)); + } + + #[tokio::test] + async fn tally_buckets_every_status() { + let statuses: Vec = ["present", "present", "late", "absent", "excused"] + .iter() + .map(|s| AttendanceStatus::try_new(s).unwrap()) + .collect(); + let counts = StatusCounts::tally(statuses.iter()); + assert_eq!(counts.present, 2); + assert_eq!(counts.late, 1); + assert_eq!(counts.absent, 1); + assert_eq!(counts.excused, 1); + assert_eq!(counts.total, 5); + // (2 + 1) / (2 + 1 + 1) + assert_eq!(counts.rate, Some(0.75)); + } +} diff --git a/src/web/courses.rs b/src/web/courses.rs index 1a14f87..2984201 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -9,6 +9,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; +use crate::domain::course_session::{CourseSession, SessionTopic}; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, @@ -19,7 +20,11 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map}; +use super::sessions::resolve_session_teacher; +use super::{ + CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse, + check_time_range, person_map, +}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -29,6 +34,7 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(enroll, list_roster)) .routes(routes!(unenroll)) .routes(routes!(create_exam_in_course, list_course_exams)) + .routes(routes!(create_session_in_course, list_course_sessions)) } #[derive(Deserialize, ToSchema)] @@ -485,3 +491,107 @@ async fn list_course_exams( let exams = Exam::list_for_course(&course_id, &st.db).await?; Ok(Json(exams.iter().map(ExamResponse::new).collect())) } + +// ---- sessions in a course -------------------------------------------------- + +#[derive(Deserialize, ToSchema)] +struct CreateSessionInCourse { + /// What the lesson covers. Optional. + #[schema(example = "Limits and continuity")] + topic: Option, + /// Who teaches the session. Defaults to the caller; must hold the + /// `teacher` role or higher. + teacher_id: Option, + /// Lesson start, UTC unix-milliseconds. + #[schema(example = 1_752_275_000_000_i64)] + starts_at: i64, + /// Lesson end, UTC unix-milliseconds. Optional (open-ended). + ends_at: Option, +} + +/// Create a lesson session inside a course. Requires teacher+ and course +/// management rights. The session's teacher defaults to the caller. +#[utoipa::path( + post, + path = "/{id}/sessions", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + request_body = CreateSessionInCourse, + responses( + (status = 201, description = "Session created", body = SessionResponse), + (status = 400, description = "Invalid fields, time range, or teacher", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn create_session_in_course( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result<(StatusCode, Json), AppError> { + let course = Course::read(&CourseId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can add sessions to this course", + )); + } + + let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; + let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; + let starts_at = Timestamp::from_millis(req.starts_at); + let ends_at = req.ends_at.map(Timestamp::from_millis); + check_time_range(Some(starts_at), ends_at)?; + + let session = CourseSession::create( + course.get_id(), + teacher.get_id(), + topic, + starts_at, + ends_at, + &st.db, + ) + .await?; + let people = PersonRef::map_of(&[&teacher]); + Ok(( + StatusCode::CREATED, + Json(SessionResponse::new(&session, &people)), + )) +} + +/// List a course's lesson sessions, most recent first. +#[utoipa::path( + get, + path = "/{id}/sessions", + tag = "courses", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Course id")), + responses( + (status = 200, description = "The course's sessions", body = [SessionResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Course not found", body = ErrorResponse), + ), +)] +async fn list_course_sessions( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let course_id = CourseId::from_key(&id); + // Course must exist — a missing course is a 404, not an empty list. + Course::read(&course_id, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let sessions = CourseSession::list_for_course(&course_id, &st.db).await?; + let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; + Ok(Json( + sessions + .iter() + .map(|s| SessionResponse::new(s, &people)) + .collect(), + )) +} diff --git a/src/web/dto.rs b/src/web/dto.rs index 14465d0..3889066 100644 --- a/src/web/dto.rs +++ b/src/web/dto.rs @@ -7,6 +7,7 @@ use utoipa::ToSchema; use crate::database::Database; use crate::domain::course::Course; +use crate::domain::course_session::CourseSession; use crate::domain::exam::Exam; use crate::domain::role::Role as DomainRole; use crate::domain::user::{User, UserId}; @@ -162,6 +163,35 @@ impl CourseResponse { } } +/// Public shape of a course session (one lesson). Shared by `courses` +/// (in-course creation and listing) and `sessions` (CRUD + roll call). +#[derive(Serialize, ToSchema)] +pub struct SessionResponse { + pub id: String, + /// The course this lesson belongs to. + pub course: String, + /// Who teaches this session. + pub teacher: PersonRef, + pub topic: String, + /// Lesson start, UTC unix-milliseconds. + pub starts_at: i64, + /// Lesson end, UTC unix-milliseconds; `null` when open-ended. + pub ends_at: Option, +} + +impl SessionResponse { + pub fn new(session: &CourseSession, people: &HashMap) -> Self { + Self { + id: session.get_id().key().to_string(), + course: session.get_course().key().to_string(), + teacher: PersonRef::resolve(people, session.get_teacher()), + topic: session.get_topic().as_str().to_string(), + starts_at: session.get_starts_at().as_millis(), + ends_at: session.get_ends_at().map(|t| t.as_millis()), + } + } +} + /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` /// (in-course creation and listing). The schedule fields are all `null` for an /// unscheduled (offline-graded) exam; see the create/update endpoints for the diff --git a/src/web/events.rs b/src/web/events.rs index cebc0b4..8aca29c 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -16,7 +16,7 @@ use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; -use super::{CurrentUser, PersonRef, RequireTeacher, person_map, set_or_clear}; +use super::{CurrentUser, PersonRef, RequireTeacher, check_time_range, person_map, set_or_clear}; pub fn routes() -> OpenApiRouter { OpenApiRouter::new() @@ -92,22 +92,6 @@ fn can_manage(event: &Event, user: &User) -> bool { event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) } -/// If both ends are present, `ends_at` must not precede `starts_at`. -fn check_time_range( - starts_at: Option, - ends_at: Option, -) -> Result<(), AppError> { - if let (Some(starts), Some(ends)) = (starts_at, ends_at) - && ends < starts - { - return Err(AppError::Validation(ValidationError::Invalid { - field: "ends_at", - reason: "must be at or after starts_at", - })); - } - Ok(()) -} - #[derive(Serialize, ToSchema)] struct AttendanceResponse { id: String, diff --git a/src/web/extractor.rs b/src/web/extractor.rs index 7cfca48..b1e2b05 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -74,6 +74,26 @@ where } } +/// Like [`CurrentUser`], but also requires at least the `manager` role. +/// Authenticated-but-under-privileged callers get `403`. +pub struct RequireManager(pub User); + +impl FromRequestParts for RequireManager +where + S: Send + Sync, + AppState: FromRef, +{ + type Rejection = AppError; + + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { + let user = authed_user(parts, state).await?; + if !user.get_role().at_least(Role::Manager) { + return Err(AppError::Forbidden("requires manager role or higher")); + } + Ok(RequireManager(user)) + } +} + /// Like [`CurrentUser`], but also requires the `admin` role. Anyone below admin /// gets `403`. pub struct RequireAdmin(pub User); diff --git a/src/web/mod.rs b/src/web/mod.rs index 1698587..7e0c12a 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -3,6 +3,7 @@ //! validated domain newtypes before doing anything. Role-gated endpoints take a //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. +pub mod attendance; pub mod auth; pub mod courses; pub mod events; @@ -10,16 +11,38 @@ pub mod exam_ws; pub mod exams; pub mod marks; pub mod notes; +pub mod sessions; pub mod users; +pub mod work; mod dto; mod extractor; -pub use dto::{CourseResponse, ExamResponse, PersonRef, UserResponse, person_map}; -pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; +pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map}; +pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; use serde::{Deserialize, Deserializer}; +use crate::domain::timestamp::Timestamp; +use crate::error::{AppError, ValidationError}; + +/// If both ends are present, `ends_at` must not precede `starts_at`. Shared by +/// everything that carries a time range (events, course sessions). +pub(crate) fn check_time_range( + starts_at: Option, + ends_at: Option, +) -> Result<(), AppError> { + if let (Some(starts), Some(ends)) = (starts_at, ends_at) + && ends < starts + { + return Err(AppError::Validation(ValidationError::Invalid { + field: "ends_at", + reason: "must be at or after starts_at", + })); + } + Ok(()) +} + /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the /// stored value); `null` or a value lands here as `Some(inner)` (clear or set). diff --git a/src/web/sessions.rs b/src/web/sessions.rs new file mode 100644 index 0000000..377b04e --- /dev/null +++ b/src/web/sessions.rs @@ -0,0 +1,395 @@ +use std::collections::HashMap; + +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::database::Database; +use crate::domain::attendance::AttendanceStatus; +use crate::domain::course::Course; +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; +use crate::domain::enrollment::Enrollment; +use crate::domain::role::Role; +use crate::domain::session_attendance::SessionAttendance; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::courses::can_manage_course; +use super::{ + CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_time_range, person_map, + set_or_clear, +}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(get_session, update_session, delete_session)) + .routes(routes!(mark_roll_call, list_roll_call)) + .routes(routes!(remove_roll_call)) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateSession { + topic: Option, + /// Reassign the session's teacher. Omit to keep; must be teacher+. + teacher_id: Option, + /// Unix-millisecond timestamp. Omit to keep the current value. + starts_at: Option, + /// Unix-millisecond timestamp. Omit to keep the current value; send `null` + /// to clear it. + #[serde(default, deserialize_with = "set_or_clear")] + #[schema(value_type = Option)] + ends_at: Option>, +} + +#[derive(Deserialize, ToSchema)] +struct MarkRollCall { + /// One of the accepted attendance statuses (e.g. `present`, `absent`). + #[schema(example = "present")] + status: String, + /// Whose roll-call state to record: an enrolled student, or the session's + /// teacher (the latter requires manager+). + user_id: String, +} + +#[derive(Serialize, ToSchema)] +struct SessionAttendanceResponse { + id: String, + session: String, + course: String, + /// Whose attendance this row records. + user: PersonRef, + status: String, + /// Who recorded it. + marked_by: PersonRef, +} + +impl SessionAttendanceResponse { + fn new(attendance: &SessionAttendance, people: &HashMap) -> Self { + Self { + id: attendance.get_id().key().to_string(), + session: attendance.get_session().key().to_string(), + course: attendance.get_course().key().to_string(), + user: PersonRef::resolve(people, attendance.get_user()), + status: attendance.get_status().as_str().to_string(), + marked_by: PersonRef::resolve(people, attendance.get_marked_by()), + } + } +} + +/// Resolve who a session's teacher should be: the caller when `teacher_id` is +/// omitted (or names them), otherwise the referenced user — who must exist and +/// hold the `teacher` role or higher (a student cannot teach a lesson). +pub(crate) async fn resolve_session_teacher( + teacher_id: Option<&str>, + caller: &User, + db: &Database, +) -> Result { + let target = match teacher_id { + None => return Ok(caller.clone()), + Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), + Some(key) => UserId::from_key(key), + }; + let Some(user) = User::read(&target, db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "session teacher does not exist", + })); + }; + if !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "session teacher must hold the teacher role or higher", + })); + } + Ok(user) +} + +/// Load a session and its course together; a session whose course is gone +/// cannot happen given the delete cascade, so both misses are plain 404s. +async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, Course), AppError> { + let session = CourseSession::read(&CourseSessionId::from_key(id), db) + .await? + .ok_or(AppError::NotFound)?; + let course = Course::read(session.get_course(), db) + .await? + .ok_or(AppError::NotFound)?; + Ok((session, course)) +} + +/// Who may take (or amend) a session's roll call: the session's own teacher, +/// or anyone with course-management rights (creator / manager+). +fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool { + session.is_teacher(user.get_id()) || can_manage_course(course, user) +} + +// ---- sessions ------------------------------------------------------------- + +/// Fetch a single session by id. +#[utoipa::path( + get, + path = "/{id}", + tag = "sessions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Session id")), + responses( + (status = 200, description = "The session", body = SessionResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn get_session( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result, AppError> { + let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let people = person_map([session.get_teacher().clone()], &st.db).await?; + Ok(Json(SessionResponse::new(&session, &people))) +} + +/// Update a session. Requires teacher+ with course-management rights. Omitted +/// fields keep their value; an explicit `null` clears `ends_at`. +#[utoipa::path( + patch, + path = "/{id}", + tag = "sessions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Session id")), + request_body = UpdateSession, + responses( + (status = 200, description = "Updated session", body = SessionResponse), + (status = 400, description = "Invalid fields, time range, or teacher", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn update_session( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let (session, course) = session_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can edit this session", + )); + } + + let topic = match req.topic { + Some(ref topic) => SessionTopic::try_new(topic)?, + None => session.get_topic().clone(), + }; + let teacher = match req.teacher_id { + Some(ref key) => resolve_session_teacher(Some(key), &user, &st.db) + .await? + .get_id() + .clone(), + None => session.get_teacher().clone(), + }; + let starts_at = match req.starts_at { + Some(millis) => Timestamp::from_millis(millis), + None => session.get_starts_at(), + }; + // A provided value sets the field, an explicit `null` clears it, and an + // omitted one keeps the current value. + let ends_at = match req.ends_at { + Some(update) => update.map(Timestamp::from_millis), + None => session.get_ends_at(), + }; + check_time_range(Some(starts_at), ends_at)?; + + let updated = session + .update(teacher, topic, starts_at, ends_at, &st.db) + .await?; + let people = person_map([updated.get_teacher().clone()], &st.db).await?; + Ok(Json(SessionResponse::new(&updated, &people))) +} + +/// Delete a session and its roll-call rows. Requires teacher+ with +/// course-management rights. +#[utoipa::path( + delete, + path = "/{id}", + tag = "sessions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Session id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_session( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, +) -> Result { + let (session, course) = session_with_course(&id, &st.db).await?; + if !can_manage_course(&course, &user) { + return Err(AppError::Forbidden( + "only the course creator or a manager/admin can delete this session", + )); + } + session.delete(&st.db).await?; + Ok(StatusCode::NO_CONTENT) +} + +// ---- roll call -------------------------------------------------------------- + +/// Record a user's roll-call state for a session. The session's teacher or a +/// course manager marks **enrolled students**; marking the **session's +/// teacher** requires manager+ (staff presence is management's call, so a +/// teacher can't mark themselves present). Students never self-mark a lesson. +#[utoipa::path( + post, + path = "/{id}/attendance", + tag = "sessions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Session id")), + request_body = MarkRollCall, + responses( + (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse), + (status = 400, description = "Invalid status, unknown user, or target not on the roster", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), + (status = 404, description = "Session not found", body = ErrorResponse), + ), +)] +async fn mark_roll_call( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let (session, course) = session_with_course(&id, &st.db).await?; + if !can_roll_call(&session, &course, &user) { + return Err(AppError::Forbidden( + "only the session's teacher or a course manager can take roll call", + )); + } + + let status = AttendanceStatus::try_new(&req.status)?; + let target = UserId::from_key(&req.user_id); + + // Target user must exist. + let Some(target_user) = User::read(&target, &st.db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user does not exist", + })); + }; + + if session.is_teacher(&target) { + // The session teacher's own presence is recorded by management. + if !user.get_role().at_least(Role::Manager) { + return Err(AppError::Forbidden( + "marking the session's teacher requires manager role or higher", + )); + } + } else if Enrollment::read_for_user(session.get_course(), &target, &st.db) + .await? + .is_none() + { + // Everyone else on a lesson's roster comes from the enrollment list. + return Err(AppError::Validation(ValidationError::Invalid { + field: "user_id", + reason: "target user is not enrolled in this course", + })); + } + + let attendance = + SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?; + let people = PersonRef::map_of(&[&target_user, &user]); + Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) +} + +/// List a session's roll call. +#[utoipa::path( + get, + path = "/{id}/attendance", + tag = "sessions", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Session id")), + responses( + (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 404, description = "Session not found", body = ErrorResponse), + ), +)] +async fn list_roll_call( + State(st): State, + _user: CurrentUser, + Path(id): Path, +) -> Result>, AppError> { + let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; + let people = person_map( + roster + .iter() + .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), + &st.db, + ) + .await?; + Ok(Json( + roster + .iter() + .map(|a| SessionAttendanceResponse::new(a, &people)) + .collect(), + )) +} + +/// Remove a user's roll-call row from a session. Same rights as marking: +/// session teacher or course manager for students, manager+ for the session +/// teacher's own row. +#[utoipa::path( + delete, + path = "/{id}/attendance/{user}", + tag = "sessions", + security(("session_cookie" = [])), + params( + ("id" = String, Path, description = "Session id"), + ("user" = String, Path, description = "User id"), + ), + responses( + (status = 204, description = "Removed"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Not the session teacher or a course manager; or removing the teacher's row without manager+", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn remove_roll_call( + State(st): State, + RequireTeacher(user): RequireTeacher, + Path((id, target)): Path<(String, String)>, +) -> Result { + let (session, course) = session_with_course(&id, &st.db).await?; + if !can_roll_call(&session, &course, &user) { + return Err(AppError::Forbidden( + "only the session's teacher or a course manager can take roll call", + )); + } + let target = UserId::from_key(&target); + if session.is_teacher(&target) && !user.get_role().at_least(Role::Manager) { + return Err(AppError::Forbidden( + "removing the session teacher's row requires manager role or higher", + )); + } + let removed = SessionAttendance::remove(session.get_id(), &target, &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +} diff --git a/src/web/work.rs b/src/web/work.rs new file mode 100644 index 0000000..948741e --- /dev/null +++ b/src/web/work.rs @@ -0,0 +1,230 @@ +use axum::Json; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::domain::work_entry::{WorkEntry, WorkEntryId}; +use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::state::AppState; + +use super::{RequireManager, RequireTeacher}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(check_in)) + .routes(routes!(check_out)) + .routes(routes!(my_work)) + .routes(routes!(user_work)) + .routes(routes!(update_entry, delete_entry)) +} + +#[derive(Deserialize, ToSchema)] +struct UpdateWorkEntry { + /// Corrected check-in, UTC unix-milliseconds. Omit to keep. + check_in: Option, + /// Corrected check-out, UTC unix-milliseconds. Omit to keep. + check_out: Option, +} + +#[derive(Serialize, ToSchema)] +struct WorkEntryResponse { + id: String, + /// The staff member this stint belongs to. + user: String, + /// Stint start, UTC unix-milliseconds (server-stamped). + check_in: i64, + /// Stint end, UTC unix-milliseconds; `null` while still checked in. + check_out: Option, + /// `check_out - check_in`; `null` while still checked in. + duration_ms: Option, +} + +impl WorkEntryResponse { + fn new(entry: &WorkEntry) -> Self { + let check_in = entry.get_check_in().as_millis(); + let check_out = entry.get_check_out().map(|t| t.as_millis()); + Self { + id: entry.get_id().key().to_string(), + user: entry.get_user().key().to_string(), + check_in, + check_out, + duration_ms: check_out.map(|out| out - check_in), + } + } +} + +/// Check in for work. Requires teacher+ (staff). The instant is stamped by the +/// server clock — clients never supply it. `409` while already checked in. +#[utoipa::path( + post, + path = "/check-in", + tag = "work", + security(("session_cookie" = [])), + responses( + (status = 201, description = "Checked in — the open stint", body = WorkEntryResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 409, description = "Already checked in", body = ErrorResponse), + ), +)] +async fn check_in( + State(st): State, + RequireTeacher(user): RequireTeacher, +) -> Result<(StatusCode, Json), AppError> { + let entry = WorkEntry::check_in(user.get_id(), &st.db).await?; + Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry)))) +} + +/// Check out of work, closing the open stint. Requires teacher+ (staff). The +/// instant is stamped by the server clock. `409` when not checked in. +#[utoipa::path( + post, + path = "/check-out", + tag = "work", + security(("session_cookie" = [])), + responses( + (status = 200, description = "Checked out — the closed stint", body = WorkEntryResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 409, description = "Not checked in", body = ErrorResponse), + ), +)] +async fn check_out( + State(st): State, + RequireTeacher(user): RequireTeacher, +) -> Result, AppError> { + let entry = WorkEntry::check_out(user.get_id(), &st.db).await?; + Ok(Json(WorkEntryResponse::new(&entry))) +} + +/// The caller's own work log, newest first — the open stint (if any) included +/// (`check_out: null`). Requires teacher+ (staff). +#[utoipa::path( + get, + path = "/me", + tag = "work", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The caller's work log", body = [WorkEntryResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + ), +)] +async fn my_work( + State(st): State, + RequireTeacher(user): RequireTeacher, +) -> Result>, AppError> { + let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?; + Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) +} + +/// A staff member's work log. Requires manager+. +#[utoipa::path( + get, + path = "/{user}", + tag = "work", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id")), + responses( + (status = 200, description = "The user's work log", body = [WorkEntryResponse]), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn user_work( + State(st): State, + _manager: RequireManager, + Path(user): Path, +) -> Result>, AppError> { + let target = UserId::from_key(&user); + // User must exist — a missing user is a 404, not an empty log. + User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let entries = WorkEntry::list_for_user(&target, &st.db).await?; + Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) +} + +/// Correct a closed stint's instants. Requires manager+. An open stint can't +/// be corrected (`409`) — it has no end yet; check out first (or delete it). +#[utoipa::path( + patch, + path = "/entries/{id}", + tag = "work", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Work entry id")), + request_body = UpdateWorkEntry, + responses( + (status = 200, description = "Corrected entry", body = WorkEntryResponse), + (status = 400, description = "check_out precedes check_in", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "Entry is still open", body = ErrorResponse), + ), +)] +async fn update_entry( + State(st): State, + _manager: RequireManager, + Path(id): Path, + Json(req): Json, +) -> Result, AppError> { + let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let Some(current_out) = entry.get_check_out() else { + return Err(AppError::Conflict( + "entry is still open — check out first, or delete it", + )); + }; + + let check_in = req + .check_in + .map(Timestamp::from_millis) + .unwrap_or_else(|| entry.get_check_in()); + let check_out = req + .check_out + .map(Timestamp::from_millis) + .unwrap_or(current_out); + if check_out < check_in { + return Err(AppError::Validation(ValidationError::Invalid { + field: "check_out", + reason: "must be at or after check_in", + })); + } + + let updated = entry.update(check_in, check_out, &st.db).await?; + Ok(Json(WorkEntryResponse::new(&updated))) +} + +/// Delete a work entry (open or closed). Requires manager+. +#[utoipa::path( + delete, + path = "/entries/{id}", + tag = "work", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Work entry id")), + responses( + (status = 204, description = "Deleted"), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn delete_entry( + State(st): State, + _manager: RequireManager, + Path(id): Path, +) -> Result { + let removed = WorkEntry::remove(&WorkEntryId::from_key(&id), &st.db).await?; + if removed.is_none() { + return Err(AppError::NotFound); + } + Ok(StatusCode::NO_CONTENT) +}