Course sessions, roll call, work log, reports
Browse files at this commit5b6aac1695d4720c60e99d74f68169efcf1d4d60Parent: 52f608d- feat
- course sessions, roll call, work log, reports
17 changed files +1606 -24
- src/constant.rs +2 -0
- src/database.rs +29 -0
- src/domain/attendance.rs +11 -0
- src/domain/course.rs +20 -3
- src/domain/course_session.rs +175 -0
- src/domain/mod.rs +3 -0
- src/domain/session_attendance.rs +141 -0
- src/domain/work_entry.rs +199 -0
- src/lib.rs +7 -1
- src/web/attendance.rs +207 -0
- src/web/courses.rs +111 -1
- src/web/dto.rs +30 -0
- src/web/events.rs +1 -17
- src/web/extractor.rs +20 -0
- src/web/mod.rs +25 -2
- src/web/sessions.rs +395 -0
- src/web/work.rs +230 -0
src/constant.rsmodified+2 -0
| @@ -30,6 +30,8 @@ pub const MAX_COURSE_DESCRIPTION_LEN: usize = 2_000; | |||
| 30 | /// The only accepted attendance states. | 30 | /// The only accepted attendance states. |
| 31 | pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; | 31 | pub const ATTENDANCE_STATUSES: [&str; 4] = ["present", "absent", "late", "excused"]; |
| 32 | 32 | ||
| 33 | +pub const MAX_SESSION_TOPIC_LEN: usize = 200; | ||
| 34 | + | ||
| 33 | /// The only accepted exam kinds. Informational metadata only — `weight` drives | 35 | /// The only accepted exam kinds. Informational metadata only — `weight` drives |
| 34 | /// the course average. | 36 | /// the course average. |
| 35 | pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; | 37 | pub const EXAM_KINDS: [&str; 6] = ["homework", "quiz", "midterm", "final", "project", "oral"]; |
src/database.rsmodified+29 -0
| @@ -20,6 +20,9 @@ pub const EXAM_QUESTION_TABLE: &str = "exam_question"; | |||
| 20 | pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; | 20 | pub const EXAM_ANSWER_TABLE: &str = "exam_answer"; |
| 21 | pub const COURSE_TABLE: &str = "course"; | 21 | pub const COURSE_TABLE: &str = "course"; |
| 22 | pub const ENROLLMENT_TABLE: &str = "enrollment"; | 22 | pub const ENROLLMENT_TABLE: &str = "enrollment"; |
| 23 | +pub const COURSE_SESSION_TABLE: &str = "course_session"; | ||
| 24 | +pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; | ||
| 25 | +pub const WORK_ENTRY_TABLE: &str = "work_entry"; | ||
| 23 | 26 | ||
| 24 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. | 27 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 25 | /// Idempotent — safe to run on every boot. | 28 | /// Idempotent — safe to run on every boot. |
| @@ -62,6 +65,7 @@ const MIGRATION: &str = " | |||
| 62 | DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; | 65 | DEFINE FIELD IF NOT EXISTS status ON attendance TYPE string; |
| 63 | DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>; | 66 | DEFINE FIELD IF NOT EXISTS marked_by ON attendance TYPE record<user>; |
| 64 | DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; | 67 | DEFINE INDEX IF NOT EXISTS attendance_event_user ON attendance FIELDS event, user UNIQUE; |
| 68 | + DEFINE INDEX IF NOT EXISTS attendance_user ON attendance FIELDS user; | ||
| 65 | 69 | ||
| 66 | DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; | 70 | DEFINE TABLE IF NOT EXISTS course SCHEMAFULL; |
| 67 | DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>; | 71 | DEFINE FIELD IF NOT EXISTS creator ON course TYPE record<user>; |
| @@ -75,6 +79,31 @@ const MIGRATION: &str = " | |||
| 75 | DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; | 79 | DEFINE INDEX IF NOT EXISTS enrollment_course_user ON enrollment FIELDS course, user UNIQUE; |
| 76 | DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; | 80 | DEFINE INDEX IF NOT EXISTS enrollment_user ON enrollment FIELDS user; |
| 77 | 81 | ||
| 82 | + DEFINE TABLE IF NOT EXISTS course_session SCHEMAFULL; | ||
| 83 | + DEFINE FIELD IF NOT EXISTS course ON course_session TYPE record<course>; | ||
| 84 | + DEFINE FIELD IF NOT EXISTS teacher ON course_session TYPE record<user>; | ||
| 85 | + DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; | ||
| 86 | + DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; | ||
| 87 | + DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>; | ||
| 88 | + DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; | ||
| 89 | + | ||
| 90 | + DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; | ||
| 91 | + DEFINE FIELD IF NOT EXISTS session ON session_attendance TYPE record<course_session>; | ||
| 92 | + DEFINE FIELD IF NOT EXISTS course ON session_attendance TYPE record<course>; | ||
| 93 | + DEFINE FIELD IF NOT EXISTS user ON session_attendance TYPE record<user>; | ||
| 94 | + DEFINE FIELD IF NOT EXISTS status ON session_attendance TYPE string; | ||
| 95 | + DEFINE FIELD IF NOT EXISTS marked_by ON session_attendance TYPE record<user>; | ||
| 96 | + DEFINE INDEX IF NOT EXISTS session_attendance_session_user ON session_attendance FIELDS session, user UNIQUE; | ||
| 97 | + DEFINE INDEX IF NOT EXISTS session_attendance_session ON session_attendance FIELDS session; | ||
| 98 | + DEFINE INDEX IF NOT EXISTS session_attendance_user ON session_attendance FIELDS user; | ||
| 99 | + DEFINE INDEX IF NOT EXISTS session_attendance_course ON session_attendance FIELDS course; | ||
| 100 | + | ||
| 101 | + DEFINE TABLE IF NOT EXISTS work_entry SCHEMAFULL; | ||
| 102 | + DEFINE FIELD IF NOT EXISTS user ON work_entry TYPE record<user>; | ||
| 103 | + DEFINE FIELD IF NOT EXISTS check_in ON work_entry TYPE int; | ||
| 104 | + DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>; | ||
| 105 | + DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; | ||
| 106 | + | ||
| 78 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; | 107 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; |
| 79 | DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; | 108 | DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; |
| 80 | DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>; | 109 | DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>; |
src/domain/attendance.rsmodified+11 -0
| @@ -115,6 +115,17 @@ impl Attendance { | |||
| 115 | Ok(result.take::<Vec<Attendance>>(0)?) | 115 | Ok(result.take::<Vec<Attendance>>(0)?) |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | + /// Every event-attendance row recorded for `user` — the events half of the | ||
| 119 | + /// attendance report. | ||
| 120 | + pub async fn list_for_user(user: &UserId, db: &Database) -> Result<Vec<Attendance>, AppError> { | ||
| 121 | + let mut result = db | ||
| 122 | + .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC") | ||
| 123 | + .bind(("usr", user.record())) | ||
| 124 | + .await? | ||
| 125 | + .check()?; | ||
| 126 | + Ok(result.take::<Vec<Attendance>>(0)?) | ||
| 127 | + } | ||
| 128 | + | ||
| 118 | pub async fn remove( | 129 | pub async fn remove( |
| 119 | event: &EventId, | 130 | event: &EventId, |
| 120 | user: &UserId, | 131 | user: &UserId, |
src/domain/course.rsmodified+20 -3
| @@ -133,6 +133,21 @@ impl Course { | |||
| 133 | Ok(result.take::<Vec<Course>>(0)?) | 133 | Ok(result.take::<Vec<Course>>(0)?) |
| 134 | } | 134 | } |
| 135 | 135 | ||
| 136 | + /// Load every course behind `ids` (one query) — the join half of the | ||
| 137 | + /// attendance report's per-course blocks. | ||
| 138 | + pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 139 | + if ids.is_empty() { | ||
| 140 | + return Ok(Vec::new()); | ||
| 141 | + } | ||
| 142 | + let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect(); | ||
| 143 | + let mut result = db | ||
| 144 | + .query("SELECT * FROM course WHERE id IN $ids") | ||
| 145 | + .bind(("ids", records)) | ||
| 146 | + .await? | ||
| 147 | + .check()?; | ||
| 148 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 149 | + } | ||
| 150 | + | ||
| 136 | pub async fn update( | 151 | pub async fn update( |
| 137 | mut self, | 152 | mut self, |
| 138 | title: CourseTitle, | 153 | title: CourseTitle, |
| @@ -146,9 +161,9 @@ impl Course { | |||
| 146 | } | 161 | } |
| 147 | 162 | ||
| 148 | /// Delete the course and cascade-remove everything inside it: results and | 163 | /// Delete the course and cascade-remove everything inside it: results and |
| 149 | - /// attempts of its exams, its enrollments, and the exams themselves. The | 164 | + /// attempts of its exams, its enrollments, its sessions with their roll |
| 150 | - /// children go in one transaction so a crash can't leave an exam pointing | 165 | + /// call, and the exams themselves. The children go in one transaction so a |
| 151 | - /// at a deleted course. | 166 | + /// crash can't leave an exam pointing at a deleted course. |
| 152 | pub async fn delete(self, db: &Database) -> Result<Course, AppError> { | 167 | pub async fn delete(self, db: &Database) -> Result<Course, AppError> { |
| 153 | db.query( | 168 | db.query( |
| 154 | "BEGIN TRANSACTION; | 169 | "BEGIN TRANSACTION; |
| @@ -156,6 +171,8 @@ impl Course { | |||
| 156 | DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | 171 | DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); |
| 157 | DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | 172 | DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); |
| 158 | DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | 173 | DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); |
| 174 | + DELETE session_attendance WHERE course = $course; | ||
| 175 | + DELETE course_session WHERE course = $course; | ||
| 159 | DELETE enrollment WHERE course = $course; | 176 | DELETE enrollment WHERE course = $course; |
| 160 | DELETE exam WHERE course = $course; | 177 | DELETE exam WHERE course = $course; |
| 161 | COMMIT TRANSACTION;", | 178 | COMMIT TRANSACTION;", |
src/domain/course_session.rsadded+175 -0
| @@ -0,0 +1,175 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::constant::MAX_SESSION_TOPIC_LEN; | ||
| 5 | +use crate::database::{COURSE_SESSION_TABLE, Database}; | ||
| 6 | +use crate::domain::course::CourseId; | ||
| 7 | +use crate::domain::timestamp::Timestamp; | ||
| 8 | +use crate::domain::user::UserId; | ||
| 9 | +use crate::error::{AppError, ValidationError}; | ||
| 10 | +use crate::validate::validate_optional; | ||
| 11 | + | ||
| 12 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 13 | +pub struct CourseSessionId(RecordId); | ||
| 14 | + | ||
| 15 | +impl CourseSessionId { | ||
| 16 | + pub fn generate() -> Self { | ||
| 17 | + Self(RecordId::new(COURSE_SESSION_TABLE, Ulid::new().to_string())) | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + pub fn from_key(key: &str) -> Self { | ||
| 21 | + Self(RecordId::new(COURSE_SESSION_TABLE, key)) | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + pub fn record(&self) -> RecordId { | ||
| 25 | + self.0.clone() | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + pub fn key(&self) -> &str { | ||
| 29 | + match &self.0.key { | ||
| 30 | + RecordIdKey::String(key) => key, | ||
| 31 | + _ => "", | ||
| 32 | + } | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 37 | +pub struct SessionTopic(String); | ||
| 38 | + | ||
| 39 | +impl SessionTopic { | ||
| 40 | + pub fn try_new(value: &str) -> Result<Self, ValidationError> { | ||
| 41 | + validate_optional("topic", value, MAX_SESSION_TOPIC_LEN)?; | ||
| 42 | + Ok(Self(value.to_string())) | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + pub fn as_str(&self) -> &str { | ||
| 46 | + &self.0 | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// One scheduled lesson of a course: the unit roll call is taken on. Unlike a | ||
| 51 | +/// generic event, a session always has a start instant and belongs to a course, | ||
| 52 | +/// so its roster is the course's enrollment plus the assigned teacher. | ||
| 53 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 54 | +pub struct CourseSession { | ||
| 55 | + id: CourseSessionId, | ||
| 56 | + course: CourseId, | ||
| 57 | + /// Who teaches this session. Must hold the `teacher` role or higher — | ||
| 58 | + /// enforced at the web layer, where the target user row is at hand. | ||
| 59 | + teacher: UserId, | ||
| 60 | + topic: SessionTopic, | ||
| 61 | + starts_at: Timestamp, | ||
| 62 | + ends_at: Option<Timestamp>, | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +impl CourseSession { | ||
| 66 | + pub fn get_id(&self) -> &CourseSessionId { | ||
| 67 | + &self.id | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + pub fn get_course(&self) -> &CourseId { | ||
| 71 | + &self.course | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + pub fn get_teacher(&self) -> &UserId { | ||
| 75 | + &self.teacher | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + pub fn get_topic(&self) -> &SessionTopic { | ||
| 79 | + &self.topic | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + pub fn get_starts_at(&self) -> Timestamp { | ||
| 83 | + self.starts_at | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + pub fn get_ends_at(&self) -> Option<Timestamp> { | ||
| 87 | + self.ends_at | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + pub fn is_teacher(&self, user: &UserId) -> bool { | ||
| 91 | + &self.teacher == user | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + pub async fn create( | ||
| 95 | + course: &CourseId, | ||
| 96 | + teacher: &UserId, | ||
| 97 | + topic: SessionTopic, | ||
| 98 | + starts_at: Timestamp, | ||
| 99 | + ends_at: Option<Timestamp>, | ||
| 100 | + db: &Database, | ||
| 101 | + ) -> Result<CourseSession, AppError> { | ||
| 102 | + let session = CourseSession { | ||
| 103 | + id: CourseSessionId::generate(), | ||
| 104 | + course: course.clone(), | ||
| 105 | + teacher: teacher.clone(), | ||
| 106 | + topic, | ||
| 107 | + starts_at, | ||
| 108 | + ends_at, | ||
| 109 | + }; | ||
| 110 | + let created: Option<CourseSession> = | ||
| 111 | + db.create(session.id.record()).content(session).await?; | ||
| 112 | + created.ok_or_else(|| AppError::Internal("failed to create session".into())) | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + pub async fn read( | ||
| 116 | + id: &CourseSessionId, | ||
| 117 | + db: &Database, | ||
| 118 | + ) -> Result<Option<CourseSession>, AppError> { | ||
| 119 | + Ok(db.select(id.record()).await?) | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + /// A course's sessions, most recent lesson first. Ordered by `starts_at` | ||
| 123 | + /// (not id): a timetable is read by when the lesson happens, not by when | ||
| 124 | + /// the row was created. | ||
| 125 | + pub async fn list_for_course( | ||
| 126 | + course: &CourseId, | ||
| 127 | + db: &Database, | ||
| 128 | + ) -> Result<Vec<CourseSession>, AppError> { | ||
| 129 | + let mut result = db | ||
| 130 | + .query("SELECT * FROM course_session WHERE course = $course ORDER BY starts_at DESC") | ||
| 131 | + .bind(("course", course.record())) | ||
| 132 | + .await? | ||
| 133 | + .check()?; | ||
| 134 | + Ok(result.take::<Vec<CourseSession>>(0)?) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + pub async fn update( | ||
| 138 | + mut self, | ||
| 139 | + teacher: UserId, | ||
| 140 | + topic: SessionTopic, | ||
| 141 | + starts_at: Timestamp, | ||
| 142 | + ends_at: Option<Timestamp>, | ||
| 143 | + db: &Database, | ||
| 144 | + ) -> Result<CourseSession, AppError> { | ||
| 145 | + self.teacher = teacher; | ||
| 146 | + self.topic = topic; | ||
| 147 | + self.starts_at = starts_at; | ||
| 148 | + self.ends_at = ends_at; | ||
| 149 | + let updated: Option<CourseSession> = db.update(self.id.record()).content(self).await?; | ||
| 150 | + updated.ok_or(AppError::NotFound) | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + /// Delete the session and cascade-remove its roll-call rows. | ||
| 154 | + pub async fn delete(self, db: &Database) -> Result<CourseSession, AppError> { | ||
| 155 | + db.query("DELETE session_attendance WHERE session = $s") | ||
| 156 | + .bind(("s", self.id.record())) | ||
| 157 | + .await? | ||
| 158 | + .check()?; | ||
| 159 | + let deleted: Option<CourseSession> = db.delete(self.id.record()).await?; | ||
| 160 | + deleted.ok_or(AppError::NotFound) | ||
| 161 | + } | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +#[cfg(test)] | ||
| 165 | +mod tests { | ||
| 166 | + use super::*; | ||
| 167 | + | ||
| 168 | + #[tokio::test] | ||
| 169 | + async fn topic_is_optional_but_bounded() { | ||
| 170 | + assert!(SessionTopic::try_new("").is_ok()); | ||
| 171 | + assert!(SessionTopic::try_new("limits and continuity").is_ok()); | ||
| 172 | + assert!(SessionTopic::try_new(&"x".repeat(MAX_SESSION_TOPIC_LEN)).is_ok()); | ||
| 173 | + assert!(SessionTopic::try_new(&"x".repeat(MAX_SESSION_TOPIC_LEN + 1)).is_err()); | ||
| 174 | + } | ||
| 175 | +} | ||
src/domain/mod.rsmodified+3 -0
| @@ -4,6 +4,7 @@ | |||
| 4 | 4 | ||
| 5 | pub mod attendance; | 5 | pub mod attendance; |
| 6 | pub mod course; | 6 | pub mod course; |
| 7 | +pub mod course_session; | ||
| 7 | pub mod enrollment; | 8 | pub mod enrollment; |
| 8 | pub mod event; | 9 | pub mod event; |
| 9 | pub mod exam; | 10 | pub mod exam; |
| @@ -15,5 +16,7 @@ pub mod note; | |||
| 15 | pub mod profile; | 16 | pub mod profile; |
| 16 | pub mod role; | 17 | pub mod role; |
| 17 | pub mod session; | 18 | pub mod session; |
| 19 | +pub mod session_attendance; | ||
| 18 | pub mod timestamp; | 20 | pub mod timestamp; |
| 19 | pub mod user; | 21 | pub mod user; |
| 22 | +pub mod work_entry; | ||
src/domain/session_attendance.rsadded+141 -0
| @@ -0,0 +1,141 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | + | ||
| 3 | +use crate::database::{Database, SESSION_ATTENDANCE_TABLE}; | ||
| 4 | +use crate::domain::attendance::AttendanceStatus; | ||
| 5 | +use crate::domain::course::CourseId; | ||
| 6 | +use crate::domain::course_session::{CourseSession, CourseSessionId}; | ||
| 7 | +use crate::domain::user::UserId; | ||
| 8 | +use crate::error::AppError; | ||
| 9 | + | ||
| 10 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 11 | +pub struct SessionAttendanceId(RecordId); | ||
| 12 | + | ||
| 13 | +impl SessionAttendanceId { | ||
| 14 | + /// A deterministic id for the (session, user) pair. Because the same pair | ||
| 15 | + /// always maps to the same record id, marking is a single atomic UPSERT with | ||
| 16 | + /// no find-then-insert race, and one-row-per-pair holds by construction. | ||
| 17 | + /// ULID keys are alphanumeric, so `_` is an unambiguous joiner. | ||
| 18 | + pub fn composite(session: &CourseSessionId, user: &UserId) -> Self { | ||
| 19 | + Self(RecordId::new( | ||
| 20 | + SESSION_ATTENDANCE_TABLE, | ||
| 21 | + format!("{}_{}", session.key(), user.key()), | ||
| 22 | + )) | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + pub fn record(&self) -> RecordId { | ||
| 26 | + self.0.clone() | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + pub fn key(&self) -> &str { | ||
| 30 | + match &self.0.key { | ||
| 31 | + RecordIdKey::String(key) => key, | ||
| 32 | + _ => "", | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// One person's roll-call state for one lesson. `course` is denormalized from | ||
| 38 | +/// the session so the per-course attendance report is a single indexed query | ||
| 39 | +/// (`WHERE user = $u`) with no join. | ||
| 40 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 41 | +pub struct SessionAttendance { | ||
| 42 | + id: SessionAttendanceId, | ||
| 43 | + session: CourseSessionId, | ||
| 44 | + course: CourseId, | ||
| 45 | + user: UserId, | ||
| 46 | + status: AttendanceStatus, | ||
| 47 | + marked_by: UserId, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +impl SessionAttendance { | ||
| 51 | + pub fn get_id(&self) -> &SessionAttendanceId { | ||
| 52 | + &self.id | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + pub fn get_session(&self) -> &CourseSessionId { | ||
| 56 | + &self.session | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + pub fn get_course(&self) -> &CourseId { | ||
| 60 | + &self.course | ||
| 61 | + } | ||
| 62 | + | ||
| 63 | + pub fn get_user(&self) -> &UserId { | ||
| 64 | + &self.user | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + pub fn get_status(&self) -> &AttendanceStatus { | ||
| 68 | + &self.status | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + pub fn get_marked_by(&self) -> &UserId { | ||
| 72 | + &self.marked_by | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + /// Record (or overwrite) `user`'s status for the session. One row per | ||
| 76 | + /// (session, user), keyed by a deterministic composite id so this is a | ||
| 77 | + /// single atomic UPSERT — concurrent marks converge on the one row. | ||
| 78 | + pub async fn mark( | ||
| 79 | + session: &CourseSession, | ||
| 80 | + user: &UserId, | ||
| 81 | + status: AttendanceStatus, | ||
| 82 | + marked_by: &UserId, | ||
| 83 | + db: &Database, | ||
| 84 | + ) -> Result<SessionAttendance, AppError> { | ||
| 85 | + let attendance = SessionAttendance { | ||
| 86 | + id: SessionAttendanceId::composite(session.get_id(), user), | ||
| 87 | + session: session.get_id().clone(), | ||
| 88 | + course: session.get_course().clone(), | ||
| 89 | + user: user.clone(), | ||
| 90 | + status, | ||
| 91 | + marked_by: marked_by.clone(), | ||
| 92 | + }; | ||
| 93 | + let saved: Option<SessionAttendance> = db | ||
| 94 | + .upsert(attendance.id.record()) | ||
| 95 | + .content(attendance) | ||
| 96 | + .await?; | ||
| 97 | + saved.ok_or_else(|| AppError::Internal("failed to mark session attendance".into())) | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + pub async fn list_for_session( | ||
| 101 | + session: &CourseSessionId, | ||
| 102 | + db: &Database, | ||
| 103 | + ) -> Result<Vec<SessionAttendance>, AppError> { | ||
| 104 | + let mut result = db | ||
| 105 | + .query("SELECT * FROM session_attendance WHERE session = $s ORDER BY id DESC") | ||
| 106 | + .bind(("s", session.record())) | ||
| 107 | + .await? | ||
| 108 | + .check()?; | ||
| 109 | + Ok(result.take::<Vec<SessionAttendance>>(0)?) | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + /// Every roll-call row ever recorded for `user` — the session half of the | ||
| 113 | + /// attendance report. Deliberately not filtered by current enrollment: | ||
| 114 | + /// attendance is a historical record, so unenrolling hides marks (report | ||
| 115 | + /// semantics) but never absences. | ||
| 116 | + pub async fn list_for_user( | ||
| 117 | + user: &UserId, | ||
| 118 | + db: &Database, | ||
| 119 | + ) -> Result<Vec<SessionAttendance>, AppError> { | ||
| 120 | + let mut result = db | ||
| 121 | + .query("SELECT * FROM session_attendance WHERE user = $usr ORDER BY id DESC") | ||
| 122 | + .bind(("usr", user.record())) | ||
| 123 | + .await? | ||
| 124 | + .check()?; | ||
| 125 | + Ok(result.take::<Vec<SessionAttendance>>(0)?) | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + pub async fn remove( | ||
| 129 | + session: &CourseSessionId, | ||
| 130 | + user: &UserId, | ||
| 131 | + db: &Database, | ||
| 132 | + ) -> Result<Option<SessionAttendance>, AppError> { | ||
| 133 | + let mut result = db | ||
| 134 | + .query("DELETE session_attendance WHERE session = $s AND user = $usr RETURN BEFORE") | ||
| 135 | + .bind(("s", session.record())) | ||
| 136 | + .bind(("usr", user.record())) | ||
| 137 | + .await? | ||
| 138 | + .check()?; | ||
| 139 | + Ok(result.take::<Vec<SessionAttendance>>(0)?.into_iter().next()) | ||
| 140 | + } | ||
| 141 | +} | ||
src/domain/work_entry.rsadded+199 -0
| @@ -0,0 +1,199 @@ | |||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | ||
| 2 | +use ulid::Ulid; | ||
| 3 | + | ||
| 4 | +use crate::database::{Database, WORK_ENTRY_TABLE}; | ||
| 5 | +use crate::domain::timestamp::Timestamp; | ||
| 6 | +use crate::domain::user::UserId; | ||
| 7 | +use crate::error::AppError; | ||
| 8 | + | ||
| 9 | +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | ||
| 10 | +pub struct WorkEntryId(RecordId); | ||
| 11 | + | ||
| 12 | +impl WorkEntryId { | ||
| 13 | + pub fn generate() -> Self { | ||
| 14 | + Self(RecordId::new(WORK_ENTRY_TABLE, Ulid::new().to_string())) | ||
| 15 | + } | ||
| 16 | + | ||
| 17 | + /// The deterministic id of `user`'s *open* entry. At most one open stint | ||
| 18 | + /// per user holds by construction: checking in is a single `INSERT IGNORE` | ||
| 19 | + /// on this id (atomic — a second check-in changes nothing), and checking | ||
| 20 | + /// out atomically takes the row and re-files it under a ULID id. | ||
| 21 | + /// `open_` cannot collide with a ULID key (ULIDs are bare alphanumerics). | ||
| 22 | + pub fn open_for(user: &UserId) -> Self { | ||
| 23 | + Self(RecordId::new( | ||
| 24 | + WORK_ENTRY_TABLE, | ||
| 25 | + format!("open_{}", user.key()), | ||
| 26 | + )) | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + pub fn from_key(key: &str) -> Self { | ||
| 30 | + Self(RecordId::new(WORK_ENTRY_TABLE, key)) | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + pub fn record(&self) -> RecordId { | ||
| 34 | + self.0.clone() | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + pub fn key(&self) -> &str { | ||
| 38 | + match &self.0.key { | ||
| 39 | + RecordIdKey::String(key) => key, | ||
| 40 | + _ => "", | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +/// One work stint of a staff member: server-stamped `check_in`, and | ||
| 46 | +/// `check_out` once closed. The wall clock is read server-side only — a | ||
| 47 | +/// client can never supply its own instants (managers correct closed entries | ||
| 48 | +/// through an explicit endpoint instead). | ||
| 49 | +#[derive(Debug, Clone, SurrealValue)] | ||
| 50 | +pub struct WorkEntry { | ||
| 51 | + id: WorkEntryId, | ||
| 52 | + user: UserId, | ||
| 53 | + check_in: Timestamp, | ||
| 54 | + check_out: Option<Timestamp>, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +impl WorkEntry { | ||
| 58 | + pub fn get_id(&self) -> &WorkEntryId { | ||
| 59 | + &self.id | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + pub fn get_user(&self) -> &UserId { | ||
| 63 | + &self.user | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + pub fn get_check_in(&self) -> Timestamp { | ||
| 67 | + self.check_in | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + pub fn get_check_out(&self) -> Option<Timestamp> { | ||
| 71 | + self.check_out | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + pub fn is_open(&self) -> bool { | ||
| 75 | + self.check_out.is_none() | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE` | ||
| 79 | + /// on the deterministic open id makes this atomic: if an open entry | ||
| 80 | + /// already exists the insert is skipped (empty result) and the caller gets | ||
| 81 | + /// a conflict — two racing check-ins can never create two open rows or | ||
| 82 | + /// reset a running clock. | ||
| 83 | + pub async fn check_in(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> { | ||
| 84 | + let entry = WorkEntry { | ||
| 85 | + id: WorkEntryId::open_for(user), | ||
| 86 | + user: user.clone(), | ||
| 87 | + check_in: Timestamp::now(), | ||
| 88 | + check_out: None, | ||
| 89 | + }; | ||
| 90 | + let mut result = db | ||
| 91 | + .query("INSERT IGNORE INTO work_entry $entry") | ||
| 92 | + .bind(("entry", entry)) | ||
| 93 | + .await? | ||
| 94 | + .check()?; | ||
| 95 | + result | ||
| 96 | + .take::<Vec<WorkEntry>>(0)? | ||
| 97 | + .into_iter() | ||
| 98 | + .next() | ||
| 99 | + .ok_or(AppError::Conflict("already checked in — check out first")) | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + /// Close `user`'s open stint. The `DELETE .. RETURN BEFORE` is an atomic | ||
| 103 | + /// take: of two racing check-outs exactly one receives the row (the other | ||
| 104 | + /// gets the conflict). The closed stint is then re-filed under a ULID id, | ||
| 105 | + /// freeing the open slot for the next check-in. | ||
| 106 | + pub async fn check_out(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> { | ||
| 107 | + let mut result = db | ||
| 108 | + .query("DELETE $open RETURN BEFORE") | ||
| 109 | + .bind(("open", WorkEntryId::open_for(user).record())) | ||
| 110 | + .await? | ||
| 111 | + .check()?; | ||
| 112 | + let open = result | ||
| 113 | + .take::<Vec<WorkEntry>>(0)? | ||
| 114 | + .into_iter() | ||
| 115 | + .next() | ||
| 116 | + .ok_or(AppError::Conflict("not checked in"))?; | ||
| 117 | + | ||
| 118 | + let closed = WorkEntry { | ||
| 119 | + id: WorkEntryId::generate(), | ||
| 120 | + user: open.user, | ||
| 121 | + check_in: open.check_in, | ||
| 122 | + check_out: Some(Timestamp::now()), | ||
| 123 | + }; | ||
| 124 | + let saved: Option<WorkEntry> = db.create(closed.id.record()).content(closed).await?; | ||
| 125 | + saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + pub async fn read(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> { | ||
| 129 | + Ok(db.select(id.record()).await?) | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + /// Every stint of `user`, newest first — the open one (if any) included. | ||
| 133 | + /// Ordered by `check_in`: the open entry's `open_` key doesn't sort with | ||
| 134 | + /// the ULIDs, so id order would misplace it. | ||
| 135 | + pub async fn list_for_user(user: &UserId, db: &Database) -> Result<Vec<WorkEntry>, AppError> { | ||
| 136 | + let mut result = db | ||
| 137 | + .query("SELECT * FROM work_entry WHERE user = $usr ORDER BY check_in DESC") | ||
| 138 | + .bind(("usr", user.record())) | ||
| 139 | + .await? | ||
| 140 | + .check()?; | ||
| 141 | + Ok(result.take::<Vec<WorkEntry>>(0)?) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + /// Persist corrected instants (manager fix-ups on closed entries; the web | ||
| 145 | + /// layer validates ordering and rejects open entries). | ||
| 146 | + pub async fn update( | ||
| 147 | + mut self, | ||
| 148 | + check_in: Timestamp, | ||
| 149 | + check_out: Timestamp, | ||
| 150 | + db: &Database, | ||
| 151 | + ) -> Result<WorkEntry, AppError> { | ||
| 152 | + self.check_in = check_in; | ||
| 153 | + self.check_out = Some(check_out); | ||
| 154 | + let updated: Option<WorkEntry> = db.update(self.id.record()).content(self).await?; | ||
| 155 | + updated.ok_or(AppError::NotFound) | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + pub async fn remove(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> { | ||
| 159 | + Ok(db.delete(id.record()).await?) | ||
| 160 | + } | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +#[cfg(test)] | ||
| 164 | +mod tests { | ||
| 165 | + use super::*; | ||
| 166 | + use crate::database; | ||
| 167 | + | ||
| 168 | + #[tokio::test] | ||
| 169 | + async fn check_in_is_exclusive_until_check_out() { | ||
| 170 | + let db = database::init_mem().await.unwrap(); | ||
| 171 | + // A `record<user>` column checks the table of the id, not row | ||
| 172 | + // existence — a fabricated id keeps this test free of user ceremony. | ||
| 173 | + let user = UserId::from_key(&Ulid::new().to_string()); | ||
| 174 | + | ||
| 175 | + let open = WorkEntry::check_in(&user, &db).await.unwrap(); | ||
| 176 | + assert!(open.is_open()); | ||
| 177 | + assert_eq!(open.get_id().key(), format!("open_{}", user.key())); | ||
| 178 | + | ||
| 179 | + // Second check-in must not create a second stint or reset the clock. | ||
| 180 | + let dup = WorkEntry::check_in(&user, &db).await; | ||
| 181 | + assert!(matches!(dup, Err(AppError::Conflict(_)))); | ||
| 182 | + let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); | ||
| 183 | + assert_eq!(entries.len(), 1); | ||
| 184 | + assert_eq!(entries[0].get_check_in(), open.get_check_in()); | ||
| 185 | + | ||
| 186 | + let closed = WorkEntry::check_out(&user, &db).await.unwrap(); | ||
| 187 | + assert!(!closed.is_open()); | ||
| 188 | + assert!(closed.get_check_out().unwrap() >= closed.get_check_in()); | ||
| 189 | + | ||
| 190 | + // The open slot is free again; a stray second check-out conflicts. | ||
| 191 | + assert!(matches!( | ||
| 192 | + WorkEntry::check_out(&user, &db).await, | ||
| 193 | + Err(AppError::Conflict(_)) | ||
| 194 | + )); | ||
| 195 | + WorkEntry::check_in(&user, &db).await.unwrap(); | ||
| 196 | + let entries = WorkEntry::list_for_user(&user, &db).await.unwrap(); | ||
| 197 | + assert_eq!(entries.len(), 2); | ||
| 198 | + } | ||
| 199 | +} | ||
src/lib.rsmodified+7 -1
| @@ -41,7 +41,10 @@ use crate::state::AppState; | |||
| 41 | (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), | 41 | (name = "users", description = "User info: self-service profile, plus listing, lookup, and role/profile administration (admin only)"), |
| 42 | (name = "notes", description = "Per-user notes CRUD"), | 42 | (name = "notes", description = "Per-user notes CRUD"), |
| 43 | (name = "events", description = "Events and attendance"), | 43 | (name = "events", description = "Events and attendance"), |
| 44 | - (name = "courses", description = "Courses, enrollment, and course exams"), | 44 | + (name = "courses", description = "Courses, enrollment, course exams, and course sessions"), |
| 45 | + (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), | ||
| 46 | + (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | ||
| 47 | + (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), | ||
| 45 | (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"), | 48 | (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"), |
| 46 | (name = "marks", description = "Weighted mark reports per course and overall"), | 49 | (name = "marks", description = "Weighted mark reports per course and overall"), |
| 47 | ), | 50 | ), |
| @@ -77,8 +80,11 @@ pub fn build_router(state: AppState) -> Router { | |||
| 77 | .nest("/notes", web::notes::routes()) | 80 | .nest("/notes", web::notes::routes()) |
| 78 | .nest("/events", web::events::routes()) | 81 | .nest("/events", web::events::routes()) |
| 79 | .nest("/courses", web::courses::routes()) | 82 | .nest("/courses", web::courses::routes()) |
| 83 | + .nest("/sessions", web::sessions::routes()) | ||
| 80 | .nest("/exams", web::exams::routes()) | 84 | .nest("/exams", web::exams::routes()) |
| 81 | .nest("/marks", web::marks::routes()) | 85 | .nest("/marks", web::marks::routes()) |
| 86 | + .nest("/work", web::work::routes()) | ||
| 87 | + .nest("/attendance", web::attendance::routes()) | ||
| 82 | .split_for_parts(); | 88 | .split_for_parts(); |
| 83 | 89 | ||
| 84 | // Catch-all per-IP limit over every route (Swagger included). Kept inside | 90 | // Catch-all per-IP limit over every route (Swagger included). Kept inside |
src/web/attendance.rsadded+207 -0
| @@ -0,0 +1,207 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 3 | +use axum::Json; | ||
| 4 | +use axum::extract::{Path, State}; | ||
| 5 | +use serde::Serialize; | ||
| 6 | +use utoipa::ToSchema; | ||
| 7 | +use utoipa_axum::router::OpenApiRouter; | ||
| 8 | +use utoipa_axum::routes; | ||
| 9 | + | ||
| 10 | +use crate::database::Database; | ||
| 11 | +use crate::domain::attendance::{Attendance, AttendanceStatus}; | ||
| 12 | +use crate::domain::course::{Course, CourseId}; | ||
| 13 | +use crate::domain::session_attendance::SessionAttendance; | ||
| 14 | +use crate::domain::user::{User, UserId}; | ||
| 15 | +use crate::error::{AppError, ErrorResponse}; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +use super::{CourseResponse, CurrentUser, RequireTeacher}; | ||
| 19 | + | ||
| 20 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 21 | + OpenApiRouter::new() | ||
| 22 | + .routes(routes!(my_report)) | ||
| 23 | + .routes(routes!(user_report)) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Per-status tallies over a set of attendance rows, plus the attendance rate. | ||
| 27 | +#[derive(Serialize, ToSchema, Default)] | ||
| 28 | +struct StatusCounts { | ||
| 29 | + present: u64, | ||
| 30 | + absent: u64, | ||
| 31 | + late: u64, | ||
| 32 | + excused: u64, | ||
| 33 | + /// All rows, `excused` included. | ||
| 34 | + total: u64, | ||
| 35 | + /// `(present + late) / (present + absent + late)` — being late is still | ||
| 36 | + /// attending, and an excused absence counts against no one. `null` when | ||
| 37 | + /// every row is excused (or there are none). | ||
| 38 | + rate: Option<f64>, | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +impl StatusCounts { | ||
| 42 | + fn tally<'a>(statuses: impl Iterator<Item = &'a AttendanceStatus>) -> Self { | ||
| 43 | + let mut counts = StatusCounts::default(); | ||
| 44 | + for status in statuses { | ||
| 45 | + counts.total += 1; | ||
| 46 | + match status.as_str() { | ||
| 47 | + "present" => counts.present += 1, | ||
| 48 | + "absent" => counts.absent += 1, | ||
| 49 | + "late" => counts.late += 1, | ||
| 50 | + // `AttendanceStatus` admits exactly four values. | ||
| 51 | + _ => counts.excused += 1, | ||
| 52 | + } | ||
| 53 | + } | ||
| 54 | + counts.rate = attendance_rate(counts.present, counts.absent, counts.late); | ||
| 55 | + counts | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// `(present + late) / (present + absent + late)`; `None` when the denominator | ||
| 60 | +/// is zero. | ||
| 61 | +fn attendance_rate(present: u64, absent: u64, late: u64) -> Option<f64> { | ||
| 62 | + let counted = present + absent + late; | ||
| 63 | + (counted > 0).then(|| (present + late) as f64 / counted as f64) | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// A user's roll-call tallies in one course. | ||
| 67 | +#[derive(Serialize, ToSchema)] | ||
| 68 | +struct CourseAttendance { | ||
| 69 | + course: CourseResponse, | ||
| 70 | + counts: StatusCounts, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// A user's full attendance report: generic events, lesson roll call overall, | ||
| 74 | +/// and the roll call broken down per course. | ||
| 75 | +#[derive(Serialize, ToSchema)] | ||
| 76 | +struct AttendanceReport { | ||
| 77 | + /// The user's id. | ||
| 78 | + user: String, | ||
| 79 | + /// Tallies over event attendance (`/events/{id}/attendance`). | ||
| 80 | + events: StatusCounts, | ||
| 81 | + /// Tallies over every lesson roll-call row, all courses combined. | ||
| 82 | + sessions: StatusCounts, | ||
| 83 | + /// The session tallies split per course. Courses appear as long as the | ||
| 84 | + /// user has roll-call rows in them — attendance is a historical record, | ||
| 85 | + /// so unenrolling never hides an absence. | ||
| 86 | + courses: Vec<CourseAttendance>, | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// Assemble the report: tally the user's event rows, then their session rows | ||
| 90 | +/// grouped by the (denormalized) course reference. | ||
| 91 | +async fn build_report(user: &UserId, db: &Database) -> Result<AttendanceReport, AppError> { | ||
| 92 | + let events = Attendance::list_for_user(user, db).await?; | ||
| 93 | + let sessions = SessionAttendance::list_for_user(user, db).await?; | ||
| 94 | + | ||
| 95 | + // Group session rows by course, preserving first-seen (newest-first) order. | ||
| 96 | + let mut course_ids: Vec<CourseId> = Vec::new(); | ||
| 97 | + let mut by_course: HashMap<String, Vec<&SessionAttendance>> = HashMap::new(); | ||
| 98 | + for row in &sessions { | ||
| 99 | + let key = row.get_course().key().to_string(); | ||
| 100 | + if !by_course.contains_key(&key) { | ||
| 101 | + course_ids.push(row.get_course().clone()); | ||
| 102 | + } | ||
| 103 | + by_course.entry(key).or_default().push(row); | ||
| 104 | + } | ||
| 105 | + | ||
| 106 | + let courses = Course::list_by_ids(&course_ids, db).await?; | ||
| 107 | + let course_by_key: HashMap<&str, &Course> = | ||
| 108 | + courses.iter().map(|c| (c.get_id().key(), c)).collect(); | ||
| 109 | + | ||
| 110 | + let mut blocks = Vec::with_capacity(course_ids.len()); | ||
| 111 | + for course_id in &course_ids { | ||
| 112 | + // A row whose course is gone cannot happen given the delete cascade — | ||
| 113 | + // skip defensively rather than fabricate a course block. | ||
| 114 | + let Some(course) = course_by_key.get(course_id.key()) else { | ||
| 115 | + continue; | ||
| 116 | + }; | ||
| 117 | + let rows = &by_course[course_id.key()]; | ||
| 118 | + blocks.push(CourseAttendance { | ||
| 119 | + course: CourseResponse::new(course), | ||
| 120 | + counts: StatusCounts::tally(rows.iter().map(|r| r.get_status())), | ||
| 121 | + }); | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + Ok(AttendanceReport { | ||
| 125 | + user: user.key().to_string(), | ||
| 126 | + events: StatusCounts::tally(events.iter().map(|a| a.get_status())), | ||
| 127 | + sessions: StatusCounts::tally(sessions.iter().map(|a| a.get_status())), | ||
| 128 | + courses: blocks, | ||
| 129 | + }) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// The current user's attendance report: event tallies, lesson roll-call | ||
| 133 | +/// tallies, and a per-course breakdown with attendance rates. | ||
| 134 | +#[utoipa::path( | ||
| 135 | + get, | ||
| 136 | + path = "/me", | ||
| 137 | + tag = "attendance", | ||
| 138 | + security(("session_cookie" = [])), | ||
| 139 | + responses( | ||
| 140 | + (status = 200, description = "The caller's attendance report", body = AttendanceReport), | ||
| 141 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 142 | + ), | ||
| 143 | +)] | ||
| 144 | +async fn my_report( | ||
| 145 | + State(st): State<AppState>, | ||
| 146 | + CurrentUser(user): CurrentUser, | ||
| 147 | +) -> Result<Json<AttendanceReport>, AppError> { | ||
| 148 | + Ok(Json(build_report(user.get_id(), &st.db).await?)) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// Any user's attendance report. Requires teacher+. | ||
| 152 | +#[utoipa::path( | ||
| 153 | + get, | ||
| 154 | + path = "/{user}", | ||
| 155 | + tag = "attendance", | ||
| 156 | + security(("session_cookie" = [])), | ||
| 157 | + params(("user" = String, Path, description = "User id")), | ||
| 158 | + responses( | ||
| 159 | + (status = 200, description = "The user's attendance report", body = AttendanceReport), | ||
| 160 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 161 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 162 | + (status = 404, description = "User not found", body = ErrorResponse), | ||
| 163 | + ), | ||
| 164 | +)] | ||
| 165 | +async fn user_report( | ||
| 166 | + State(st): State<AppState>, | ||
| 167 | + _teacher: RequireTeacher, | ||
| 168 | + Path(user): Path<String>, | ||
| 169 | +) -> Result<Json<AttendanceReport>, AppError> { | ||
| 170 | + let target = UserId::from_key(&user); | ||
| 171 | + // User must exist — a missing user is a 404, not an empty report. | ||
| 172 | + User::read(&target, &st.db) | ||
| 173 | + .await? | ||
| 174 | + .ok_or(AppError::NotFound)?; | ||
| 175 | + Ok(Json(build_report(&target, &st.db).await?)) | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +#[cfg(test)] | ||
| 179 | +mod tests { | ||
| 180 | + use super::*; | ||
| 181 | + | ||
| 182 | + #[tokio::test] | ||
| 183 | + async fn rate_counts_late_as_attended_and_ignores_excused() { | ||
| 184 | + // 3 present + 1 late out of 5 unexcused rows. | ||
| 185 | + assert_eq!(attendance_rate(3, 1, 1), Some(0.8)); | ||
| 186 | + // Excused rows are outside both sides of the division. | ||
| 187 | + assert_eq!(attendance_rate(0, 0, 0), None); | ||
| 188 | + assert_eq!(attendance_rate(2, 0, 0), Some(1.0)); | ||
| 189 | + assert_eq!(attendance_rate(0, 2, 0), Some(0.0)); | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + #[tokio::test] | ||
| 193 | + async fn tally_buckets_every_status() { | ||
| 194 | + let statuses: Vec<AttendanceStatus> = ["present", "present", "late", "absent", "excused"] | ||
| 195 | + .iter() | ||
| 196 | + .map(|s| AttendanceStatus::try_new(s).unwrap()) | ||
| 197 | + .collect(); | ||
| 198 | + let counts = StatusCounts::tally(statuses.iter()); | ||
| 199 | + assert_eq!(counts.present, 2); | ||
| 200 | + assert_eq!(counts.late, 1); | ||
| 201 | + assert_eq!(counts.absent, 1); | ||
| 202 | + assert_eq!(counts.excused, 1); | ||
| 203 | + assert_eq!(counts.total, 5); | ||
| 204 | + // (2 + 1) / (2 + 1 + 1) | ||
| 205 | + assert_eq!(counts.rate, Some(0.75)); | ||
| 206 | + } | ||
| 207 | +} | ||
src/web/courses.rsmodified+111 -1
| @@ -9,6 +9,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 9 | use utoipa_axum::routes; | 9 | use utoipa_axum::routes; |
| 10 | 10 | ||
| 11 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; | 11 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseTitle}; |
| 12 | +use crate::domain::course_session::{CourseSession, SessionTopic}; | ||
| 12 | use crate::domain::enrollment::Enrollment; | 13 | use crate::domain::enrollment::Enrollment; |
| 13 | use crate::domain::exam::{ | 14 | use crate::domain::exam::{ |
| 14 | Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, | 15 | Exam, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, ExamWeight, |
| @@ -19,7 +20,11 @@ use crate::domain::user::{User, UserId}; | |||
| 19 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 20 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 20 | use crate::state::AppState; | 21 | use crate::state::AppState; |
| 21 | 22 | ||
| 22 | -use super::{CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, person_map}; | 23 | +use super::sessions::resolve_session_teacher; |
| 24 | +use super::{ | ||
| 25 | + CourseResponse, CurrentUser, ExamResponse, PersonRef, RequireTeacher, SessionResponse, | ||
| 26 | + check_time_range, person_map, | ||
| 27 | +}; | ||
| 23 | 28 | ||
| 24 | pub fn routes() -> OpenApiRouter<AppState> { | 29 | pub fn routes() -> OpenApiRouter<AppState> { |
| 25 | OpenApiRouter::new() | 30 | OpenApiRouter::new() |
| @@ -29,6 +34,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 29 | .routes(routes!(enroll, list_roster)) | 34 | .routes(routes!(enroll, list_roster)) |
| 30 | .routes(routes!(unenroll)) | 35 | .routes(routes!(unenroll)) |
| 31 | .routes(routes!(create_exam_in_course, list_course_exams)) | 36 | .routes(routes!(create_exam_in_course, list_course_exams)) |
| 37 | + .routes(routes!(create_session_in_course, list_course_sessions)) | ||
| 32 | } | 38 | } |
| 33 | 39 | ||
| 34 | #[derive(Deserialize, ToSchema)] | 40 | #[derive(Deserialize, ToSchema)] |
| @@ -485,3 +491,107 @@ async fn list_course_exams( | |||
| 485 | let exams = Exam::list_for_course(&course_id, &st.db).await?; | 491 | let exams = Exam::list_for_course(&course_id, &st.db).await?; |
| 486 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) | 492 | Ok(Json(exams.iter().map(ExamResponse::new).collect())) |
| 487 | } | 493 | } |
| 494 | + | ||
| 495 | +// ---- sessions in a course -------------------------------------------------- | ||
| 496 | + | ||
| 497 | +#[derive(Deserialize, ToSchema)] | ||
| 498 | +struct CreateSessionInCourse { | ||
| 499 | + /// What the lesson covers. Optional. | ||
| 500 | + #[schema(example = "Limits and continuity")] | ||
| 501 | + topic: Option<String>, | ||
| 502 | + /// Who teaches the session. Defaults to the caller; must hold the | ||
| 503 | + /// `teacher` role or higher. | ||
| 504 | + teacher_id: Option<String>, | ||
| 505 | + /// Lesson start, UTC unix-milliseconds. | ||
| 506 | + #[schema(example = 1_752_275_000_000_i64)] | ||
| 507 | + starts_at: i64, | ||
| 508 | + /// Lesson end, UTC unix-milliseconds. Optional (open-ended). | ||
| 509 | + ends_at: Option<i64>, | ||
| 510 | +} | ||
| 511 | + | ||
| 512 | +/// Create a lesson session inside a course. Requires teacher+ and course | ||
| 513 | +/// management rights. The session's teacher defaults to the caller. | ||
| 514 | +#[utoipa::path( | ||
| 515 | + post, | ||
| 516 | + path = "/{id}/sessions", | ||
| 517 | + tag = "courses", | ||
| 518 | + security(("session_cookie" = [])), | ||
| 519 | + params(("id" = String, Path, description = "Course id")), | ||
| 520 | + request_body = CreateSessionInCourse, | ||
| 521 | + responses( | ||
| 522 | + (status = 201, description = "Session created", body = SessionResponse), | ||
| 523 | + (status = 400, description = "Invalid fields, time range, or teacher", body = ErrorResponse), | ||
| 524 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 525 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 526 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 527 | + ), | ||
| 528 | +)] | ||
| 529 | +async fn create_session_in_course( | ||
| 530 | + State(st): State<AppState>, | ||
| 531 | + RequireTeacher(user): RequireTeacher, | ||
| 532 | + Path(id): Path<String>, | ||
| 533 | + Json(req): Json<CreateSessionInCourse>, | ||
| 534 | +) -> Result<(StatusCode, Json<SessionResponse>), AppError> { | ||
| 535 | + let course = Course::read(&CourseId::from_key(&id), &st.db) | ||
| 536 | + .await? | ||
| 537 | + .ok_or(AppError::NotFound)?; | ||
| 538 | + if !can_manage_course(&course, &user) { | ||
| 539 | + return Err(AppError::Forbidden( | ||
| 540 | + "only the course creator or a manager/admin can add sessions to this course", | ||
| 541 | + )); | ||
| 542 | + } | ||
| 543 | + | ||
| 544 | + let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; | ||
| 545 | + let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; | ||
| 546 | + let starts_at = Timestamp::from_millis(req.starts_at); | ||
| 547 | + let ends_at = req.ends_at.map(Timestamp::from_millis); | ||
| 548 | + check_time_range(Some(starts_at), ends_at)?; | ||
| 549 | + | ||
| 550 | + let session = CourseSession::create( | ||
| 551 | + course.get_id(), | ||
| 552 | + teacher.get_id(), | ||
| 553 | + topic, | ||
| 554 | + starts_at, | ||
| 555 | + ends_at, | ||
| 556 | + &st.db, | ||
| 557 | + ) | ||
| 558 | + .await?; | ||
| 559 | + let people = PersonRef::map_of(&[&teacher]); | ||
| 560 | + Ok(( | ||
| 561 | + StatusCode::CREATED, | ||
| 562 | + Json(SessionResponse::new(&session, &people)), | ||
| 563 | + )) | ||
| 564 | +} | ||
| 565 | + | ||
| 566 | +/// List a course's lesson sessions, most recent first. | ||
| 567 | +#[utoipa::path( | ||
| 568 | + get, | ||
| 569 | + path = "/{id}/sessions", | ||
| 570 | + tag = "courses", | ||
| 571 | + security(("session_cookie" = [])), | ||
| 572 | + params(("id" = String, Path, description = "Course id")), | ||
| 573 | + responses( | ||
| 574 | + (status = 200, description = "The course's sessions", body = [SessionResponse]), | ||
| 575 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 576 | + (status = 404, description = "Course not found", body = ErrorResponse), | ||
| 577 | + ), | ||
| 578 | +)] | ||
| 579 | +async fn list_course_sessions( | ||
| 580 | + State(st): State<AppState>, | ||
| 581 | + _user: CurrentUser, | ||
| 582 | + Path(id): Path<String>, | ||
| 583 | +) -> Result<Json<Vec<SessionResponse>>, AppError> { | ||
| 584 | + let course_id = CourseId::from_key(&id); | ||
| 585 | + // Course must exist — a missing course is a 404, not an empty list. | ||
| 586 | + Course::read(&course_id, &st.db) | ||
| 587 | + .await? | ||
| 588 | + .ok_or(AppError::NotFound)?; | ||
| 589 | + let sessions = CourseSession::list_for_course(&course_id, &st.db).await?; | ||
| 590 | + let people = person_map(sessions.iter().map(|s| s.get_teacher().clone()), &st.db).await?; | ||
| 591 | + Ok(Json( | ||
| 592 | + sessions | ||
| 593 | + .iter() | ||
| 594 | + .map(|s| SessionResponse::new(s, &people)) | ||
| 595 | + .collect(), | ||
| 596 | + )) | ||
| 597 | +} | ||
src/web/dto.rsmodified+30 -0
| @@ -7,6 +7,7 @@ use utoipa::ToSchema; | |||
| 7 | 7 | ||
| 8 | use crate::database::Database; | 8 | use crate::database::Database; |
| 9 | use crate::domain::course::Course; | 9 | use crate::domain::course::Course; |
| 10 | +use crate::domain::course_session::CourseSession; | ||
| 10 | use crate::domain::exam::Exam; | 11 | use crate::domain::exam::Exam; |
| 11 | use crate::domain::role::Role as DomainRole; | 12 | use crate::domain::role::Role as DomainRole; |
| 12 | use crate::domain::user::{User, UserId}; | 13 | use crate::domain::user::{User, UserId}; |
| @@ -162,6 +163,35 @@ impl CourseResponse { | |||
| 162 | } | 163 | } |
| 163 | } | 164 | } |
| 164 | 165 | ||
| 166 | +/// Public shape of a course session (one lesson). Shared by `courses` | ||
| 167 | +/// (in-course creation and listing) and `sessions` (CRUD + roll call). | ||
| 168 | +#[derive(Serialize, ToSchema)] | ||
| 169 | +pub struct SessionResponse { | ||
| 170 | + pub id: String, | ||
| 171 | + /// The course this lesson belongs to. | ||
| 172 | + pub course: String, | ||
| 173 | + /// Who teaches this session. | ||
| 174 | + pub teacher: PersonRef, | ||
| 175 | + pub topic: String, | ||
| 176 | + /// Lesson start, UTC unix-milliseconds. | ||
| 177 | + pub starts_at: i64, | ||
| 178 | + /// Lesson end, UTC unix-milliseconds; `null` when open-ended. | ||
| 179 | + pub ends_at: Option<i64>, | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +impl SessionResponse { | ||
| 183 | + pub fn new(session: &CourseSession, people: &HashMap<String, PersonRef>) -> Self { | ||
| 184 | + Self { | ||
| 185 | + id: session.get_id().key().to_string(), | ||
| 186 | + course: session.get_course().key().to_string(), | ||
| 187 | + teacher: PersonRef::resolve(people, session.get_teacher()), | ||
| 188 | + topic: session.get_topic().as_str().to_string(), | ||
| 189 | + starts_at: session.get_starts_at().as_millis(), | ||
| 190 | + ends_at: session.get_ends_at().map(|t| t.as_millis()), | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | +} | ||
| 194 | + | ||
| 165 | /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` | 195 | /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses` |
| 166 | /// (in-course creation and listing). The schedule fields are all `null` for an | 196 | /// (in-course creation and listing). The schedule fields are all `null` for an |
| 167 | /// unscheduled (offline-graded) exam; see the create/update endpoints for the | 197 | /// unscheduled (offline-graded) exam; see the create/update endpoints for the |
src/web/events.rsmodified+1 -17
| @@ -16,7 +16,7 @@ use crate::domain::user::{User, UserId}; | |||
| 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 17 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 18 | 18 | ||
| 19 | -use super::{CurrentUser, PersonRef, RequireTeacher, person_map, set_or_clear}; | 19 | +use super::{CurrentUser, PersonRef, RequireTeacher, check_time_range, person_map, set_or_clear}; |
| 20 | 20 | ||
| 21 | pub fn routes() -> OpenApiRouter<AppState> { | 21 | pub fn routes() -> OpenApiRouter<AppState> { |
| 22 | OpenApiRouter::new() | 22 | OpenApiRouter::new() |
| @@ -92,22 +92,6 @@ fn can_manage(event: &Event, user: &User) -> bool { | |||
| 92 | event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) | 92 | event.is_creator(user.get_id()) || user.get_role().at_least(Role::Manager) |
| 93 | } | 93 | } |
| 94 | 94 | ||
| 95 | -/// If both ends are present, `ends_at` must not precede `starts_at`. | ||
| 96 | -fn check_time_range( | ||
| 97 | - starts_at: Option<Timestamp>, | ||
| 98 | - ends_at: Option<Timestamp>, | ||
| 99 | -) -> Result<(), AppError> { | ||
| 100 | - if let (Some(starts), Some(ends)) = (starts_at, ends_at) | ||
| 101 | - && ends < starts | ||
| 102 | - { | ||
| 103 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 104 | - field: "ends_at", | ||
| 105 | - reason: "must be at or after starts_at", | ||
| 106 | - })); | ||
| 107 | - } | ||
| 108 | - Ok(()) | ||
| 109 | -} | ||
| 110 | - | ||
| 111 | #[derive(Serialize, ToSchema)] | 95 | #[derive(Serialize, ToSchema)] |
| 112 | struct AttendanceResponse { | 96 | struct AttendanceResponse { |
| 113 | id: String, | 97 | id: String, |
src/web/extractor.rsmodified+20 -0
| @@ -74,6 +74,26 @@ where | |||
| 74 | } | 74 | } |
| 75 | } | 75 | } |
| 76 | 76 | ||
| 77 | +/// Like [`CurrentUser`], but also requires at least the `manager` role. | ||
| 78 | +/// Authenticated-but-under-privileged callers get `403`. | ||
| 79 | +pub struct RequireManager(pub User); | ||
| 80 | + | ||
| 81 | +impl<S> FromRequestParts<S> for RequireManager | ||
| 82 | +where | ||
| 83 | + S: Send + Sync, | ||
| 84 | + AppState: FromRef<S>, | ||
| 85 | +{ | ||
| 86 | + type Rejection = AppError; | ||
| 87 | + | ||
| 88 | + async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { | ||
| 89 | + let user = authed_user(parts, state).await?; | ||
| 90 | + if !user.get_role().at_least(Role::Manager) { | ||
| 91 | + return Err(AppError::Forbidden("requires manager role or higher")); | ||
| 92 | + } | ||
| 93 | + Ok(RequireManager(user)) | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 77 | /// Like [`CurrentUser`], but also requires the `admin` role. Anyone below admin | 97 | /// Like [`CurrentUser`], but also requires the `admin` role. Anyone below admin |
| 78 | /// gets `403`. | 98 | /// gets `403`. |
| 79 | pub struct RequireAdmin(pub User); | 99 | pub struct RequireAdmin(pub User); |
src/web/mod.rsmodified+25 -2
| @@ -3,6 +3,7 @@ | |||
| 3 | //! validated domain newtypes before doing anything. Role-gated endpoints take a | 3 | //! validated domain newtypes before doing anything. Role-gated endpoints take a |
| 4 | //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. | 4 | //! `RequireTeacher` / `RequireAdmin` extractor instead of `CurrentUser`. |
| 5 | 5 | ||
| 6 | +pub mod attendance; | ||
| 6 | pub mod auth; | 7 | pub mod auth; |
| 7 | pub mod courses; | 8 | pub mod courses; |
| 8 | pub mod events; | 9 | pub mod events; |
| @@ -10,16 +11,38 @@ pub mod exam_ws; | |||
| 10 | pub mod exams; | 11 | pub mod exams; |
| 11 | pub mod marks; | 12 | pub mod marks; |
| 12 | pub mod notes; | 13 | pub mod notes; |
| 14 | +pub mod sessions; | ||
| 13 | pub mod users; | 15 | pub mod users; |
| 16 | +pub mod work; | ||
| 14 | 17 | ||
| 15 | mod dto; | 18 | mod dto; |
| 16 | mod extractor; | 19 | mod extractor; |
| 17 | 20 | ||
| 18 | -pub use dto::{CourseResponse, ExamResponse, PersonRef, UserResponse, person_map}; | 21 | +pub use dto::{CourseResponse, ExamResponse, PersonRef, SessionResponse, UserResponse, person_map}; |
| 19 | -pub use extractor::{CurrentUser, RequireAdmin, RequireTeacher}; | 22 | +pub use extractor::{CurrentUser, RequireAdmin, RequireManager, RequireTeacher}; |
| 20 | 23 | ||
| 21 | use serde::{Deserialize, Deserializer}; | 24 | use serde::{Deserialize, Deserializer}; |
| 22 | 25 | ||
| 26 | +use crate::domain::timestamp::Timestamp; | ||
| 27 | +use crate::error::{AppError, ValidationError}; | ||
| 28 | + | ||
| 29 | +/// If both ends are present, `ends_at` must not precede `starts_at`. Shared by | ||
| 30 | +/// everything that carries a time range (events, course sessions). | ||
| 31 | +pub(crate) fn check_time_range( | ||
| 32 | + starts_at: Option<Timestamp>, | ||
| 33 | + ends_at: Option<Timestamp>, | ||
| 34 | +) -> Result<(), AppError> { | ||
| 35 | + if let (Some(starts), Some(ends)) = (starts_at, ends_at) | ||
| 36 | + && ends < starts | ||
| 37 | + { | ||
| 38 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 39 | + field: "ends_at", | ||
| 40 | + reason: "must be at or after starts_at", | ||
| 41 | + })); | ||
| 42 | + } | ||
| 43 | + Ok(()) | ||
| 44 | +} | ||
| 45 | + | ||
| 23 | /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never | 46 | /// Distinguishes an *absent* PATCH field from an explicit `null`: absent never |
| 24 | /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the | 47 | /// reaches the deserializer and stays `None` via `#[serde(default)]` (keep the |
| 25 | /// stored value); `null` or a value lands here as `Some(inner)` (clear or set). | 48 | /// stored value); `null` or a value lands here as `Some(inner)` (clear or set). |
src/web/sessions.rsadded+395 -0
| @@ -0,0 +1,395 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 3 | +use axum::Json; | ||
| 4 | +use axum::extract::{Path, State}; | ||
| 5 | +use axum::http::StatusCode; | ||
| 6 | +use serde::{Deserialize, Serialize}; | ||
| 7 | +use utoipa::ToSchema; | ||
| 8 | +use utoipa_axum::router::OpenApiRouter; | ||
| 9 | +use utoipa_axum::routes; | ||
| 10 | + | ||
| 11 | +use crate::database::Database; | ||
| 12 | +use crate::domain::attendance::AttendanceStatus; | ||
| 13 | +use crate::domain::course::Course; | ||
| 14 | +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; | ||
| 15 | +use crate::domain::enrollment::Enrollment; | ||
| 16 | +use crate::domain::role::Role; | ||
| 17 | +use crate::domain::session_attendance::SessionAttendance; | ||
| 18 | +use crate::domain::timestamp::Timestamp; | ||
| 19 | +use crate::domain::user::{User, UserId}; | ||
| 20 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 21 | +use crate::state::AppState; | ||
| 22 | + | ||
| 23 | +use super::courses::can_manage_course; | ||
| 24 | +use super::{ | ||
| 25 | + CurrentUser, PersonRef, RequireTeacher, SessionResponse, check_time_range, person_map, | ||
| 26 | + set_or_clear, | ||
| 27 | +}; | ||
| 28 | + | ||
| 29 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 30 | + OpenApiRouter::new() | ||
| 31 | + .routes(routes!(get_session, update_session, delete_session)) | ||
| 32 | + .routes(routes!(mark_roll_call, list_roll_call)) | ||
| 33 | + .routes(routes!(remove_roll_call)) | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +#[derive(Deserialize, ToSchema)] | ||
| 37 | +struct UpdateSession { | ||
| 38 | + topic: Option<String>, | ||
| 39 | + /// Reassign the session's teacher. Omit to keep; must be teacher+. | ||
| 40 | + teacher_id: Option<String>, | ||
| 41 | + /// Unix-millisecond timestamp. Omit to keep the current value. | ||
| 42 | + starts_at: Option<i64>, | ||
| 43 | + /// Unix-millisecond timestamp. Omit to keep the current value; send `null` | ||
| 44 | + /// to clear it. | ||
| 45 | + #[serde(default, deserialize_with = "set_or_clear")] | ||
| 46 | + #[schema(value_type = Option<i64>)] | ||
| 47 | + ends_at: Option<Option<i64>>, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +#[derive(Deserialize, ToSchema)] | ||
| 51 | +struct MarkRollCall { | ||
| 52 | + /// One of the accepted attendance statuses (e.g. `present`, `absent`). | ||
| 53 | + #[schema(example = "present")] | ||
| 54 | + status: String, | ||
| 55 | + /// Whose roll-call state to record: an enrolled student, or the session's | ||
| 56 | + /// teacher (the latter requires manager+). | ||
| 57 | + user_id: String, | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +#[derive(Serialize, ToSchema)] | ||
| 61 | +struct SessionAttendanceResponse { | ||
| 62 | + id: String, | ||
| 63 | + session: String, | ||
| 64 | + course: String, | ||
| 65 | + /// Whose attendance this row records. | ||
| 66 | + user: PersonRef, | ||
| 67 | + status: String, | ||
| 68 | + /// Who recorded it. | ||
| 69 | + marked_by: PersonRef, | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +impl SessionAttendanceResponse { | ||
| 73 | + fn new(attendance: &SessionAttendance, people: &HashMap<String, PersonRef>) -> Self { | ||
| 74 | + Self { | ||
| 75 | + id: attendance.get_id().key().to_string(), | ||
| 76 | + session: attendance.get_session().key().to_string(), | ||
| 77 | + course: attendance.get_course().key().to_string(), | ||
| 78 | + user: PersonRef::resolve(people, attendance.get_user()), | ||
| 79 | + status: attendance.get_status().as_str().to_string(), | ||
| 80 | + marked_by: PersonRef::resolve(people, attendance.get_marked_by()), | ||
| 81 | + } | ||
| 82 | + } | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +/// Resolve who a session's teacher should be: the caller when `teacher_id` is | ||
| 86 | +/// omitted (or names them), otherwise the referenced user — who must exist and | ||
| 87 | +/// hold the `teacher` role or higher (a student cannot teach a lesson). | ||
| 88 | +pub(crate) async fn resolve_session_teacher( | ||
| 89 | + teacher_id: Option<&str>, | ||
| 90 | + caller: &User, | ||
| 91 | + db: &Database, | ||
| 92 | +) -> Result<User, AppError> { | ||
| 93 | + let target = match teacher_id { | ||
| 94 | + None => return Ok(caller.clone()), | ||
| 95 | + Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), | ||
| 96 | + Some(key) => UserId::from_key(key), | ||
| 97 | + }; | ||
| 98 | + let Some(user) = User::read(&target, db).await? else { | ||
| 99 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 100 | + field: "teacher_id", | ||
| 101 | + reason: "session teacher does not exist", | ||
| 102 | + })); | ||
| 103 | + }; | ||
| 104 | + if !user.get_role().at_least(Role::Teacher) { | ||
| 105 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 106 | + field: "teacher_id", | ||
| 107 | + reason: "session teacher must hold the teacher role or higher", | ||
| 108 | + })); | ||
| 109 | + } | ||
| 110 | + Ok(user) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +/// Load a session and its course together; a session whose course is gone | ||
| 114 | +/// cannot happen given the delete cascade, so both misses are plain 404s. | ||
| 115 | +async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, Course), AppError> { | ||
| 116 | + let session = CourseSession::read(&CourseSessionId::from_key(id), db) | ||
| 117 | + .await? | ||
| 118 | + .ok_or(AppError::NotFound)?; | ||
| 119 | + let course = Course::read(session.get_course(), db) | ||
| 120 | + .await? | ||
| 121 | + .ok_or(AppError::NotFound)?; | ||
| 122 | + Ok((session, course)) | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// Who may take (or amend) a session's roll call: the session's own teacher, | ||
| 126 | +/// or anyone with course-management rights (creator / manager+). | ||
| 127 | +fn can_roll_call(session: &CourseSession, course: &Course, user: &User) -> bool { | ||
| 128 | + session.is_teacher(user.get_id()) || can_manage_course(course, user) | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +// ---- sessions ------------------------------------------------------------- | ||
| 132 | + | ||
| 133 | +/// Fetch a single session by id. | ||
| 134 | +#[utoipa::path( | ||
| 135 | + get, | ||
| 136 | + path = "/{id}", | ||
| 137 | + tag = "sessions", | ||
| 138 | + security(("session_cookie" = [])), | ||
| 139 | + params(("id" = String, Path, description = "Session id")), | ||
| 140 | + responses( | ||
| 141 | + (status = 200, description = "The session", body = SessionResponse), | ||
| 142 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 143 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 144 | + ), | ||
| 145 | +)] | ||
| 146 | +async fn get_session( | ||
| 147 | + State(st): State<AppState>, | ||
| 148 | + _user: CurrentUser, | ||
| 149 | + Path(id): Path<String>, | ||
| 150 | +) -> Result<Json<SessionResponse>, AppError> { | ||
| 151 | + let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) | ||
| 152 | + .await? | ||
| 153 | + .ok_or(AppError::NotFound)?; | ||
| 154 | + let people = person_map([session.get_teacher().clone()], &st.db).await?; | ||
| 155 | + Ok(Json(SessionResponse::new(&session, &people))) | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// Update a session. Requires teacher+ with course-management rights. Omitted | ||
| 159 | +/// fields keep their value; an explicit `null` clears `ends_at`. | ||
| 160 | +#[utoipa::path( | ||
| 161 | + patch, | ||
| 162 | + path = "/{id}", | ||
| 163 | + tag = "sessions", | ||
| 164 | + security(("session_cookie" = [])), | ||
| 165 | + params(("id" = String, Path, description = "Session id")), | ||
| 166 | + request_body = UpdateSession, | ||
| 167 | + responses( | ||
| 168 | + (status = 200, description = "Updated session", body = SessionResponse), | ||
| 169 | + (status = 400, description = "Invalid fields, time range, or teacher", body = ErrorResponse), | ||
| 170 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 171 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 172 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 173 | + ), | ||
| 174 | +)] | ||
| 175 | +async fn update_session( | ||
| 176 | + State(st): State<AppState>, | ||
| 177 | + RequireTeacher(user): RequireTeacher, | ||
| 178 | + Path(id): Path<String>, | ||
| 179 | + Json(req): Json<UpdateSession>, | ||
| 180 | +) -> Result<Json<SessionResponse>, AppError> { | ||
| 181 | + let (session, course) = session_with_course(&id, &st.db).await?; | ||
| 182 | + if !can_manage_course(&course, &user) { | ||
| 183 | + return Err(AppError::Forbidden( | ||
| 184 | + "only the course creator or a manager/admin can edit this session", | ||
| 185 | + )); | ||
| 186 | + } | ||
| 187 | + | ||
| 188 | + let topic = match req.topic { | ||
| 189 | + Some(ref topic) => SessionTopic::try_new(topic)?, | ||
| 190 | + None => session.get_topic().clone(), | ||
| 191 | + }; | ||
| 192 | + let teacher = match req.teacher_id { | ||
| 193 | + Some(ref key) => resolve_session_teacher(Some(key), &user, &st.db) | ||
| 194 | + .await? | ||
| 195 | + .get_id() | ||
| 196 | + .clone(), | ||
| 197 | + None => session.get_teacher().clone(), | ||
| 198 | + }; | ||
| 199 | + let starts_at = match req.starts_at { | ||
| 200 | + Some(millis) => Timestamp::from_millis(millis), | ||
| 201 | + None => session.get_starts_at(), | ||
| 202 | + }; | ||
| 203 | + // A provided value sets the field, an explicit `null` clears it, and an | ||
| 204 | + // omitted one keeps the current value. | ||
| 205 | + let ends_at = match req.ends_at { | ||
| 206 | + Some(update) => update.map(Timestamp::from_millis), | ||
| 207 | + None => session.get_ends_at(), | ||
| 208 | + }; | ||
| 209 | + check_time_range(Some(starts_at), ends_at)?; | ||
| 210 | + | ||
| 211 | + let updated = session | ||
| 212 | + .update(teacher, topic, starts_at, ends_at, &st.db) | ||
| 213 | + .await?; | ||
| 214 | + let people = person_map([updated.get_teacher().clone()], &st.db).await?; | ||
| 215 | + Ok(Json(SessionResponse::new(&updated, &people))) | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +/// Delete a session and its roll-call rows. Requires teacher+ with | ||
| 219 | +/// course-management rights. | ||
| 220 | +#[utoipa::path( | ||
| 221 | + delete, | ||
| 222 | + path = "/{id}", | ||
| 223 | + tag = "sessions", | ||
| 224 | + security(("session_cookie" = [])), | ||
| 225 | + params(("id" = String, Path, description = "Session id")), | ||
| 226 | + responses( | ||
| 227 | + (status = 204, description = "Deleted"), | ||
| 228 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 229 | + (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), | ||
| 230 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 231 | + ), | ||
| 232 | +)] | ||
| 233 | +async fn delete_session( | ||
| 234 | + State(st): State<AppState>, | ||
| 235 | + RequireTeacher(user): RequireTeacher, | ||
| 236 | + Path(id): Path<String>, | ||
| 237 | +) -> Result<StatusCode, AppError> { | ||
| 238 | + let (session, course) = session_with_course(&id, &st.db).await?; | ||
| 239 | + if !can_manage_course(&course, &user) { | ||
| 240 | + return Err(AppError::Forbidden( | ||
| 241 | + "only the course creator or a manager/admin can delete this session", | ||
| 242 | + )); | ||
| 243 | + } | ||
| 244 | + session.delete(&st.db).await?; | ||
| 245 | + Ok(StatusCode::NO_CONTENT) | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +// ---- roll call -------------------------------------------------------------- | ||
| 249 | + | ||
| 250 | +/// Record a user's roll-call state for a session. The session's teacher or a | ||
| 251 | +/// course manager marks **enrolled students**; marking the **session's | ||
| 252 | +/// teacher** requires manager+ (staff presence is management's call, so a | ||
| 253 | +/// teacher can't mark themselves present). Students never self-mark a lesson. | ||
| 254 | +#[utoipa::path( | ||
| 255 | + post, | ||
| 256 | + path = "/{id}/attendance", | ||
| 257 | + tag = "sessions", | ||
| 258 | + security(("session_cookie" = [])), | ||
| 259 | + params(("id" = String, Path, description = "Session id")), | ||
| 260 | + request_body = MarkRollCall, | ||
| 261 | + responses( | ||
| 262 | + (status = 200, description = "Roll-call state recorded", body = SessionAttendanceResponse), | ||
| 263 | + (status = 400, description = "Invalid status, unknown user, or target not on the roster", body = ErrorResponse), | ||
| 264 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 265 | + (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), | ||
| 266 | + (status = 404, description = "Session not found", body = ErrorResponse), | ||
| 267 | + ), | ||
| 268 | +)] | ||
| 269 | +async fn mark_roll_call( | ||
| 270 | + State(st): State<AppState>, | ||
| 271 | + RequireTeacher(user): RequireTeacher, | ||
| 272 | + Path(id): Path<String>, | ||
| 273 | + Json(req): Json<MarkRollCall>, | ||
| 274 | +) -> Result<Json<SessionAttendanceResponse>, AppError> { | ||
| 275 | + let (session, course) = session_with_course(&id, &st.db).await?; | ||
| 276 | + if !can_roll_call(&session, &course, &user) { | ||
| 277 | + return Err(AppError::Forbidden( | ||
| 278 | + "only the session's teacher or a course manager can take roll call", | ||
| 279 | + )); | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + let status = AttendanceStatus::try_new(&req.status)?; | ||
| 283 | + let target = UserId::from_key(&req.user_id); | ||
| 284 | + | ||
| 285 | + // Target user must exist. | ||
| 286 | + let Some(target_user) = User::read(&target, &st.db).await? else { | ||
| 287 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 288 | + field: "user_id", | ||
| 289 | + reason: "target user does not exist", | ||
| 290 | + })); | ||
| 291 | + }; | ||
| 292 | + | ||
| 293 | + if session.is_teacher(&target) { | ||
| 294 | + // The session teacher's own presence is recorded by management. | ||
| 295 | + if !user.get_role().at_least(Role::Manager) { | ||
| 296 | + return Err(AppError::Forbidden( | ||
| 297 | + "marking the session's teacher requires manager role or higher", | ||
| 298 | + )); | ||
| 299 | + } | ||
| 300 | + } else if Enrollment::read_for_user(session.get_course(), &target, &st.db) | ||
| 301 | + .await? | ||
| 302 | + .is_none() | ||
| 303 | + { | ||
| 304 | + // Everyone else on a lesson's roster comes from the enrollment list. | ||
| 305 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 306 | + field: "user_id", | ||
| 307 | + reason: "target user is not enrolled in this course", | ||
| 308 | + })); | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + let attendance = | ||
| 312 | + SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?; | ||
| 313 | + let people = PersonRef::map_of(&[&target_user, &user]); | ||
| 314 | + Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) | ||
| 315 | +} | ||
| 316 | + | ||
| 317 | +/// List a session's roll call. | ||
| 318 | +#[utoipa::path( | ||
| 319 | + get, | ||
| 320 | + path = "/{id}/attendance", | ||
| 321 | + tag = "sessions", | ||
| 322 | + security(("session_cookie" = [])), | ||
| 323 | + params(("id" = String, Path, description = "Session id")), | ||
| 324 | + responses( | ||
| 325 | + (status = 200, description = "Roll-call roster", body = [SessionAttendanceResponse]), | ||
| 326 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 327 | + (status = 404, description = "Session not found", body = ErrorResponse), | ||
| 328 | + ), | ||
| 329 | +)] | ||
| 330 | +async fn list_roll_call( | ||
| 331 | + State(st): State<AppState>, | ||
| 332 | + _user: CurrentUser, | ||
| 333 | + Path(id): Path<String>, | ||
| 334 | +) -> Result<Json<Vec<SessionAttendanceResponse>>, AppError> { | ||
| 335 | + let session = CourseSession::read(&CourseSessionId::from_key(&id), &st.db) | ||
| 336 | + .await? | ||
| 337 | + .ok_or(AppError::NotFound)?; | ||
| 338 | + let roster = SessionAttendance::list_for_session(session.get_id(), &st.db).await?; | ||
| 339 | + let people = person_map( | ||
| 340 | + roster | ||
| 341 | + .iter() | ||
| 342 | + .flat_map(|a| [a.get_user().clone(), a.get_marked_by().clone()]), | ||
| 343 | + &st.db, | ||
| 344 | + ) | ||
| 345 | + .await?; | ||
| 346 | + Ok(Json( | ||
| 347 | + roster | ||
| 348 | + .iter() | ||
| 349 | + .map(|a| SessionAttendanceResponse::new(a, &people)) | ||
| 350 | + .collect(), | ||
| 351 | + )) | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +/// Remove a user's roll-call row from a session. Same rights as marking: | ||
| 355 | +/// session teacher or course manager for students, manager+ for the session | ||
| 356 | +/// teacher's own row. | ||
| 357 | +#[utoipa::path( | ||
| 358 | + delete, | ||
| 359 | + path = "/{id}/attendance/{user}", | ||
| 360 | + tag = "sessions", | ||
| 361 | + security(("session_cookie" = [])), | ||
| 362 | + params( | ||
| 363 | + ("id" = String, Path, description = "Session id"), | ||
| 364 | + ("user" = String, Path, description = "User id"), | ||
| 365 | + ), | ||
| 366 | + responses( | ||
| 367 | + (status = 204, description = "Removed"), | ||
| 368 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 369 | + (status = 403, description = "Not the session teacher or a course manager; or removing the teacher's row without manager+", body = ErrorResponse), | ||
| 370 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 371 | + ), | ||
| 372 | +)] | ||
| 373 | +async fn remove_roll_call( | ||
| 374 | + State(st): State<AppState>, | ||
| 375 | + RequireTeacher(user): RequireTeacher, | ||
| 376 | + Path((id, target)): Path<(String, String)>, | ||
| 377 | +) -> Result<StatusCode, AppError> { | ||
| 378 | + let (session, course) = session_with_course(&id, &st.db).await?; | ||
| 379 | + if !can_roll_call(&session, &course, &user) { | ||
| 380 | + return Err(AppError::Forbidden( | ||
| 381 | + "only the session's teacher or a course manager can take roll call", | ||
| 382 | + )); | ||
| 383 | + } | ||
| 384 | + let target = UserId::from_key(&target); | ||
| 385 | + if session.is_teacher(&target) && !user.get_role().at_least(Role::Manager) { | ||
| 386 | + return Err(AppError::Forbidden( | ||
| 387 | + "removing the session teacher's row requires manager role or higher", | ||
| 388 | + )); | ||
| 389 | + } | ||
| 390 | + let removed = SessionAttendance::remove(session.get_id(), &target, &st.db).await?; | ||
| 391 | + if removed.is_none() { | ||
| 392 | + return Err(AppError::NotFound); | ||
| 393 | + } | ||
| 394 | + Ok(StatusCode::NO_CONTENT) | ||
| 395 | +} | ||
src/web/work.rsadded+230 -0
| @@ -0,0 +1,230 @@ | |||
| 1 | +use axum::Json; | ||
| 2 | +use axum::extract::{Path, State}; | ||
| 3 | +use axum::http::StatusCode; | ||
| 4 | +use serde::{Deserialize, Serialize}; | ||
| 5 | +use utoipa::ToSchema; | ||
| 6 | +use utoipa_axum::router::OpenApiRouter; | ||
| 7 | +use utoipa_axum::routes; | ||
| 8 | + | ||
| 9 | +use crate::domain::timestamp::Timestamp; | ||
| 10 | +use crate::domain::user::{User, UserId}; | ||
| 11 | +use crate::domain::work_entry::{WorkEntry, WorkEntryId}; | ||
| 12 | +use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 13 | +use crate::state::AppState; | ||
| 14 | + | ||
| 15 | +use super::{RequireManager, RequireTeacher}; | ||
| 16 | + | ||
| 17 | +pub fn routes() -> OpenApiRouter<AppState> { | ||
| 18 | + OpenApiRouter::new() | ||
| 19 | + .routes(routes!(check_in)) | ||
| 20 | + .routes(routes!(check_out)) | ||
| 21 | + .routes(routes!(my_work)) | ||
| 22 | + .routes(routes!(user_work)) | ||
| 23 | + .routes(routes!(update_entry, delete_entry)) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +#[derive(Deserialize, ToSchema)] | ||
| 27 | +struct UpdateWorkEntry { | ||
| 28 | + /// Corrected check-in, UTC unix-milliseconds. Omit to keep. | ||
| 29 | + check_in: Option<i64>, | ||
| 30 | + /// Corrected check-out, UTC unix-milliseconds. Omit to keep. | ||
| 31 | + check_out: Option<i64>, | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +#[derive(Serialize, ToSchema)] | ||
| 35 | +struct WorkEntryResponse { | ||
| 36 | + id: String, | ||
| 37 | + /// The staff member this stint belongs to. | ||
| 38 | + user: String, | ||
| 39 | + /// Stint start, UTC unix-milliseconds (server-stamped). | ||
| 40 | + check_in: i64, | ||
| 41 | + /// Stint end, UTC unix-milliseconds; `null` while still checked in. | ||
| 42 | + check_out: Option<i64>, | ||
| 43 | + /// `check_out - check_in`; `null` while still checked in. | ||
| 44 | + duration_ms: Option<i64>, | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +impl WorkEntryResponse { | ||
| 48 | + fn new(entry: &WorkEntry) -> Self { | ||
| 49 | + let check_in = entry.get_check_in().as_millis(); | ||
| 50 | + let check_out = entry.get_check_out().map(|t| t.as_millis()); | ||
| 51 | + Self { | ||
| 52 | + id: entry.get_id().key().to_string(), | ||
| 53 | + user: entry.get_user().key().to_string(), | ||
| 54 | + check_in, | ||
| 55 | + check_out, | ||
| 56 | + duration_ms: check_out.map(|out| out - check_in), | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Check in for work. Requires teacher+ (staff). The instant is stamped by the | ||
| 62 | +/// server clock — clients never supply it. `409` while already checked in. | ||
| 63 | +#[utoipa::path( | ||
| 64 | + post, | ||
| 65 | + path = "/check-in", | ||
| 66 | + tag = "work", | ||
| 67 | + security(("session_cookie" = [])), | ||
| 68 | + responses( | ||
| 69 | + (status = 201, description = "Checked in — the open stint", body = WorkEntryResponse), | ||
| 70 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 71 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 72 | + (status = 409, description = "Already checked in", body = ErrorResponse), | ||
| 73 | + ), | ||
| 74 | +)] | ||
| 75 | +async fn check_in( | ||
| 76 | + State(st): State<AppState>, | ||
| 77 | + RequireTeacher(user): RequireTeacher, | ||
| 78 | +) -> Result<(StatusCode, Json<WorkEntryResponse>), AppError> { | ||
| 79 | + let entry = WorkEntry::check_in(user.get_id(), &st.db).await?; | ||
| 80 | + Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry)))) | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// Check out of work, closing the open stint. Requires teacher+ (staff). The | ||
| 84 | +/// instant is stamped by the server clock. `409` when not checked in. | ||
| 85 | +#[utoipa::path( | ||
| 86 | + post, | ||
| 87 | + path = "/check-out", | ||
| 88 | + tag = "work", | ||
| 89 | + security(("session_cookie" = [])), | ||
| 90 | + responses( | ||
| 91 | + (status = 200, description = "Checked out — the closed stint", body = WorkEntryResponse), | ||
| 92 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 93 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 94 | + (status = 409, description = "Not checked in", body = ErrorResponse), | ||
| 95 | + ), | ||
| 96 | +)] | ||
| 97 | +async fn check_out( | ||
| 98 | + State(st): State<AppState>, | ||
| 99 | + RequireTeacher(user): RequireTeacher, | ||
| 100 | +) -> Result<Json<WorkEntryResponse>, AppError> { | ||
| 101 | + let entry = WorkEntry::check_out(user.get_id(), &st.db).await?; | ||
| 102 | + Ok(Json(WorkEntryResponse::new(&entry))) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// The caller's own work log, newest first — the open stint (if any) included | ||
| 106 | +/// (`check_out: null`). Requires teacher+ (staff). | ||
| 107 | +#[utoipa::path( | ||
| 108 | + get, | ||
| 109 | + path = "/me", | ||
| 110 | + tag = "work", | ||
| 111 | + security(("session_cookie" = [])), | ||
| 112 | + responses( | ||
| 113 | + (status = 200, description = "The caller's work log", body = [WorkEntryResponse]), | ||
| 114 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 115 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | ||
| 116 | + ), | ||
| 117 | +)] | ||
| 118 | +async fn my_work( | ||
| 119 | + State(st): State<AppState>, | ||
| 120 | + RequireTeacher(user): RequireTeacher, | ||
| 121 | +) -> Result<Json<Vec<WorkEntryResponse>>, AppError> { | ||
| 122 | + let entries = WorkEntry::list_for_user(user.get_id(), &st.db).await?; | ||
| 123 | + Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// A staff member's work log. Requires manager+. | ||
| 127 | +#[utoipa::path( | ||
| 128 | + get, | ||
| 129 | + path = "/{user}", | ||
| 130 | + tag = "work", | ||
| 131 | + security(("session_cookie" = [])), | ||
| 132 | + params(("user" = String, Path, description = "User id")), | ||
| 133 | + responses( | ||
| 134 | + (status = 200, description = "The user's work log", body = [WorkEntryResponse]), | ||
| 135 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 136 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 137 | + (status = 404, description = "User not found", body = ErrorResponse), | ||
| 138 | + ), | ||
| 139 | +)] | ||
| 140 | +async fn user_work( | ||
| 141 | + State(st): State<AppState>, | ||
| 142 | + _manager: RequireManager, | ||
| 143 | + Path(user): Path<String>, | ||
| 144 | +) -> Result<Json<Vec<WorkEntryResponse>>, AppError> { | ||
| 145 | + let target = UserId::from_key(&user); | ||
| 146 | + // User must exist — a missing user is a 404, not an empty log. | ||
| 147 | + User::read(&target, &st.db) | ||
| 148 | + .await? | ||
| 149 | + .ok_or(AppError::NotFound)?; | ||
| 150 | + let entries = WorkEntry::list_for_user(&target, &st.db).await?; | ||
| 151 | + Ok(Json(entries.iter().map(WorkEntryResponse::new).collect())) | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +/// Correct a closed stint's instants. Requires manager+. An open stint can't | ||
| 155 | +/// be corrected (`409`) — it has no end yet; check out first (or delete it). | ||
| 156 | +#[utoipa::path( | ||
| 157 | + patch, | ||
| 158 | + path = "/entries/{id}", | ||
| 159 | + tag = "work", | ||
| 160 | + security(("session_cookie" = [])), | ||
| 161 | + params(("id" = String, Path, description = "Work entry id")), | ||
| 162 | + request_body = UpdateWorkEntry, | ||
| 163 | + responses( | ||
| 164 | + (status = 200, description = "Corrected entry", body = WorkEntryResponse), | ||
| 165 | + (status = 400, description = "check_out precedes check_in", body = ErrorResponse), | ||
| 166 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 167 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 168 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 169 | + (status = 409, description = "Entry is still open", body = ErrorResponse), | ||
| 170 | + ), | ||
| 171 | +)] | ||
| 172 | +async fn update_entry( | ||
| 173 | + State(st): State<AppState>, | ||
| 174 | + _manager: RequireManager, | ||
| 175 | + Path(id): Path<String>, | ||
| 176 | + Json(req): Json<UpdateWorkEntry>, | ||
| 177 | +) -> Result<Json<WorkEntryResponse>, AppError> { | ||
| 178 | + let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db) | ||
| 179 | + .await? | ||
| 180 | + .ok_or(AppError::NotFound)?; | ||
| 181 | + let Some(current_out) = entry.get_check_out() else { | ||
| 182 | + return Err(AppError::Conflict( | ||
| 183 | + "entry is still open — check out first, or delete it", | ||
| 184 | + )); | ||
| 185 | + }; | ||
| 186 | + | ||
| 187 | + let check_in = req | ||
| 188 | + .check_in | ||
| 189 | + .map(Timestamp::from_millis) | ||
| 190 | + .unwrap_or_else(|| entry.get_check_in()); | ||
| 191 | + let check_out = req | ||
| 192 | + .check_out | ||
| 193 | + .map(Timestamp::from_millis) | ||
| 194 | + .unwrap_or(current_out); | ||
| 195 | + if check_out < check_in { | ||
| 196 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 197 | + field: "check_out", | ||
| 198 | + reason: "must be at or after check_in", | ||
| 199 | + })); | ||
| 200 | + } | ||
| 201 | + | ||
| 202 | + let updated = entry.update(check_in, check_out, &st.db).await?; | ||
| 203 | + Ok(Json(WorkEntryResponse::new(&updated))) | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// Delete a work entry (open or closed). Requires manager+. | ||
| 207 | +#[utoipa::path( | ||
| 208 | + delete, | ||
| 209 | + path = "/entries/{id}", | ||
| 210 | + tag = "work", | ||
| 211 | + security(("session_cookie" = [])), | ||
| 212 | + params(("id" = String, Path, description = "Work entry id")), | ||
| 213 | + responses( | ||
| 214 | + (status = 204, description = "Deleted"), | ||
| 215 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 216 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | ||
| 217 | + (status = 404, description = "Not found", body = ErrorResponse), | ||
| 218 | + ), | ||
| 219 | +)] | ||
| 220 | +async fn delete_entry( | ||
| 221 | + State(st): State<AppState>, | ||
| 222 | + _manager: RequireManager, | ||
| 223 | + Path(id): Path<String>, | ||
| 224 | +) -> Result<StatusCode, AppError> { | ||
| 225 | + let removed = WorkEntry::remove(&WorkEntryId::from_key(&id), &st.db).await?; | ||
| 226 | + if removed.is_none() { | ||
| 227 | + return Err(AppError::NotFound); | ||
| 228 | + } | ||
| 229 | + Ok(StatusCode::NO_CONTENT) | ||
| 230 | +} | ||