diff --git a/README.md b/README.md index 72416b5..ca36aa6 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,9 @@ marks stay out of the weighted `/marks` averages. 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**, 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), +backend records the focus stints — every one of them, though only stints of at +least 5 minutes and at most 16 a UTC day *count* towards the badges — and +teachers can read any student's log), and every user has an **attendance report** (event + per-course lesson tallies with rates). A school-wide **question pool** runs on moderation: a student asks a question @@ -376,6 +378,7 @@ response in the same commit. "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 }, "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200, "min_max_message_len": 100, "…": 0 }, + "pomodoro": { "min_counted_ms": 300000, "max_counted_per_day": 16 }, "board": { "max_title_len": 200, "max_participants": 200, "max_stroke_payload_len": 4096, "max_epoch_strokes": 5000, "max_board_strokes": 50000, @@ -393,6 +396,11 @@ response in the same commit. } ``` +The `pomodoro` group is the one that bounds no input: `POST /pomodoro/finish` +never refuses a stint over it, it records the stint and answers +`counted: false`. It is published for the same reason as the rest — a client +that has to guess what a session was worth is a client with a hard-coded copy. + The `rate` group is the one part that is **not** compile-time: those tiers are environment-tunable, so the endpoint serves *this* server's live values (read from its running limiters), not the shipped defaults. `0` means the tier is @@ -634,7 +642,7 @@ still left exactly as they stand. | 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 | +| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session; a stint moves the badge counters only if it is long enough and within the day's quota (`counted`) | | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms`; a `parent` reads their linked students' | | Ask into the school question pool | student | **Students only** (exact); born `pending` — visible to the asker + teacher+ only; the asker may attach/replace/remove one photo while pending | | Read the pool; offer / edit / withdraw own solutions | student | Every `approved` question is school-wide (parents stay out); a solution's author edits its body and photo anytime (solutions never freeze) and deletes it, teacher+ delete any | @@ -998,7 +1006,7 @@ window filtering, before paging; negative values are a `400` naming the field. | 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) | +| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running); answers `counted` — whether it moved the badge counters (≥ `pomodoro.min_counted_ms`, within the UTC day's `pomodoro.max_counted_per_day`) | | 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; *or a `parent` linked to `{user}` | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | @@ -1273,7 +1281,10 @@ twelve `*_total` keys are **stored lifetime tallies**, maintained at write time `exam_sat_total` still counts an exam a teacher has since deleted, which is the point of a lifetime counter. Either kind reads a true `0` on a fresh account, never `null`. Only *finished* pomodoro stints count on either side — a timer -left running is not study time. Exam averages, homework-done rates and +left running is not study time — and on the stored side only the ones that +**counted** (long enough, within the day's quota; see "Pomodoro" below), so +`pomodoro_sessions` may legitimately run ahead of `pomodoro_finished_total`: +the first is the student's whole log, the second what the badges read. Exam averages, homework-done rates and attendance rates are deliberately absent: those tables are indexed for their own reads, so a per-user aggregate over them is a full table scan, and a profile is far too cheap a page to pay for one — which is also why the twelve @@ -1349,11 +1360,24 @@ catalog — awards carrying it stop being served, no migration. alone with no teacher in it. Resuming an attempt already running is not a new sitting either. Deleting an exam removes the attempt rows but does **not** decrement anyone: a teacher tidying up does not un-sit the exam. -- **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its - duration into `pomodoro_focus_ms_total`. An open stint counts for neither — - unfinished focus has no honest duration to add. -- **Study streak.** Finishing a stint also extends `study_streak_total`, the - **longest** run of consecutive days on which the student finished one. A +- **Pomodoro.** Finishing a stint that **counts** is `+1 + pomodoro_finished_total` and its duration into `pomodoro_focus_ms_total`. An + open stint counts for neither — unfinished focus has no honest duration to + add. A stint counts when it ran at least `pomodoro.min_counted_ms` (5 minutes, + on `GET /limits`) and is within that **UTC day's** + `pomodoro.max_counted_per_day` (16); every further stint that day is recorded + and listed exactly like the others and moves nothing. Without that rule the + ladder was self-serve in the plainest way there is: `start`/`finish` is two + requests, no second person and no elapsed time, so 200 pairs — about ninety + seconds inside the rate limit — bought `pomodoro_finished_10`, `_50` and + `_200` permanently. The verdict is stamped on the stint itself and handed + back as `counted`, so a client can say what a session was worth instead of + guessing why a badge did not arrive, and a threshold moved in a later deploy + never re-judges an old stint. +- **Study streak.** Finishing a stint that counts also extends + `study_streak_total`, the **longest** run of consecutive days on which the + student had one — a day bought with an instant round-trip is not a day + studied, so the same rule gates this counter as the two above. A second stint the same day extends nothing; a gap of any length starts the run over at 1. The badge reads the longest run ever held, never the run in progress, so a broken streak takes no badge away and the counter never comes @@ -2823,9 +2847,24 @@ 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. -Finishing a stint also feeds the **study streak** behind the `study_streak` -badges: consecutive **UTC** days on which one was finished, kept as the longest -run ever held (see "Badges"). +A finished stint carries a `counted` verdict: whether it moved the lifetime +counters the badges read. It counts when it ran at least +`pomodoro.min_counted_ms` (5 minutes) and is within that **UTC day's** +`pomodoro.max_counted_per_day` (16) — both published on `GET /limits`, both +compiled in, so they move only with a deploy. A stint that counts for nothing +is still recorded, still listed, and still sums into `total_focus_ms`: the rule +bounds what *counts*, never what is kept. It exists because finishing is +self-service — one stint is two requests, no second person and no elapsed +time — and a badge counter moved once per round-trip is farmable, permanently, +since a badge is never revoked. Five minutes is well under a conventional +25-minute pomodoro on purpose (breaking off early is still studying) and four +orders of magnitude above a scripted pair; sixteen a day is above any honest +school day while capping the minimum-length farm at eighty minutes of real +waiting a day. + +Finishing a stint that counts also feeds the **study streak** behind the +`study_streak` badges: consecutive **UTC** days on which one was finished, kept +as the longest run ever held (see "Badges"). **Attendance reports** mirror the marks report: `GET /attendance/me` for any logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the diff --git a/src/constant.rs b/src/constant.rs index 6fd3269..380ee5c 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -928,6 +928,34 @@ pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total"; pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total"; pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total"; +/// The bookkeeping behind the counted-stint rule below: which UTC day the +/// student last had a stint counted on, and how many counted that day. Internal +/// state like the two streak columns — no badge reads either, `/limits` names +/// neither, no profile key serves them. The day rolls the tally back to zero. +pub const POMODORO_COUNTED_DAY_FIELD: &str = "pomodoro_counted_day"; +pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today"; +/// What makes a finished stint *count* towards `pomodoro_finished_total` and +/// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at +/// least this long, and it must be within the day's quota. +/// +/// Without them the pair is the farm [`crate::domain::pool_question::PoolQuestion::approve`] +/// reasons about from the other end: `finish` is self-service, a stint costs two +/// requests and no second person, so a counter moved once per round-trip is +/// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`, +/// permanently, since a badge is never revoked. +/// +/// Five minutes is well under a conventional 25-minute pomodoro on purpose: a +/// student who breaks off early still focused, and the counter should not +/// punish that. It is four orders of magnitude above a scripted round-trip, +/// which is the whole distance that matters — the cheat now costs the wall +/// clock it claims. Sixteen a day is likewise above any honest school day +/// (sixteen full pomodoros is over six hours of pure focus) while capping the +/// minimum-length farm at eighty minutes of real waiting per day, so +/// `pomodoro_finished_200` takes at least thirteen calendar days to buy instead +/// of ninety seconds. Both are read `>=`/`<`, i.e. a stint of exactly the +/// 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; /// 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/domain/pomodoro.rs b/src/domain/pomodoro.rs index f07b593..3423e4b 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -1,8 +1,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE, - STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, + MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD, + POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, + POMODORO_SESSION_TABLE, STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, + STUDY_STREAK_LONGEST_FIELD, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::badge; @@ -61,6 +63,7 @@ pub struct PomodoroSession { user: UserId, started_at: Timestamp, finished_at: Option, + counted: Option, } impl PomodoroSession { @@ -80,6 +83,13 @@ impl PomodoroSession { self.finished_at } + /// Whether this stint moved the lifetime counters, as [`Self::finish`] + /// judged it. `None` while it is still running — and on any stint closed + /// before the rule existed, which cannot honestly be given a verdict now. + pub fn get_counted(&self) -> Option { + self.counted + } + /// 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 — @@ -127,13 +137,44 @@ impl PomodoroSession { /// rolled the increment back with the rest. They are written field-scoped: /// the row also carries admin-owned data (`role`), which a whole-row save /// would silently revert. The clamped duration is the *same* expression the - /// `CREATE` stores, so the counter can never take a negative summand and - /// nothing downstream needs a floor. Only *finished* stints reach here — an - /// open row is a `pomodoro_session` row and nothing else — and there is no - /// student-facing delete for a stint, so neither counter ever decrements. + /// `CREATE` stores (both read `$ms`), so the counter can never take a + /// negative summand and nothing downstream needs a floor. Only *finished* + /// stints reach here — an open row is a `pomodoro_session` row and nothing + /// else — and there is no student-facing delete for a stint, so neither + /// counter ever decrements. + /// + /// They move only for a stint that **counts**, which is + /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most + /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this + /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] + /// argues about from the other end: finishing is self-service, one stint is + /// two requests and no second person, so a counter moved once per + /// round-trip is farmable — two hundred pairs inside the rate limit bought + /// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked. + /// Both stamps are the server's own clock, so the duration needs no + /// distrusting, only a floor. + /// + /// The verdict is *stamped* on the closed row (`counted`), not re-derived + /// later: the thresholds are compiled in and will move, and a reader that + /// re-judged an old stint against today's numbers would answer something + /// other than what was credited. Nothing debits these counters today; the + /// stamp is what lets one be added without that asymmetry. A stint below + /// the bar is still recorded, still listed, and still sums into the log's + /// `total_focus_ms` — the rule bounds what *counts*, never what is kept. + /// + /// 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 + /// it, which resolves against the row as it was *before* the statement — + /// the same rule that forces the streak pair apart, used here on purpose. A + /// row that predates the two columns reads as no day at all (`?? -1`), so + /// the first finish after this deploy opens a fresh bucket and no backfill + /// is owed. The bucket write happens whether the stint counts or not; only + /// the `+ 1` sits behind the verdict. /// - /// The **study streak** rides the same transaction. A study day is a UTC - /// calendar day on which a stint was *finished* (midnight UTC, like every + /// The **study streak** rides the same transaction, and the same verdict: a + /// study day is a UTC calendar day on which a stint *counted*, so a day + /// bought with one instant round-trip is not a day studied (midnight UTC, like every /// other day calculation here — no timezone is stored anywhere): the same /// day again changes nothing, the next day extends the run, any other gap /// starts a new one at 1. It is written as **two** statements, not one: @@ -182,26 +223,43 @@ impl PomodoroSession { "BEGIN TRANSACTION; LET $before = (DELETE $open RETURN BEFORE); IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; - UPDATE $usr SET - {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, - {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) - + (math::max([$before[0].started_at, $done]) - $before[0].started_at); - LET $streak = (UPDATE $usr SET - {STUDY_STREAK_CURRENT_FIELD} = - IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day - THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) - ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) - THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) - ELSE 1 END, - {STUDY_STREAK_LAST_DAY_FIELD} = $day + LET $end = math::max([$before[0].started_at, $done]); + LET $ms = $end - $before[0].started_at; + LET $bucket = (UPDATE $usr SET + {POMODORO_COUNTED_TODAY_FIELD} = + IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day + THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END, + {POMODORO_COUNTED_DAY_FIELD} = $day RETURN AFTER); - UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), - ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]); + LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS}) + AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0) + < {MAX_COUNTED_POMODORO_PER_DAY}); + IF $counted {{ + UPDATE $usr SET + {POMODORO_FINISHED_TOTAL_FIELD} = + ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, + {POMODORO_FOCUS_MS_TOTAL_FIELD} = + ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms, + {POMODORO_COUNTED_TODAY_FIELD} = + ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1; + LET $streak = (UPDATE $usr SET + {STUDY_STREAK_CURRENT_FIELD} = + IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day + THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) + ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) + THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) + ELSE 1 END, + {STUDY_STREAK_LAST_DAY_FIELD} = $day + RETURN AFTER); + UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), + ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]) + }}; CREATE $closed CONTENT {{ user: $before[0].user, started_at: $before[0].started_at, - finished_at: math::max([$before[0].started_at, $done]), + finished_at: $end, + counted: $counted, }}; COMMIT TRANSACTION;" ), @@ -332,10 +390,12 @@ mod tests { (row[0], row[1], row[2]) } - /// Age the streak bookkeeping by `days`, so the *next* finish lands that - /// many days later on the calendar. The day is injected into the stored - /// state rather than into the clock, which keeps `Timestamp::now` the sole - /// clock read and the test free of sleeping. + /// Age *both* day buckets by `days`, so the next finish lands that many + /// days later on the calendar — the streak's and the day quota's, since + /// they are the same calendar and a test that moved one would be asserting + /// against a day the other has never heard of. The day is injected into the + /// stored state rather than into the clock, which keeps `Timestamp::now` + /// the sole clock read and the test free of sleeping. /// /// Known flake, left as-is: every caller assumes the UTC day does not turn /// over mid-test — a crossing between two stints shifts the real day under @@ -345,7 +405,9 @@ mod tests { /// happens near midnight UTC. async fn age_by_days(user: &UserId, db: &Database, days: i64) { db.query(format!( - "UPDATE $usr SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days" + "UPDATE $usr SET + {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, + {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" )) .bind(("usr", user.record())) .bind(("days", days)) @@ -355,9 +417,28 @@ mod tests { .unwrap(); } - /// Start and close one stint. + /// Open a stint that has already been running for `ms` — the stamp the + /// close measures against, injected instead of slept through. + /// + /// One `UPSERT`, not `start` followed by a backdate: the concurrent test + /// races four of these onto the same open row, and a separate backdate can + /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a + /// zero-length stint and reddening the run for no defect. Same statement + /// `start` runs, one clock read earlier. + async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { + 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().as_millis() - ms)) + .await? + .check()?; + Ok(()) + } + + /// Start and close one stint that counts: exactly the minimum on the clock, + /// so every streak assertion below is about the day and not the duration. async fn one_stint(user: &UserId, db: &Database) { - PomodoroSession::start(user, db).await.unwrap(); + start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap(); PomodoroSession::finish(user, db).await.unwrap(); } @@ -454,7 +535,12 @@ mod tests { .map(|_| { let (user, db) = (user.clone(), db.clone()); tokio::spawn(async move { - PomodoroSession::start(&user, &db).await?; + // Aged past the minimum, so whichever racer wins the + // open row closes a stint that *counts* — a fresh + // `start` here would hand the winner a zero-length + // stint, which now moves nothing and would leave this + // test asserting against an untouched counter. + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?; PomodoroSession::finish(&user, &db).await }) }) @@ -513,7 +599,9 @@ mod tests { // An open stint is not a finished one: neither counter moves until it // closes. - PomodoroSession::start(&user, &db).await.unwrap(); + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); assert_eq!(counters(&user, &db).await, (0, 0)); let mut focus_ms = 0; @@ -521,7 +609,9 @@ mod tests { let closed = PomodoroSession::finish(&user, &db).await.unwrap(); focus_ms += closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); - PomodoroSession::start(&user, &db).await.unwrap(); + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); } // Three starts, two finishes — the third is still running. assert_eq!(counters(&user, &db).await, (2, focus_ms)); @@ -541,8 +631,143 @@ mod tests { .check() .unwrap(); - PomodoroSession::finish(&user, &db).await.unwrap(); - assert_eq!(counters(&user, &db).await, (1, 0)); + // The clamp holds: zero milliseconds, never a negative — and a stint + // measuring zero is below the minimum, so it moves neither counter. + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); + assert_eq!(closed.get_counted(), Some(false)); + assert_eq!(counters(&user, &db).await, (0, 0)); + } + + /// The minimum, from both sides. A round-trip is not a study session, and + /// the boundary is inclusive (`>=`) — a stint of exactly the minimum + /// counts, which is the side these assertions pin. + /// + /// The near miss is a whole minute short, not one millisecond: `finish` + /// reads its own clock *after* the stint is opened, so a stint aged to + /// exactly one millisecond under the bar crosses it by the time the close + /// measures it (measured — that assertion failed on the first run). A + /// millisecond-exact probe would need a clock seam in production code, and + /// what matters here is the four orders of magnitude between a scripted + /// pair and a study session, not the last millisecond. + #[tokio::test] + async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) + .await + .unwrap(); + let short = PomodoroSession::finish(&user, &db).await.unwrap(); + assert_eq!(short.get_counted(), Some(false)); + assert_eq!(counters(&user, &db).await, (0, 0)); + // Not a study day either — and no streak column was even opened. + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + // But it happened, and the log says so. + let log = PomodoroSession::list_for_user(&user, &db).await.unwrap(); + assert_eq!(log.len(), 1); + assert_eq!(log[0].get_finished_at(), short.get_finished_at()); + + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + let counted = PomodoroSession::finish(&user, &db).await.unwrap(); + assert_eq!(counted.get_counted(), Some(true)); + let (finished, focus_ms) = counters(&user, &db).await; + // The counter took the *same* duration the row stores, not a second + // reading of the clock. + assert_eq!( + (finished, focus_ms), + ( + 1, + counted.get_finished_at().unwrap().as_millis() + - counted.get_started_at().as_millis() + ) + ); + assert_eq!(streak(&user, &db).await.0, 1); + assert_eq!( + PomodoroSession::list_for_user(&user, &db) + .await + .unwrap() + .len(), + 2 + ); + } + + /// The day quota: it stops the counter, it never stops the log, and it + /// rolls at midnight UTC. + #[tokio::test] + async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { + one_stint(&user, &db).await; + } + let (finished, focus_ms) = counters(&user, &db).await; + assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY); + + // Past the quota: recorded, listed, worth nothing — neither stint count + // nor focus milliseconds. + for _ in 0..3 { + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + let over = PomodoroSession::finish(&user, &db).await.unwrap(); + assert_eq!(over.get_counted(), Some(false)); + } + assert_eq!(counters(&user, &db).await, (finished, focus_ms)); + assert_eq!( + PomodoroSession::list_for_user(&user, &db) + .await + .unwrap() + .len() as i64, + MAX_COUNTED_POMODORO_PER_DAY + 3 + ); + // The quota is a day's, not a lifetime's. + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!( + counters(&user, &db).await.0, + MAX_COUNTED_POMODORO_PER_DAY + 1 + ); + } + + /// The farm, run: `start`/`finish` in a loop is two requests a round with + /// no second person in it, which used to move `pomodoro_finished_total` one + /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`, + /// and a badge is never taken back. + #[tokio::test] + async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + for _ in 0..200 { + PomodoroSession::start(&user, &db).await.unwrap(); + PomodoroSession::finish(&user, &db).await.unwrap(); + } + assert_eq!(counters(&user, &db).await, (0, 0)); + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + // Every one of them is still the student's own history. + assert_eq!( + PomodoroSession::list_for_user(&user, &db) + .await + .unwrap() + .len(), + 200 + ); + assert!( + badge::BadgeAward::list_for(&user, &db) + .await + .unwrap() + .is_empty(), + "the farm minted a permanent badge" + ); + + // And paying the minimum for each one only buys the day's quota. + for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) { + one_stint(&user, &db).await; + } + assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY); } #[tokio::test] diff --git a/src/lib.rs b/src/lib.rs index b74e855..8ac6fce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,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). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. 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; students can attach an answer drawing to any question in their attempt. 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 three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework 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. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak) and the named see only themselves in, subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. 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`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. 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. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", + 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). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. 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; students can attach an answer drawing to any question in their attempt. 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 three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework 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; every stint is logged, but only one of at least `pomodoro.min_counted_ms` and within the UTC day's `pomodoro.max_counted_per_day` *counts* towards the badges, which is what keeps a start/finish loop from buying them); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak) and the named see only themselves in, subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. 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`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. 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. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", ), modifiers(&SecurityAddon), tags( @@ -44,7 +44,7 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), + (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused"), @@ -53,12 +53,12 @@ use crate::state::AppState; (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=