From 54ec62d5a3c956c29eae9381bf453c3685e7fdda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 23:30:57 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20optional=20student=20label?= =?UTF-8?q?=20on=20pomodoro=20sessions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /pomodoro/start accepts an optional {label} body (trimmed, blank stored as absent, >100 chars rejected). The label rides the finish re-file, is returned on start/finish and in both log endpoints, and is published as pomodoro.max_label_len on GET /limits. SCHEMAFULL field added; pre-feature rows read as no label. --- README.md | 2 +- src/constant.rs | 4 ++++ src/db/pomodoro.rs | 33 ++++++++++++++++++++------- src/domain/pomodoro.rs | 11 +++++++++ src/migration_sql.rs | 6 +++++ src/service/pomodoro.rs | 10 +++++++-- src/web/limits.rs | 4 ++++ src/web/pomodoro.rs | 41 +++++++++++++++++++++++++++++++--- tests/integration.rs | 49 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 146 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index ca62cc6..9eb96cd 100644 --- a/README.md +++ b/README.md @@ -1256,7 +1256,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/payments/statement/{user}` | manager | One student's statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is overdue. Own record always; otherwise manager+ or a parent link (a teacher gets a `403`). The rows are paged via `?limit=&offset=`; `balance_minor` is the same on every page. | | POST | `/pomodoro/finish` | student | Finish the running pomodoro session, closing it with a server-stamped instant (`409` when nothing is running); answers `counted` — whether it moved the badge counters (ran at least `pomodoro.min_counted_ms`, within that UTC day's `pomodoro.max_counted_per_day`). | | GET | `/pomodoro/me` | student | 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). | -| POST | `/pomodoro/start` | student | 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. | +| POST | `/pomodoro/start` | student | 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. The body is optional and names the stint: a `label` rides the response and every log it lists in — a blank or absent body starts an unnamed stint, an over-long label is `400`. | | GET | `/pomodoro/{user}` | teacher | A student's pomodoro log, newest first, with `total_focus_ms` — the same shape as `/me`. Requires teacher+ (study oversight), or a parent tied to the target student. Paged via `?limit=&offset=`. | | GET | `/questions` | student | The question pool, newest first. Everyone (parents excepted) sees every `approved` question; `pending` ones appear only to their asker and to teacher+ — so for a teacher, `?status=pending` is the approval queue. Paged via `?limit=&offset=`. | | POST | `/questions` | student | Ask a question. Students only — the pool exists for students to get help; staff answer, they don't ask. Born `pending`: invisible to the school until a teacher+ approves it, so nothing unmoderated ever reaches the pool. Attach a photo of the problem afterwards via `POST /questions/{id}/image` (only while pending). | diff --git a/src/constant.rs b/src/constant.rs index 4a55b75..32b2677 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -1042,6 +1042,10 @@ pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today"; /// minimum counts and the sixteenth of the day counts. pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000; pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16; +/// A stint's optional student-given label — the student's own name for what +/// the stint is for ("math", "TYT denemesi"), free text rather than a subject +/// link, bounded like the other short labels. +pub const MAX_POMODORO_LABEL_LEN: usize = 100; /// The staff-side and second student-side totals, same shape and same rules: /// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and /// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index 7ba6434..da5afe5 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -21,12 +21,22 @@ use crate::error::AppError; /// 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(db: &Database, user: &UserId) -> Result { +/// +/// `label` is the student's own name for the stint, validated and trimmed +/// upstream and stored verbatim. A `None` binds NONE, which an +/// `option` field stores as absent — an unnamed start reads back +/// unnamed. +pub async fn start( + db: &Database, + user: &UserId, + label: Option, +) -> Result { let mut result = db - .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") + .query("UPSERT $open CONTENT { user: $usr, started_at: $at, label: $label }") .bind(("open", PomodoroSessionId::open_for(user).record())) .bind(("usr", user.record())) .bind(("at", Timestamp::now())) + .bind(("label", label)) .await? .check()?; result @@ -88,6 +98,12 @@ pub async fn start(db: &Database, user: &UserId) -> Result` column stores, so no backfill is owed (the same +/// ruling as the `counted` stamp). +/// /// The day quota is bucketed like the streak below (midnight UTC, /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting @@ -186,6 +202,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result= first.get_started_at()); let sessions = list_for_user(&db, &user).await.unwrap(); assert_eq!(sessions.len(), 1); @@ -708,7 +725,7 @@ mod tests { finish(&db, &user).await, Err(AppError::Conflict(_)) )); - start(&db, &user).await.unwrap(); + start(&db, &user, None).await.unwrap(); let sessions = list_for_user(&db, &user).await.unwrap(); assert_eq!(sessions.len(), 2); } @@ -718,7 +735,7 @@ mod tests { let db = database::init_mem().await.unwrap(); let user = UserId::from_key(&Ulid::new().to_string()); - start(&db, &user).await.unwrap(); + start(&db, &user, None).await.unwrap(); // Stand in for the NTP step: push the running stint's start an hour // ahead, so the server clock `finish` reads is *behind* it. db.query("UPDATE $open SET started_at = $future") diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 5c2192a..af9c4a4 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -55,6 +55,11 @@ pub struct PomodoroSession { user: UserId, started_at: Timestamp, finished_at: Option, + /// The student's own name for what this stint is for ("math", "TYT + /// denemesi") — free text given at start, not a subject reference. + /// `None` on an unnamed stint and on any row from before the field + /// existed, which reads exactly like an unnamed one. + label: Option, counted: Option, } @@ -82,4 +87,10 @@ impl PomodoroSession { pub fn get_counted(&self) -> Option { self.counted } + + /// What the student called this stint when they started it. `None` when + /// they started it unnamed, and on rows that predate the field. + pub fn get_label(&self) -> Option<&str> { + self.label.as_deref() + } } diff --git a/src/migration_sql.rs b/src/migration_sql.rs index f0cb839..1445735 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -462,6 +462,12 @@ pub const MIGRATION: &str = " -- `option`: a running stint has no verdict yet, and a stint closed -- before the rule existed carries none and cannot honestly be given one. DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option; + -- The student's own name for what the stint is for ('math', 'TYT + -- denemesi') — free text given at start, not a subject link. Shipped in + -- the same deploy as the code that writes it: on a SCHEMAFULL table a + -- write naming an undefined field fails, and `option` lets rows from + -- before the field read as none. + DEFINE FIELD IF NOT EXISTS label 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; diff --git a/src/service/pomodoro.rs b/src/service/pomodoro.rs index a9116a6..7994e20 100644 --- a/src/service/pomodoro.rs +++ b/src/service/pomodoro.rs @@ -9,8 +9,14 @@ use crate::domain::pomodoro::PomodoroSession; use crate::domain::user::UserId; use crate::error::AppError; -pub async fn start(db: &Database, user: &UserId) -> Result { - pomodoro::start(db, user).await +/// Start a session for `user`; `label` is the stint's optional +/// student-supplied name, already validated and trimmed by the web layer. +pub async fn start( + db: &Database, + user: &UserId, + label: Option, +) -> Result { + pomodoro::start(db, user, label).await } /// Close the running session (`409` when none runs); the returned row diff --git a/src/web/limits.rs b/src/web/limits.rs index 0e195ff..c2b31cf 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -362,6 +362,9 @@ struct PomodoroLimits { /// recorded and listed as usual, and counts nothing. #[schema(example = 16)] max_counted_per_day: i64, + /// How long a stint's optional student-given label may be — the student's + /// own name for what the stint is for, given at `POST /pomodoro/start`. + max_label_len: usize, } /// A collaborative whiteboard: its title, its roster, and the two growth caps @@ -631,6 +634,7 @@ impl LimitsResponse { pomodoro: PomodoroLimits { min_counted_ms: MIN_COUNTED_POMODORO_MS, max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY, + max_label_len: MAX_POMODORO_LABEL_LEN, }, board: BoardLimits { max_title_len: MAX_BOARD_TITLE_LEN, diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index ea2ace9..be46112 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -2,11 +2,12 @@ use crate::web::tenant_state::State; use axum::Json; use axum::extract::{Path, Query}; use axum::http::StatusCode; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; +use crate::constant::MAX_POMODORO_LABEL_LEN; use crate::domain::pomodoro::PomodoroSession; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; @@ -14,6 +15,7 @@ use crate::error::{AppError, ErrorResponse}; use crate::service::parent_link::ensure_can_observe; use crate::service::pomodoro; use crate::state::AppState; +use crate::validate::validate_optional; use super::{CurrentUser, PageParams, paginate}; @@ -54,6 +56,10 @@ struct PomodoroResponse { /// still running, and on stints closed before the rule existed. An /// uncounted stint is kept and listed exactly like any other. counted: Option, + /// What the student called this stint when they started it — their own + /// name for what it was for. `null` on an unnamed stint and on rows + /// from before the field existed. + label: Option, } impl PomodoroResponse { @@ -67,6 +73,7 @@ impl PomodoroResponse { finished_at, duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), counted: session.get_counted(), + label: session.get_label().map(str::to_string), } } } @@ -117,29 +124,57 @@ impl PomodoroLog { } } +/// The optional body names the stint: `{"label": "math"}` stores what the +/// student called it, trimmed, and the label then rides every response that +/// carries the session. A blank label starts an unnamed stint and an +/// over-long one is `400`; no body at all is exactly the old no-label start. +#[derive(Deserialize, ToSchema)] +struct StartPomodoro { + /// The student's own name for what this stint is for — free text, not a + /// subject reference, bounded by `pomodoro.max_label_len` on `GET + /// /limits`. + label: Option, +} + /// 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. +/// records only the focus stint. The body is optional and names the stint: +/// a `label` rides the response and every log it lists in — a blank or +/// absent body starts an unnamed stint, an over-long label is `400`. #[utoipa::path( post, path = "/start", tag = "pomodoro", security(("session_cookie" = [])), + request_body(content = StartPomodoro, description = "Optional; names the stint"), responses( (status = 201, description = "Session started — the running session", body = PomodoroResponse), + (status = 400, description = "Label is over-long", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires the student role", body = ErrorResponse), + (status = 422, description = "The body does not fit this request: a field has the wrong type", body = ErrorResponse), ), )] async fn start( State(st): State, CurrentUser(user): CurrentUser, + body: Option>, ) -> Result<(StatusCode, Json), AppError> { ensure_student(&user)?; - let session = pomodoro::start(&st.db, user.get_id()).await?; + // A blank or absent label records none; a present one is validated (400 + // if over-long) and trimmed before it reaches the row. + let label = match body.and_then(|Json(req)| req.label) { + Some(label) if !label.trim().is_empty() => { + let trimmed = label.trim(); + validate_optional("label", trimmed, MAX_POMODORO_LABEL_LEN)?; + Some(trimmed.to_string()) + } + _ => None, + }; + let session = pomodoro::start(&st.db, user.get_id(), label).await?; Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) } diff --git a/tests/integration.rs b/tests/integration.rs index 5a9c306..e7bc6fa 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -10703,6 +10703,7 @@ async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; assert_eq!(res.status, StatusCode::CREATED); assert!(res.body["finished_at"].is_null()); + assert!(res.body["label"].is_null()); let first_start = res.body["started_at"].as_i64().unwrap(); // A restart discards the dangling session: one row, clock reset allowed. @@ -10759,6 +10760,54 @@ async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { 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); + + // The start body is optional and names the stint: the label comes back + // on start, reads the same from the log, and survives the close. + let res = send( + &app, + "POST", + "/pomodoro/start", + Some(&ali), + Some(json!({ "label": "math" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert_eq!(res.body["label"], "math"); + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; + assert_eq!(common::items(&res.body)[0]["label"], "math"); + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; + assert_eq!(res.status, StatusCode::OK); + assert_eq!(res.body["label"], "math", "the close keeps the label"); + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; + assert_eq!( + common::items(&res.body)[0]["label"], + "math", + "so does the log afterwards" + ); + + // An over-long label answers the same 400 every other optional + // free-text field does, and starts nothing. + let res = send( + &app, + "POST", + "/pomodoro/start", + Some(&ali), + Some(json!({ "label": "x".repeat(101) })), + ) + .await; + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); + + // A blank label is no label: the stint starts unnamed. + let res = send( + &app, + "POST", + "/pomodoro/start", + Some(&ali), + Some(json!({ "label": " " })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED); + assert!(res.body["label"].is_null()); } #[tokio::test]