Stop a start/finish loop buying the pomodoro badges
Browse files at this commit37ee719a00bd08863bf43060f3e089f5b76cb433Parent: e879fd3- fix
- stop a start/finish loop buying the pomodoro badges
8 changed files +424 -57
- README.md +51 -12
- src/constant.rs +28 -0
- src/domain/pomodoro.rs +261 -36
- src/lib.rs +4 -4
- src/migration_sql.rs +12 -0
- src/web/limits.rs +24 -0
- src/web/pomodoro.rs +17 -0
- tests/regress_badges.rs +27 -5
README.mdmodified+51 -12
| @@ -90,7 +90,9 @@ marks stay out of the weighted `/marks` averages. Courses also carry **lesson | |||
| 90 | sessions** with teacher-taken roll call (students never self-mark a lesson), | 90 | sessions** with teacher-taken roll call (students never self-mark a lesson), |
| 91 | staff clock in/out on a server-stamped **work log**, students track study time | 91 | staff clock in/out on a server-stamped **work log**, students track study time |
| 92 | with a server-stamped **pomodoro log** (the timer runs in the frontend; the | 92 | with a server-stamped **pomodoro log** (the timer runs in the frontend; the |
| 93 | -backend records the focus stints, and teachers can read any student's log), | 93 | +backend records the focus stints — every one of them, though only stints of at |
| 94 | +least 5 minutes and at most 16 a UTC day *count* towards the badges — and | ||
| 95 | +teachers can read any student's log), | ||
| 94 | and every user has an | 96 | and every user has an |
| 95 | **attendance report** (event + per-course lesson tallies with rates). | 97 | **attendance report** (event + per-course lesson tallies with rates). |
| 96 | A school-wide **question pool** runs on moderation: a student asks a question | 98 | A school-wide **question pool** runs on moderation: a student asks a question |
| @@ -376,6 +378,7 @@ response in the same commit. | |||
| 376 | "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 }, | 378 | "appointment": { "max_note_len": 500, "max_reason_len": 1000, "max_slot_occurrences": 52 }, |
| 377 | "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200, | 379 | "chatbot": { "max_message_len": 8000, "max_thread_title_len": 200, |
| 378 | "min_max_message_len": 100, "…": 0 }, | 380 | "min_max_message_len": 100, "…": 0 }, |
| 381 | + "pomodoro": { "min_counted_ms": 300000, "max_counted_per_day": 16 }, | ||
| 379 | "board": { "max_title_len": 200, "max_participants": 200, | 382 | "board": { "max_title_len": 200, "max_participants": 200, |
| 380 | "max_stroke_payload_len": 4096, | 383 | "max_stroke_payload_len": 4096, |
| 381 | "max_epoch_strokes": 5000, "max_board_strokes": 50000, | 384 | "max_epoch_strokes": 5000, "max_board_strokes": 50000, |
| @@ -393,6 +396,11 @@ response in the same commit. | |||
| 393 | } | 396 | } |
| 394 | ``` | 397 | ``` |
| 395 | 398 | ||
| 399 | +The `pomodoro` group is the one that bounds no input: `POST /pomodoro/finish` | ||
| 400 | +never refuses a stint over it, it records the stint and answers | ||
| 401 | +`counted: false`. It is published for the same reason as the rest — a client | ||
| 402 | +that has to guess what a session was worth is a client with a hard-coded copy. | ||
| 403 | + | ||
| 396 | The `rate` group is the one part that is **not** compile-time: those tiers are | 404 | The `rate` group is the one part that is **not** compile-time: those tiers are |
| 397 | environment-tunable, so the endpoint serves *this* server's live values (read | 405 | environment-tunable, so the endpoint serves *this* server's live values (read |
| 398 | from its running limiters), not the shipped defaults. `0` means the tier is | 406 | from its running limiters), not the shipped defaults. `0` means the tier is |
| @@ -634,7 +642,7 @@ still left exactly as they stand. | |||
| 634 | | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | | 642 | | Mark / remove the **session teacher's** presence row | manager | Staff presence is management's call — the teacher can't self-mark | |
| 635 | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | | 643 | | Work check-in / check-out; view **own** work log | teacher | Instants are server-stamped, never client-supplied | |
| 636 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | | 644 | | View / correct / delete **any** staff work log entry | manager | Corrections only on closed entries | |
| 637 | -| Start / finish a pomodoro focus session; view **own** pomodoro log | student | **Students only** start; instants server-stamped; starting discards a dangling unfinished session | | 645 | +| 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`) | |
| 638 | | 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' | | 646 | | 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' | |
| 639 | | 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 | | 647 | | 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 | |
| 640 | | 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 | | 648 | | 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. | |||
| 998 | | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) | | 1006 | | PATCH | `/work/entries/{id}` | manager | `{check_in?, check_out?}` — correct a **closed** stint (`409` on open) | |
| 999 | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | | 1007 | | DELETE | `/work/entries/{id}` | manager | Delete a work entry (open or closed) | |
| 1000 | | POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** — a dangling unfinished session is discarded and replaced) | | 1008 | | POST | `/pomodoro/start` | student | Start a focus session (server-stamped; **students only** — a dangling unfinished session is discarded and replaced) | |
| 1001 | -| POST | `/pomodoro/finish` | student | Close the running session (`409` if none running) | | 1009 | +| 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`) | |
| 1002 | | GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` · paged | | 1010 | | GET | `/pomodoro/me` | student | Own pomodoro log, newest first, + unpaged `total_focus_ms` · paged | |
| 1003 | | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` | | 1011 | | GET | `/pomodoro/{user}` | teacher* | A user's pomodoro log, same shape · paged; *or a `parent` linked to `{user}` | |
| 1004 | | GET | `/attendance/me` | student | Own attendance report: events + sessions + per-course tallies | | 1012 | | 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 | |||
| 1273 | `exam_sat_total` still counts an exam a teacher has since deleted, which is the | 1281 | `exam_sat_total` still counts an exam a teacher has since deleted, which is the |
| 1274 | point of a lifetime counter. Either kind reads a true `0` on a fresh account, | 1282 | point of a lifetime counter. Either kind reads a true `0` on a fresh account, |
| 1275 | never `null`. Only *finished* pomodoro stints count on either side — a timer | 1283 | never `null`. Only *finished* pomodoro stints count on either side — a timer |
| 1276 | -left running is not study time. Exam averages, homework-done rates and | 1284 | +left running is not study time — and on the stored side only the ones that |
| 1285 | +**counted** (long enough, within the day's quota; see "Pomodoro" below), so | ||
| 1286 | +`pomodoro_sessions` may legitimately run ahead of `pomodoro_finished_total`: | ||
| 1287 | +the first is the student's whole log, the second what the badges read. Exam averages, homework-done rates and | ||
| 1277 | attendance rates are deliberately absent: those tables are indexed for their | 1288 | attendance rates are deliberately absent: those tables are indexed for their |
| 1278 | own reads, so a per-user aggregate over them is a full table scan, and a | 1289 | own reads, so a per-user aggregate over them is a full table scan, and a |
| 1279 | profile is far too cheap a page to pay for one — which is also why the twelve | 1290 | 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. | |||
| 1349 | alone with no teacher in it. Resuming an attempt already running is not a new | 1360 | alone with no teacher in it. Resuming an attempt already running is not a new |
| 1350 | sitting either. Deleting an exam removes the attempt rows but does **not** | 1361 | sitting either. Deleting an exam removes the attempt rows but does **not** |
| 1351 | decrement anyone: a teacher tidying up does not un-sit the exam. | 1362 | decrement anyone: a teacher tidying up does not un-sit the exam. |
| 1352 | -- **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its | 1363 | +- **Pomodoro.** Finishing a stint that **counts** is `+1 |
| 1353 | - duration into `pomodoro_focus_ms_total`. An open stint counts for neither — | 1364 | + pomodoro_finished_total` and its duration into `pomodoro_focus_ms_total`. An |
| 1354 | - unfinished focus has no honest duration to add. | 1365 | + open stint counts for neither — unfinished focus has no honest duration to |
| 1355 | -- **Study streak.** Finishing a stint also extends `study_streak_total`, the | 1366 | + add. A stint counts when it ran at least `pomodoro.min_counted_ms` (5 minutes, |
| 1356 | - **longest** run of consecutive days on which the student finished one. A | 1367 | + on `GET /limits`) and is within that **UTC day's** |
| 1368 | + `pomodoro.max_counted_per_day` (16); every further stint that day is recorded | ||
| 1369 | + and listed exactly like the others and moves nothing. Without that rule the | ||
| 1370 | + ladder was self-serve in the plainest way there is: `start`/`finish` is two | ||
| 1371 | + requests, no second person and no elapsed time, so 200 pairs — about ninety | ||
| 1372 | + seconds inside the rate limit — bought `pomodoro_finished_10`, `_50` and | ||
| 1373 | + `_200` permanently. The verdict is stamped on the stint itself and handed | ||
| 1374 | + back as `counted`, so a client can say what a session was worth instead of | ||
| 1375 | + guessing why a badge did not arrive, and a threshold moved in a later deploy | ||
| 1376 | + never re-judges an old stint. | ||
| 1377 | +- **Study streak.** Finishing a stint that counts also extends | ||
| 1378 | + `study_streak_total`, the **longest** run of consecutive days on which the | ||
| 1379 | + student had one — a day bought with an instant round-trip is not a day | ||
| 1380 | + studied, so the same rule gates this counter as the two above. A | ||
| 1357 | second stint the same day extends nothing; a gap of any length starts the run | 1381 | second stint the same day extends nothing; a gap of any length starts the run |
| 1358 | over at 1. The badge reads the longest run ever held, never the run in | 1382 | over at 1. The badge reads the longest run ever held, never the run in |
| 1359 | progress, so a broken streak takes no badge away and the counter never comes | 1383 | 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 | |||
| 2823 | every finished session's duration: `GET /pomodoro/me` for your own, | 2847 | every finished session's duration: `GET /pomodoro/me` for your own, |
| 2824 | `GET /pomodoro/{user}` for teacher+ (study oversight). Only students start | 2848 | `GET /pomodoro/{user}` for teacher+ (study oversight). Only students start |
| 2825 | sessions — pomodoro is the study tool, the work log is the staff timesheet. | 2849 | sessions — pomodoro is the study tool, the work log is the staff timesheet. |
| 2826 | -Finishing a stint also feeds the **study streak** behind the `study_streak` | 2850 | +A finished stint carries a `counted` verdict: whether it moved the lifetime |
| 2827 | -badges: consecutive **UTC** days on which one was finished, kept as the longest | 2851 | +counters the badges read. It counts when it ran at least |
| 2828 | -run ever held (see "Badges"). | 2852 | +`pomodoro.min_counted_ms` (5 minutes) and is within that **UTC day's** |
| 2853 | +`pomodoro.max_counted_per_day` (16) — both published on `GET /limits`, both | ||
| 2854 | +compiled in, so they move only with a deploy. A stint that counts for nothing | ||
| 2855 | +is still recorded, still listed, and still sums into `total_focus_ms`: the rule | ||
| 2856 | +bounds what *counts*, never what is kept. It exists because finishing is | ||
| 2857 | +self-service — one stint is two requests, no second person and no elapsed | ||
| 2858 | +time — and a badge counter moved once per round-trip is farmable, permanently, | ||
| 2859 | +since a badge is never revoked. Five minutes is well under a conventional | ||
| 2860 | +25-minute pomodoro on purpose (breaking off early is still studying) and four | ||
| 2861 | +orders of magnitude above a scripted pair; sixteen a day is above any honest | ||
| 2862 | +school day while capping the minimum-length farm at eighty minutes of real | ||
| 2863 | +waiting a day. | ||
| 2864 | + | ||
| 2865 | +Finishing a stint that counts also feeds the **study streak** behind the | ||
| 2866 | +`study_streak` badges: consecutive **UTC** days on which one was finished, kept | ||
| 2867 | +as the longest run ever held (see "Badges"). | ||
| 2829 | 2868 | ||
| 2830 | **Attendance reports** mirror the marks report: `GET /attendance/me` for any | 2869 | **Attendance reports** mirror the marks report: `GET /attendance/me` for any |
| 2831 | logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the | 2870 | logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the |
src/constant.rsmodified+28 -0
| @@ -928,6 +928,34 @@ pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total"; | |||
| 928 | pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; | 928 | pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; |
| 929 | pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total"; | 929 | pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total"; |
| 930 | pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total"; | 930 | pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total"; |
| 931 | +/// The bookkeeping behind the counted-stint rule below: which UTC day the | ||
| 932 | +/// student last had a stint counted on, and how many counted that day. Internal | ||
| 933 | +/// state like the two streak columns — no badge reads either, `/limits` names | ||
| 934 | +/// neither, no profile key serves them. The day rolls the tally back to zero. | ||
| 935 | +pub const POMODORO_COUNTED_DAY_FIELD: &str = "pomodoro_counted_day"; | ||
| 936 | +pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today"; | ||
| 937 | +/// What makes a finished stint *count* towards `pomodoro_finished_total` and | ||
| 938 | +/// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at | ||
| 939 | +/// least this long, and it must be within the day's quota. | ||
| 940 | +/// | ||
| 941 | +/// Without them the pair is the farm [`crate::domain::pool_question::PoolQuestion::approve`] | ||
| 942 | +/// reasons about from the other end: `finish` is self-service, a stint costs two | ||
| 943 | +/// requests and no second person, so a counter moved once per round-trip is | ||
| 944 | +/// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`, | ||
| 945 | +/// permanently, since a badge is never revoked. | ||
| 946 | +/// | ||
| 947 | +/// Five minutes is well under a conventional 25-minute pomodoro on purpose: a | ||
| 948 | +/// student who breaks off early still focused, and the counter should not | ||
| 949 | +/// punish that. It is four orders of magnitude above a scripted round-trip, | ||
| 950 | +/// which is the whole distance that matters — the cheat now costs the wall | ||
| 951 | +/// clock it claims. Sixteen a day is likewise above any honest school day | ||
| 952 | +/// (sixteen full pomodoros is over six hours of pure focus) while capping the | ||
| 953 | +/// minimum-length farm at eighty minutes of real waiting per day, so | ||
| 954 | +/// `pomodoro_finished_200` takes at least thirteen calendar days to buy instead | ||
| 955 | +/// of ninety seconds. Both are read `>=`/`<`, i.e. a stint of exactly the | ||
| 956 | +/// minimum counts and the sixteenth of the day counts. | ||
| 957 | +pub const MIN_COUNTED_POMODORO_MS: i64 = 300_000; | ||
| 958 | +pub const MAX_COUNTED_POMODORO_PER_DAY: i64 = 16; | ||
| 931 | /// The staff-side and second student-side totals, same shape and same rules: | 959 | /// The staff-side and second student-side totals, same shape and same rules: |
| 932 | /// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and | 960 | /// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and |
| 933 | /// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the | 961 | /// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the |
src/domain/pomodoro.rsmodified+261 -36
| @@ -1,8 +1,10 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | ||
| 3 | use crate::constant::{ | 3 | use crate::constant::{ |
| 4 | - POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE, | 4 | + MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD, |
| 5 | - STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, | 5 | + POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, |
| 6 | + POMODORO_SESSION_TABLE, STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, | ||
| 7 | + STUDY_STREAK_LONGEST_FIELD, | ||
| 6 | }; | 8 | }; |
| 7 | use crate::database::{Database, transaction_with_retry}; | 9 | use crate::database::{Database, transaction_with_retry}; |
| 8 | use crate::domain::badge; | 10 | use crate::domain::badge; |
| @@ -61,6 +63,7 @@ pub struct PomodoroSession { | |||
| 61 | user: UserId, | 63 | user: UserId, |
| 62 | started_at: Timestamp, | 64 | started_at: Timestamp, |
| 63 | finished_at: Option<Timestamp>, | 65 | finished_at: Option<Timestamp>, |
| 66 | + counted: Option<bool>, | ||
| 64 | } | 67 | } |
| 65 | 68 | ||
| 66 | impl PomodoroSession { | 69 | impl PomodoroSession { |
| @@ -80,6 +83,13 @@ impl PomodoroSession { | |||
| 80 | self.finished_at | 83 | self.finished_at |
| 81 | } | 84 | } |
| 82 | 85 | ||
| 86 | + /// Whether this stint moved the lifetime counters, as [`Self::finish`] | ||
| 87 | + /// judged it. `None` while it is still running — and on any stint closed | ||
| 88 | + /// before the rule existed, which cannot honestly be given a verdict now. | ||
| 89 | + pub fn get_counted(&self) -> Option<bool> { | ||
| 90 | + self.counted | ||
| 91 | + } | ||
| 92 | + | ||
| 83 | /// Start a session for `user`, stamped with the server clock. `UPSERT` on | 93 | /// Start a session for `user`, stamped with the server clock. `UPSERT` on |
| 84 | /// the deterministic open id makes this atomic and always succeed: a | 94 | /// the deterministic open id makes this atomic and always succeed: a |
| 85 | /// dangling unfinished session (the browser died mid-timer) is replaced — | 95 | /// dangling unfinished session (the browser died mid-timer) is replaced — |
| @@ -127,13 +137,44 @@ impl PomodoroSession { | |||
| 127 | /// rolled the increment back with the rest. They are written field-scoped: | 137 | /// rolled the increment back with the rest. They are written field-scoped: |
| 128 | /// the row also carries admin-owned data (`role`), which a whole-row save | 138 | /// the row also carries admin-owned data (`role`), which a whole-row save |
| 129 | /// would silently revert. The clamped duration is the *same* expression the | 139 | /// would silently revert. The clamped duration is the *same* expression the |
| 130 | - /// `CREATE` stores, so the counter can never take a negative summand and | 140 | + /// `CREATE` stores (both read `$ms`), so the counter can never take a |
| 131 | - /// nothing downstream needs a floor. Only *finished* stints reach here — an | 141 | + /// negative summand and nothing downstream needs a floor. Only *finished* |
| 132 | - /// open row is a `pomodoro_session` row and nothing else — and there is no | 142 | + /// stints reach here — an open row is a `pomodoro_session` row and nothing |
| 133 | - /// student-facing delete for a stint, so neither counter ever decrements. | 143 | + /// else — and there is no student-facing delete for a stint, so neither |
| 144 | + /// counter ever decrements. | ||
| 145 | + /// | ||
| 146 | + /// They move only for a stint that **counts**, which is | ||
| 147 | + /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most | ||
| 148 | + /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this | ||
| 149 | + /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] | ||
| 150 | + /// argues about from the other end: finishing is self-service, one stint is | ||
| 151 | + /// two requests and no second person, so a counter moved once per | ||
| 152 | + /// round-trip is farmable — two hundred pairs inside the rate limit bought | ||
| 153 | + /// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked. | ||
| 154 | + /// Both stamps are the server's own clock, so the duration needs no | ||
| 155 | + /// distrusting, only a floor. | ||
| 156 | + /// | ||
| 157 | + /// The verdict is *stamped* on the closed row (`counted`), not re-derived | ||
| 158 | + /// later: the thresholds are compiled in and will move, and a reader that | ||
| 159 | + /// re-judged an old stint against today's numbers would answer something | ||
| 160 | + /// other than what was credited. Nothing debits these counters today; the | ||
| 161 | + /// stamp is what lets one be added without that asymmetry. A stint below | ||
| 162 | + /// the bar is still recorded, still listed, and still sums into the log's | ||
| 163 | + /// `total_focus_ms` — the rule bounds what *counts*, never what is kept. | ||
| 164 | + /// | ||
| 165 | + /// The day quota is bucketed like the streak below (midnight UTC, | ||
| 166 | + /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the | ||
| 167 | + /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting | ||
| 168 | + /// it, which resolves against the row as it was *before* the statement — | ||
| 169 | + /// the same rule that forces the streak pair apart, used here on purpose. A | ||
| 170 | + /// row that predates the two columns reads as no day at all (`?? -1`), so | ||
| 171 | + /// the first finish after this deploy opens a fresh bucket and no backfill | ||
| 172 | + /// is owed. The bucket write happens whether the stint counts or not; only | ||
| 173 | + /// the `+ 1` sits behind the verdict. | ||
| 134 | /// | 174 | /// |
| 135 | - /// The **study streak** rides the same transaction. A study day is a UTC | 175 | + /// The **study streak** rides the same transaction, and the same verdict: a |
| 136 | - /// calendar day on which a stint was *finished* (midnight UTC, like every | 176 | + /// study day is a UTC calendar day on which a stint *counted*, so a day |
| 177 | + /// bought with one instant round-trip is not a day studied (midnight UTC, like every | ||
| 137 | /// other day calculation here — no timezone is stored anywhere): the same | 178 | /// other day calculation here — no timezone is stored anywhere): the same |
| 138 | /// day again changes nothing, the next day extends the run, any other gap | 179 | /// day again changes nothing, the next day extends the run, any other gap |
| 139 | /// starts a new one at 1. It is written as **two** statements, not one: | 180 | /// starts a new one at 1. It is written as **two** statements, not one: |
| @@ -182,26 +223,43 @@ impl PomodoroSession { | |||
| 182 | "BEGIN TRANSACTION; | 223 | "BEGIN TRANSACTION; |
| 183 | LET $before = (DELETE $open RETURN BEFORE); | 224 | LET $before = (DELETE $open RETURN BEFORE); |
| 184 | IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; | 225 | IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; |
| 185 | - UPDATE $usr SET | 226 | + LET $end = math::max([$before[0].started_at, $done]); |
| 186 | - {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, | 227 | + LET $ms = $end - $before[0].started_at; |
| 187 | - {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) | 228 | + LET $bucket = (UPDATE $usr SET |
| 188 | - + (math::max([$before[0].started_at, $done]) - $before[0].started_at); | 229 | + {POMODORO_COUNTED_TODAY_FIELD} = |
| 189 | - LET $streak = (UPDATE $usr SET | 230 | + IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day |
| 190 | - {STUDY_STREAK_CURRENT_FIELD} = | 231 | + THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END, |
| 191 | - IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day | 232 | + {POMODORO_COUNTED_DAY_FIELD} = $day |
| 192 | - THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) | ||
| 193 | - ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) | ||
| 194 | - THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) | ||
| 195 | - ELSE 1 END, | ||
| 196 | - {STUDY_STREAK_LAST_DAY_FIELD} = $day | ||
| 197 | RETURN AFTER); | 233 | RETURN AFTER); |
| 198 | - UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ | 234 | + LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS}) |
| 199 | - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), | 235 | + AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0) |
| 200 | - ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]); | 236 | + < {MAX_COUNTED_POMODORO_PER_DAY}); |
| 237 | + IF $counted {{ | ||
| 238 | + UPDATE $usr SET | ||
| 239 | + {POMODORO_FINISHED_TOTAL_FIELD} = | ||
| 240 | + ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, | ||
| 241 | + {POMODORO_FOCUS_MS_TOTAL_FIELD} = | ||
| 242 | + ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms, | ||
| 243 | + {POMODORO_COUNTED_TODAY_FIELD} = | ||
| 244 | + ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1; | ||
| 245 | + LET $streak = (UPDATE $usr SET | ||
| 246 | + {STUDY_STREAK_CURRENT_FIELD} = | ||
| 247 | + IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day | ||
| 248 | + THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) | ||
| 249 | + ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) | ||
| 250 | + THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) | ||
| 251 | + ELSE 1 END, | ||
| 252 | + {STUDY_STREAK_LAST_DAY_FIELD} = $day | ||
| 253 | + RETURN AFTER); | ||
| 254 | + UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ | ||
| 255 | + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), | ||
| 256 | + ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]) | ||
| 257 | + }}; | ||
| 201 | CREATE $closed CONTENT {{ | 258 | CREATE $closed CONTENT {{ |
| 202 | user: $before[0].user, | 259 | user: $before[0].user, |
| 203 | started_at: $before[0].started_at, | 260 | started_at: $before[0].started_at, |
| 204 | - finished_at: math::max([$before[0].started_at, $done]), | 261 | + finished_at: $end, |
| 262 | + counted: $counted, | ||
| 205 | }}; | 263 | }}; |
| 206 | COMMIT TRANSACTION;" | 264 | COMMIT TRANSACTION;" |
| 207 | ), | 265 | ), |
| @@ -332,10 +390,12 @@ mod tests { | |||
| 332 | (row[0], row[1], row[2]) | 390 | (row[0], row[1], row[2]) |
| 333 | } | 391 | } |
| 334 | 392 | ||
| 335 | - /// Age the streak bookkeeping by `days`, so the *next* finish lands that | 393 | + /// Age *both* day buckets by `days`, so the next finish lands that many |
| 336 | - /// many days later on the calendar. The day is injected into the stored | 394 | + /// days later on the calendar — the streak's and the day quota's, since |
| 337 | - /// state rather than into the clock, which keeps `Timestamp::now` the sole | 395 | + /// they are the same calendar and a test that moved one would be asserting |
| 338 | - /// clock read and the test free of sleeping. | 396 | + /// against a day the other has never heard of. The day is injected into the |
| 397 | + /// stored state rather than into the clock, which keeps `Timestamp::now` | ||
| 398 | + /// the sole clock read and the test free of sleeping. | ||
| 339 | /// | 399 | /// |
| 340 | /// Known flake, left as-is: every caller assumes the UTC day does not turn | 400 | /// Known flake, left as-is: every caller assumes the UTC day does not turn |
| 341 | /// over mid-test — a crossing between two stints shifts the real day under | 401 | /// over mid-test — a crossing between two stints shifts the real day under |
| @@ -345,7 +405,9 @@ mod tests { | |||
| 345 | /// happens near midnight UTC. | 405 | /// happens near midnight UTC. |
| 346 | async fn age_by_days(user: &UserId, db: &Database, days: i64) { | 406 | async fn age_by_days(user: &UserId, db: &Database, days: i64) { |
| 347 | db.query(format!( | 407 | db.query(format!( |
| 348 | - "UPDATE $usr SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days" | 408 | + "UPDATE $usr SET |
| 409 | + {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, | ||
| 410 | + {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" | ||
| 349 | )) | 411 | )) |
| 350 | .bind(("usr", user.record())) | 412 | .bind(("usr", user.record())) |
| 351 | .bind(("days", days)) | 413 | .bind(("days", days)) |
| @@ -355,9 +417,28 @@ mod tests { | |||
| 355 | .unwrap(); | 417 | .unwrap(); |
| 356 | } | 418 | } |
| 357 | 419 | ||
| 358 | - /// Start and close one stint. | 420 | + /// Open a stint that has already been running for `ms` — the stamp the |
| 421 | + /// close measures against, injected instead of slept through. | ||
| 422 | + /// | ||
| 423 | + /// One `UPSERT`, not `start` followed by a backdate: the concurrent test | ||
| 424 | + /// races four of these onto the same open row, and a separate backdate can | ||
| 425 | + /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a | ||
| 426 | + /// zero-length stint and reddening the run for no defect. Same statement | ||
| 427 | + /// `start` runs, one clock read earlier. | ||
| 428 | + async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { | ||
| 429 | + db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }") | ||
| 430 | + .bind(("open", PomodoroSessionId::open_for(user).record())) | ||
| 431 | + .bind(("usr", user.record())) | ||
| 432 | + .bind(("at", Timestamp::now().as_millis() - ms)) | ||
| 433 | + .await? | ||
| 434 | + .check()?; | ||
| 435 | + Ok(()) | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + /// Start and close one stint that counts: exactly the minimum on the clock, | ||
| 439 | + /// so every streak assertion below is about the day and not the duration. | ||
| 359 | async fn one_stint(user: &UserId, db: &Database) { | 440 | async fn one_stint(user: &UserId, db: &Database) { |
| 360 | - PomodoroSession::start(user, db).await.unwrap(); | 441 | + start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap(); |
| 361 | PomodoroSession::finish(user, db).await.unwrap(); | 442 | PomodoroSession::finish(user, db).await.unwrap(); |
| 362 | } | 443 | } |
| 363 | 444 | ||
| @@ -454,7 +535,12 @@ mod tests { | |||
| 454 | .map(|_| { | 535 | .map(|_| { |
| 455 | let (user, db) = (user.clone(), db.clone()); | 536 | let (user, db) = (user.clone(), db.clone()); |
| 456 | tokio::spawn(async move { | 537 | tokio::spawn(async move { |
| 457 | - PomodoroSession::start(&user, &db).await?; | 538 | + // Aged past the minimum, so whichever racer wins the |
| 539 | + // open row closes a stint that *counts* — a fresh | ||
| 540 | + // `start` here would hand the winner a zero-length | ||
| 541 | + // stint, which now moves nothing and would leave this | ||
| 542 | + // test asserting against an untouched counter. | ||
| 543 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?; | ||
| 458 | PomodoroSession::finish(&user, &db).await | 544 | PomodoroSession::finish(&user, &db).await |
| 459 | }) | 545 | }) |
| 460 | }) | 546 | }) |
| @@ -513,7 +599,9 @@ mod tests { | |||
| 513 | 599 | ||
| 514 | // An open stint is not a finished one: neither counter moves until it | 600 | // An open stint is not a finished one: neither counter moves until it |
| 515 | // closes. | 601 | // closes. |
| 516 | - PomodoroSession::start(&user, &db).await.unwrap(); | 602 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) |
| 603 | + .await | ||
| 604 | + .unwrap(); | ||
| 517 | assert_eq!(counters(&user, &db).await, (0, 0)); | 605 | assert_eq!(counters(&user, &db).await, (0, 0)); |
| 518 | 606 | ||
| 519 | let mut focus_ms = 0; | 607 | let mut focus_ms = 0; |
| @@ -521,7 +609,9 @@ mod tests { | |||
| 521 | let closed = PomodoroSession::finish(&user, &db).await.unwrap(); | 609 | let closed = PomodoroSession::finish(&user, &db).await.unwrap(); |
| 522 | focus_ms += | 610 | focus_ms += |
| 523 | closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); | 611 | closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); |
| 524 | - PomodoroSession::start(&user, &db).await.unwrap(); | 612 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) |
| 613 | + .await | ||
| 614 | + .unwrap(); | ||
| 525 | } | 615 | } |
| 526 | // Three starts, two finishes — the third is still running. | 616 | // Three starts, two finishes — the third is still running. |
| 527 | assert_eq!(counters(&user, &db).await, (2, focus_ms)); | 617 | assert_eq!(counters(&user, &db).await, (2, focus_ms)); |
| @@ -541,8 +631,143 @@ mod tests { | |||
| 541 | .check() | 631 | .check() |
| 542 | .unwrap(); | 632 | .unwrap(); |
| 543 | 633 | ||
| 544 | - PomodoroSession::finish(&user, &db).await.unwrap(); | 634 | + // The clamp holds: zero milliseconds, never a negative — and a stint |
| 545 | - assert_eq!(counters(&user, &db).await, (1, 0)); | 635 | + // measuring zero is below the minimum, so it moves neither counter. |
| 636 | + let closed = PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 637 | + assert_eq!(closed.get_counted(), Some(false)); | ||
| 638 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 639 | + } | ||
| 640 | + | ||
| 641 | + /// The minimum, from both sides. A round-trip is not a study session, and | ||
| 642 | + /// the boundary is inclusive (`>=`) — a stint of exactly the minimum | ||
| 643 | + /// counts, which is the side these assertions pin. | ||
| 644 | + /// | ||
| 645 | + /// The near miss is a whole minute short, not one millisecond: `finish` | ||
| 646 | + /// reads its own clock *after* the stint is opened, so a stint aged to | ||
| 647 | + /// exactly one millisecond under the bar crosses it by the time the close | ||
| 648 | + /// measures it (measured — that assertion failed on the first run). A | ||
| 649 | + /// millisecond-exact probe would need a clock seam in production code, and | ||
| 650 | + /// what matters here is the four orders of magnitude between a scripted | ||
| 651 | + /// pair and a study session, not the last millisecond. | ||
| 652 | + #[tokio::test] | ||
| 653 | + async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { | ||
| 654 | + let db = database::init_mem().await.unwrap(); | ||
| 655 | + let user = a_user(&db).await; | ||
| 656 | + | ||
| 657 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) | ||
| 658 | + .await | ||
| 659 | + .unwrap(); | ||
| 660 | + let short = PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 661 | + assert_eq!(short.get_counted(), Some(false)); | ||
| 662 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 663 | + // Not a study day either — and no streak column was even opened. | ||
| 664 | + assert_eq!(streak(&user, &db).await, (0, 0, -1)); | ||
| 665 | + // But it happened, and the log says so. | ||
| 666 | + let log = PomodoroSession::list_for_user(&user, &db).await.unwrap(); | ||
| 667 | + assert_eq!(log.len(), 1); | ||
| 668 | + assert_eq!(log[0].get_finished_at(), short.get_finished_at()); | ||
| 669 | + | ||
| 670 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) | ||
| 671 | + .await | ||
| 672 | + .unwrap(); | ||
| 673 | + let counted = PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 674 | + assert_eq!(counted.get_counted(), Some(true)); | ||
| 675 | + let (finished, focus_ms) = counters(&user, &db).await; | ||
| 676 | + // The counter took the *same* duration the row stores, not a second | ||
| 677 | + // reading of the clock. | ||
| 678 | + assert_eq!( | ||
| 679 | + (finished, focus_ms), | ||
| 680 | + ( | ||
| 681 | + 1, | ||
| 682 | + counted.get_finished_at().unwrap().as_millis() | ||
| 683 | + - counted.get_started_at().as_millis() | ||
| 684 | + ) | ||
| 685 | + ); | ||
| 686 | + assert_eq!(streak(&user, &db).await.0, 1); | ||
| 687 | + assert_eq!( | ||
| 688 | + PomodoroSession::list_for_user(&user, &db) | ||
| 689 | + .await | ||
| 690 | + .unwrap() | ||
| 691 | + .len(), | ||
| 692 | + 2 | ||
| 693 | + ); | ||
| 694 | + } | ||
| 695 | + | ||
| 696 | + /// The day quota: it stops the counter, it never stops the log, and it | ||
| 697 | + /// rolls at midnight UTC. | ||
| 698 | + #[tokio::test] | ||
| 699 | + async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { | ||
| 700 | + let db = database::init_mem().await.unwrap(); | ||
| 701 | + let user = a_user(&db).await; | ||
| 702 | + | ||
| 703 | + for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { | ||
| 704 | + one_stint(&user, &db).await; | ||
| 705 | + } | ||
| 706 | + let (finished, focus_ms) = counters(&user, &db).await; | ||
| 707 | + assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY); | ||
| 708 | + | ||
| 709 | + // Past the quota: recorded, listed, worth nothing — neither stint count | ||
| 710 | + // nor focus milliseconds. | ||
| 711 | + for _ in 0..3 { | ||
| 712 | + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) | ||
| 713 | + .await | ||
| 714 | + .unwrap(); | ||
| 715 | + let over = PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 716 | + assert_eq!(over.get_counted(), Some(false)); | ||
| 717 | + } | ||
| 718 | + assert_eq!(counters(&user, &db).await, (finished, focus_ms)); | ||
| 719 | + assert_eq!( | ||
| 720 | + PomodoroSession::list_for_user(&user, &db) | ||
| 721 | + .await | ||
| 722 | + .unwrap() | ||
| 723 | + .len() as i64, | ||
| 724 | + MAX_COUNTED_POMODORO_PER_DAY + 3 | ||
| 725 | + ); | ||
| 726 | + // The quota is a day's, not a lifetime's. | ||
| 727 | + age_by_days(&user, &db, 1).await; | ||
| 728 | + one_stint(&user, &db).await; | ||
| 729 | + assert_eq!( | ||
| 730 | + counters(&user, &db).await.0, | ||
| 731 | + MAX_COUNTED_POMODORO_PER_DAY + 1 | ||
| 732 | + ); | ||
| 733 | + } | ||
| 734 | + | ||
| 735 | + /// The farm, run: `start`/`finish` in a loop is two requests a round with | ||
| 736 | + /// no second person in it, which used to move `pomodoro_finished_total` one | ||
| 737 | + /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`, | ||
| 738 | + /// and a badge is never taken back. | ||
| 739 | + #[tokio::test] | ||
| 740 | + async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { | ||
| 741 | + let db = database::init_mem().await.unwrap(); | ||
| 742 | + let user = a_user(&db).await; | ||
| 743 | + | ||
| 744 | + for _ in 0..200 { | ||
| 745 | + PomodoroSession::start(&user, &db).await.unwrap(); | ||
| 746 | + PomodoroSession::finish(&user, &db).await.unwrap(); | ||
| 747 | + } | ||
| 748 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 749 | + assert_eq!(streak(&user, &db).await, (0, 0, -1)); | ||
| 750 | + // Every one of them is still the student's own history. | ||
| 751 | + assert_eq!( | ||
| 752 | + PomodoroSession::list_for_user(&user, &db) | ||
| 753 | + .await | ||
| 754 | + .unwrap() | ||
| 755 | + .len(), | ||
| 756 | + 200 | ||
| 757 | + ); | ||
| 758 | + assert!( | ||
| 759 | + badge::BadgeAward::list_for(&user, &db) | ||
| 760 | + .await | ||
| 761 | + .unwrap() | ||
| 762 | + .is_empty(), | ||
| 763 | + "the farm minted a permanent badge" | ||
| 764 | + ); | ||
| 765 | + | ||
| 766 | + // And paying the minimum for each one only buys the day's quota. | ||
| 767 | + for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) { | ||
| 768 | + one_stint(&user, &db).await; | ||
| 769 | + } | ||
| 770 | + assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY); | ||
| 546 | } | 771 | } |
| 547 | 772 | ||
| 548 | #[tokio::test] | 773 | #[tokio::test] |
src/lib.rsmodified+4 -4
| @@ -36,7 +36,7 @@ use crate::state::AppState; | |||
| 36 | info( | 36 | info( |
| 37 | title = "Hezarfen Backend API", | 37 | title = "Hezarfen Backend API", |
| 38 | version = env!("CARGO_PKG_VERSION"), | 38 | version = env!("CARGO_PKG_VERSION"), |
| 39 | - 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.", | 39 | + 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.", |
| 40 | ), | 40 | ), |
| 41 | modifiers(&SecurityAddon), | 41 | modifiers(&SecurityAddon), |
| 42 | tags( | 42 | tags( |
| @@ -44,7 +44,7 @@ use crate::state::AppState; | |||
| 44 | (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"), | 44 | (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"), |
| 45 | (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`"), | 45 | (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`"), |
| 46 | (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"), | 46 | (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"), |
| 47 | - (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`"), | 47 | + (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`"), |
| 48 | (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`)"), | 48 | (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`)"), |
| 49 | (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"), | 49 | (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"), |
| 50 | (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"), | 50 | (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; | |||
| 53 | (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=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), | 53 | (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=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"), |
| 54 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson **at or after its own `starts_at`** credits its teacher's `lessons_held_total` once — a sheet opened early is never refused, it simply holds nothing until the bell — and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"), | 54 | (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson **at or after its own `starts_at`** credits its teacher's `lessons_held_total` once — a sheet opened early is never refused, it simply holds nothing until the bell — and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"), |
| 55 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), | 55 | (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), |
| 56 | - (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"), | 56 | + (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints. A finished stint answers `counted`: whether it moved the lifetime counters the badges and the study streak read, which it does when it ran at least `pomodoro.min_counted_ms` and is within that UTC day's `pomodoro.max_counted_per_day` (both on `GET /limits`, both compiled in). 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, and it exists because finishing is self-service: two requests, no second person and no elapsed time, so a counter moved once per round-trip is farmable and a badge is never revoked"), |
| 57 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), | 57 | (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"), |
| 58 | (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), | 58 | (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), |
| 59 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 59 | (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 60 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), | 60 | (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), |
| 61 | - (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `<student>_k_<key>`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), | 61 | + (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`. The date is parsed by the same calendar library that computes the serving instant and compared back to the text it came from, so a signed component (`2026-+1-01`, which `\"+1\".parse()` once accepted) is a `400` rather than a **second** menu id for the 1st of January — one with its own capacity and seat counter, invisible to every `?from=&to=` read because `+` sorts below `0`. The day must also not already be over (`400`, measured against the end of the day, so today publishes all day long): a published menu is a bookable one and a booking is what charges, so a menu behind the calendar mints real debt for food nobody can be served. The day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a menu whose **day has already passed** takes no booking at all (`409`), whatever the cutoff is set to and with no role able to bypass it — the booking is the charge, so a seat taken on a day already served bills a meal that cannot be eaten; *cancelling* a seat on such a menu stays open, since money already taken has to stay reversible. A full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `<student>_k_<key>`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), |
| 62 | (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. One request is bounded by the charges it would raise rather than by the head count alone — `student_ids × installments` may not exceed 3 000 (200 students up to a 15-installment plan, 50 at a time on a 60-installment one) — and a bigger batch is a `400` naming the split, refused whole before anything is written, since a batch billed in part would leave the office guessing which families were charged. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. That sum costs one query per line of the target's subtree, all of them under that lock, so a line carries **at most 20 applied lines** (the payments under a charge, the refunds under a payment, and the reversals among them): past that a further payment or refund against it is a `409`, an installment settled in more than twenty pieces being pathological. The ceiling binds new writes only — a line that already carries more still reads, still refunds through its own children, and is still reversible. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), | 62 | (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. One request is bounded by the charges it would raise rather than by the head count alone — `student_ids × installments` may not exceed 3 000 (200 students up to a 15-installment plan, 50 at a time on a 60-installment one) — and a bigger batch is a `400` naming the split, refused whole before anything is written, since a batch billed in part would leave the office guessing which families were charged. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. That sum costs one query per line of the target's subtree, all of them under that lock, so a line carries **at most 20 applied lines** (the payments under a charge, the refunds under a payment, and the reversals among them): past that a further payment or refund against it is a `409`, an installment settled in more than twenty pieces being pathological. The ceiling binds new writes only — a line that already carries more still reads, still refunds through its own children, and is still reversible. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), |
| 63 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), | 63 | (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), |
| 64 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), | 64 | (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), |
src/migration_sql.rsmodified+12 -0
| @@ -90,6 +90,13 @@ pub const MIGRATION: &str = " | |||
| 90 | DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option<int>; | 90 | DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option<int>; |
| 91 | DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option<int>; | 91 | DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option<int>; |
| 92 | DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option<int>; | 92 | DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option<int>; |
| 93 | + -- The counted-stint quota (2026-08-05): which UTC day the student last had | ||
| 94 | + -- a pomodoro stint counted on, and how many counted that day. Bookkeeping | ||
| 95 | + -- for the daily cap, read by nothing else; absent reads as no day yet, | ||
| 96 | + -- which is what makes the first finish after this deploy open a fresh | ||
| 97 | + -- bucket with no backfill. | ||
| 98 | + DEFINE FIELD IF NOT EXISTS pomodoro_counted_day ON user TYPE option<int>; | ||
| 99 | + DEFINE FIELD IF NOT EXISTS pomodoro_counted_today ON user TYPE option<int>; | ||
| 93 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; | 100 | DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; |
| 94 | 101 | ||
| 95 | DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; | 102 | DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; |
| @@ -413,6 +420,11 @@ pub const MIGRATION: &str = " | |||
| 413 | DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>; | 420 | DEFINE FIELD IF NOT EXISTS user ON pomodoro_session TYPE record<user>; |
| 414 | DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; | 421 | DEFINE FIELD IF NOT EXISTS started_at ON pomodoro_session TYPE int; |
| 415 | DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>; | 422 | DEFINE FIELD IF NOT EXISTS finished_at ON pomodoro_session TYPE option<int>; |
| 423 | + -- The verdict `finish` reached for this stint, stamped at close so a later | ||
| 424 | + -- reader never re-derives it against thresholds that have since moved. | ||
| 425 | + -- `option<bool>`: a running stint has no verdict yet, and a stint closed | ||
| 426 | + -- before the rule existed carries none and cannot honestly be given one. | ||
| 427 | + DEFINE FIELD IF NOT EXISTS counted ON pomodoro_session TYPE option<bool>; | ||
| 416 | DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; | 428 | DEFINE INDEX IF NOT EXISTS pomodoro_session_user ON pomodoro_session FIELDS user; |
| 417 | 429 | ||
| 418 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; | 430 | DEFINE TABLE IF NOT EXISTS exam SCHEMAFULL; |
src/web/limits.rsmodified+24 -0
| @@ -333,6 +333,25 @@ struct ChatbotLimits { | |||
| 333 | default_max_threads: i64, | 333 | default_max_threads: i64, |
| 334 | } | 334 | } |
| 335 | 335 | ||
| 336 | +/// What a finished pomodoro stint must be to *count* — to move the lifetime | ||
| 337 | +/// counters the badges and the study streak read. Not a validation bound: | ||
| 338 | +/// `POST /pomodoro/finish` never refuses a stint over these, it records it and | ||
| 339 | +/// answers `counted: false`. Published so a client can say what a stint is | ||
| 340 | +/// worth (and what is left of today's quota) instead of guessing why a badge | ||
| 341 | +/// did not arrive. | ||
| 342 | +#[derive(Serialize, ToSchema)] | ||
| 343 | +struct PomodoroLimits { | ||
| 344 | + /// Shortest stint that counts, milliseconds — a stint of exactly this long | ||
| 345 | + /// counts. Well under a conventional 25-minute pomodoro: breaking off early | ||
| 346 | + /// is still studying. Its job is only to price a scripted round-trip out. | ||
| 347 | + #[schema(example = 300000)] | ||
| 348 | + min_counted_ms: i64, | ||
| 349 | + /// How many stints count per UTC day. Every further one that day is | ||
| 350 | + /// recorded and listed as usual, and counts nothing. | ||
| 351 | + #[schema(example = 16)] | ||
| 352 | + max_counted_per_day: i64, | ||
| 353 | +} | ||
| 354 | + | ||
| 336 | /// A collaborative whiteboard: its title, its roster, and the two growth caps | 355 | /// A collaborative whiteboard: its title, its roster, and the two growth caps |
| 337 | /// that decide when a canvas must be cleared and when a board is finished. | 356 | /// that decide when a canvas must be cleared and when a board is finished. |
| 338 | #[derive(Serialize, ToSchema)] | 357 | #[derive(Serialize, ToSchema)] |
| @@ -430,6 +449,7 @@ struct LimitsResponse { | |||
| 430 | meal: MealLimits, | 449 | meal: MealLimits, |
| 431 | payment: PaymentLimits, | 450 | payment: PaymentLimits, |
| 432 | chatbot: ChatbotLimits, | 451 | chatbot: ChatbotLimits, |
| 452 | + pomodoro: PomodoroLimits, | ||
| 433 | board: BoardLimits, | 453 | board: BoardLimits, |
| 434 | settings: SettingsLimits, | 454 | settings: SettingsLimits, |
| 435 | request: RequestLimits, | 455 | request: RequestLimits, |
| @@ -587,6 +607,10 @@ impl LimitsResponse { | |||
| 587 | max_max_threads: MAX_MAX_CHATBOT_THREADS, | 607 | max_max_threads: MAX_MAX_CHATBOT_THREADS, |
| 588 | default_max_threads: DEFAULT_MAX_CHATBOT_THREADS, | 608 | default_max_threads: DEFAULT_MAX_CHATBOT_THREADS, |
| 589 | }, | 609 | }, |
| 610 | + pomodoro: PomodoroLimits { | ||
| 611 | + min_counted_ms: MIN_COUNTED_POMODORO_MS, | ||
| 612 | + max_counted_per_day: MAX_COUNTED_POMODORO_PER_DAY, | ||
| 613 | + }, | ||
| 590 | board: BoardLimits { | 614 | board: BoardLimits { |
| 591 | max_title_len: MAX_BOARD_TITLE_LEN, | 615 | max_title_len: MAX_BOARD_TITLE_LEN, |
| 592 | max_participants: MAX_BOARD_PARTICIPANTS, | 616 | max_participants: MAX_BOARD_PARTICIPANTS, |
src/web/pomodoro.rsmodified+17 -0
| @@ -44,6 +44,13 @@ struct PomodoroResponse { | |||
| 44 | finished_at: Option<i64>, | 44 | finished_at: Option<i64>, |
| 45 | /// `finished_at - started_at`; `null` while still running. | 45 | /// `finished_at - started_at`; `null` while still running. |
| 46 | duration_ms: Option<i64>, | 46 | duration_ms: Option<i64>, |
| 47 | + /// Whether this stint moved the lifetime pomodoro counters (and so the | ||
| 48 | + /// badges and the study streak): it did when it ran at least | ||
| 49 | + /// `pomodoro.min_counted_ms` and was within that UTC day's | ||
| 50 | + /// `pomodoro.max_counted_per_day` (both on `GET /limits`). `null` while | ||
| 51 | + /// still running, and on stints closed before the rule existed. An | ||
| 52 | + /// uncounted stint is kept and listed exactly like any other. | ||
| 53 | + counted: Option<bool>, | ||
| 47 | } | 54 | } |
| 48 | 55 | ||
| 49 | impl PomodoroResponse { | 56 | impl PomodoroResponse { |
| @@ -56,6 +63,7 @@ impl PomodoroResponse { | |||
| 56 | started_at, | 63 | started_at, |
| 57 | finished_at, | 64 | finished_at, |
| 58 | duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), | 65 | duration_ms: finished_at.map(|done| done.saturating_sub(started_at)), |
| 66 | + counted: session.get_counted(), | ||
| 59 | } | 67 | } |
| 60 | } | 68 | } |
| 61 | } | 69 | } |
| @@ -134,6 +142,15 @@ async fn start( | |||
| 134 | 142 | ||
| 135 | /// Finish the running pomodoro session, closing it with a server-stamped | 143 | /// Finish the running pomodoro session, closing it with a server-stamped |
| 136 | /// instant. `409` when nothing is running. | 144 | /// instant. `409` when nothing is running. |
| 145 | +/// | ||
| 146 | +/// The response's `counted` says whether the stint moved the lifetime pomodoro | ||
| 147 | +/// counters — the badges and the study streak read those. It counts when it ran | ||
| 148 | +/// at least `pomodoro.min_counted_ms` and is within that UTC day's | ||
| 149 | +/// `pomodoro.max_counted_per_day` (both published on `GET /limits`); the day | ||
| 150 | +/// bucket rolls at midnight UTC. A stint that counts for nothing is still | ||
| 151 | +/// recorded, still listed, and still sums into `total_focus_ms` — only the | ||
| 152 | +/// badge counters are held to the rule, because finishing is self-service and a | ||
| 153 | +/// counter moved once per round-trip is farmable. | ||
| 137 | #[utoipa::path( | 154 | #[utoipa::path( |
| 138 | post, | 155 | post, |
| 139 | path = "/finish", | 156 | path = "/finish", |
tests/regress_badges.rsmodified+27 -5
| @@ -25,7 +25,9 @@ use common::{ | |||
| 25 | app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, | 25 | app_and_db, create_course, create_exam, create_exam_with, create_session, enroll, id_of, login, |
| 26 | login_as, me_id, send, set_role, | 26 | login_as, me_id, send, set_role, |
| 27 | }; | 27 | }; |
| 28 | -use hezarfen_backend::constant::{BADGES, HIGH_MARK_MIN, STUDY_STREAK_LAST_DAY_FIELD}; | 28 | +use hezarfen_backend::constant::{ |
| 29 | + BADGES, HIGH_MARK_MIN, MIN_COUNTED_POMODORO_MS, STUDY_STREAK_LAST_DAY_FIELD, | ||
| 30 | +}; | ||
| 29 | use hezarfen_backend::database::Database; | 31 | use hezarfen_backend::database::Database; |
| 30 | use hezarfen_backend::domain::timestamp::Timestamp; | 32 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 31 | use serde_json::{Value, json}; | 33 | use serde_json::{Value, json}; |
| @@ -492,12 +494,32 @@ async fn a_correction_lowers_the_counter_but_never_takes_the_badge_back() { | |||
| 492 | 494 | ||
| 493 | // --- the study streak ------------------------------------------------------ | 495 | // --- the study streak ------------------------------------------------------ |
| 494 | 496 | ||
| 495 | -/// Start and finish one focus stint as `cookie` (asserts both statuses). | 497 | +/// Start and finish one focus stint as `cookie` that *counts* (asserts both |
| 496 | -async fn stint(app: &Router, cookie: &str) { | 498 | +/// statuses, and the verdict the finish hands back). |
| 499 | +/// | ||
| 500 | +/// The running stint is aged past `MIN_COUNTED_POMODORO_MS` in between — stored | ||
| 501 | +/// state again, never the clock, and the same reason `age_one_day` exists: a | ||
| 502 | +/// stint that instant is exactly the farm the rule refuses, and no route can | ||
| 503 | +/// make one older. The domain suite pins the rule itself; what this buys is the | ||
| 504 | +/// streak arriving on a real profile. | ||
| 505 | +async fn stint(app: &Router, db: &Database, cookie: &str, user: &str) { | ||
| 497 | let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await; | 506 | let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await; |
| 498 | assert_eq!(started.status, StatusCode::CREATED, "{}", started.body); | 507 | assert_eq!(started.status, StatusCode::CREATED, "{}", started.body); |
| 508 | + db.query("UPDATE type::record('pomodoro_session', $id) SET started_at = started_at - $ms") | ||
| 509 | + .bind(("id", format!("open_{user}"))) | ||
| 510 | + .bind(("ms", MIN_COUNTED_POMODORO_MS)) | ||
| 511 | + .await | ||
| 512 | + .unwrap() | ||
| 513 | + .check() | ||
| 514 | + .unwrap(); | ||
| 499 | let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await; | 515 | let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await; |
| 500 | assert_eq!(finished.status, StatusCode::OK, "{}", finished.body); | 516 | assert_eq!(finished.status, StatusCode::OK, "{}", finished.body); |
| 517 | + assert_eq!( | ||
| 518 | + finished.body["counted"], | ||
| 519 | + Value::from(true), | ||
| 520 | + "{}", | ||
| 521 | + finished.body | ||
| 522 | + ); | ||
| 501 | } | 523 | } |
| 502 | 524 | ||
| 503 | /// Wind `user`'s streak bookkeeping back one day, so the *next* finish lands on | 525 | /// Wind `user`'s streak bookkeeping back one day, so the *next* finish lands on |
| @@ -540,7 +562,7 @@ async fn a_finished_stint_reaches_the_profile_and_three_days_earn_the_badge() { | |||
| 540 | let student = login(&app, "stu").await; | 562 | let student = login(&app, "stu").await; |
| 541 | let student_id = me_id(&app, &student).await; | 563 | let student_id = me_id(&app, &student).await; |
| 542 | 564 | ||
| 543 | - stint(&app, &student).await; | 565 | + stint(&app, &db, &student, &student_id).await; |
| 544 | 566 | ||
| 545 | let first = profile_of(&app, &student, &student_id).await; | 567 | let first = profile_of(&app, &student, &student_id).await; |
| 546 | assert_eq!( | 568 | assert_eq!( |
| @@ -555,7 +577,7 @@ async fn a_finished_stint_reaches_the_profile_and_three_days_earn_the_badge() { | |||
| 555 | 577 | ||
| 556 | for _ in 0..2 { | 578 | for _ in 0..2 { |
| 557 | age_one_day(&db, &student_id).await; | 579 | age_one_day(&db, &student_id).await; |
| 558 | - stint(&app, &student).await; | 580 | + stint(&app, &db, &student, &student_id).await; |
| 559 | } | 581 | } |
| 560 | 582 | ||
| 561 | let after = profile_of(&app, &student, &student_id).await; | 583 | let after = profile_of(&app, &student, &student_id).await; |