Optional student label on pomodoro sessions
Browse files at this commit54ec62d5a3c956c29eae9381bf453c3685e7fddaParent: e2d0e43- feat
- optional student label on pomodoro sessions
9 changed files +146 -14
- README.md +1 -1
- src/constant.rs +4 -0
- src/db/pomodoro.rs +25 -8
- src/domain/pomodoro.rs +11 -0
- src/migration_sql.rs +6 -0
- src/service/pomodoro.rs +8 -2
- src/web/limits.rs +4 -0
- src/web/pomodoro.rs +38 -3
- tests/integration.rs +49 -0
README.mdmodified+1 -1
| @@ -1256,7 +1256,7 @@ window filtering, before paging; negative values are a `400` naming the field. | |||
| 1256 | | 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. | | 1256 | | 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. | |
| 1257 | | 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`). | | 1257 | | 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`). | |
| 1258 | | 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). | | 1258 | | 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). | |
| 1259 | -| 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. | | 1259 | +| 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`. | |
| 1260 | | 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=`. | | 1260 | | 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=`. | |
| 1261 | | 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=`. | | 1261 | | 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=`. | |
| 1262 | | 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). | | 1262 | | 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). | |
src/constant.rsmodified+4 -0
| @@ -1042,6 +1042,10 @@ pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today"; | |||
| 1042 | /// minimum counts and the sixteenth of the day counts. | 1042 | /// minimum counts and the sixteenth of the day counts. |
| 1043 | pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000; | 1043 | pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000; |
| 1044 | pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16; | 1044 | pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16; |
| 1045 | +/// A stint's optional student-given label — the student's own name for what | ||
| 1046 | +/// the stint is for ("math", "TYT denemesi"), free text rather than a subject | ||
| 1047 | +/// link, bounded like the other short labels. | ||
| 1048 | +pub const MAX_POMODORO_LABEL_LEN: usize = 100; | ||
| 1045 | /// The staff-side and second student-side totals, same shape and same rules: | 1049 | /// The staff-side and second student-side totals, same shape and same rules: |
| 1046 | /// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and | 1050 | /// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and |
| 1047 | /// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the | 1051 | /// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the |
src/db/pomodoro.rsmodified+25 -8
| @@ -21,12 +21,22 @@ use crate::error::AppError; | |||
| 21 | /// dangling unfinished session (the browser died mid-timer) is replaced — | 21 | /// dangling unfinished session (the browser died mid-timer) is replaced — |
| 22 | /// it never counted, and blocking the next start behind it would only | 22 | /// it never counted, and blocking the next start behind it would only |
| 23 | /// punish the student for a crash. | 23 | /// punish the student for a crash. |
| 24 | -pub async fn start(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> { | 24 | +/// |
| 25 | +/// `label` is the student's own name for the stint, validated and trimmed | ||
| 26 | +/// upstream and stored verbatim. A `None` binds NONE, which an | ||
| 27 | +/// `option<string>` field stores as absent — an unnamed start reads back | ||
| 28 | +/// unnamed. | ||
| 29 | +pub async fn start( | ||
| 30 | + db: &Database, | ||
| 31 | + user: &UserId, | ||
| 32 | + label: Option<String>, | ||
| 33 | +) -> Result<PomodoroSession, AppError> { | ||
| 25 | let mut result = db | 34 | let mut result = db |
| 26 | - .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") | 35 | + .query("UPSERT $open CONTENT { user: $usr, started_at: $at, label: $label }") |
| 27 | .bind(("open", PomodoroSessionId::open_for(user).record())) | 36 | .bind(("open", PomodoroSessionId::open_for(user).record())) |
| 28 | .bind(("usr", user.record())) | 37 | .bind(("usr", user.record())) |
| 29 | .bind(("at", Timestamp::now())) | 38 | .bind(("at", Timestamp::now())) |
| 39 | + .bind(("label", label)) | ||
| 30 | .await? | 40 | .await? |
| 31 | .check()?; | 41 | .check()?; |
| 32 | result | 42 | result |
| @@ -88,6 +98,12 @@ pub async fn start(db: &Database, user: &UserId) -> Result<PomodoroSession, AppE | |||
| 88 | /// the bar is still recorded, still listed, and still sums into the log's | 98 | /// the bar is still recorded, still listed, and still sums into the log's |
| 89 | /// `total_focus_ms` — the rule bounds what *counts*, never what is kept. | 99 | /// `total_focus_ms` — the rule bounds what *counts*, never what is kept. |
| 90 | /// | 100 | /// |
| 101 | +/// The re-filed row carries the start's `label` through verbatim | ||
| 102 | +/// (`$before[0].label`): the close copies whatever the student named the | ||
| 103 | +/// stint. On a row that predates the field that read is NONE — exactly what | ||
| 104 | +/// an `option<string>` column stores, so no backfill is owed (the same | ||
| 105 | +/// ruling as the `counted` stamp). | ||
| 106 | +/// | ||
| 91 | /// The day quota is bucketed like the streak below (midnight UTC, | 107 | /// The day quota is bucketed like the streak below (midnight UTC, |
| 92 | /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the | 108 | /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the |
| 93 | /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting | 109 | /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting |
| @@ -186,6 +202,7 @@ pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, App | |||
| 186 | started_at: $before[0].started_at, | 202 | started_at: $before[0].started_at, |
| 187 | finished_at: $end, | 203 | finished_at: $end, |
| 188 | counted: $counted, | 204 | counted: $counted, |
| 205 | + label: $before[0].label, | ||
| 189 | }}; | 206 | }}; |
| 190 | COMMIT TRANSACTION;" | 207 | COMMIT TRANSACTION;" |
| 191 | ), | 208 | ), |
| @@ -544,7 +561,7 @@ mod tests { | |||
| 544 | let db = database::init_mem().await.unwrap(); | 561 | let db = database::init_mem().await.unwrap(); |
| 545 | let user = a_user(&db).await; | 562 | let user = a_user(&db).await; |
| 546 | 563 | ||
| 547 | - start(&db, &user).await.unwrap(); | 564 | + start(&db, &user, None).await.unwrap(); |
| 548 | db.query("UPDATE $open SET started_at = $future") | 565 | db.query("UPDATE $open SET started_at = $future") |
| 549 | .bind(("open", PomodoroSessionId::open_for(&user).record())) | 566 | .bind(("open", PomodoroSessionId::open_for(&user).record())) |
| 550 | .bind(("future", Timestamp::now().as_millis() + 3_600_000)) | 567 | .bind(("future", Timestamp::now().as_millis() + 3_600_000)) |
| @@ -655,7 +672,7 @@ mod tests { | |||
| 655 | let user = a_user(&db).await; | 672 | let user = a_user(&db).await; |
| 656 | 673 | ||
| 657 | for _ in 0..200 { | 674 | for _ in 0..200 { |
| 658 | - start(&db, &user).await.unwrap(); | 675 | + start(&db, &user, None).await.unwrap(); |
| 659 | finish(&db, &user).await.unwrap(); | 676 | finish(&db, &user).await.unwrap(); |
| 660 | } | 677 | } |
| 661 | assert_eq!(counters(&user, &db).await, (0, 0)); | 678 | assert_eq!(counters(&user, &db).await, (0, 0)); |
| @@ -690,12 +707,12 @@ mod tests { | |||
| 690 | Err(AppError::Conflict(_)) | 707 | Err(AppError::Conflict(_)) |
| 691 | )); | 708 | )); |
| 692 | 709 | ||
| 693 | - let first = start(&db, &user).await.unwrap(); | 710 | + let first = start(&db, &user, None).await.unwrap(); |
| 694 | assert!(first.get_finished_at().is_none()); | 711 | assert!(first.get_finished_at().is_none()); |
| 695 | assert_eq!(first.get_id().key(), format!("open_{}", user.key())); | 712 | assert_eq!(first.get_id().key(), format!("open_{}", user.key())); |
| 696 | 713 | ||
| 697 | // A restart replaces the dangling session: still one row, fresh clock. | 714 | // A restart replaces the dangling session: still one row, fresh clock. |
| 698 | - let second = start(&db, &user).await.unwrap(); | 715 | + let second = start(&db, &user, None).await.unwrap(); |
| 699 | assert!(second.get_started_at() >= first.get_started_at()); | 716 | assert!(second.get_started_at() >= first.get_started_at()); |
| 700 | let sessions = list_for_user(&db, &user).await.unwrap(); | 717 | let sessions = list_for_user(&db, &user).await.unwrap(); |
| 701 | assert_eq!(sessions.len(), 1); | 718 | assert_eq!(sessions.len(), 1); |
| @@ -708,7 +725,7 @@ mod tests { | |||
| 708 | finish(&db, &user).await, | 725 | finish(&db, &user).await, |
| 709 | Err(AppError::Conflict(_)) | 726 | Err(AppError::Conflict(_)) |
| 710 | )); | 727 | )); |
| 711 | - start(&db, &user).await.unwrap(); | 728 | + start(&db, &user, None).await.unwrap(); |
| 712 | let sessions = list_for_user(&db, &user).await.unwrap(); | 729 | let sessions = list_for_user(&db, &user).await.unwrap(); |
| 713 | assert_eq!(sessions.len(), 2); | 730 | assert_eq!(sessions.len(), 2); |
| 714 | } | 731 | } |
| @@ -718,7 +735,7 @@ mod tests { | |||
| 718 | let db = database::init_mem().await.unwrap(); | 735 | let db = database::init_mem().await.unwrap(); |
| 719 | let user = UserId::from_key(&Ulid::new().to_string()); | 736 | let user = UserId::from_key(&Ulid::new().to_string()); |
| 720 | 737 | ||
| 721 | - start(&db, &user).await.unwrap(); | 738 | + start(&db, &user, None).await.unwrap(); |
| 722 | // Stand in for the NTP step: push the running stint's start an hour | 739 | // Stand in for the NTP step: push the running stint's start an hour |
| 723 | // ahead, so the server clock `finish` reads is *behind* it. | 740 | // ahead, so the server clock `finish` reads is *behind* it. |
| 724 | db.query("UPDATE $open SET started_at = $future") | 741 | db.query("UPDATE $open SET started_at = $future") |
src/domain/pomodoro.rsmodified+11 -0
| @@ -55,6 +55,11 @@ pub struct PomodoroSession { | |||
| 55 | user: UserId, | 55 | user: UserId, |
| 56 | started_at: Timestamp, | 56 | started_at: Timestamp, |
| 57 | finished_at: Option<Timestamp>, | 57 | finished_at: Option<Timestamp>, |
| 58 | + /// The student's own name for what this stint is for ("math", "TYT | ||
| 59 | + /// denemesi") — free text given at start, not a subject reference. | ||
| 60 | + /// `None` on an unnamed stint and on any row from before the field | ||
| 61 | + /// existed, which reads exactly like an unnamed one. | ||
| 62 | + label: Option<String>, | ||
| 58 | counted: Option<bool>, | 63 | counted: Option<bool>, |
| 59 | } | 64 | } |
| 60 | 65 | ||
| @@ -82,4 +87,10 @@ impl PomodoroSession { | |||
| 82 | pub fn get_counted(&self) -> Option<bool> { | 87 | pub fn get_counted(&self) -> Option<bool> { |
| 83 | self.counted | 88 | self.counted |
| 84 | } | 89 | } |
| 90 | + | ||
| 91 | + /// What the student called this stint when they started it. `None` when | ||
| 92 | + /// they started it unnamed, and on rows that predate the field. | ||
| 93 | + pub fn get_label(&self) -> Option<&str> { | ||
| 94 | + self.label.as_deref() | ||
| 95 | + } | ||
| 85 | } | 96 | } |
src/migration_sql.rsmodified+6 -0
| @@ -462,6 +462,12 @@ pub const MIGRATION: &str = " | |||
| 462 | -- `option<bool>`: a running stint has no verdict yet, and a stint closed | 462 | -- `option<bool>`: a running stint has no verdict yet, and a stint closed |
| 463 | -- before the rule existed carries none and cannot honestly be given one. | 463 | -- before the rule existed carries none and cannot honestly be given one. |
| 464 | DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option<bool>; | 464 | DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option<bool>; |
| 465 | + -- The student's own name for what the stint is for ('math', 'TYT | ||
| 466 | + -- denemesi') — free text given at start, not a subject link. Shipped in | ||
| 467 | + -- the same deploy as the code that writes it: on a SCHEMAFULL table a | ||
| 468 | + -- write naming an undefined field fails, and `option` lets rows from | ||
| 469 | + -- before the field read as none. | ||
| 470 | + DEFINE FIELD IF NOT EXISTS label ON pomodoro_session TYPE option<string>; | ||
| 465 | DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; | 471 | DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; |
| 466 | 472 | ||
| 467 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; | 473 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; |
src/service/pomodoro.rsmodified+8 -2
| @@ -9,8 +9,14 @@ use crate::domain::pomodoro::PomodoroSession; | |||
| 9 | use crate::domain::user::UserId; | 9 | use crate::domain::user::UserId; |
| 10 | use crate::error::AppError; | 10 | use crate::error::AppError; |
| 11 | 11 | ||
| 12 | -pub async fn start(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> { | 12 | +/// Start a session for `user`; `label` is the stint's optional |
| 13 | - pomodoro::start(db, user).await | 13 | +/// student-supplied name, already validated and trimmed by the web layer. |
| 14 | +pub async fn start( | ||
| 15 | + db: &Database, | ||
| 16 | + user: &UserId, | ||
| 17 | + label: Option<String>, | ||
| 18 | +) -> Result<PomodoroSession, AppError> { | ||
| 19 | + pomodoro::start(db, user, label).await | ||
| 14 | } | 20 | } |
| 15 | 21 | ||
| 16 | /// Close the running session (`409` when none runs); the returned row | 22 | /// Close the running session (`409` when none runs); the returned row |
src/web/limits.rsmodified+4 -0
| @@ -362,6 +362,9 @@ struct PomodoroLimits { | |||
| 362 | /// recorded and listed as usual, and counts nothing. | 362 | /// recorded and listed as usual, and counts nothing. |
| 363 | #[schema(example = 16)] | 363 | #[schema(example = 16)] |
| 364 | max_counted_per_day: i64, | 364 | max_counted_per_day: i64, |
| 365 | + /// How long a stint's optional student-given label may be — the student's | ||
| 366 | + /// own name for what the stint is for, given at `POST /pomodoro/start`. | ||
| 367 | + max_label_len: usize, | ||
| 365 | } | 368 | } |
| 366 | 369 | ||
| 367 | /// A collaborative whiteboard: its title, its roster, and the two growth caps | 370 | /// A collaborative whiteboard: its title, its roster, and the two growth caps |
| @@ -631,6 +634,7 @@ impl LimitsResponse { | |||
| 631 | pomodoro: PomodoroLimits { | 634 | pomodoro: PomodoroLimits { |
| 632 | min_counted_ms: MIN_COUNTED_POMODORO_MS, | 635 | min_counted_ms: MIN_COUNTED_POMODORO_MS, |
| 633 | max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY, | 636 | max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY, |
| 637 | + max_label_len: MAX_POMODORO_LABEL_LEN, | ||
| 634 | }, | 638 | }, |
| 635 | board: BoardLimits { | 639 | board: BoardLimits { |
| 636 | max_title_len: MAX_BOARD_TITLE_LEN, | 640 | max_title_len: MAX_BOARD_TITLE_LEN, |
src/web/pomodoro.rsmodified+38 -3
| @@ -2,11 +2,12 @@ use crate::web::tenant_state::State; | |||
| 2 | use axum::Json; | 2 | use axum::Json; |
| 3 | use axum::extract::{Path, Query}; | 3 | use axum::extract::{Path, Query}; |
| 4 | use axum::http::StatusCode; | 4 | use axum::http::StatusCode; |
| 5 | -use serde::Serialize; | 5 | +use serde::{Deserialize, Serialize}; |
| 6 | use utoipa::ToSchema; | 6 | use utoipa::ToSchema; |
| 7 | use utoipa_axum::router::OpenApiRouter; | 7 | use utoipa_axum::router::OpenApiRouter; |
| 8 | use utoipa_axum::routes; | 8 | use utoipa_axum::routes; |
| 9 | 9 | ||
| 10 | +use crate::constant::MAX_POMODORO_LABEL_LEN; | ||
| 10 | use crate::domain::pomodoro::PomodoroSession; | 11 | use crate::domain::pomodoro::PomodoroSession; |
| 11 | use crate::domain::role::Role; | 12 | use crate::domain::role::Role; |
| 12 | use crate::domain::user::{User, UserId}; | 13 | use crate::domain::user::{User, UserId}; |
| @@ -14,6 +15,7 @@ use crate::error::{AppError, ErrorResponse}; | |||
| 14 | use crate::service::parent_link::ensure_can_observe; | 15 | use crate::service::parent_link::ensure_can_observe; |
| 15 | use crate::service::pomodoro; | 16 | use crate::service::pomodoro; |
| 16 | use crate::state::AppState; | 17 | use crate::state::AppState; |
| 18 | +use crate::validate::validate_optional; | ||
| 17 | 19 | ||
| 18 | use super::{CurrentUser, PageParams, paginate}; | 20 | use super::{CurrentUser, PageParams, paginate}; |
| 19 | 21 | ||
| @@ -54,6 +56,10 @@ struct PomodoroResponse { | |||
| 54 | /// still running, and on stints closed before the rule existed. An | 56 | /// still running, and on stints closed before the rule existed. An |
| 55 | /// uncounted stint is kept and listed exactly like any other. | 57 | /// uncounted stint is kept and listed exactly like any other. |
| 56 | counted: Option<bool>, | 58 | counted: Option<bool>, |
| 59 | + /// What the student called this stint when they started it — their own | ||
| 60 | + /// name for what it was for. `null` on an unnamed stint and on rows | ||
| 61 | + /// from before the field existed. | ||
| 62 | + label: Option<String>, | ||
| 57 | } | 63 | } |
| 58 | 64 | ||
| 59 | impl PomodoroResponse { | 65 | impl PomodoroResponse { |
| @@ -67,6 +73,7 @@ impl PomodoroResponse { | |||
| 67 | finished_at, | 73 | finished_at, |
| 68 | duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), | 74 | duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), |
| 69 | counted: session.get_counted(), | 75 | counted: session.get_counted(), |
| 76 | + label: session.get_label().map(str::to_string), | ||
| 70 | } | 77 | } |
| 71 | } | 78 | } |
| 72 | } | 79 | } |
| @@ -117,29 +124,57 @@ impl PomodoroLog { | |||
| 117 | } | 124 | } |
| 118 | } | 125 | } |
| 119 | 126 | ||
| 127 | +/// The optional body names the stint: `{"label": "math"}` stores what the | ||
| 128 | +/// student called it, trimmed, and the label then rides every response that | ||
| 129 | +/// carries the session. A blank label starts an unnamed stint and an | ||
| 130 | +/// over-long one is `400`; no body at all is exactly the old no-label start. | ||
| 131 | +#[derive(Deserialize, ToSchema)] | ||
| 132 | +struct StartPomodoro { | ||
| 133 | + /// The student's own name for what this stint is for — free text, not a | ||
| 134 | + /// subject reference, bounded by `pomodoro.max_label_len` on `GET | ||
| 135 | + /// /limits`. | ||
| 136 | + label: Option<String>, | ||
| 137 | +} | ||
| 138 | + | ||
| 120 | /// Start a pomodoro focus session. Students only. The instant is stamped by | 139 | /// Start a pomodoro focus session. Students only. The instant is stamped by |
| 121 | /// the server clock — clients never supply it. Always succeeds for a student: | 140 | /// the server clock — clients never supply it. Always succeeds for a student: |
| 122 | /// a dangling unfinished session (the browser died mid-timer) is discarded | 141 | /// a dangling unfinished session (the browser died mid-timer) is discarded |
| 123 | /// and replaced, so there is no way to lock yourself out of starting. The | 142 | /// and replaced, so there is no way to lock yourself out of starting. The |
| 124 | /// frontend runs the visible countdown and the break rhythm; the backend | 143 | /// frontend runs the visible countdown and the break rhythm; the backend |
| 125 | -/// records only the focus stint. | 144 | +/// records only the focus stint. The body is optional and names the stint: |
| 145 | +/// a `label` rides the response and every log it lists in — a blank or | ||
| 146 | +/// absent body starts an unnamed stint, an over-long label is `400`. | ||
| 126 | #[utoipa::path( | 147 | #[utoipa::path( |
| 127 | post, | 148 | post, |
| 128 | path = "/start", | 149 | path = "/start", |
| 129 | tag = "pomodoro", | 150 | tag = "pomodoro", |
| 130 | security(("session_cookie" = [])), | 151 | security(("session_cookie" = [])), |
| 152 | + request_body(content = StartPomodoro, description = "Optional; names the stint"), | ||
| 131 | responses( | 153 | responses( |
| 132 | (status = 201, description = "Session started — the running session", body = PomodoroResponse), | 154 | (status = 201, description = "Session started — the running session", body = PomodoroResponse), |
| 155 | + (status = 400, description = "Label is over-long", body = ErrorResponse), | ||
| 133 | (status = 401, description = "Not authenticated", body = ErrorResponse), | 156 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 134 | (status = 403, description = "Requires the student role", body = ErrorResponse), | 157 | (status = 403, description = "Requires the student role", body = ErrorResponse), |
| 158 | + (status = 422, description = "The body does not fit this request: a field has the wrong type", body = ErrorResponse), | ||
| 135 | ), | 159 | ), |
| 136 | )] | 160 | )] |
| 137 | async fn start( | 161 | async fn start( |
| 138 | State(st): State<AppState>, | 162 | State(st): State<AppState>, |
| 139 | CurrentUser(user): CurrentUser, | 163 | CurrentUser(user): CurrentUser, |
| 164 | + body: Option<Json<StartPomodoro>>, | ||
| 140 | ) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> { | 165 | ) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> { |
| 141 | ensure_student(&user)?; | 166 | ensure_student(&user)?; |
| 142 | - let session = pomodoro::start(&st.db, user.get_id()).await?; | 167 | + // A blank or absent label records none; a present one is validated (400 |
| 168 | + // if over-long) and trimmed before it reaches the row. | ||
| 169 | + let label = match body.and_then(|Json(req)| req.label) { | ||
| 170 | + Some(label) if !label.trim().is_empty() => { | ||
| 171 | + let trimmed = label.trim(); | ||
| 172 | + validate_optional("label", trimmed, MAX_POMODORO_LABEL_LEN)?; | ||
| 173 | + Some(trimmed.to_string()) | ||
| 174 | + } | ||
| 175 | + _ => None, | ||
| 176 | + }; | ||
| 177 | + let session = pomodoro::start(&st.db, user.get_id(), label).await?; | ||
| 143 | Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) | 178 | Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) |
| 144 | } | 179 | } |
| 145 | 180 | ||
tests/integration.rsmodified+49 -0
| @@ -10703,6 +10703,7 @@ async fn pomodoro_restart_replaces_finish_closes_and_teachers_read() { | |||
| 10703 | let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; | 10703 | let res = send(&app, "POST", "/pomodoro/start", Some(&ali), None).await; |
| 10704 | assert_eq!(res.status, StatusCode::CREATED); | 10704 | assert_eq!(res.status, StatusCode::CREATED); |
| 10705 | assert!(res.body["finished_at"].is_null()); | 10705 | assert!(res.body["finished_at"].is_null()); |
| 10706 | + assert!(res.body["label"].is_null()); | ||
| 10706 | let first_start = res.body["started_at"].as_i64().unwrap(); | 10707 | let first_start = res.body["started_at"].as_i64().unwrap(); |
| 10707 | 10708 | ||
| 10708 | // A restart discards the dangling session: one row, clock reset allowed. | 10709 | // 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() { | |||
| 10759 | assert_eq!(common::items(&res.body).len(), 2); | 10760 | assert_eq!(common::items(&res.body).len(), 2); |
| 10760 | let res = send(&app, "GET", "/pomodoro/01UNKNOWN", Some(&hoca), None).await; | 10761 | let res = send(&app, "GET", "/pomodoro/01UNKNOWN", Some(&hoca), None).await; |
| 10761 | assert_eq!(res.status, StatusCode::NOT_FOUND); | 10762 | assert_eq!(res.status, StatusCode::NOT_FOUND); |
| 10763 | + | ||
| 10764 | + // The start body is optional and names the stint: the label comes back | ||
| 10765 | + // on start, reads the same from the log, and survives the close. | ||
| 10766 | + let res = send( | ||
| 10767 | + &app, | ||
| 10768 | + "POST", | ||
| 10769 | + "/pomodoro/start", | ||
| 10770 | + Some(&ali), | ||
| 10771 | + Some(json!({ "label": "math" })), | ||
| 10772 | + ) | ||
| 10773 | + .await; | ||
| 10774 | + assert_eq!(res.status, StatusCode::CREATED); | ||
| 10775 | + assert_eq!(res.body["label"], "math"); | ||
| 10776 | + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; | ||
| 10777 | + assert_eq!(common::items(&res.body)[0]["label"], "math"); | ||
| 10778 | + let res = send(&app, "POST", "/pomodoro/finish", Some(&ali), None).await; | ||
| 10779 | + assert_eq!(res.status, StatusCode::OK); | ||
| 10780 | + assert_eq!(res.body["label"], "math", "the close keeps the label"); | ||
| 10781 | + let res = send(&app, "GET", "/pomodoro/me", Some(&ali), None).await; | ||
| 10782 | + assert_eq!( | ||
| 10783 | + common::items(&res.body)[0]["label"], | ||
| 10784 | + "math", | ||
| 10785 | + "so does the log afterwards" | ||
| 10786 | + ); | ||
| 10787 | + | ||
| 10788 | + // An over-long label answers the same 400 every other optional | ||
| 10789 | + // free-text field does, and starts nothing. | ||
| 10790 | + let res = send( | ||
| 10791 | + &app, | ||
| 10792 | + "POST", | ||
| 10793 | + "/pomodoro/start", | ||
| 10794 | + Some(&ali), | ||
| 10795 | + Some(json!({ "label": "x".repeat(101) })), | ||
| 10796 | + ) | ||
| 10797 | + .await; | ||
| 10798 | + assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | ||
| 10799 | + | ||
| 10800 | + // A blank label is no label: the stint starts unnamed. | ||
| 10801 | + let res = send( | ||
| 10802 | + &app, | ||
| 10803 | + "POST", | ||
| 10804 | + "/pomodoro/start", | ||
| 10805 | + Some(&ali), | ||
| 10806 | + Some(json!({ "label": " " })), | ||
| 10807 | + ) | ||
| 10808 | + .await; | ||
| 10809 | + assert_eq!(res.status, StatusCode::CREATED); | ||
| 10810 | + assert!(res.body["label"].is_null()); | ||
| 10762 | } | 10811 | } |
| 10763 | 10812 | ||
| 10764 | #[tokio::test] | 10813 | #[tokio::test] |