diff --git a/README.md b/README.md index 177acfd..b1ed3c4 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,10 @@ watch attendance, per-student remaining time, sittings, walk-outs, no-shows (`absent` once the window closes), submissions, and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also carry **lesson sessions** with teacher-taken roll call (students never self-mark a lesson), -staff clock in/out on a server-stamped **work log**, and every user has an +staff clock in/out on a server-stamped **work log**, students track study time +with a server-stamped **pomodoro log** (the timer runs in the frontend; the +backend records the focus stints, and teachers can read any student's log), +and every user has an **attendance report** (event + per-course lesson tallies with rates). School-varying policy is data, not code: exam kinds (each with its weight in 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). | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | +| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | +| View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` | | Read **own** attendance report | student | | | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all | | 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 | GET | `/work/{user}` | manager | A staff member's work log · paged | | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | +| POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** — a dangling unfinished session is discarded and replaced) | +| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) | +| GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` · paged | +| GET | `/pomodoro/{user}` | teacher | A user's pomodoro log, same shape · paged | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | GET | `/attendance/{user}` | teacher | A user's attendance report, narrowed to the caller's courses (manager+: full) | | 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 The student's own `GET /exams/{id}/attempt` echoes the same `answered`/`question_count` pair. -## Lesson sessions, roll call, the work log & attendance reports +## Lesson sessions, roll call, the work log, pomodoro & attendance reports Events cover ad-hoc gatherings; **sessions** are a course's lessons. A session 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 (`PATCH /work/entries/{id}`, `409` while open — check out or delete instead), and deletes entries. +The **pomodoro log** (`/pomodoro`) is the students' study-time twin of the +work log. The frontend owns the timer — the visible countdown, the work/break +rhythm, the durations; the backend stores no timing policy and records only +**focus stints**, stamped by the server clock exactly like work stints. +`POST /pomodoro/start` opens a session and — unlike a work check-in — always +succeeds for a student: a dangling unfinished session (a laptop closed +mid-timer) is **discarded and replaced**, because it recorded no focus and +must not lock the student out of the next one. `POST /pomodoro/finish` closes +the running session (`409` when nothing runs); breaks are never reported. +Logs return the usual page envelope plus `total_focus_ms`, the unpaged sum of +every finished session's duration: `GET /pomodoro/me` for your own, +`GET /pomodoro/{user}` for teacher+ (study oversight). Only students start +sessions — pomodoro is the study tool, the work log is the staff timesheet. + **Attendance reports** mirror the marks report: `GET /attendance/me` for any logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the courses the caller manages (manager+ sees every course; event tallies are @@ -874,6 +897,10 @@ curl -s -b $JAR $BASE/work/me # ...and as the student: curl -s -b $STUDENT_JAR $BASE/marks/me curl -s -b $STUDENT_JAR $BASE/attendance/me +# pomodoro: start when the timer starts, finish when it rings +curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/start +curl -s -b $STUDENT_JAR -X POST $BASE/pomodoro/finish +curl -s -b $STUDENT_JAR $BASE/pomodoro/me ``` ## Layout diff --git a/src/database.rs b/src/database.rs index 70eae92..f58dbb5 100644 --- a/src/database.rs +++ b/src/database.rs @@ -26,6 +26,7 @@ pub const ENROLLMENT_TABLE: &str = "enrollment"; pub const COURSE_SESSION_TABLE: &str = "course_session"; pub const SESSION_ATTENDANCE_TABLE: &str = "session_attendance"; pub const WORK_ENTRY_TABLE: &str = "work_entry"; +pub const POMODORO_SESSION_TABLE: &str = "pomodoro_session"; pub const SETTINGS_TABLE: &str = "settings"; pub const TERM_TABLE: &str = "term"; pub const SUBJECT_TABLE: &str = "subject"; @@ -150,6 +151,12 @@ const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS check_out ON work_entry TYPE option; DEFINE INDEX IF NOT EXISTS work_entry_user ON work_entry FIELDS user; + DEFINE TABLE IF NOT EXISTS pomodoro_session SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record; + DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; + DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option; + DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; + DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; DEFINE FIELD IF NOT EXISTS creator ON exam TYPE record; DEFINE FIELD IF NOT EXISTS course ON exam TYPE record; diff --git a/src/domain/mod.rs b/src/domain/mod.rs index 5102962..ecea4ae 100644 --- a/src/domain/mod.rs +++ b/src/domain/mod.rs @@ -14,6 +14,7 @@ pub mod exam_question; pub mod exam_result; pub mod note; pub mod note_file; +pub mod pomodoro; pub mod preferences; pub mod profile; pub mod question_image; diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs new file mode 100644 index 0000000..6cfc459 --- /dev/null +++ b/src/domain/pomodoro.rs @@ -0,0 +1,191 @@ +use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; +use ulid::Ulid; + +use crate::database::{Database, POMODORO_SESSION_TABLE}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] +pub struct PomodoroSessionId(RecordId); + +impl PomodoroSessionId { + pub fn generate() -> Self { + Self(RecordId::new( + POMODORO_SESSION_TABLE, + Ulid::new().to_string(), + )) + } + + /// The deterministic id of `user`'s *running* session. At most one runs + /// per user by construction: starting is a single `UPSERT` on this id + /// (atomic — a restart replaces the row in place), and finishing + /// atomically takes the row and re-files it under a ULID id. `open_` + /// cannot collide with a ULID key (ULIDs are bare alphanumerics). + pub fn open_for(user: &UserId) -> Self { + Self(RecordId::new( + POMODORO_SESSION_TABLE, + format!("open_{}", user.key()), + )) + } + + pub fn record(&self) -> RecordId { + self.0.clone() + } + + pub fn key(&self) -> &str { + match &self.0.key { + RecordIdKey::String(key) => key, + _ => "", + } + } +} + +/// One pomodoro focus session of a student: server-stamped `started_at`, and +/// `finished_at` once closed. The wall clock is read server-side only — a +/// client can never supply its own instants, so the recorded focus time is +/// honest. Breaks are not stored; the frontend owns the work/break rhythm and +/// the backend records only the focus stint. +#[derive(Debug, Clone, SurrealValue)] +pub struct PomodoroSession { + id: PomodoroSessionId, + user: UserId, + started_at: Timestamp, + finished_at: Option, +} + +impl PomodoroSession { + pub fn get_id(&self) -> &PomodoroSessionId { + &self.id + } + + pub fn get_user(&self) -> &UserId { + &self.user + } + + pub fn get_started_at(&self) -> Timestamp { + self.started_at + } + + pub fn get_finished_at(&self) -> Option { + self.finished_at + } + + /// Start a session for `user`, stamped with the server clock. `UPSERT` on + /// the deterministic open id makes this atomic and always succeed: a + /// dangling unfinished session (the browser died mid-timer) is replaced — + /// it never counted, and blocking the next start behind it would only + /// punish the student for a crash. + pub async fn start(user: &UserId, db: &Database) -> Result { + let mut result = db + .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") + .bind(("open", PomodoroSessionId::open_for(user).record())) + .bind(("usr", user.record())) + .bind(("at", Timestamp::now())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into())) + } + + /// Close `user`'s running session: atomically take the open row and + /// re-file it under a ULID id, freeing the open slot for the next start. + /// Take and re-file share one transaction — a failed re-file rolls the + /// take back, so a session can never vanish half-closed. Of two racing + /// finishes exactly one receives the row (the other gets the conflict). + pub async fn finish(user: &UserId, db: &Database) -> Result { + let mut result = db + .query( + "BEGIN TRANSACTION; + LET $before = (DELETE $open RETURN BEFORE); + IF array::len($before) = 0 { THROW 'no_pomodoro_running' }; + CREATE $closed CONTENT { + user: $before[0].user, + started_at: $before[0].started_at, + finished_at: $done, + }; + COMMIT TRANSACTION;", + ) + .bind(("open", PomodoroSessionId::open_for(user).record())) + .bind(("closed", PomodoroSessionId::generate().record())) + .bind(("done", Timestamp::now())) + .await?; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the THROW's own slot names the reason, so scan + // them all for the marker instead of trusting the first. + let mut errors = result.take_errors(); + if errors + .values() + .any(|error| error.to_string().contains("no_pomodoro_running")) + { + return Err(AppError::Conflict("no pomodoro session running")); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. + let saved: Option = + result.take::>(3)?.into_iter().next(); + saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into())) + } + + /// Every session of `user`, newest first — the running one (if any) + /// included. Ordered by `started_at`: the open entry's `open_` key doesn't + /// sort with the ULIDs, so id order would misplace it. + pub async fn list_for_user( + user: &UserId, + db: &Database, + ) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database; + + #[tokio::test] + async fn restart_replaces_the_open_session_and_finish_closes_it() { + let db = database::init_mem().await.unwrap(); + // A `record` column checks the table of the id, not row + // existence — a fabricated id keeps this test free of user ceremony. + let user = UserId::from_key(&Ulid::new().to_string()); + + // Nothing running yet — finishing conflicts. + assert!(matches!( + PomodoroSession::finish(&user, &db).await, + Err(AppError::Conflict(_)) + )); + + let first = PomodoroSession::start(&user, &db).await.unwrap(); + assert!(first.get_finished_at().is_none()); + assert_eq!(first.get_id().key(), format!("open_{}", user.key())); + + // A restart replaces the dangling session: still one row, fresh clock. + let second = PomodoroSession::start(&user, &db).await.unwrap(); + assert!(second.get_started_at() >= first.get_started_at()); + let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); + assert_eq!(sessions.len(), 1); + + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); + assert!(closed.get_finished_at().unwrap() >= closed.get_started_at()); + + // The open slot is free again; a stray second finish conflicts. + assert!(matches!( + PomodoroSession::finish(&user, &db).await, + Err(AppError::Conflict(_)) + )); + PomodoroSession::start(&user, &db).await.unwrap(); + let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); + assert_eq!(sessions.len(), 2); + } +} diff --git a/src/lib.rs b/src/lib.rs index 464ce7a..f41443d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,7 +32,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - 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.", + 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.", ), modifiers(&SecurityAddon), tags( @@ -44,6 +44,7 @@ use crate::state::AppState; (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"), (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), + (name = "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"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"), (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"), (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 { .nest("/exams", web::exams::routes()) .nest("/marks", web::marks::routes()) .nest("/work", web::work::routes()) + .nest("/pomodoro", web::pomodoro::routes()) .nest("/attendance", web::attendance::routes()) .nest("/settings", web::settings::routes()) .nest("/subjects", web::subjects::routes()) diff --git a/src/web/mod.rs b/src/web/mod.rs index a832c6b..6639e25 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -11,6 +11,7 @@ pub mod exam_ws; pub mod exams; pub mod marks; pub mod notes; +pub mod pomodoro; pub mod sessions; pub mod settings; pub mod subjects; diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs new file mode 100644 index 0000000..d5b99db --- /dev/null +++ b/src/web/pomodoro.rs @@ -0,0 +1,211 @@ +use axum::Json; +use axum::extract::{Path, Query, State}; +use axum::http::StatusCode; +use serde::Serialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::domain::pomodoro::PomodoroSession; +use crate::domain::role::Role; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; + +use super::{CurrentUser, PageParams, RequireTeacher, paginate}; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new() + .routes(routes!(start)) + .routes(routes!(finish)) + .routes(routes!(my_pomodoro)) + .routes(routes!(user_pomodoro)) +} + +/// A 403 unless `user` is a student — the pomodoro timer is the students' +/// study tool (staff time-keeping is the work log). Only `start` is gated: +/// finishing merely closes a session that only a student could have opened, +/// so a mid-session promotion still gets its last stint on the record. +fn ensure_student(user: &User) -> Result<(), AppError> { + if user.get_role() != Role::Student { + return Err(AppError::Forbidden("only students run pomodoro sessions")); + } + Ok(()) +} + +#[derive(Serialize, ToSchema)] +struct PomodoroResponse { + id: String, + /// The student this session belongs to. + user: String, + /// Session start, UTC unix-milliseconds (server-stamped). + started_at: i64, + /// Session end, UTC unix-milliseconds; `null` while still running. + finished_at: Option, + /// `finished_at - started_at`; `null` while still running. + duration_ms: Option, +} + +impl PomodoroResponse { + fn new(session: &PomodoroSession) -> Self { + let started_at = session.get_started_at().as_millis(); + let finished_at = session.get_finished_at().map(|t| t.as_millis()); + Self { + id: session.get_id().key().to_string(), + user: session.get_user().key().to_string(), + started_at, + finished_at, + duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), + } + } +} + +/// The standard `{items, total, limit, offset}` page envelope over the +/// sessions, plus the unpaged focus total — spelled out (not `Page`) so the +/// extra field rides inside the same flat object. +#[derive(Serialize, ToSchema)] +struct PomodoroLog { + items: Vec, + /// Total sessions in the full log, before `limit`/`offset` are applied. + #[schema(example = 256)] + total: i64, + /// Echo of the applied `limit`; `null` when the response is unbounded. + #[schema(example = 100)] + limit: Option, + /// Echo of the applied `offset`. + #[schema(example = 0)] + offset: i64, + /// Sum of `duration_ms` over every *finished* session — the whole log, + /// not just this page. A running session counts nothing until finished. + total_focus_ms: i64, +} + +impl PomodoroLog { + fn new(sessions: &[PomodoroSession], limit: Option, offset: i64) -> Self { + let total_focus_ms = sessions + .iter() + .filter_map(|session| { + session.get_finished_at().map(|done| { + done.as_millis() + .saturating_sub(session.get_started_at().as_millis()) + }) + }) + .sum(); + Self { + items: paginate(sessions, limit, offset) + .iter() + .map(PomodoroResponse::new) + .collect(), + total: sessions.len() as i64, + limit, + offset, + total_focus_ms, + } + } +} + +/// Start a pomodoro focus session. Students only. The instant is stamped by +/// the server clock — clients never supply it. Always succeeds for a student: +/// a dangling unfinished session (the browser died mid-timer) is discarded +/// and replaced, so there is no way to lock yourself out of starting. The +/// frontend runs the visible countdown and the break rhythm; the backend +/// records only the focus stint. +#[utoipa::path( + post, + path = "/start", + tag = "pomodoro", + security(("session_cookie" = [])), + responses( + (status = 201, description = "Session started — the running session", body = PomodoroResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires the student role", body = ErrorResponse), + ), +)] +async fn start( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result<(StatusCode, Json), AppError> { + ensure_student(&user)?; + let session = PomodoroSession::start(user.get_id(), &st.db).await?; + Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) +} + +/// Finish the running pomodoro session, closing it with a server-stamped +/// instant. `409` when nothing is running. +#[utoipa::path( + post, + path = "/finish", + tag = "pomodoro", + security(("session_cookie" = [])), + responses( + (status = 200, description = "Session finished — the closed session", body = PomodoroResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 409, description = "No pomodoro session running", body = ErrorResponse), + ), +)] +async fn finish( + State(st): State, + CurrentUser(user): CurrentUser, +) -> Result, AppError> { + let session = PomodoroSession::finish(user.get_id(), &st.db).await?; + Ok(Json(PomodoroResponse::new(&session))) +} + +/// The caller's own pomodoro log, newest first — the running session (if any) +/// included (`finished_at: null`) — plus `total_focus_ms`, the unpaged sum of +/// finished-session durations. Paged via `?limit=&offset=` (omit `limit` for +/// the whole log). +#[utoipa::path( + get, + path = "/me", + tag = "pomodoro", + security(("session_cookie" = [])), + params(PageParams), + responses( + (status = 200, description = "A page of the caller's pomodoro log with the unpaged focus total", body = PomodoroLog), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn my_pomodoro( + State(st): State, + CurrentUser(user): CurrentUser, + Query(page): Query, +) -> Result, AppError> { + let (limit, offset) = page.resolve()?; + let sessions = PomodoroSession::list_for_user(user.get_id(), &st.db).await?; + Ok(Json(PomodoroLog::new(&sessions, limit, offset))) +} + +/// A student's pomodoro log, newest first, with `total_focus_ms` — the same +/// shape as `/me`. Requires teacher+ (study oversight). Paged via +/// `?limit=&offset=`. +#[utoipa::path( + get, + path = "/{user}", + tag = "pomodoro", + security(("session_cookie" = [])), + params(("user" = String, Path, description = "User id"), PageParams), + responses( + (status = 200, description = "A page of the user's pomodoro log with the unpaged focus total", body = PomodoroLog), + (status = 400, description = "Invalid limit or offset", body = ErrorResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 404, description = "User not found", body = ErrorResponse), + ), +)] +async fn user_pomodoro( + State(st): State, + _teacher: RequireTeacher, + Path(user): Path, + Query(page): Query, +) -> Result, AppError> { + let (limit, offset) = page.resolve()?; + let target = UserId::from_key(&user); + // User must exist — a missing user is a 404, not an empty log. + User::read(&target, &st.db) + .await? + .ok_or(AppError::NotFound)?; + let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; + Ok(Json(PomodoroLog::new(&sessions, limit, offset))) +} diff --git a/tests/integration.rs b/tests/integration.rs index 486f0e9..18a3cf1 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -231,6 +231,10 @@ async fn protected_routes_require_session() { ("GET", "/work/u"), ("PATCH", "/work/entries/x"), ("DELETE", "/work/entries/x"), + ("POST", "/pomodoro/start"), + ("POST", "/pomodoro/finish"), + ("GET", "/pomodoro/me"), + ("GET", "/pomodoro/u"), ("GET", "/attendance/me"), ("GET", "/attendance/u"), ] { @@ -8845,6 +8849,82 @@ async fn work_log_lifecycle_is_server_stamped_and_exclusive() { assert!(!log[1]["check_out"].is_null()); } +// --- pomodoro ---------------------------------------------------------------- + +#[tokio::test] +async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let ali_id = me_id(&app, &ali).await; + + // Students only on start; finishing with nothing running conflicts. + let res = send(&app, "POST", "/pomodoro/start", Some(&hoca), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::CONFLICT); + + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::CREATED); + assert!(res.body["finished_at"].is_null()); + let first_start = res.body["started_at"].as_i64().unwrap(); + + // A restart discards the dangling session: one row, clock reset allowed. + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::CREATED); + assert!(res.body["started_at"].as_i64().unwrap() >= first_start); + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; + assert_eq!(common::items(&res.body).len(), 1); + assert_eq!( + res.body["total_focus_ms"], 0, + "running session counts nothing" + ); + + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK); + let finished_at = res.body["finished_at"].as_i64().unwrap(); + let duration = res.body["duration_ms"].as_i64().unwrap(); + assert_eq!( + duration, + finished_at - res.body["started_at"].as_i64().unwrap() + ); + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::CONFLICT, "already finished"); + + // The open slot is free again; the log keeps both sessions, newest first, + // and the focus total sums only the finished one. + let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::CREATED); + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; + let log = common::items(&res.body); + assert_eq!(log.len(), 2); + assert!(log[0]["finished_at"].is_null(), "open session sorts newest"); + assert_eq!(res.body["total_focus_ms"].as_i64().unwrap(), duration); + + // Reading someone's log is teacher+; unknown users are 404. + let res = send( + &app, + "GET", + &format!("/pomodoro/{ali_id}"), + Some(&ali), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN); + let res = send( + &app, + "GET", + &format!("/pomodoro/{ali_id}"), + Some(&hoca), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(common::items(&res.body).len(), 2); + let res = send(&app, "GET", "/pomodoro/01UNKNOWN", Some(&hoca), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND); +} + #[tokio::test] async fn work_log_manager_reads_and_corrections() { let (app, db) = app_and_db().await;