Server-stamped student focus log
Browse files at this commit73d4367a3d0e6190208462239ba9f7564a7aafa7Parent: dbeb122- feat
- server-stamped student focus log
8 changed files +523 -3
- README.md +29 -2
- src/database.rs +7 -0
- src/domain/mod.rs +1 -0
- src/domain/pomodoro.rs +191 -0
- src/lib.rs +3 -1
- src/web/mod.rs +1 -0
- src/web/pomodoro.rs +211 -0
- tests/integration.rs +80 -0
README.mdmodified+29 -2
| @@ -38,7 +38,10 @@ watch attendance, per-student remaining time, | ||
| 38 | 38 | sittings, walk-outs, no-shows (`absent` once the window closes), submissions, |
| 39 | 39 | and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also carry **lesson |
| 40 | 40 | sessions** with teacher-taken roll call (students never self-mark a lesson), |
| 41 | -staff clock in/out on a server-stamped **work log**, and every user has an | |
| 41 | +staff clock in/out on a server-stamped **work log**, students track study time | |
| 42 | +with a server-stamped **pomodoro log** (the timer runs in the frontend; the | |
| 43 | +backend records the focus stints, and teachers can read any student's log), | |
| 44 | +and every user has an | |
| 42 | 45 | **attendance report** (event + per-course lesson tallies with rates). |
| 43 | 46 | School-varying policy is data, not code: exam kinds (each with its weight in |
| 44 | 47 | course averages), attendance statuses, grade-display bands, and the note-file |
| @@ -196,6 +199,8 @@ effect on the user's very next call (no re-login). | ||
| 196 | 199 | | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | |
| 197 | 200 | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | |
| 198 | 201 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | |
| 202 | +| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | | |
| 203 | +| View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` | | |
| 199 | 204 | | Read **own** attendance report | student | | |
| 200 | 205 | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | |
| 201 | 206 | | View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) | |
| @@ -377,6 +382,10 @@ their existing shapes: the student exam-room reads | ||
| 377 | 382 | | GET | `/work/{user}` | manager | A staff member's work log · paged | |
| 378 | 383 | | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) | |
| 379 | 384 | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | |
| 385 | +| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** — a dangling unfinished session is discarded and replaced) | | |
| 386 | +| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) | | |
| 387 | +| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` · paged | | |
| 388 | +| GET | `/pomodoro/{user}` | teacher | A user's pomodoro log, same shape · paged | | |
| 380 | 389 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | |
| 381 | 390 | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | |
| 382 | 391 | | GET | `/settings` | student | The school's policy: `exam_kinds` (`{name, weight}` each), `attendance_statuses`, `grade_bands`, `max_file_bytes` | |
| @@ -751,7 +760,7 @@ The live monitor rides along: each roster row now carries `answered` and | ||
| 751 | 760 | The student's own `GET /exams/{id}/attempt` echoes the same |
| 752 | 761 | `answered`/`question_count` pair. |
| 753 | 762 | |
| 754 | -## Lesson sessions, roll call, the work log & attendance reports | |
| 763 | +## Lesson sessions, roll call, the work log, pomodoro & attendance reports | |
| 755 | 764 | |
| 756 | 765 | Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session |
| 757 | 766 | belongs to a course and carries a `teacher` (defaults to whoever creates it; |
| @@ -785,6 +794,20 @@ anyone's log (`GET /work/{user}`), corrects a **closed** stint's instants | ||
| 785 | 794 | (`PATCH /work/entries/{id}`, `409` while open — check out or delete instead), |
| 786 | 795 | and deletes entries. |
| 787 | 796 | |
| 797 | +The **pomodoro log** (`/pomodoro`) is the students' study-time twin of the | |
| 798 | +work log. The frontend owns the timer — the visible countdown, the work/break | |
| 799 | +rhythm, the durations; the backend stores no timing policy and records only | |
| 800 | +**focus stints**, stamped by the server clock exactly like work stints. | |
| 801 | +`POST /pomodoro/start` opens a session and — unlike a work check-in — always | |
| 802 | +succeeds for a student: a dangling unfinished session (a laptop closed | |
| 803 | +mid-timer) is **discarded and replaced**, because it recorded no focus and | |
| 804 | +must not lock the student out of the next one. `POST /pomodoro/finish` closes | |
| 805 | +the running session (`409` when nothing runs); breaks are never reported. | |
| 806 | +Logs return the usual page envelope plus `total_focus_ms`, the unpaged sum of | |
| 807 | +every finished session's duration: `GET /pomodoro/me` for your own, | |
| 808 | +`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start | |
| 809 | +sessions — pomodoro is the study tool, the work log is the staff timesheet. | |
| 810 | + | |
| 788 | 811 | **Attendance reports** mirror the marks report: `GET /attendance/me` for any |
| 789 | 812 | logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the |
| 790 | 813 | courses the caller manages (manager+ sees every course; event tallies are |
| @@ -874,6 +897,10 @@ curl -s -b $JAR $BASE/work/me | ||
| 874 | 897 | # ...and as the student: |
| 875 | 898 | curl -s -b $STUDENT_JAR $BASE/marks/me |
| 876 | 899 | curl -s -b $STUDENT_JAR $BASE/attendance/me |
| 900 | +# pomodoro: start when the timer starts, finish when it rings | |
| 901 | +curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start | |
| 902 | +curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish | |
| 903 | +curl -s -b $STUDENT_JAR $BASE/pomodoro/me | |
| 877 | 904 | ``` |
| 878 | 905 | |
| 879 | 906 | ## Layout |
src/database.rsmodified+7 -0
| @@ -26,6 +26,7 @@ pub const ENROLLMENT_TABLE: &str = "enrollment"; | ||
| 26 | 26 | pub const COURSE_SESSION_TABLE: &str = "course_session"; |
| 27 | 27 | pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; |
| 28 | 28 | pub const WORK_ENTRY_TABLE: &str = "work_entry"; |
| 29 | +pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session"; | |
| 29 | 30 | pub const SETTINGS_TABLE: &str = "settings"; |
| 30 | 31 | pub const TERM_TABLE: &str = "term"; |
| 31 | 32 | pub const SUBJECT_TABLE: &str = "subject"; |
| @@ -150,6 +151,12 @@ const MIGRATION: &str = " | ||
| 150 | 151 | DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option<int>; |
| 151 | 152 | DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; |
| 152 | 153 | |
| 154 | + DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; | |
| 155 | + DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>; | |
| 156 | + DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; | |
| 157 | + DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>; | |
| 158 | + DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; | |
| 159 | + | |
| 153 | 160 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; |
| 154 | 161 | DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record<user>; |
| 155 | 162 | DEFINE FIELD IF NOT EXISTS course ON exam TYPE record<course>; |
src/domain/mod.rsmodified+1 -0
| @@ -14,6 +14,7 @@ pub mod exam_question; | ||
| 14 | 14 | pub mod exam_result; |
| 15 | 15 | pub mod note; |
| 16 | 16 | pub mod note_file; |
| 17 | +pub mod pomodoro; | |
| 17 | 18 | pub mod preferences; |
| 18 | 19 | pub mod profile; |
| 19 | 20 | pub mod question_image; |
src/domain/pomodoro.rsadded+191 -0
| @@ -0,0 +1,191 @@ | ||
| 1 | +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | |
| 2 | +use ulid::Ulid; | |
| 3 | + | |
| 4 | +use crate::database::{Database, POMODORO_SESSION_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 PomodoroSessionId(RecordId); | |
| 11 | + | |
| 12 | +impl PomodoroSessionId { | |
| 13 | + pub fn generate() -> Self { | |
| 14 | + Self(RecordId::new( | |
| 15 | + POMODORO_SESSION_TABLE, | |
| 16 | + Ulid::new().to_string(), | |
| 17 | + )) | |
| 18 | + } | |
| 19 | + | |
| 20 | + /// The deterministic id of `user`'s *running* session. At most one runs | |
| 21 | + /// per user by construction: starting is a single `UPSERT` on this id | |
| 22 | + /// (atomic — a restart replaces the row in place), and finishing | |
| 23 | + /// atomically takes the row and re-files it under a ULID id. `open_` | |
| 24 | + /// cannot collide with a ULID key (ULIDs are bare alphanumerics). | |
| 25 | + pub fn open_for(user: &UserId) -> Self { | |
| 26 | + Self(RecordId::new( | |
| 27 | + POMODORO_SESSION_TABLE, | |
| 28 | + format!("open_{}", user.key()), | |
| 29 | + )) | |
| 30 | + } | |
| 31 | + | |
| 32 | + pub fn record(&self) -> RecordId { | |
| 33 | + self.0.clone() | |
| 34 | + } | |
| 35 | + | |
| 36 | + pub fn key(&self) -> &str { | |
| 37 | + match &self.0.key { | |
| 38 | + RecordIdKey::String(key) => key, | |
| 39 | + _ => "", | |
| 40 | + } | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +/// One pomodoro focus session of a student: server-stamped `started_at`, and | |
| 45 | +/// `finished_at` once closed. The wall clock is read server-side only — a | |
| 46 | +/// client can never supply its own instants, so the recorded focus time is | |
| 47 | +/// honest. Breaks are not stored; the frontend owns the work/break rhythm and | |
| 48 | +/// the backend records only the focus stint. | |
| 49 | +#[derive(Debug, Clone, SurrealValue)] | |
| 50 | +pub struct PomodoroSession { | |
| 51 | + id: PomodoroSessionId, | |
| 52 | + user: UserId, | |
| 53 | + started_at: Timestamp, | |
| 54 | + finished_at: Option<Timestamp>, | |
| 55 | +} | |
| 56 | + | |
| 57 | +impl PomodoroSession { | |
| 58 | + pub fn get_id(&self) -> &PomodoroSessionId { | |
| 59 | + &self.id | |
| 60 | + } | |
| 61 | + | |
| 62 | + pub fn get_user(&self) -> &UserId { | |
| 63 | + &self.user | |
| 64 | + } | |
| 65 | + | |
| 66 | + pub fn get_started_at(&self) -> Timestamp { | |
| 67 | + self.started_at | |
| 68 | + } | |
| 69 | + | |
| 70 | + pub fn get_finished_at(&self) -> Option<Timestamp> { | |
| 71 | + self.finished_at | |
| 72 | + } | |
| 73 | + | |
| 74 | + /// Start a session for `user`, stamped with the server clock. `UPSERT` on | |
| 75 | + /// the deterministic open id makes this atomic and always succeed: a | |
| 76 | + /// dangling unfinished session (the browser died mid-timer) is replaced — | |
| 77 | + /// it never counted, and blocking the next start behind it would only | |
| 78 | + /// punish the student for a crash. | |
| 79 | + pub async fn start(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> { | |
| 80 | + let mut result = db | |
| 81 | + .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") | |
| 82 | + .bind(("open", PomodoroSessionId::open_for(user).record())) | |
| 83 | + .bind(("usr", user.record())) | |
| 84 | + .bind(("at", Timestamp::now())) | |
| 85 | + .await? | |
| 86 | + .check()?; | |
| 87 | + result | |
| 88 | + .take::<Vec<PomodoroSession>>(0)? | |
| 89 | + .into_iter() | |
| 90 | + .next() | |
| 91 | + .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into())) | |
| 92 | + } | |
| 93 | + | |
| 94 | + /// Close `user`'s running session: atomically take the open row and | |
| 95 | + /// re-file it under a ULID id, freeing the open slot for the next start. | |
| 96 | + /// Take and re-file share one transaction — a failed re-file rolls the | |
| 97 | + /// take back, so a session can never vanish half-closed. Of two racing | |
| 98 | + /// finishes exactly one receives the row (the other gets the conflict). | |
| 99 | + pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> { | |
| 100 | + let mut result = db | |
| 101 | + .query( | |
| 102 | + "BEGIN TRANSACTION; | |
| 103 | + LET $before = (DELETE $open RETURN BEFORE); | |
| 104 | + IF array::len($before) = 0 { THROW 'no_pomodoro_running' }; | |
| 105 | + CREATE $closed CONTENT { | |
| 106 | + user: $before[0].user, | |
| 107 | + started_at: $before[0].started_at, | |
| 108 | + finished_at: $done, | |
| 109 | + }; | |
| 110 | + COMMIT TRANSACTION;", | |
| 111 | + ) | |
| 112 | + .bind(("open", PomodoroSessionId::open_for(user).record())) | |
| 113 | + .bind(("closed", PomodoroSessionId::generate().record())) | |
| 114 | + .bind(("done", Timestamp::now())) | |
| 115 | + .await?; | |
| 116 | + // An aborted transaction errors *every* slot, most with a generic | |
| 117 | + // "not executed" — only the THROW's own slot names the reason, so scan | |
| 118 | + // them all for the marker instead of trusting the first. | |
| 119 | + let mut errors = result.take_errors(); | |
| 120 | + if errors | |
| 121 | + .values() | |
| 122 | + .any(|error| error.to_string().contains("no_pomodoro_running")) | |
| 123 | + { | |
| 124 | + return Err(AppError::Conflict("no pomodoro session running")); | |
| 125 | + } | |
| 126 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 127 | + return Err(error.into()); | |
| 128 | + } | |
| 129 | + // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. | |
| 130 | + let saved: Option<PomodoroSession> = | |
| 131 | + result.take::<Vec<PomodoroSession>>(3)?.into_iter().next(); | |
| 132 | + saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into())) | |
| 133 | + } | |
| 134 | + | |
| 135 | + /// Every session of `user`, newest first — the running one (if any) | |
| 136 | + /// included. Ordered by `started_at`: the open entry's `open_` key doesn't | |
| 137 | + /// sort with the ULIDs, so id order would misplace it. | |
| 138 | + pub async fn list_for_user( | |
| 139 | + user: &UserId, | |
| 140 | + db: &Database, | |
| 141 | + ) -> Result<Vec<PomodoroSession>, AppError> { | |
| 142 | + let mut result = db | |
| 143 | + .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC") | |
| 144 | + .bind(("usr", user.record())) | |
| 145 | + .await? | |
| 146 | + .check()?; | |
| 147 | + Ok(result.take::<Vec<PomodoroSession>>(0)?) | |
| 148 | + } | |
| 149 | +} | |
| 150 | + | |
| 151 | +#[cfg(test)] | |
| 152 | +mod tests { | |
| 153 | + use super::*; | |
| 154 | + use crate::database; | |
| 155 | + | |
| 156 | + #[tokio::test] | |
| 157 | + async fn restart_replaces_the_open_session_and_finish_closes_it() { | |
| 158 | + let db = database::init_mem().await.unwrap(); | |
| 159 | + // A `record<user>` column checks the table of the id, not row | |
| 160 | + // existence — a fabricated id keeps this test free of user ceremony. | |
| 161 | + let user = UserId::from_key(&Ulid::new().to_string()); | |
| 162 | + | |
| 163 | + // Nothing running yet — finishing conflicts. | |
| 164 | + assert!(matches!( | |
| 165 | + PomodoroSession::finish(&user, &db).await, | |
| 166 | + Err(AppError::Conflict(_)) | |
| 167 | + )); | |
| 168 | + | |
| 169 | + let first = PomodoroSession::start(&user, &db).await.unwrap(); | |
| 170 | + assert!(first.get_finished_at().is_none()); | |
| 171 | + assert_eq!(first.get_id().key(), format!("open_{}", user.key())); | |
| 172 | + | |
| 173 | + // A restart replaces the dangling session: still one row, fresh clock. | |
| 174 | + let second = PomodoroSession::start(&user, &db).await.unwrap(); | |
| 175 | + assert!(second.get_started_at() >= first.get_started_at()); | |
| 176 | + let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); | |
| 177 | + assert_eq!(sessions.len(), 1); | |
| 178 | + | |
| 179 | + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); | |
| 180 | + assert!(closed.get_finished_at().unwrap() >= closed.get_started_at()); | |
| 181 | + | |
| 182 | + // The open slot is free again; a stray second finish conflicts. | |
| 183 | + assert!(matches!( | |
| 184 | + PomodoroSession::finish(&user, &db).await, | |
| 185 | + Err(AppError::Conflict(_)) | |
| 186 | + )); | |
| 187 | + PomodoroSession::start(&user, &db).await.unwrap(); | |
| 188 | + let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); | |
| 189 | + assert_eq!(sessions.len(), 2); | |
| 190 | + } | |
| 191 | +} |
src/lib.rsmodified+3 -1
| @@ -32,7 +32,7 @@ use crate::state::AppState; | ||
| 32 | 32 | info( |
| 33 | 33 | title = "Hezarfen Backend API", |
| 34 | 34 | version = env!("CARGO_PKG_VERSION"), |
| 35 | - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", | |
| 35 | + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in two behaviorally identical kinds — `course` (a regular class) and `study` (a supervised study session — etüt) — and carry lesson sessions with teacher-taken roll call; each course also owns its curriculum as a list of subjects, and every exam question must be tagged with one of its course's subjects (a subject still referenced by questions cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`) and language (`tr`/`en`) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count.", | |
| 36 | 36 | ), |
| 37 | 37 | modifiers(&SecurityAddon), |
| 38 | 38 | tags( |
| @@ -44,6 +44,7 @@ use crate::state::AppState; | ||
| 44 | 44 | (name = "courses", description = "Courses — kind `course` (regular class) or `study` (etüt, a supervised study session; same behavior, different label) — enrollment (students only), course exams, and course sessions"), |
| 45 | 45 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), |
| 46 | 46 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 47 | + (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), | |
| 47 | 48 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), |
| 48 | 49 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"), |
| 49 | 50 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"), |
| @@ -87,6 +88,7 @@ pub fn build_router(state: AppState) -> Router { | ||
| 87 | 88 | .nest("/exams", web::exams::routes()) |
| 88 | 89 | .nest("/marks", web::marks::routes()) |
| 89 | 90 | .nest("/work", web::work::routes()) |
| 91 | + .nest("/pomodoro", web::pomodoro::routes()) | |
| 90 | 92 | .nest("/attendance", web::attendance::routes()) |
| 91 | 93 | .nest("/settings", web::settings::routes()) |
| 92 | 94 | .nest("/subjects", web::subjects::routes()) |
src/web/mod.rsmodified+1 -0
| @@ -11,6 +11,7 @@ pub mod exam_ws; | ||
| 11 | 11 | pub mod exams; |
| 12 | 12 | pub mod marks; |
| 13 | 13 | pub mod notes; |
| 14 | +pub mod pomodoro; | |
| 14 | 15 | pub mod sessions; |
| 15 | 16 | pub mod settings; |
| 16 | 17 | pub mod subjects; |
src/web/pomodoro.rsadded+211 -0
| @@ -0,0 +1,211 @@ | ||
| 1 | +use axum::Json; | |
| 2 | +use axum::extract::{Path, Query, State}; | |
| 3 | +use axum::http::StatusCode; | |
| 4 | +use serde::Serialize; | |
| 5 | +use utoipa::ToSchema; | |
| 6 | +use utoipa_axum::router::OpenApiRouter; | |
| 7 | +use utoipa_axum::routes; | |
| 8 | + | |
| 9 | +use crate::domain::pomodoro::PomodoroSession; | |
| 10 | +use crate::domain::role::Role; | |
| 11 | +use crate::domain::user::{User, UserId}; | |
| 12 | +use crate::error::{AppError, ErrorResponse}; | |
| 13 | +use crate::state::AppState; | |
| 14 | + | |
| 15 | +use super::{CurrentUser, PageParams, RequireTeacher, paginate}; | |
| 16 | + | |
| 17 | +pub fn routes() -> OpenApiRouter<AppState> { | |
| 18 | + OpenApiRouter::new() | |
| 19 | + .routes(routes!(start)) | |
| 20 | + .routes(routes!(finish)) | |
| 21 | + .routes(routes!(my_pomodoro)) | |
| 22 | + .routes(routes!(user_pomodoro)) | |
| 23 | +} | |
| 24 | + | |
| 25 | +/// A 403 unless `user` is a student — the pomodoro timer is the students' | |
| 26 | +/// study tool (staff time-keeping is the work log). Only `start` is gated: | |
| 27 | +/// finishing merely closes a session that only a student could have opened, | |
| 28 | +/// so a mid-session promotion still gets its last stint on the record. | |
| 29 | +fn ensure_student(user: &User) -> Result<(), AppError> { | |
| 30 | + if user.get_role() != Role::Student { | |
| 31 | + return Err(AppError::Forbidden("only students run pomodoro sessions")); | |
| 32 | + } | |
| 33 | + Ok(()) | |
| 34 | +} | |
| 35 | + | |
| 36 | +#[derive(Serialize, ToSchema)] | |
| 37 | +struct PomodoroResponse { | |
| 38 | + id: String, | |
| 39 | + /// The student this session belongs to. | |
| 40 | + user: String, | |
| 41 | + /// Session start, UTC unix-milliseconds (server-stamped). | |
| 42 | + started_at: i64, | |
| 43 | + /// Session end, UTC unix-milliseconds; `null` while still running. | |
| 44 | + finished_at: Option<i64>, | |
| 45 | + /// `finished_at - started_at`; `null` while still running. | |
| 46 | + duration_ms: Option<i64>, | |
| 47 | +} | |
| 48 | + | |
| 49 | +impl PomodoroResponse { | |
| 50 | + fn new(session: &PomodoroSession) -> Self { | |
| 51 | + let started_at = session.get_started_at().as_millis(); | |
| 52 | + let finished_at = session.get_finished_at().map(|t| t.as_millis()); | |
| 53 | + Self { | |
| 54 | + id: session.get_id().key().to_string(), | |
| 55 | + user: session.get_user().key().to_string(), | |
| 56 | + started_at, | |
| 57 | + finished_at, | |
| 58 | + duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), | |
| 59 | + } | |
| 60 | + } | |
| 61 | +} | |
| 62 | + | |
| 63 | +/// The standard `{items, total, limit, offset}` page envelope over the | |
| 64 | +/// sessions, plus the unpaged focus total — spelled out (not `Page<T>`) so the | |
| 65 | +/// extra field rides inside the same flat object. | |
| 66 | +#[derive(Serialize, ToSchema)] | |
| 67 | +struct PomodoroLog { | |
| 68 | + items: Vec<PomodoroResponse>, | |
| 69 | + /// Total sessions in the full log, before `limit`/`offset` are applied. | |
| 70 | + #[schema(example = 256)] | |
| 71 | + total: i64, | |
| 72 | + /// Echo of the applied `limit`; `null` when the response is unbounded. | |
| 73 | + #[schema(example = 100)] | |
| 74 | + limit: Option<i64>, | |
| 75 | + /// Echo of the applied `offset`. | |
| 76 | + #[schema(example = 0)] | |
| 77 | + offset: i64, | |
| 78 | + /// Sum of `duration_ms` over every *finished* session — the whole log, | |
| 79 | + /// not just this page. A running session counts nothing until finished. | |
| 80 | + total_focus_ms: i64, | |
| 81 | +} | |
| 82 | + | |
| 83 | +impl PomodoroLog { | |
| 84 | + fn new(sessions: &[PomodoroSession], limit: Option<i64>, offset: i64) -> Self { | |
| 85 | + let total_focus_ms = sessions | |
| 86 | + .iter() | |
| 87 | + .filter_map(|session| { | |
| 88 | + session.get_finished_at().map(|done| { | |
| 89 | + done.as_millis() | |
| 90 | + .saturating_sub(session.get_started_at().as_millis()) | |
| 91 | + }) | |
| 92 | + }) | |
| 93 | + .sum(); | |
| 94 | + Self { | |
| 95 | + items: paginate(sessions, limit, offset) | |
| 96 | + .iter() | |
| 97 | + .map(PomodoroResponse::new) | |
| 98 | + .collect(), | |
| 99 | + total: sessions.len() as i64, | |
| 100 | + limit, | |
| 101 | + offset, | |
| 102 | + total_focus_ms, | |
| 103 | + } | |
| 104 | + } | |
| 105 | +} | |
| 106 | + | |
| 107 | +/// Start a pomodoro focus session. Students only. The instant is stamped by | |
| 108 | +/// the server clock — clients never supply it. Always succeeds for a student: | |
| 109 | +/// a dangling unfinished session (the browser died mid-timer) is discarded | |
| 110 | +/// and replaced, so there is no way to lock yourself out of starting. The | |
| 111 | +/// frontend runs the visible countdown and the break rhythm; the backend | |
| 112 | +/// records only the focus stint. | |
| 113 | +#[utoipa::path( | |
| 114 | + post, | |
| 115 | + path = "/start", | |
| 116 | + tag = "pomodoro", | |
| 117 | + security(("session_cookie" = [])), | |
| 118 | + responses( | |
| 119 | + (status = 201, description = "Session started — the running session", body = PomodoroResponse), | |
| 120 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 121 | + (status = 403, description = "Requires the student role", body = ErrorResponse), | |
| 122 | + ), | |
| 123 | +)] | |
| 124 | +async fn start( | |
| 125 | + State(st): State<AppState>, | |
| 126 | + CurrentUser(user): CurrentUser, | |
| 127 | +) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> { | |
| 128 | + ensure_student(&user)?; | |
| 129 | + let session = PomodoroSession::start(user.get_id(), &st.db).await?; | |
| 130 | + Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) | |
| 131 | +} | |
| 132 | + | |
| 133 | +/// Finish the running pomodoro session, closing it with a server-stamped | |
| 134 | +/// instant. `409` when nothing is running. | |
| 135 | +#[utoipa::path( | |
| 136 | + post, | |
| 137 | + path = "/finish", | |
| 138 | + tag = "pomodoro", | |
| 139 | + security(("session_cookie" = [])), | |
| 140 | + responses( | |
| 141 | + (status = 200, description = "Session finished — the closed session", body = PomodoroResponse), | |
| 142 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 143 | + (status = 409, description = "No pomodoro session running", body = ErrorResponse), | |
| 144 | + ), | |
| 145 | +)] | |
| 146 | +async fn finish( | |
| 147 | + State(st): State<AppState>, | |
| 148 | + CurrentUser(user): CurrentUser, | |
| 149 | +) -> Result<Json<PomodoroResponse>, AppError> { | |
| 150 | + let session = PomodoroSession::finish(user.get_id(), &st.db).await?; | |
| 151 | + Ok(Json(PomodoroResponse::new(&session))) | |
| 152 | +} | |
| 153 | + | |
| 154 | +/// The caller's own pomodoro log, newest first — the running session (if any) | |
| 155 | +/// included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of | |
| 156 | +/// finished-session durations. Paged via `?limit=&offset=` (omit `limit` for | |
| 157 | +/// the whole log). | |
| 158 | +#[utoipa::path( | |
| 159 | + get, | |
| 160 | + path = "/me", | |
| 161 | + tag = "pomodoro", | |
| 162 | + security(("session_cookie" = [])), | |
| 163 | + params(PageParams), | |
| 164 | + responses( | |
| 165 | + (status = 200, description = "A page of the caller's pomodoro log with the unpaged focus total", body = PomodoroLog), | |
| 166 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | |
| 167 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 168 | + ), | |
| 169 | +)] | |
| 170 | +async fn my_pomodoro( | |
| 171 | + State(st): State<AppState>, | |
| 172 | + CurrentUser(user): CurrentUser, | |
| 173 | + Query(page): Query<PageParams>, | |
| 174 | +) -> Result<Json<PomodoroLog>, AppError> { | |
| 175 | + let (limit, offset) = page.resolve()?; | |
| 176 | + let sessions = PomodoroSession::list_for_user(user.get_id(), &st.db).await?; | |
| 177 | + Ok(Json(PomodoroLog::new(&sessions, limit, offset))) | |
| 178 | +} | |
| 179 | + | |
| 180 | +/// A student's pomodoro log, newest first, with `total_focus_ms` — the same | |
| 181 | +/// shape as `/me`. Requires teacher+ (study oversight). Paged via | |
| 182 | +/// `?limit=&offset=`. | |
| 183 | +#[utoipa::path( | |
| 184 | + get, | |
| 185 | + path = "/{user}", | |
| 186 | + tag = "pomodoro", | |
| 187 | + security(("session_cookie" = [])), | |
| 188 | + params(("user" = String, Path, description = "User id"), PageParams), | |
| 189 | + responses( | |
| 190 | + (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog), | |
| 191 | + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), | |
| 192 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 193 | + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), | |
| 194 | + (status = 404, description = "User not found", body = ErrorResponse), | |
| 195 | + ), | |
| 196 | +)] | |
| 197 | +async fn user_pomodoro( | |
| 198 | + State(st): State<AppState>, | |
| 199 | + _teacher: RequireTeacher, | |
| 200 | + Path(user): Path<String>, | |
| 201 | + Query(page): Query<PageParams>, | |
| 202 | +) -> Result<Json<PomodoroLog>, AppError> { | |
| 203 | + let (limit, offset) = page.resolve()?; | |
| 204 | + let target = UserId::from_key(&user); | |
| 205 | + // User must exist — a missing user is a 404, not an empty log. | |
| 206 | + User::read(&target, &st.db) | |
| 207 | + .await? | |
| 208 | + .ok_or(AppError::NotFound)?; | |
| 209 | + let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; | |
| 210 | + Ok(Json(PomodoroLog::new(&sessions, limit, offset))) | |
| 211 | +} |
tests/integration.rsmodified+80 -0
| @@ -231,6 +231,10 @@ async fn protected_routes_require_session() { | ||
| 231 | 231 | ("GET", "/work/u"), |
| 232 | 232 | ("PATCH", "/work/entries/x"), |
| 233 | 233 | ("DELETE", "/work/entries/x"), |
| 234 | + ("POST", "/pomodoro/start"), | |
| 235 | + ("POST", "/pomodoro/finish"), | |
| 236 | + ("GET", "/pomodoro/me"), | |
| 237 | + ("GET", "/pomodoro/u"), | |
| 234 | 238 | ("GET", "/attendance/me"), |
| 235 | 239 | ("GET", "/attendance/u"), |
| 236 | 240 | ] { |
| @@ -8845,6 +8849,82 @@ async fn work_log_lifecycle_is_server_stamped_and_exclusive() { | ||
| 8845 | 8849 | assert!(!log[1]["check_out"].is_null()); |
| 8846 | 8850 | } |
| 8847 | 8851 | |
| 8852 | +// --- pomodoro ---------------------------------------------------------------- | |
| 8853 | + | |
| 8854 | +#[tokio::test] | |
| 8855 | +async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { | |
| 8856 | + let (app, db) = app_and_db().await; | |
| 8857 | + let ali = login(&app, "ali").await; | |
| 8858 | + let hoca = login_as(&app, &db, "hoca", "teacher").await; | |
| 8859 | + let ali_id = me_id(&app, &ali).await; | |
| 8860 | + | |
| 8861 | + // Students only on start; finishing with nothing running conflicts. | |
| 8862 | + let res = send(&app, "POST", "/pomodoro/start", Some(&hoca), None).await; | |
| 8863 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | |
| 8864 | + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; | |
| 8865 | + assert_eq!(res.status, StatusCode::CONFLICT); | |
| 8866 | + | |
| 8867 | + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; | |
| 8868 | + assert_eq!(res.status, StatusCode::CREATED); | |
| 8869 | + assert!(res.body["finished_at"].is_null()); | |
| 8870 | + let first_start = res.body["started_at"].as_i64().unwrap(); | |
| 8871 | + | |
| 8872 | + // A restart discards the dangling session: one row, clock reset allowed. | |
| 8873 | + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; | |
| 8874 | + assert_eq!(res.status, StatusCode::CREATED); | |
| 8875 | + assert!(res.body["started_at"].as_i64().unwrap() >= first_start); | |
| 8876 | + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; | |
| 8877 | + assert_eq!(common::items(&res.body).len(), 1); | |
| 8878 | + assert_eq!( | |
| 8879 | + res.body["total_focus_ms"], 0, | |
| 8880 | + "running session counts nothing" | |
| 8881 | + ); | |
| 8882 | + | |
| 8883 | + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; | |
| 8884 | + assert_eq!(res.status, StatusCode::OK); | |
| 8885 | + let finished_at = res.body["finished_at"].as_i64().unwrap(); | |
| 8886 | + let duration = res.body["duration_ms"].as_i64().unwrap(); | |
| 8887 | + assert_eq!( | |
| 8888 | + duration, | |
| 8889 | + finished_at - res.body["started_at"].as_i64().unwrap() | |
| 8890 | + ); | |
| 8891 | + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; | |
| 8892 | + assert_eq!(res.status, StatusCode::CONFLICT, "already finished"); | |
| 8893 | + | |
| 8894 | + // The open slot is free again; the log keeps both sessions, newest first, | |
| 8895 | + // and the focus total sums only the finished one. | |
| 8896 | + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; | |
| 8897 | + assert_eq!(res.status, StatusCode::CREATED); | |
| 8898 | + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; | |
| 8899 | + let log = common::items(&res.body); | |
| 8900 | + assert_eq!(log.len(), 2); | |
| 8901 | + assert!(log[0]["finished_at"].is_null(), "open session sorts newest"); | |
| 8902 | + assert_eq!(res.body["total_focus_ms"].as_i64().unwrap(), duration); | |
| 8903 | + | |
| 8904 | + // Reading someone's log is teacher+; unknown users are 404. | |
| 8905 | + let res = send( | |
| 8906 | + &app, | |
| 8907 | + "GET", | |
| 8908 | + &format!("/pomodoro/{ali_id}"), | |
| 8909 | + Some(&ali), | |
| 8910 | + None, | |
| 8911 | + ) | |
| 8912 | + .await; | |
| 8913 | + assert_eq!(res.status, StatusCode::FORBIDDEN); | |
| 8914 | + let res = send( | |
| 8915 | + &app, | |
| 8916 | + "GET", | |
| 8917 | + &format!("/pomodoro/{ali_id}"), | |
| 8918 | + Some(&hoca), | |
| 8919 | + None, | |
| 8920 | + ) | |
| 8921 | + .await; | |
| 8922 | + assert_eq!(res.status, StatusCode::OK); | |
| 8923 | + assert_eq!(common::items(&res.body).len(), 2); | |
| 8924 | + let res = send(&app, "GET", "/pomodoro/01UNKNOWN", Some(&hoca), None).await; | |
| 8925 | + assert_eq!(res.status, StatusCode::NOT_FOUND); | |
| 8926 | +} | |
| 8927 | + | |
| 8848 | 8928 | #[tokio::test] |
| 8849 | 8929 | async fn work_log_manager_reads_and_corrections() { |
| 8850 | 8930 | let (app, db) = app_and_db().await; |