forge
Explore
Log in

Don't you dare go Hollow

πŸ… earn badges for the work already done

Browse files at this commit

a00880eebfe5f5ecd12c37a54b32d81a24159abaAhmet Kaan GümüşParent: b326165
  • feat
    • πŸ… earn badges for the work already done
Show full message
feat: πŸ… earn badges for the work already done

Thirteen badges a student earns by doing the work, so the profile has
something to be proud of rather than just a photo and a bio.

Nothing awards a badge by hand and nothing takes one away. A badge is
earned when a counter crosses a threshold, and it is permanent: withdraw
the submission that earned it and the count falls while the badge stays,
because a stamped `earned_at` is the motivational payload and a badge
that evaporates is worse than no badge. The catalog is hardcoded, so
changing a threshold is a deploy and the evaluator stays a pure function
of the counters. It rides GET /limits as a group like every other bound;
labels and icons are the frontend's, keyed by badge id.

The counters are the real work. Homework, exam and attempt tables are
indexed for the questions the rest of the API asks, so counting a single
student's history meant a full table scan β€” the numbers are therefore
tallied at write time, in the same transaction as the write that causes
them. Existing accounts are seeded once from their real history, gated by
a mark whose skip is proven rather than assumed, so nobody starts at zero
for work they already did.

Withdrawing your own submission decrements, and that is the only
decrement in the codebase: withdrawal is student-callable, so without it
submit/delete/submit would farm the counter. Cascades never decrement β€”
history a teacher erased is still history the student lived. The cost is
that a re-run seed, which can only count rows that still exist, comes out
lower than the live tally; documented where someone would otherwise
"repair" it.

Deadlines move, so the on-time verdict is now stored on the submission
beside the count it fed. Judging it again at withdrawal read whatever the
deadline had become since, which drifted the tally in both directions β€”
far enough that on-time could exceed submitted.

Attendance counters were dropped: those tables already carry per-user
indexes, so there is no scan to fix, the status list is school-editable,
and roll-call corrections would need a decrement that fights permanence.

18 changed files +2441 -107

README.mdmodified+94 -14
@@ -116,8 +116,11 @@ anyone, `null` until chosen so the client can fall back to the device
116 preference (or, for the accent, its own default).116 preference (or, for the accent, its own default).
117 Every account also has a **public profile** (`/users/{id}/profile`): a117 Every account also has a **public profile** (`/users/{id}/profile`): a
118 self-chosen `display_name` and `bio`, one **avatar**, the classes and courses118 self-chosen `display_name` and `bio`, one **avatar**, the classes and courses
119-it belongs to, and counters computed at read (finished pomodoro stints, course119+it belongs to, counters computed at read (finished pomodoro stints, course and
120-and class totals). Contact details are deliberately not part of it β€” email,120+class totals) beside stored lifetime tallies of homework handed in, exams sat
121+and focus time, and the **badges** those tallies have earned β€” auto-earned
122+only, no route awards or revokes one, and permanent once earned even if the
123+counter later falls. Contact details are deliberately not part of it β€” email,
121 phone and birth date keep the gate they already have β€” and any authenticated124 phone and birth date keep the gate they already have β€” and any authenticated
122 account reads any profile, except a `parent`, who reads their own and their125 account reads any profile, except a `parent`, who reads their own and their
123 linked students' only (see "User profiles & avatars").126 linked students' only (see "User profiles & avatars").
@@ -334,6 +337,9 @@ response in the same commit.
334 "themes": ["light", "dark"], "languages": ["tr", "en"],337 "themes": ["light", "dark"], "languages": ["tr", "en"],
335 "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7,338 "palette_color_pattern": "^#[0-9a-fA-F]{6}$", "palette_color_len": 7,
336 "session_duration_days": 7 },339 "session_duration_days": 7 },
340+ "badges": { "catalog": [ { "id": "homework_submitted_10",
341+ "stat": "homework_submitted", "threshold": 10 },
342+ { "…": 0 } ] },
337 "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 },343 "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 },
338 "file": { "max_name_len": 255, "max_content_type_len": 100,344 "file": { "max_name_len": 255, "max_content_type_len": 100,
339 "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400,345 "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400,
@@ -393,7 +399,7 @@ drift from it**, which is enforced rather than asked for:
393 and fails unless each one is either referenced by `src/web/limits.rs` or399 and fails unless each one is either referenced by `src/web/limits.rs` or
394 listed as a deliberate exclusion *with a reason*. A new constant breaks the400 listed as a deliberate exclusion *with a reason*. A new constant breaks the
395 suite until someone decides, consciously, whether clients need it.401 suite until someone decides, consciously, whether clients need it.
396-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 161 published402+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 168 published
397 bounds back out of the emitted JSON, and asserts each equals its constant.403 bounds back out of the emitted JSON, and asserts each equals its constant.
398 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal404 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
399 only** β€” a `const` there does not compile β€” so the annotations are405 only** β€” a `const` there does not compile β€” so the annotations are
@@ -435,6 +441,19 @@ Notes:
435 `stroke_kinds`, and the441 `stroke_kinds`, and the
436 uploadable `image_content_types` are the exact accepted spellings β€” build442 uploadable `image_content_types` are the exact accepted spellings β€” build
437 pickers from these rather than from a literal list.443 pickers from these rather than from a literal list.
444+- **The badge catalog rides here too.** `badges.catalog[]` is every badge the
445+ system can auto-award β€” `{id, stat, threshold}`, 13 of them, in catalog
446+ order. It is a group (an object with one `catalog` key) rather than a bare
447+ array because every key of this document is a group, and that uniformity is
448+ what lets a client walk the response generically. `stat` is the API's name
449+ for the lifetime counter behind the badge (`homework_submitted`,
450+ `homework_on_time`, `exam_sat`, `pomodoro_finished`, `pomodoro_focus_ms`),
451+ deliberately not the database column it is stored in, so storage can be
452+ renamed without moving a published contract; badges sharing a `stat` form a
453+ ladder. The catalog is compiled in, so a threshold moves only with a deploy β€”
454+ the rules stay reviewable in a diff instead of editable in a settings row.
455+ Labels and icons are **not** here: like `roles` and course `kinds`, the id is
456+ the whole contract and the client owns what it looks like.
438 457
439 **`422` versus `400`.** The two refusals mean different things and a client458 **`422` versus `400`.** The two refusals mean different things and a client
440 must not treat them alike. Every JSON-bodied route can answer **`422`**: the459 must not treat them alike. Every JSON-bodied route can answer **`422`**: the
@@ -1116,8 +1135,12 @@ the school. `GET /users/me/profile` is the caller's own copy of it,
1116 "avatar": { "content_type": "image/png", "size": 20480 },1135 "avatar": { "content_type": "image/png", "size": 20480 },
1117 "classes": [ { "id": "01J8…", "name": "9-A", "grade": "9" } ],1136 "classes": [ { "id": "01J8…", "name": "9-A", "grade": "9" } ],
1118 "courses": [ { "id": "01J8…", "title": "Matematik", "kind": "course" } ],1137 "courses": [ { "id": "01J8…", "title": "Matematik", "kind": "course" } ],
1138+ "badges": [ { "id": "homework_submitted_10", "earned_at": 1754300000000 } ],
1119 "stats": { "pomodoro_sessions": 42, "pomodoro_focus_ms": 63000000,1139 "stats": { "pomodoro_sessions": 42, "pomodoro_focus_ms": 63000000,
1120- "courses": 7, "classes": 1 }1140+ "courses": 7, "classes": 1,
1141+ "homework_submitted_total": 12, "homework_on_time_total": 11,
1142+ "exam_sat_total": 5, "pomodoro_finished_total": 44,
1143+ "pomodoro_focus_ms_total": 65400000 }
1121 }1144 }
1122 ```1145 ```
1123 1146
@@ -1169,13 +1192,20 @@ owner's true total on purpose β€” it is the motivational counter, a per-reader
1169 number would be meaningless, and a magnitude names no course. One consequence,1192 number would be meaningless, and a magnitude names no course. One consequence,
1170 by design: a teacher you share nothing with has an empty `courses` block.1193 by design: a teacher you share nothing with has an empty `courses` block.
1171 1194
1172-**Stats are computed at read, never stored.** No counter column can drift out1195+**`stats` holds nine numbers of two different kinds, and the difference is
1173-of sync with the rows behind it, and an account with no data reads a true `0`1196+worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and
1174-rather than `null`. Only *finished* pomodoro stints count β€” a timer left1197+`classes` are **computed at read**: they are recounted from the live rows on
1175-running is not study time. Exam averages, homework-done rates and attendance1198+every call, so no column can drift out of sync with what is behind it. The five
1176-rates are deliberately absent: those tables are indexed for their own reads, so1199+`*_total` keys are **stored lifetime tallies**, maintained at write time (see
1177-a per-user aggregate over them is a full table scan, and a profile is far too1200+below), so a tally can outlive the rows behind it β€” a student's
1178-cheap a page to pay for one.1201+`exam_sat_total` still counts an exam a teacher has since deleted, which is the
1202+point of a lifetime counter. Either kind reads a true `0` on a fresh account,
1203+never `null`. Only *finished* pomodoro stints count on either side β€” a timer
1204+left running is not study time. Exam averages, homework-done rates and
1205+attendance rates are deliberately absent: those tables are indexed for their
1206+own reads, so a per-user aggregate over them is a full table scan, and a
1207+profile is far too cheap a page to pay for one β€” which is also why the five
1208+lifetime counters are tallied at write rather than recounted here.
1179 1209
1180 **The avatar** is one picture per account, uploaded as `multipart/form-data`1210 **The avatar** is one picture per account, uploaded as `multipart/form-data`
1181 with the image under a `file` field. Raster types only (`image/png`,1211 with the image under a `file` field. Raster types only (`image/png`,
@@ -1191,9 +1221,57 @@ offensive picture is a school problem. The bytes come back from
1191 `GET /users/me/avatar` is the same read for the caller's own picture, so a1221 `GET /users/me/avatar` is the same read for the caller's own picture, so a
1192 client that never learned its own id still has a route.1222 client that never learned its own id still has a route.
1193 1223
1194-There is no `badges` key yet. Auto-earned badges are a planned second pass and1224+### Badges
1195-will be added to `stats`' neighborhood additively, so a client written against1225+
1196-today's document keeps working.1226+**`badges` is auto-earned and nothing else.** There is no route that awards one
1227+and none that revokes one β€” a badge appears when a stored counter crosses a
1228+hardcoded threshold, normally on the same write that moved the counter (and, as
1229+a backstop, on a profile read that finds an earned badge missing β€” the sync
1230+after a write is best-effort, so a failed one heals rather than being lost).
1231+The rule is the only author. Handing a teacher an award button would make
1232+the counters decorative, and a badge that can be given can be argued about.
1233+
1234+**A badge is permanent.** Once earned it stays, whatever the counter does
1235+afterwards: withdraw a submission and `homework_submitted_total` falls, but the
1236+badge it earned does not come off. The award records that the student *did* the
1237+thing, not that they still have it. `earned_at` is pinned at the first crossing
1238+and never moved, so the list is a history and stays in order β€” it comes back
1239+oldest first.
1240+
1241+**Ids only.** Each entry is `{id, earned_at}`. The label, the icon and the
1242+description are the frontend's, keyed by the id β€” the same deal `roles` and
1243+course `kinds` already have. The catalog behind the ids is at `GET /limits` as
1244+`badges.catalog[]` (`{id, stat, threshold}`, 13 badges); it is compiled into
1245+the binary, so changing a threshold is a deploy, not a settings edit. An id is
1246+never reused for another meaning, and retiring a badge just drops it from the
1247+catalog β€” awards carrying it stop being served, no migration.
1248+
1249+**How the counters move**, since a badge is exactly a threshold on one of them:
1250+
1251+- **Homework.** A genuine first hand-in is `+1 homework_submitted_total`, and
1252+ `+1 homework_on_time_total` if that hand-in beat `due_at`. **Withdrawing your
1253+ own submission decrements both** β€” the one place a counter comes down, and it
1254+ exists because withdrawal is student-callable: without it, submit/delete/
1255+ submit farms one homework into fifty. Editing an existing submission moves
1256+ nothing, so the on-time verdict is fixed at the first hand-in and attaching a
1257+ file after the deadline cannot turn an on-time submission late.
1258+- **Exams.** `+1 exam_sat_total` per attempt created, retakes included β€”
1259+ sitting an exam twice is two sittings. Resuming an attempt already running is
1260+ not a new one. Deleting an exam removes the attempt rows but does **not**
1261+ decrement anyone: a teacher tidying up does not un-sit the exam.
1262+- **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its
1263+ duration into `pomodoro_focus_ms_total`. An open stint counts for neither β€”
1264+ unfinished focus has no honest duration to add.
1265+
1266+**Existing accounts are seeded once.** The first boot of this version tallies
1267+every account from its real history, so nobody starts at zero for work they
1268+already did; the pass is marked done and skipped on every boot after. One
1269+consequence is not fixable and is not an oversight: the seed can only count
1270+rows that still exist, so a student whose exam was deleted before the upgrade
1271+is seeded short on `exam_sat_total`. The live rule (never decrement) and the
1272+seed (count what is there) simply cannot agree about history that is gone β€”
1273+and the fix is not to make deletion decrement, which would break the tally for
1274+everyone in order to patch it for a few.
1197 1275
1198 ## Appointments1276 ## Appointments
1199 1277
@@ -3516,6 +3594,8 @@ src/
3516 bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank3594 bank_question_image.rs BankQuestionImageId Β· BankQuestionImage (bank
3517 question/choice picture metadata; bytes on disk under FILES_PATH)3595 question/choice picture metadata; bytes on disk under FILES_PATH)
3518 profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)3596 profile.rs PersonName Β· Email Β· Phone Β· BirthDate (personal-info newtypes)
3597+ badge.rs BadgeStat Β· BadgeStats Β· earned Β· BadgeAward (auto-earned,
3598+ permanent badges off the lifetime counters on the user row)
3519 preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)3599 preferences.rs Theme Β· Language Β· PaletteColor (own UI preferences)
3520 message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·3600 message.rs MessageId Β· MessageSubject Β· MessageBody Β· MessageLabel Β·
3521 Message (per-copy folders: inbox/sent/archive/trash)3601 Message (per-copy folders: inbox/sent/archive/trash)
src/constant.rsmodified+62 -0
@@ -1,5 +1,6 @@
1 //! Validation limits, in one place.1 //! Validation limits, in one place.
2 2
3+use crate::domain::badge::BadgeStat;
3 use crate::domain::message::Folder;4 use crate::domain::message::Folder;
4 use crate::domain::preferences::{Language, Theme};5 use crate::domain::preferences::{Language, Theme};
5 use crate::domain::role::Role;6 use crate::domain::role::Role;
@@ -798,6 +799,11 @@ pub const FEE_PLAN_ASSIGNMENT_TABLE: &str = "fee_plan_assignment";
798 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";799 pub const PAYMENT_LEDGER_TABLE: &str = "payment_ledger";
799 pub const BOARD_TABLE: &str = "board";800 pub const BOARD_TABLE: &str = "board";
800 pub const BOARD_STROKE_TABLE: &str = "board_stroke";801 pub const BOARD_STROKE_TABLE: &str = "board_stroke";
802+/// One row per badge a user has earned, keyed by the pair. A table of its own
803+/// rather than an array column on the user row: an `array<…>` there breaks
804+/// every `PATCH` of that row, and awards are append-only facts with their own
805+/// timestamp (see [`crate::domain::badge`]).
806+pub const BADGE_AWARD_TABLE: &str = "badge_award";
801 /// One row per *name* the school's settings offer, keyed by the name itself:807 /// One row per *name* the school's settings offer, keyed by the name itself:
802 /// how many rows still reference it, and whether it has been retired out of the808 /// how many rows still reference it, and whether it has been retired out of the
803 /// list (see the reference counters in [`crate::domain::cap`]).809 /// list (see the reference counters in [`crate::domain::cap`]).
@@ -850,6 +856,62 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
850 /// what closes the "open another board" way around the two board counters856 /// what closes the "open another board" way around the two board counters
851 /// below; released when a board is deleted.857 /// below; released when a board is deleted.
852 pub const USER_BOARD_COUNT_FIELD: &str = "board_count";858 pub const USER_BOARD_COUNT_FIELD: &str = "board_count";
859+/// The lifetime totals behind the badges, all on the user row. Not caps: each
860+/// one counts something the student *did*. Only the two homework counters ever
861+/// come down, and in exactly one case β€” a student withdrawing their own
862+/// submission β€” because that route is self-service and a strictly monotonic
863+/// counter would let one homework be farmed into fifty by submit/delete/submit.
864+/// The exam and pomodoro totals never decrease at all: there is no student-facing
865+/// delete behind them, so sitting an exam or finishing a stint is a lifetime
866+/// fact. Nothing else decrements: a teacher's delete and the course cascade
867+/// (which do take the attempt rows with them) leave them alone,
868+/// since history a teacher erased is still history the student lived. A badge
869+/// already earned is never taken back either, whatever a counter does
870+/// afterwards β€” [`crate::domain::badge`] only ever adds award rows. Floored at
871+/// zero, and absent means zero: an account older than the columns reads exactly
872+/// like a fresh one.
873+pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";
874+pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
875+pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
876+pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total";
877+pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
878+
879+/// The badge catalog: every badge the system can award, as
880+/// `(id, the counter it reads, the value that earns it)`. Hardcoded on
881+/// purpose β€” moving a threshold is a deploy, which is what keeps
882+/// [`crate::domain::badge::earned`] a pure function of the stats and makes the
883+/// rules reviewable in a diff instead of editable in a settings row.
884+///
885+/// The ids are the API: the frontend maps them to a label and an icon, and an
886+/// award row stores one forever. So an id is never reused for a different
887+/// meaning; retiring one is done by deleting the line, and the awards that
888+/// carry it simply stop being served (no data migration β€”
889+/// [`crate::domain::badge::BadgeAward::list_for`] filters to the live
890+/// catalog).
891+pub const BADGES: [(&str, BadgeStat, i64); 13] = [
892+ ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
893+ ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
894+ ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
895+ ("homework_on_time_10", BadgeStat::HomeworkOnTime, 10),
896+ ("homework_on_time_25", BadgeStat::HomeworkOnTime, 25),
897+ ("exam_sat_1", BadgeStat::ExamSat, 1),
898+ ("exam_sat_10", BadgeStat::ExamSat, 10),
899+ ("exam_sat_25", BadgeStat::ExamSat, 25),
900+ ("pomodoro_finished_10", BadgeStat::PomodoroFinished, 10),
901+ ("pomodoro_finished_50", BadgeStat::PomodoroFinished, 50),
902+ ("pomodoro_finished_200", BadgeStat::PomodoroFinished, 200),
903+ // Ten and fifty hours of focus, in the milliseconds the counter stores.
904+ (
905+ "pomodoro_focus_ms_36000000",
906+ BadgeStat::PomodoroFocusMs,
907+ 36_000_000,
908+ ),
909+ (
910+ "pomodoro_focus_ms_180000000",
911+ BadgeStat::PomodoroFocusMs,
912+ 180_000_000,
913+ ),
914+];
853 /// The two stroke counters on a board row. `epoch_stroke_count` is reset to915 /// The two stroke counters on a board row. `epoch_stroke_count` is reset to
854 /// zero by a clear and capped at `MAX_EPOCH_STROKES` β€” a full epoch is916 /// zero by a clear and capped at `MAX_EPOCH_STROKES` β€” a full epoch is
855 /// recoverable. `total_stroke_count` is never reset and capped at917 /// recoverable. `total_stroke_count` is never reset and capped at
src/database.rsmodified+177 -0
@@ -581,6 +581,183 @@ mod tests {
581 assert_eq!(writes(&db).await, vec![2]);581 assert_eq!(writes(&db).await, vec![2]);
582 }582 }
583 583
584+ /// Stale-data path for the 2026-08-04 badge counters. Every account on an
585+ /// existing volume predates the columns, and a badge is decided off the
586+ /// stored total β€” so a zero start would not lose a number, it would
587+ /// permanently mis-award the student who really did the work. Boot seeds the
588+ /// counters from the rows that exist, exactly once.
589+ #[tokio::test]
590+ async fn the_badge_counters_are_seeded_from_history_exactly_once() {
591+ let db = super::init_mem().await.unwrap();
592+ db.query(
593+ "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student';
594+ CREATE user:b SET username = 'b', password_hash = 'x', role = 'student';
595+ CREATE user:c SET username = 'c', password_hash = 'x', role = 'student';
596+ CREATE homework:h SET course = course:c, subject = subject:s, title = 'H',
597+ due_at = 100, created_by = user:a, created_at = 1;
598+ -- Three on time (the equal case counts as on time) and one whose
599+ -- homework was deleted out from under it: that last one is
600+ -- submitted but not on time, because the traversal yields nothing.
601+ CREATE homework_submission:s1 SET homework = homework:h, user = user:a,
602+ submitted_at = 50, updated_at = 50;
603+ CREATE homework_submission:s2 SET homework = homework:h, user = user:a,
604+ submitted_at = 60, updated_at = 100;
605+ -- Handed in before the deadline, then edited well after it β€” a
606+ -- `touch()` from a single file add does this. On time, because the
607+ -- live path credits the hand-in and debits by `submitted_at`; if
608+ -- the seed judged this one by `updated_at` a later withdrawal
609+ -- would decrement a credit that was never given.
610+ CREATE homework_submission:s3 SET homework = homework:h, user = user:a,
611+ submitted_at = 70, updated_at = 200;
612+ CREATE homework_submission:s4 SET homework = homework:gone, user = user:a,
613+ submitted_at = 80, updated_at = 1;
614+ CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1;
615+ CREATE exam_attempt:e2 SET exam = exam:y, user = user:a, seq = 1, started_at = 2;
616+ -- Two finished stints and one still open, which counts for neither.
617+ CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;
618+ CREATE pomodoro_session:p2 SET user = user:a, started_at = 5000, finished_at = 7500;
619+ CREATE pomodoro_session:p3 SET user = user:a, started_at = 9000;
620+ -- One real stint beside one written with a backwards clock. The
621+ -- floor is per row, like the live close, so the negative one
622+ -- contributes zero and the real 1000ms survives; flooring the
623+ -- per-user sum instead would seed 0 and lose the real stint.
624+ CREATE pomodoro_session:p4 SET user = user:c, started_at = 0, finished_at = 1000;
625+ CREATE pomodoro_session:p5 SET user = user:c, started_at = 9000, finished_at = 3000;
626+ DELETE migration_mark:profile_counters;",
627+ )
628+ .await
629+ .unwrap()
630+ .check()
631+ .unwrap();
632+ // `init_mem` boots a *migrated* database, so the seed is already marked
633+ // done on an empty store β€” which is right, and is exactly why the mark is
634+ // dropped here: a volume written before the columns existed carries
635+ // history and no mark at all, and that is the state under test.
636+ // A write probe on the table being seeded: the event fires *inside* the
637+ // UPDATE, so it counts real writes rather than trusting a re-read.
638+ db.query(
639+ "DEFINE TABLE user_write_probe SCHEMALESS;
640+ DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN {
641+ UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1;
642+ };",
643+ )
644+ .await
645+ .unwrap()
646+ .check()
647+ .unwrap();
648+
649+ super::migrate(&db).await.unwrap();
650+
651+ async fn counters(db: &super::Database) -> Vec<(i64, i64, i64, i64, i64)> {
652+ let mut rows = db
653+ .query(
654+ "SELECT VALUE [homework_submitted_total, homework_on_time_total,
655+ exam_sat_total, pomodoro_finished_total,
656+ pomodoro_focus_ms_total]
657+ FROM user ORDER BY id",
658+ )
659+ .await
660+ .unwrap();
661+ rows.take::<Vec<Vec<i64>>>(0)
662+ .unwrap()
663+ .into_iter()
664+ .map(|row| (row[0], row[1], row[2], row[3], row[4]))
665+ .collect()
666+ }
667+ let after_first = counters(&db).await;
668+ // `a`, `b`, `c` by id. `b` has no history at all and reads as a fresh
669+ // account; `c` keeps the 1000ms real stint the -6000ms one sits beside.
670+ assert_eq!(
671+ after_first,
672+ vec![(4, 3, 2, 2, 3500), (0, 0, 0, 0, 0), (0, 0, 0, 2, 1000)],
673+ "{after_first:?}"
674+ );
675+
676+ // The seed also stamps each submission with the verdict it was counted
677+ // under, because `due_at` is mutable: a withdrawal after the teacher
678+ // moves the deadline must debit what was credited, not what the
679+ // deadline says by then. Asserted through `WHERE` rather than read back
680+ // as a column, so an unstamped row would show up as belonging to
681+ // neither set instead of deserializing as some default.
682+ async fn stamped(db: &super::Database, cond: &str) -> Vec<String> {
683+ let mut rows = db
684+ .query(format!(
685+ "SELECT VALUE record::id(id) FROM homework_submission
686+ WHERE {cond} ORDER BY id"
687+ ))
688+ .await
689+ .unwrap();
690+ rows.take(0).unwrap()
691+ }
692+ // s1/s2/s3 beat the deadline (50, 60, 70 vs 100). s4 hangs off a
693+ // deleted homework, so `submitted_at <= homework.due_at` compares
694+ // against NONE and lands on `false` β€” which is exactly what the count
695+ // above credited it as, so the stamp agrees with the counter rather
696+ // than leaving the row to a fallback that could later disagree.
697+ assert_eq!(
698+ stamped(&db, "counted_on_time = true").await,
699+ ["s1", "s2", "s3"]
700+ );
701+ assert_eq!(stamped(&db, "counted_on_time = false").await, ["s4"]);
702+
703+ async fn writes(db: &super::Database) -> Vec<i64> {
704+ let mut rows = db
705+ .query("SELECT VALUE n FROM user_write_probe:n")
706+ .await
707+ .unwrap();
708+ rows.take(0).unwrap()
709+ }
710+ let first_writes = writes(&db).await;
711+ // Pinned non-zero, not just compared: "the second pass wrote nothing"
712+ // would hold vacuously if the probe itself stopped firing, and then the
713+ // test would pass on a seed that never ran.
714+ assert!(
715+ matches!(first_writes.as_slice(), [n] if *n > 0),
716+ "{first_writes:?}"
717+ );
718+
719+ // The second boot: every boot runs the backfill, and a recount here
720+ // would not converge the way the counters above it do β€” these columns
721+ // are maintained by the request path from now on, so a second pass would
722+ // overwrite everything earned since. It must not write at all…
723+ super::migrate(&db).await.unwrap();
724+ assert_eq!(counters(&db).await, after_first);
725+ assert_eq!(
726+ writes(&db).await,
727+ first_writes,
728+ "the second pass wrote nothing"
729+ );
730+
731+ // …and it must not *look*, either, which is the whole point of the mark:
732+ // writing nothing is not the same as scanning nothing. A submission that
733+ // lands after the mark is the probe β€” its counter stays where the request
734+ // path left it, which no recomputing backfill could produce.
735+ let mut mark = db
736+ .query("SELECT VALUE done_at FROM migration_mark:profile_counters")
737+ .await
738+ .unwrap();
739+ assert_eq!(
740+ mark.take::<Vec<i64>>(0).unwrap().len(),
741+ 1,
742+ "the seed marks itself finished"
743+ );
744+ db.query(
745+ "CREATE homework_submission:late SET homework = homework:h, user = user:b,
746+ submitted_at = 90, updated_at = 90;",
747+ )
748+ .await
749+ .unwrap()
750+ .check()
751+ .unwrap();
752+ super::migrate(&db).await.unwrap();
753+ assert_eq!(
754+ counters(&db).await,
755+ after_first,
756+ "a marked database skips the seed entirely"
757+ );
758+ assert_eq!(writes(&db).await, first_writes);
759+ }
760+
584 #[tokio::test]761 #[tokio::test]
585 async fn the_retired_claim_columns_are_dropped_off_a_live_row() {762 async fn the_retired_claim_columns_are_dropped_off_a_live_row() {
586 // Stale-data path for the 2026-07-30 removal of the chat claim queue.763 // Stale-data path for the 2026-07-30 removal of the chat claim queue.
src/domain/badge.rsadded+498 -0
@@ -0,0 +1,498 @@
1+//! Auto-earned badges: the lifetime counters a badge is decided from, the
2+//! catalog rule that decides it, and the award rows it writes.
3+//!
4+//! Three properties hold here and nowhere else:
5+//!
6+//! - **Auto-earned only.** No route awards a badge; [`sync`] is called after
7+//! the writes that move a counter, and that is the only way a row appears.
8+//! - **Permanent.** Nothing in this file deletes or revokes an award. A
9+//! counter that later drops below the threshold β€” a submission withdrawn,
10+//! say β€” leaves the badge standing, because it records that the student did
11+//! the thing, not that they still have it.
12+//! - **Pure rules.** The catalog is [`crate::constant::BADGES`], a hardcoded
13+//! table, so [`earned`] is a total function of [`BadgeStats`] with no I/O
14+//! and no configuration behind it.
15+
16+use surrealdb::types::SurrealValue;
17+
18+use crate::constant::{
19+ BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD,
20+ HOMEWORK_SUBMITTED_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD,
21+};
22+use crate::database::Database;
23+use crate::domain::timestamp::Timestamp;
24+use crate::domain::user::UserId;
25+use crate::error::AppError;
26+
27+/// The counter a badge family reads. One variant per column, and the enum is
28+/// what ties a catalog line to a real number: a family added here cannot be
29+/// referenced from `BADGES` until [`BadgeStats`] carries its counter, because
30+/// both matches below are exhaustive.
31+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32+pub enum BadgeStat {
33+ HomeworkSubmitted,
34+ HomeworkOnTime,
35+ ExamSat,
36+ PomodoroFinished,
37+ PomodoroFocusMs,
38+}
39+
40+impl BadgeStat {
41+ /// Where it is *stored*: the column on the user row this counter lives in.
42+ /// Internal β€” every caller is a query in this crate, and renaming a column
43+ /// means changing this and the migration together.
44+ pub fn field(&self) -> &'static str {
45+ match self {
46+ BadgeStat::HomeworkSubmitted => HOMEWORK_SUBMITTED_TOTAL_FIELD,
47+ BadgeStat::HomeworkOnTime => HOMEWORK_ON_TIME_TOTAL_FIELD,
48+ BadgeStat::ExamSat => EXAM_SAT_TOTAL_FIELD,
49+ BadgeStat::PomodoroFinished => POMODORO_FINISHED_TOTAL_FIELD,
50+ BadgeStat::PomodoroFocusMs => POMODORO_FOCUS_MS_TOTAL_FIELD,
51+ }
52+ }
53+
54+ /// What the *API* calls it: the name `GET /limits` publishes, the same
55+ /// spelling the badge ids are built from. Deliberately not [`field`] β€”
56+ /// these are two names for two audiences, and keeping them apart is what
57+ /// lets a column be renamed without breaking a published contract. Do not
58+ /// collapse them.
59+ ///
60+ /// [`field`]: BadgeStat::field
61+ pub fn as_str(&self) -> &'static str {
62+ match self {
63+ BadgeStat::HomeworkSubmitted => "homework_submitted",
64+ BadgeStat::HomeworkOnTime => "homework_on_time",
65+ BadgeStat::ExamSat => "exam_sat",
66+ BadgeStat::PomodoroFinished => "pomodoro_finished",
67+ BadgeStat::PomodoroFocusMs => "pomodoro_focus_ms",
68+ }
69+ }
70+}
71+
72+/// The lifetime counters one user has accumulated, as the badge rules see
73+/// them. Every field is a count and never an `Option`: no rows is a true zero,
74+/// and an account that predates the columns reads like a fresh one.
75+#[derive(Debug, Clone, Default, SurrealValue)]
76+pub struct BadgeStats {
77+ homework_submitted: i64,
78+ homework_on_time: i64,
79+ exam_sat: i64,
80+ pomodoro_finished: i64,
81+ pomodoro_focus_ms: i64,
82+}
83+
84+impl BadgeStats {
85+ pub fn get_homework_submitted(&self) -> i64 {
86+ self.homework_submitted
87+ }
88+
89+ pub fn get_homework_on_time(&self) -> i64 {
90+ self.homework_on_time
91+ }
92+
93+ pub fn get_exam_sat(&self) -> i64 {
94+ self.exam_sat
95+ }
96+
97+ pub fn get_pomodoro_finished(&self) -> i64 {
98+ self.pomodoro_finished
99+ }
100+
101+ pub fn get_pomodoro_focus_ms(&self) -> i64 {
102+ self.pomodoro_focus_ms
103+ }
104+
105+ /// All five counters off the user row, in one statement β€” a record lookup,
106+ /// not a scan.
107+ ///
108+ /// Each projection is `(column ?? 0)`, parenthesized because `??` binds
109+ /// loosely, and it is the whole stale-data story: the columns are
110+ /// `option<int>`, a row written before they existed carries none of them,
111+ /// and absent must read as zero rather than as a null or an error. A user
112+ /// row that is gone entirely reads as five zeros too β€” a badge sync is not
113+ /// the place to discover a deleted account.
114+ pub async fn load(user: &UserId, db: &Database) -> Result<BadgeStats, AppError> {
115+ let mut result = db
116+ .query(format!(
117+ "SELECT ({homework_submitted} ?? 0) AS homework_submitted,
118+ ({homework_on_time} ?? 0) AS homework_on_time,
119+ ({exam_sat} ?? 0) AS exam_sat,
120+ ({pomodoro_finished} ?? 0) AS pomodoro_finished,
121+ ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms
122+ FROM $usr",
123+ homework_submitted = BadgeStat::HomeworkSubmitted.field(),
124+ homework_on_time = BadgeStat::HomeworkOnTime.field(),
125+ exam_sat = BadgeStat::ExamSat.field(),
126+ pomodoro_finished = BadgeStat::PomodoroFinished.field(),
127+ pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(),
128+ ))
129+ .bind(("usr", user.record()))
130+ .await?
131+ .check()?;
132+ Ok(result
133+ .take::<Vec<BadgeStats>>(0)?
134+ .into_iter()
135+ .next()
136+ .unwrap_or_default())
137+ }
138+}
139+
140+/// The ids of every badge `stats` has earned β€” the whole rule, and pure: no
141+/// database, no clock, no configuration. A badge is earned at `>=` its
142+/// threshold and stays earned, so this is only ever asked "what should be
143+/// held", never "what should be taken away".
144+pub fn earned(stats: &BadgeStats) -> Vec<&'static str> {
145+ BADGES
146+ .iter()
147+ .filter(|(_, stat, threshold)| {
148+ // Exhaustive on purpose: a new `BadgeStat` variant fails to compile
149+ // here until the counter behind it exists on `BadgeStats`.
150+ let value = match stat {
151+ BadgeStat::HomeworkSubmitted => stats.homework_submitted,
152+ BadgeStat::HomeworkOnTime => stats.homework_on_time,
153+ BadgeStat::ExamSat => stats.exam_sat,
154+ BadgeStat::PomodoroFinished => stats.pomodoro_finished,
155+ BadgeStat::PomodoroFocusMs => stats.pomodoro_focus_ms,
156+ };
157+ value >= *threshold
158+ })
159+ .map(|(id, ..)| *id)
160+ .collect()
161+}
162+
163+/// The record one (user, badge) pair always maps to, so a second [`sync`]
164+/// resolves onto the row the first one wrote instead of minting a duplicate.
165+/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide.
166+fn award_key(user: &UserId, badge: &str) -> String {
167+ format!("{}_{badge}", user.key())
168+}
169+
170+/// One badge one user has earned, and when.
171+#[derive(Debug, Clone, SurrealValue)]
172+pub struct BadgeAward {
173+ badge: String,
174+ earned_at: Timestamp,
175+}
176+
177+impl BadgeAward {
178+ pub fn get_badge(&self) -> &str {
179+ &self.badge
180+ }
181+
182+ pub fn get_earned_at(&self) -> Timestamp {
183+ self.earned_at
184+ }
185+
186+ /// Everything `user` has earned, oldest first.
187+ ///
188+ /// Filtered to the ids the catalog still holds: a badge retired from
189+ /// `BADGES` stops being served without a data migration, and its rows stay
190+ /// where they are in case the line comes back.
191+ ///
192+ /// The badge id breaks the tie, because one sync stamps every badge it
193+ /// awards with the same millisecond and an arbitrary order there would
194+ /// shuffle a student's shelf between reads. It is the record id's order
195+ /// too β€” the key is `{user}_{badge}` and this reads one user β€” but spelled
196+ /// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by
197+ /// an idiom the selection does not carry ("Missing order idiom `id` in
198+ /// statement selection"), and `id` is not a field of an award.
199+ pub async fn list_for(user: &UserId, db: &Database) -> Result<Vec<BadgeAward>, AppError> {
200+ let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect();
201+ let mut result = db
202+ .query(format!(
203+ "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE}
204+ WHERE user = $usr AND badge IN $ids
205+ ORDER BY earned_at ASC, badge ASC LIMIT {}",
206+ BADGES.len()
207+ ))
208+ .bind(("usr", user.record()))
209+ .bind(("ids", ids))
210+ .await?
211+ .check()?;
212+ Ok(result.take::<Vec<BadgeAward>>(0)?)
213+ }
214+}
215+
216+/// Write an award row for every badge `user` has now earned and does not
217+/// already hold.
218+///
219+/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the
220+/// whole of the idempotency: the first call creates the row, and every later
221+/// call β€” with a later `$now` β€” matches a row that already has a stamp and
222+/// writes nothing at all. So the earned-at a student sees is when they first
223+/// crossed the line, not when the counter last moved.
224+///
225+/// **Callers must log and ignore the error.** A badge is a decoration on top
226+/// of somebody's homework submission, exam sitting or pomodoro stint, and none
227+/// of those may fail because the decoration could not be written. The `Result`
228+/// is returned rather than swallowed here so the caller's log line names the
229+/// real cause; the next counter bump re-runs this and heals whatever was
230+/// missed, which is also why a lost write race needs no retry loop.
231+pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> {
232+ let stats = BadgeStats::load(user, db).await?;
233+ let earned = earned(&stats);
234+ if earned.is_empty() {
235+ return Ok(());
236+ }
237+ let mut sql = String::new();
238+ for index in 0..earned.len() {
239+ sql.push_str(&format!(
240+ "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index},
241+ earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n"
242+ ));
243+ }
244+ let mut query = db
245+ .query(sql)
246+ .bind(("table", BADGE_AWARD_TABLE))
247+ .bind(("usr", user.record()))
248+ .bind(("now", Timestamp::now()));
249+ for (index, badge) in earned.iter().enumerate() {
250+ query = query
251+ .bind((format!("key{index}"), award_key(user, badge)))
252+ .bind((format!("badge{index}"), badge.to_string()));
253+ }
254+ query.await?.check()?;
255+ Ok(())
256+}
257+
258+#[cfg(test)]
259+mod tests {
260+ use super::*;
261+
262+ /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled
263+ /// with the same `IF NOT EXISTS` guards the migration uses, so it is a
264+ /// no-op once the real definitions land next to it.
265+ async fn schema(db: &Database) {
266+ db.query(format!(
267+ "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option<int>;
268+ DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option<int>;
269+ DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option<int>;
270+ DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option<int>;
271+ DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option<int>;
272+ DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL;
273+ DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record<user>;
274+ DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string;
275+ DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option<int>;
276+ DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;"
277+ ))
278+ .await
279+ .unwrap()
280+ .check()
281+ .unwrap();
282+ }
283+
284+ /// A user row carrying `counters`, by column name.
285+ async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId {
286+ let user = UserId::from_key(&ulid::Ulid::new().to_string());
287+ let sets: Vec<String> = counters
288+ .iter()
289+ .map(|(field, value)| format!("{field} = {value}"))
290+ .collect();
291+ let extra = if sets.is_empty() {
292+ String::new()
293+ } else {
294+ format!(", {}", sets.join(", "))
295+ };
296+ db.query(format!(
297+ "CREATE $usr SET username = $name, password_hash = 'x'{extra}"
298+ ))
299+ .bind(("usr", user.record()))
300+ .bind(("name", user.key().to_string()))
301+ .await
302+ .unwrap()
303+ .check()
304+ .unwrap();
305+ user
306+ }
307+
308+ /// The stamps on the stored rows, oldest first.
309+ async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> {
310+ BadgeAward::list_for(user, db)
311+ .await
312+ .unwrap()
313+ .into_iter()
314+ .map(|award| (award.badge, award.earned_at.as_millis()))
315+ .collect()
316+ }
317+
318+ /// The wire name and the column name are two names, not one. If a later
319+ /// edit points `as_str` back at `field`, this fails β€” which is the point:
320+ /// the split is what lets a column be renamed without breaking `/limits`.
321+ #[test]
322+ fn the_wire_name_is_never_the_column_name() {
323+ for (stat, wire) in [
324+ (BadgeStat::HomeworkSubmitted, "homework_submitted"),
325+ (BadgeStat::HomeworkOnTime, "homework_on_time"),
326+ (BadgeStat::ExamSat, "exam_sat"),
327+ (BadgeStat::PomodoroFinished, "pomodoro_finished"),
328+ (BadgeStat::PomodoroFocusMs, "pomodoro_focus_ms"),
329+ ] {
330+ assert_eq!(stat.as_str(), wire, "the published name is frozen");
331+ assert_ne!(stat.as_str(), stat.field(), "{stat:?} collapsed the two");
332+ }
333+ }
334+
335+ #[tokio::test]
336+ async fn a_row_without_the_columns_loads_as_five_zeros() {
337+ let db = crate::database::init_mem().await.unwrap();
338+ schema(&db).await;
339+ // The stale-data case: an account written before the counters existed
340+ // carries none of them. And the harsher one β€” no row at all.
341+ for user in [a_user(&[], &db).await, UserId::from_key("ghost")] {
342+ let stats = BadgeStats::load(&user, &db).await.unwrap();
343+ assert_eq!(stats.get_homework_submitted(), 0);
344+ assert_eq!(stats.get_homework_on_time(), 0);
345+ assert_eq!(stats.get_exam_sat(), 0);
346+ assert_eq!(stats.get_pomodoro_finished(), 0);
347+ assert_eq!(stats.get_pomodoro_focus_ms(), 0);
348+ assert!(earned(&stats).is_empty(), "zero earns nothing");
349+ }
350+ }
351+
352+ #[tokio::test]
353+ async fn the_rule_takes_every_threshold_at_or_below_the_count() {
354+ let stats = BadgeStats {
355+ homework_submitted: 10,
356+ homework_on_time: 9,
357+ exam_sat: 0,
358+ pomodoro_finished: 200,
359+ pomodoro_focus_ms: 36_000_000,
360+ };
361+ assert_eq!(
362+ earned(&stats),
363+ vec![
364+ // 10 clears the 1 and the 10, not the 50.
365+ "homework_submitted_1",
366+ "homework_submitted_10",
367+ // 9 clears nothing; 0 exams likewise, so `exam_sat_1` is out.
368+ "pomodoro_finished_10",
369+ "pomodoro_finished_50",
370+ "pomodoro_finished_200",
371+ // Exactly at the threshold earns it.
372+ "pomodoro_focus_ms_36000000",
373+ ]
374+ );
375+ }
376+
377+ #[tokio::test]
378+ async fn a_second_sync_does_not_move_the_stamp() {
379+ let db = crate::database::init_mem().await.unwrap();
380+ schema(&db).await;
381+ let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await;
382+
383+ sync(&user, &db).await.unwrap();
384+ let first = stamps(&user, &db).await;
385+ assert_eq!(first.len(), 1, "{first:?}");
386+ assert_eq!(first[0].0, "homework_submitted_1");
387+
388+ // A later sync, provably at a later millisecond: the row must keep the
389+ // instant the badge was *first* earned, and must not be doubled.
390+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
391+ sync(&user, &db).await.unwrap();
392+ assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen");
393+ }
394+
395+ #[tokio::test]
396+ async fn an_award_survives_a_counter_that_falls_back_below_it() {
397+ let db = crate::database::init_mem().await.unwrap();
398+ schema(&db).await;
399+ let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await;
400+ sync(&user, &db).await.unwrap();
401+ assert_eq!(
402+ stamps(&user, &db).await.len(),
403+ 2,
404+ "1 and 10 are both earned"
405+ );
406+
407+ // The submission is withdrawn and the counter comes back down. A badge
408+ // records that it was done, so nothing here may take it away.
409+ db.query(format!(
410+ "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0"
411+ ))
412+ .bind(("usr", user.record()))
413+ .await
414+ .unwrap()
415+ .check()
416+ .unwrap();
417+ assert!(
418+ earned(&BadgeStats::load(&user, &db).await.unwrap()).is_empty(),
419+ "the rule no longer holds…"
420+ );
421+ sync(&user, &db).await.unwrap();
422+ let kept: Vec<String> = stamps(&user, &db)
423+ .await
424+ .into_iter()
425+ .map(|(badge, _)| badge)
426+ .collect();
427+ assert_eq!(
428+ kept,
429+ vec!["homework_submitted_1", "homework_submitted_10"],
430+ "…and the awards stand anyway"
431+ );
432+ }
433+
434+ #[tokio::test]
435+ async fn a_badge_the_catalog_dropped_is_not_served() {
436+ let db = crate::database::init_mem().await.unwrap();
437+ schema(&db).await;
438+ let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await;
439+ sync(&user, &db).await.unwrap();
440+ // The row a retired catalog line left behind: still stored, never
441+ // served, and no migration deleted it.
442+ db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1")
443+ .bind((
444+ "id",
445+ surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")),
446+ ))
447+ .bind(("usr", user.record()))
448+ .await
449+ .unwrap()
450+ .check()
451+ .unwrap();
452+
453+ let served: Vec<String> = stamps(&user, &db)
454+ .await
455+ .into_iter()
456+ .map(|(badge, _)| badge)
457+ .collect();
458+ assert_eq!(served, vec!["exam_sat_1"]);
459+ let mut rows = db
460+ .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}"))
461+ .await
462+ .unwrap();
463+ assert_eq!(rows.take::<Vec<String>>(0).unwrap().len(), 2, "both stored");
464+ }
465+
466+ /// One sync stamps every badge it writes with the same millisecond, so the
467+ /// tie-break is what makes the order stable rather than incidental.
468+ #[tokio::test]
469+ async fn same_millisecond_awards_come_back_in_badge_order() {
470+ let db = crate::database::init_mem().await.unwrap();
471+ schema(&db).await;
472+ let user = a_user(
473+ &[
474+ (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50),
475+ (EXAM_SAT_TOTAL_FIELD, 1),
476+ ],
477+ &db,
478+ )
479+ .await;
480+ sync(&user, &db).await.unwrap();
481+
482+ let served = stamps(&user, &db).await;
483+ let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect();
484+ assert_eq!(
485+ ids,
486+ vec![
487+ "exam_sat_1",
488+ "homework_submitted_1",
489+ "homework_submitted_10",
490+ "homework_submitted_50"
491+ ]
492+ );
493+ assert!(
494+ served.windows(2).all(|pair| pair[0].1 == pair[1].1),
495+ "one sync stamps one instant: {served:?}"
496+ );
497+ }
498+}
src/domain/exam_attempt.rsmodified+155 -21
@@ -1,12 +1,12 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::EXAM_ATTEMPT_TABLE;3+use crate::constant::{EXAM_ATTEMPT_TABLE, EXAM_SAT_TOTAL_FIELD};
4 use crate::database::{Database, transaction_with_retry};4 use crate::database::{Database, transaction_with_retry};
5 use crate::domain::exam::Exam;5 use crate::domain::exam::Exam;
6 use crate::domain::exam::ExamId;6 use crate::domain::exam::ExamId;
7-use crate::domain::key;
8 use crate::domain::timestamp::Timestamp;7 use crate::domain::timestamp::Timestamp;
9 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9+use crate::domain::{badge, cap, key};
10 use crate::error::AppError;10 use crate::error::AppError;
11 11
12 /// The `THROW` marker the freeze gate aborts with, and the one 409 both it and12 /// The `THROW` marker the freeze gate aborts with, and the one 409 both it and
@@ -163,6 +163,11 @@ impl ExamAttempt {
163 /// The composite id makes each create atomic; a concurrent double-start163 /// The composite id makes each create atomic; a concurrent double-start
164 /// races on the same seq, loses to the unique id, and reads the winner's164 /// races on the same seq, loses to the unique id, and reads the winner's
165 /// row.165 /// row.
166+ ///
167+ /// A created row rides [`cap::claim_and_create`] so the student's
168+ /// `exam_sat_total` moves in the same transaction β€” one per sitting,
169+ /// retakes included, which is exactly what the one-time backfill counted.
170+ /// A lost race writes neither the row nor the increment.
166 pub async fn start(171 pub async fn start(
167 exam: &Exam,172 exam: &Exam,
168 user: &UserId,173 user: &UserId,
@@ -192,23 +197,45 @@ impl ExamAttempt {
192 finished_at: None,197 finished_at: None,
193 left_at: None,198 left_at: None,
194 };199 };
195- let created: Result<Option<ExamAttempt>, surrealdb::Error> =200+ let id = attempt.id.record();
196- db.create(attempt.id.record()).content(attempt).await;201+ match cap::claim_and_create(
197- match created {202+ &user.record(),
198- Ok(Some(created)) => Ok((created, true)),203+ EXAM_SAT_TOTAL_FIELD,
199- Ok(None) => Err(AppError::Internal("failed to start exam attempt".into())),204+ cap::UNLIMITED,
205+ &id,
206+ &attempt,
207+ db,
208+ )
209+ .await?
210+ {
211+ cap::Claimed::Made(created) => {
212+ if let Err(err) = badge::sync(user, db).await {
213+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
214+ }
215+ Ok((created, true))
216+ }
200 // Only a still-running row proves the loss was a double-start217 // Only a still-running row proves the loss was a double-start
201 // collision (the winner's fresh sitting); a terminal or missing218 // collision (the winner's fresh sitting); a terminal or missing
202 // latest means the create genuinely failed β€” surface that instead219 // latest means the create genuinely failed β€” surface that instead
203- // of passing a finished sitting off as a resume.220+ // of passing a finished sitting off as a resume. The duplicate
204- Err(err) => match Self::read_latest_for_user(exam.get_id(), user, db).await? {221+ // aborted the transaction, so the loser's increment went with it.
205- Some(existing)222+ cap::Claimed::Duplicate => {
206- if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress =>223+ match Self::read_latest_for_user(exam.get_id(), user, db).await? {
207- {224+ Some(existing)
208- Ok((existing, false))225+ if existing.status(exam, Timestamp::now()) == AttemptStatus::InProgress =>
226+ {
227+ Ok((existing, false))
228+ }
229+ _ => Err(AppError::Internal("failed to start exam attempt".into())),
209 }230 }
210- _ => Err(err.into()),231+ }
211- },232+ // Nothing caps sittings, so the conditional write can only miss by
233+ // finding no user row β€” not a state a live session can reach, and
234+ // passing it off as a resume would hand out a sitting the counter
235+ // never learned about.
236+ cap::Claimed::Full => Err(AppError::Internal(
237+ "cannot start an exam attempt: the student's account row is missing".into(),
238+ )),
212 }239 }
213 }240 }
214 241
@@ -519,15 +546,122 @@ mod tests {
519 (exam, question)546 (exam, question)
520 }547 }
521 548
522- fn student() -> UserId {549+ /// A real user row: the sitting counter lives on it, and the claim that
523- UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA")550+ /// rides the attempt's create has nothing to write to without one.
551+ async fn student(db: &Database) -> UserId {
552+ let hash = crate::domain::user::Password::try_new("secret1")
553+ .unwrap()
554+ .hash_async()
555+ .await
556+ .unwrap();
557+ crate::domain::user::User::create(
558+ crate::domain::user::Username::try_new("ogrenci").unwrap(),
559+ hash,
560+ db,
561+ )
562+ .await
563+ .unwrap()
564+ .get_id()
565+ .clone()
566+ }
567+
568+ /// The student's lifetime sitting count, absent reading as zero.
569+ async fn sat_total(user: &UserId, db: &Database) -> i64 {
570+ let mut result = db
571+ .query(format!(
572+ "SELECT VALUE ({EXAM_SAT_TOTAL_FIELD} ?? 0) FROM $usr"
573+ ))
574+ .bind(("usr", user.record()))
575+ .await
576+ .unwrap()
577+ .check()
578+ .unwrap();
579+ result
580+ .take::<Vec<i64>>(0)
581+ .unwrap()
582+ .into_iter()
583+ .next()
584+ .unwrap()
585+ }
586+
587+ /// The badge counter counts *sittings*, one per created row β€” so a start
588+ /// moves it by exactly one and a resume, which creates nothing, leaves it
589+ /// alone. Anything else and a seeded account and a fresh one would mean
590+ /// different things by the same number.
591+ #[tokio::test]
592+ async fn starting_counts_one_sitting_and_resuming_counts_none() {
593+ let db = init_mem().await.unwrap();
594+ let (exam, _question) = open_exam_with_question(&db, 2).await;
595+ let user = student(&db).await;
596+ assert_eq!(sat_total(&user, &db).await, 0, "a fresh row reads as zero");
597+
598+ let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
599+ assert!(created);
600+ assert_eq!(sat_total(&user, &db).await, 1);
601+
602+ // Still in progress: this start returns the running sitting untouched.
603+ let (_, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
604+ assert!(!created);
605+ assert_eq!(
606+ sat_total(&user, &db).await,
607+ 1,
608+ "a resume writes no row, so it counts nothing"
609+ );
610+ }
611+
612+ /// The backfill counted every `seq`, retakes included β€” a second sitting
613+ /// is a second row and moves the counter again.
614+ #[tokio::test]
615+ async fn a_retake_counts_as_another_sitting() {
616+ let db = init_mem().await.unwrap();
617+ let (exam, _question) = open_exam_with_question(&db, 3).await;
618+ let user = student(&db).await;
619+
620+ let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
621+ first.finish(&db).await.unwrap();
622+ let (second, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
623+ assert!(created);
624+ assert_eq!(second.get_seq(), 2);
625+ assert_eq!(sat_total(&user, &db).await, 2);
626+ }
627+
628+ /// The lost half of a double-start race. `start` can only reach that branch
629+ /// by interleaving with a rival, so the claim is put to the counter
630+ /// directly β€” the same call `start` makes, aimed at a row that already
631+ /// exists. The duplicate aborts the transaction and takes its increment
632+ /// with it: a sitting is never counted twice.
633+ #[tokio::test]
634+ async fn a_lost_start_race_never_counts_the_sitting_twice() {
635+ let db = init_mem().await.unwrap();
636+ let (exam, _question) = open_exam_with_question(&db, 1).await;
637+ let user = student(&db).await;
638+
639+ let (winner, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
640+ assert_eq!(sat_total(&user, &db).await, 1);
641+
642+ let claimed = cap::claim_and_create(
643+ &user.record(),
644+ EXAM_SAT_TOTAL_FIELD,
645+ cap::UNLIMITED,
646+ &winner.id.record(),
647+ &winner,
648+ &db,
649+ )
650+ .await
651+ .unwrap();
652+ assert!(matches!(claimed, cap::Claimed::Duplicate));
653+ assert_eq!(
654+ sat_total(&user, &db).await,
655+ 1,
656+ "the loser's increment rolled back with its duplicate create"
657+ );
524 }658 }
525 659
526 #[tokio::test]660 #[tokio::test]
527 async fn a_retake_preserves_the_prior_sittings_sheet() {661 async fn a_retake_preserves_the_prior_sittings_sheet() {
528 let db = init_mem().await.unwrap();662 let db = init_mem().await.unwrap();
529 let (exam, question) = open_exam_with_question(&db, 2).await;663 let (exam, question) = open_exam_with_question(&db, 2).await;
530- let user = student();664+ let user = student(&db).await;
531 665
532 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();666 let (first, created) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
533 assert!(created);667 assert!(created);
@@ -565,7 +699,7 @@ mod tests {
565 async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {699 async fn a_lost_retake_race_cannot_touch_the_winners_sheet() {
566 let db = init_mem().await.unwrap();700 let db = init_mem().await.unwrap();
567 let (exam, question) = open_exam_with_question(&db, 3).await;701 let (exam, question) = open_exam_with_question(&db, 3).await;
568- let user = student();702+ let user = student(&db).await;
569 703
570 // Sitting #1 ends; the winner starts sitting #2 and saves an answer.704 // Sitting #1 ends; the winner starts sitting #2 and saves an answer.
571 let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();705 let (first, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
@@ -618,7 +752,7 @@ mod tests {
618 async fn submitting_never_reverts_a_walk_out_that_raced_it() {752 async fn submitting_never_reverts_a_walk_out_that_raced_it() {
619 let db = init_mem().await.unwrap();753 let db = init_mem().await.unwrap();
620 let (exam, _question) = open_exam_with_question(&db, 1).await;754 let (exam, _question) = open_exam_with_question(&db, 1).await;
621- let user = student();755+ let user = student(&db).await;
622 756
623 let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();757 let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
624 758
@@ -661,7 +795,7 @@ mod tests {
661 async fn stamping_left_never_reverts_a_submission() {795 async fn stamping_left_never_reverts_a_submission() {
662 let db = init_mem().await.unwrap();796 let db = init_mem().await.unwrap();
663 let (exam, _question) = open_exam_with_question(&db, 1).await;797 let (exam, _question) = open_exam_with_question(&db, 1).await;
664- let user = student();798+ let user = student(&db).await;
665 799
666 // The student is sitting the exam.800 // The student is sitting the exam.
667 let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();801 let (attempt, _) = ExamAttempt::start(&exam, &user, &db).await.unwrap();
src/domain/exam_question.rsmodified+16 -1
@@ -1183,7 +1183,22 @@ mod tests {
1183 let question = a_question(&exam, &from, &db).await;1183 let question = a_question(&exam, &from, &db).await;
1184 assert_eq!(count_on(&from, &db).await, 1);1184 assert_eq!(count_on(&from, &db).await, 1);
1185 1185
1186- ExamAttempt::start(&exam, &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), &db)1186+ // A real user row: starting a sitting moves that student's badge
1187+ // counter in the same transaction, and an `UPDATE` has nothing to
1188+ // write to without one.
1189+ let hash = crate::domain::user::Password::try_new("secret1")
1190+ .unwrap()
1191+ .hash_async()
1192+ .await
1193+ .unwrap();
1194+ let student = crate::domain::user::User::create(
1195+ crate::domain::user::Username::try_new("ogrenci").unwrap(),
1196+ hash,
1197+ &db,
1198+ )
1199+ .await
1200+ .unwrap();
1201+ ExamAttempt::start(&exam, student.get_id(), &db)
1187 .await1202 .await
1188 .unwrap();1203 .unwrap();
1189 1204
src/domain/homework_file.rsmodified+36 -4
@@ -308,6 +308,36 @@ mod tests {
308 use crate::domain::homework_submission::HomeworkSubmission;308 use crate::domain::homework_submission::HomeworkSubmission;
309 use crate::domain::user::UserId;309 use crate::domain::user::UserId;
310 310
311+ /// A real homework row (with the subject it references): `upsert` reads the
312+ /// deadline off the entity now, so a bare id no longer does.
313+ async fn a_homework(db: &Database) -> crate::domain::homework::Homework {
314+ use crate::domain::course::CourseId;
315+ use crate::domain::homework::{Homework, HomeworkTitle};
316+ use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
317+
318+ let course = CourseId::from_key("course");
319+ let subject = Subject::create(
320+ &course,
321+ SubjectName::try_new("topic").unwrap(),
322+ SubjectDescription::try_new("").unwrap(),
323+ db,
324+ )
325+ .await
326+ .unwrap();
327+ Homework::create(
328+ &course,
329+ subject.get_id(),
330+ HomeworkTitle::try_new("essay").unwrap(),
331+ None,
332+ crate::domain::timestamp::Timestamp::from_millis(1),
333+ None,
334+ &UserId::from_key("teacher"),
335+ db,
336+ )
337+ .await
338+ .unwrap()
339+ }
340+
311 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {341 fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile {
312 HomeworkFile::new(342 HomeworkFile::new(
313 submission,343 submission,
@@ -334,10 +364,11 @@ mod tests {
334 #[tokio::test]364 #[tokio::test]
335 async fn rows_scope_to_their_submission_gc_and_cap() {365 async fn rows_scope_to_their_submission_gc_and_cap() {
336 let db = crate::database::init_mem().await.unwrap();366 let db = crate::database::init_mem().await.unwrap();
337- let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");367+ let hw = a_homework(&db).await;
368+ let homework = hw.get_id().clone();
338 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");369 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
339 // A real submission row, so the GC join through it resolves.370 // A real submission row, so the GC join through it resolves.
340- let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)371+ let submission = HomeworkSubmission::upsert(&hw, &user, None, &db)
341 .await372 .await
342 .unwrap()373 .unwrap()
343 .unwrap();374 .unwrap();
@@ -432,9 +463,10 @@ mod tests {
432 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};463 use crate::domain::homework_result::{HomeworkResult, HomeworkStatus};
433 464
434 let db = crate::database::init_mem().await.unwrap();465 let db = crate::database::init_mem().await.unwrap();
435- let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");466+ let hw = a_homework(&db).await;
467+ let homework = hw.get_id().clone();
436 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");468 let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
437- let submission = HomeworkSubmission::upsert(&homework, &user, None, &db)469+ let submission = HomeworkSubmission::upsert(&hw, &user, None, &db)
438 .await470 .await
439 .unwrap()471 .unwrap()
440 .unwrap();472 .unwrap();
src/domain/homework_submission.rsmodified+350 -41
@@ -15,11 +15,11 @@
15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};15 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 16
17 use crate::constant::{17 use crate::constant::{
18- HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD,18+ HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMISSION_TABLE, HOMEWORK_SUBMITTED_TOTAL_FIELD,
19- SUBMISSION_OPEN_GUARD,19+ MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD,
20 };20 };
21-use crate::database::Database;21+use crate::database::{Database, transaction_with_retry};
22-use crate::domain::homework::HomeworkId;22+use crate::domain::homework::{Homework, HomeworkId};
23 use crate::domain::timestamp::Timestamp;23 use crate::domain::timestamp::Timestamp;
24 use crate::domain::user::UserId;24 use crate::domain::user::UserId;
25 use crate::error::{AppError, ValidationError};25 use crate::error::{AppError, ValidationError};
@@ -119,29 +119,80 @@ impl HomeworkSubmission {
119 /// yet" a condition of this very write instead of a read a concurrent grade119 /// yet" a condition of this very write instead of a read a concurrent grade
120 /// can land behind. An absent row satisfies it (the stamp is `NONE` there120 /// can land behind. An absent row satisfies it (the stamp is `NONE` there
121 /// too), so a first submit still creates.121 /// too), so a first submit still creates.
122+ ///
123+ /// The badge counters on the student's user row move in this very
124+ /// transaction, and the order is load-bearing: the increment sits *after*
125+ /// the UPSERT and is conditional on it having matched a row, because a
126+ /// frozen row makes that `WHERE` match nothing **silently** (unlike
127+ /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) β€” put
128+ /// first, it would count a submission the freeze refused. `$before = NONE`
129+ /// keeps it to a genuine first create, so an edit moves neither counter,
130+ /// which is what makes the live count mean the same thing the one-time
131+ /// backfill seeded (one per row; on time judged against `due_at`, equal
132+ /// counting as on time). Takes the whole [`Homework`] only for that
133+ /// deadline β€” both callers already hold the row.
134+ ///
135+ /// `counted_on_time` is stamped on the row from the *same* `$on_time`
136+ /// expression the increment adds, in the same statement block: the deadline
137+ /// is mutable, so a withdrawal that re-judged it against the live `due_at`
138+ /// gave back something other than what was taken. Writing the verdict beside
139+ /// the counter is what keeps the two from ever disagreeing β€” read back by
140+ /// [`HomeworkSubmission::delete`], never re-derived.
122 pub async fn upsert(141 pub async fn upsert(
123- homework: &HomeworkId,142+ homework: &Homework,
124 user: &UserId,143 user: &UserId,
125 text: Option<SubmissionText>,144 text: Option<SubmissionText>,
126 db: &Database,145 db: &Database,
127 ) -> Result<Option<HomeworkSubmission>, AppError> {146 ) -> Result<Option<HomeworkSubmission>, AppError> {
128- let id = HomeworkSubmissionId::composite(homework, user);147+ let id = HomeworkSubmissionId::composite(homework.get_id(), user);
129 let now = Timestamp::now();148 let now = Timestamp::now();
130 let text = text.map(|text| text.as_str().to_string());149 let text = text.map(|text| text.as_str().to_string());
131- let mut saved = db150+ // Sound to re-send: the UPSERT is on a deterministic id on a table with
132- .query(format!(151+ // no unique index, so it can never legitimately answer "already exists",
133- "UPSERT $id SET homework = $hw, user = $usr, text = $text, \152+ // and the counter UPDATE never can either.
134- updated_at = $now, submitted_at = submitted_at ?? $now \153+ let (mut saved, mut errors) = transaction_with_retry(
135- WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER"154+ db,
136- ))155+ &format!(
137- .bind(("id", id.record()))156+ "BEGIN TRANSACTION;
138- .bind(("hw", homework.record()))157+ LET $before = (SELECT VALUE id FROM ONLY $id);
139- .bind(("usr", user.record()))158+ LET $on_time = $now <= $due;
140- .bind(("text", text))159+ LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text,
141- .bind(("now", now))160+ updated_at = $now, submitted_at = submitted_at ?? $now
142- .await?161+ WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER);
143- .check()?;162+ IF $before = NONE AND array::len($after) > 0 {{
144- Ok(saved.take::<Vec<HomeworkSubmission>>(0)?.into_iter().next())163+ UPDATE $id SET counted_on_time = $on_time;
164+ UPDATE $usr SET
165+ {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1,
166+ {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)
167+ + IF $on_time {{ 1 }} ELSE {{ 0 }}
168+ }};
169+ RETURN $after;
170+ COMMIT TRANSACTION;"
171+ ),
172+ &[
173+ ("id".into(), id.record().into_value()),
174+ ("hw".into(), homework.get_id().record().into_value()),
175+ ("usr".into(), user.record().into_value()),
176+ ("text".into(), text.into_value()),
177+ ("now".into(), now.into_value()),
178+ ("due".into(), homework.get_due_at().into_value()),
179+ ],
180+ &[],
181+ )
182+ .await?;
183+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
184+ return Err(error.into());
185+ }
186+ // The trailing `RETURN` is always the last statement before `COMMIT`, so
187+ // its slot follows the statement count rather than a hand-kept number.
188+ // It returns the whole array, never `$after[0]`: a refused write makes
189+ // that `NONE`, which fails to deserialize ("expected object, got none")
190+ // instead of reading as the "frozen" the caller answers 409 to.
191+ let slot = saved.num_statements().saturating_sub(2);
192+ Ok(saved
193+ .take::<Vec<HomeworkSubmission>>(slot)?
194+ .into_iter()
195+ .next())
145 }196 }
146 197
147 /// Re-stamp a submission's `updated_at` to now, leaving its text and files198 /// Re-stamp a submission's `updated_at` to now, leaving its text and files
@@ -216,21 +267,64 @@ impl HomeworkSubmission {
216 /// answers 409): the submission's own delete carries267 /// answers 409): the submission's own delete carries
217 /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having268 /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having
218 /// bitten, so a refused delete leaves the children standing too.269 /// bitten, so a refused delete leaves the children standing too.
270+ ///
271+ /// The one place either badge counter comes back down, and deliberately the
272+ /// only one: this route is student-callable on their own row, so without it
273+ /// a student farms "handed in 50 homeworks" by submit/delete/submit on a
274+ /// single homework. A teacher's homework delete and the course cascade
275+ /// leave the counters alone β€” history a teacher erased is still history the
276+ /// student lived.
277+ ///
278+ /// The on-time half is given back by the verdict [`HomeworkSubmission::upsert`]
279+ /// *stored* on the row, never by re-judging the deadline: `due_at` is
280+ /// mutable, so re-deriving read whatever the teacher had moved it to since
281+ /// and gave back something other than what was taken β€” extend it after a
282+ /// late hand-in and this debited a credit that was never given; pull it back
283+ /// after a punctual one and it debited nothing, leaving `on_time` above
284+ /// `submitted`. A row from before the column exists carries no verdict, and
285+ /// cannot be given one for a credit that already happened, so it falls back
286+ /// to the old cut (`submitted_at`, the readonly stamp the increment judged,
287+ /// against the live deadline); a dangling `homework` link leaves `$due`
288+ /// `NONE` there, which compares false and so counts as late, matching the
289+ /// backfill. Floored at zero: a row that predates the columns has none.
290+ ///
291+ /// Badges already earned are never taken away β€” [`crate::domain::badge`] is
292+ /// add-only, which is where that permanence lives.
219 pub async fn delete(self, db: &Database) -> Result<Option<HomeworkSubmission>, AppError> {293 pub async fn delete(self, db: &Database) -> Result<Option<HomeworkSubmission>, AppError> {
220- let mut result = db294+ // Sound to re-send: DELETE and UPDATE can never answer "already exists".
221- .query(format!(295+ let (mut result, mut errors) = transaction_with_retry(
296+ db,
297+ &format!(
222 "BEGIN TRANSACTION;298 "BEGIN TRANSACTION;
299+ LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub);
223 LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);300 LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE);
224- IF array::len($gone) > 0 {{ DELETE homework_file WHERE submission = $sub }};301+ IF array::len($gone) > 0 {{
302+ DELETE homework_file WHERE submission = $sub;
303+ LET $on_time = IF ($gone[0].counted_on_time
304+ ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }};
305+ UPDATE $usr SET
306+ {HOMEWORK_SUBMITTED_TOTAL_FIELD} =
307+ math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]),
308+ {HOMEWORK_ON_TIME_TOTAL_FIELD} =
309+ math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0])
310+ }};
225 RETURN $gone;311 RETURN $gone;
226 COMMIT TRANSACTION;"312 COMMIT TRANSACTION;"
227- ))313+ ),
228- .bind(("sub", self.id.record()))314+ &[
229- .await?315+ ("sub".into(), self.id.record().into_value()),
230- .check()?;316+ ("usr".into(), self.user.record().into_value()),
231- // BEGIN is slot 0, the LET slot 1 and the IF slot 2; the RETURN is slot 3.317+ ],
318+ &[],
319+ )
320+ .await?;
321+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
322+ return Err(error.into());
323+ }
324+ // The trailing `RETURN` is always the last statement before `COMMIT`.
325+ let slot = result.num_statements().saturating_sub(2);
232 Ok(result326 Ok(result
233- .take::<Vec<HomeworkSubmission>>(3)?327+ .take::<Vec<HomeworkSubmission>>(slot)?
234 .into_iter()328 .into_iter()
235 .next())329 .next())
236 }330 }
@@ -240,6 +334,81 @@ impl HomeworkSubmission {
240 mod tests {334 mod tests {
241 use super::*;335 use super::*;
242 336
337+ use crate::domain::course::CourseId;
338+ use crate::domain::homework::HomeworkTitle;
339+ use crate::domain::subject::{Subject, SubjectDescription, SubjectName};
340+
341+ /// A real homework row (and the subject it must reference) due at `due_at` β€”
342+ /// `upsert` now reads the deadline off the entity, so the tests need one.
343+ async fn a_homework(due_at: Timestamp, db: &Database) -> Homework {
344+ let course = CourseId::from_key("course");
345+ let subject = Subject::create(
346+ &course,
347+ SubjectName::try_new("topic").unwrap(),
348+ SubjectDescription::try_new("").unwrap(),
349+ db,
350+ )
351+ .await
352+ .unwrap();
353+ Homework::create(
354+ &course,
355+ subject.get_id(),
356+ HomeworkTitle::try_new("essay").unwrap(),
357+ None,
358+ due_at,
359+ None,
360+ &UserId::from_key("teacher"),
361+ db,
362+ )
363+ .await
364+ .unwrap()
365+ }
366+
367+ /// A deadline no test run can reach, so a submission is unambiguously on
368+ /// time; `Timestamp::from_millis(1)` is its late twin.
369+ fn far_future() -> Timestamp {
370+ Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000)
371+ }
372+
373+ /// A real user row: the counters live on it, and an `UPDATE` has nothing to
374+ /// write to without one.
375+ async fn a_student(username: &str, db: &Database) -> UserId {
376+ let hash = crate::domain::user::Password::try_new("secret1")
377+ .unwrap()
378+ .hash_async()
379+ .await
380+ .unwrap();
381+ crate::domain::user::User::create(
382+ crate::domain::user::Username::try_new(username).unwrap(),
383+ hash,
384+ db,
385+ )
386+ .await
387+ .unwrap()
388+ .get_id()
389+ .clone()
390+ }
391+
392+ /// The two badge counters on a user row, absent counting as zero.
393+ async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
394+ let mut result = db
395+ .query(format!(
396+ "SELECT VALUE [({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0),
397+ ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)] FROM $usr"
398+ ))
399+ .bind(("usr", user.record()))
400+ .await
401+ .unwrap()
402+ .check()
403+ .unwrap();
404+ let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
405+ let row = rows.first().cloned().unwrap_or_default();
406+ (
407+ row.first().copied().unwrap_or(0),
408+ row.get(1).copied().unwrap_or(0),
409+ )
410+ }
411+
243 #[tokio::test]412 #[tokio::test]
244 async fn text_is_optional_but_bounded() {413 async fn text_is_optional_but_bounded() {
245 assert!(SubmissionText::try_new("").is_ok());414 assert!(SubmissionText::try_new("").is_ok());
@@ -250,8 +419,8 @@ mod tests {
250 #[tokio::test]419 #[tokio::test]
251 async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {420 async fn resubmit_keeps_submitted_at_and_restamps_updated_at() {
252 let db = crate::database::init_mem().await.unwrap();421 let db = crate::database::init_mem().await.unwrap();
253- let homework = HomeworkId::generate();422+ let homework = a_homework(far_future(), &db).await;
254- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");423+ let user = a_student("ogrenci", &db).await;
255 424
256 let first = HomeworkSubmission::upsert(425 let first = HomeworkSubmission::upsert(
257 &homework,426 &homework,
@@ -268,13 +437,15 @@ mod tests {
268 .await437 .await
269 .unwrap()438 .unwrap()
270 .unwrap();439 .unwrap();
440+ // ... and it is one submission, not two: the edit moves no counter.
441+ assert_eq!(counters(&user, &db).await, (1, 1));
271 assert_eq!(first.get_id(), second.get_id());442 assert_eq!(first.get_id(), second.get_id());
272 assert_eq!(first.get_submitted_at(), second.get_submitted_at());443 assert_eq!(first.get_submitted_at(), second.get_submitted_at());
273 assert!(second.get_updated_at() >= first.get_updated_at());444 assert!(second.get_updated_at() >= first.get_updated_at());
274 assert!(second.get_text().is_none());445 assert!(second.get_text().is_none());
275 // One row per (homework, user), whatever the re-submit count.446 // One row per (homework, user), whatever the re-submit count.
276 assert_eq!(447 assert_eq!(
277- HomeworkSubmission::list_for_homework(&homework, &db)448+ HomeworkSubmission::list_for_homework(homework.get_id(), &db)
278 .await449 .await
279 .unwrap()450 .unwrap()
280 .len(),451 .len(),
@@ -294,8 +465,8 @@ mod tests {
294 #[tokio::test]465 #[tokio::test]
295 async fn a_grade_freezes_the_submission_row_itself() {466 async fn a_grade_freezes_the_submission_row_itself() {
296 let db = crate::database::init_mem().await.unwrap();467 let db = crate::database::init_mem().await.unwrap();
297- let homework = HomeworkId::from_key("01TESTHWAAAAAAAAAAAAAAAAAA");468+ let homework = a_homework(far_future(), &db).await;
298- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");469+ let user = a_student("ogrenci", &db).await;
299 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");470 let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
300 let graded = |value| {471 let graded = |value| {
301 let text = SubmissionText::try_new(value).unwrap();472 let text = SubmissionText::try_new(value).unwrap();
@@ -309,8 +480,10 @@ mod tests {
309 .unwrap()480 .unwrap()
310 );481 );
311 482
483+ assert_eq!(counters(&user, &db).await, (1, 1));
484+
312 crate::domain::homework_result::HomeworkResult::grade(485 crate::domain::homework_result::HomeworkResult::grade(
313- &homework,486+ homework.get_id(),
314 &user,487 &user,
315 crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(),488 crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(),
316 None,489 None,
@@ -329,27 +502,33 @@ mod tests {
329 // still the version that was graded.502 // still the version that was graded.
330 assert!(graded("version B").await.unwrap().is_none());503 assert!(graded("version B").await.unwrap().is_none());
331 assert_eq!(504 assert_eq!(
332- HomeworkSubmission::read_for(&homework, &user, &db)505+ HomeworkSubmission::read_for(homework.get_id(), &user, &db)
333 .await506 .await
334 .unwrap()507 .unwrap()
335 .and_then(|row| row.get_text().map(|text| text.as_str().to_string())),508 .and_then(|row| row.get_text().map(|text| text.as_str().to_string())),
336 Some("version A".to_string())509 Some("version A".to_string())
337 );510 );
511+ // The refusal is silent β€” the UPSERT simply matches nothing β€” so the
512+ // counters are the only thing that can catch an increment placed in
513+ // front of it: a submission the freeze refused must count for nothing.
514+ assert_eq!(counters(&user, &db).await, (1, 1));
338 // ... and so is withdrawing it wholesale.515 // ... and so is withdrawing it wholesale.
339- let frozen = HomeworkSubmission::read_for(&homework, &user, &db)516+ let frozen = HomeworkSubmission::read_for(homework.get_id(), &user, &db)
340 .await517 .await
341 .unwrap()518 .unwrap()
342 .unwrap();519 .unwrap();
343 assert!(frozen.delete(&db).await.unwrap().is_none());520 assert!(frozen.delete(&db).await.unwrap().is_none());
344 assert!(521 assert!(
345- HomeworkSubmission::read_for(&homework, &user, &db)522+ HomeworkSubmission::read_for(homework.get_id(), &user, &db)
346 .await523 .await
347 .unwrap()524 .unwrap()
348 .is_some()525 .is_some()
349 );526 );
527+ // A refused delete decrements nothing either.
528+ assert_eq!(counters(&user, &db).await, (1, 1));
350 529
351 // Un-grading unfreezes it, stamp and all.530 // Un-grading unfreezes it, stamp and all.
352- crate::domain::homework_result::HomeworkResult::remove(&homework, &user, &db)531+ crate::domain::homework_result::HomeworkResult::remove(homework.get_id(), &user, &db)
353 .await532 .await
354 .unwrap();533 .unwrap();
355 assert!(534 assert!(
@@ -362,6 +541,8 @@ mod tests {
362 reopened.get_text().map(SubmissionText::as_str),541 reopened.get_text().map(SubmissionText::as_str),
363 Some("version B")542 Some("version B")
364 );543 );
544+ // Still an edit to the row that was already counted, un-freeze or not.
545+ assert_eq!(counters(&user, &db).await, (1, 1));
365 // The two-stamp lateness rule is untouched by any of it: the first546 // The two-stamp lateness rule is untouched by any of it: the first
366 // hand-in is still the first hand-in.547 // hand-in is still the first hand-in.
367 assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at());548 assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at());
@@ -371,8 +552,8 @@ mod tests {
371 #[tokio::test]552 #[tokio::test]
372 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {553 async fn touch_moves_updated_at_but_not_submitted_at_or_text() {
373 let db = crate::database::init_mem().await.unwrap();554 let db = crate::database::init_mem().await.unwrap();
374- let homework = HomeworkId::generate();555+ let homework = a_homework(far_future(), &db).await;
375- let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");556+ let user = a_student("ogrenci", &db).await;
376 557
377 let original = HomeworkSubmission::upsert(558 let original = HomeworkSubmission::upsert(
378 &homework,559 &homework,
@@ -395,4 +576,132 @@ mod tests {
395 Some("photo answer")576 Some("photo answer")
396 );577 );
397 }578 }
579+
580+ /// The farm, closed: `delete_submission` is the student's own route, so a
581+ /// counter that only ever went up would let one homework be handed in fifty
582+ /// times. Submit β†’ withdraw β†’ submit is worth exactly one submission.
583+ ///
584+ /// Bite check: drop the `UPDATE $usr` from [`HomeworkSubmission::delete`]
585+ /// and the last assertion reads `(2, 2)` β€” the farm.
586+ #[tokio::test]
587+ async fn submit_delete_submit_is_worth_one_submission() {
588+ let db = crate::database::init_mem().await.unwrap();
589+ let homework = a_homework(far_future(), &db).await;
590+ let user = a_student("ogrenci", &db).await;
591+
592+ HomeworkSubmission::upsert(&homework, &user, None, &db)
593+ .await
594+ .unwrap()
595+ .unwrap();
596+ assert_eq!(counters(&user, &db).await, (1, 1));
597+
598+ let mine = HomeworkSubmission::read_for(homework.get_id(), &user, &db)
599+ .await
600+ .unwrap()
601+ .unwrap();
602+ mine.delete(&db).await.unwrap().unwrap();
603+ assert_eq!(counters(&user, &db).await, (0, 0));
604+ // Floored: a second withdrawal (or a row from before the columns
605+ // existed) can never push either counter negative.
606+ assert!(
607+ HomeworkSubmission::read_for(homework.get_id(), &user, &db)
608+ .await
609+ .unwrap()
610+ .is_none()
611+ );
612+
613+ HomeworkSubmission::upsert(&homework, &user, None, &db)
614+ .await
615+ .unwrap()
616+ .unwrap();
617+ assert_eq!(counters(&user, &db).await, (1, 1));
618+ }
619+
620+ /// Lateness is judged against the homework's own deadline at hand-in, the
621+ /// same cut the one-time backfill used, and only the on-time counter sees
622+ /// it: a late hand-in is still a hand-in. Its withdrawal gives back only
623+ /// what it took.
624+ #[tokio::test]
625+ async fn a_late_submission_counts_as_submitted_but_not_on_time() {
626+ let db = crate::database::init_mem().await.unwrap();
627+ let punctual = a_homework(far_future(), &db).await;
628+ let overdue = a_homework(Timestamp::from_millis(1), &db).await;
629+ let user = a_student("ogrenci", &db).await;
630+
631+ HomeworkSubmission::upsert(&punctual, &user, None, &db)
632+ .await
633+ .unwrap()
634+ .unwrap();
635+ HomeworkSubmission::upsert(&overdue, &user, None, &db)
636+ .await
637+ .unwrap()
638+ .unwrap();
639+ assert_eq!(counters(&user, &db).await, (2, 1));
640+
641+ // Withdrawing the *late* one takes back only the submission, never the
642+ // on-time credit the punctual one earned β€” the zero floor would hide a
643+ // wrong subtraction here if the on-time count were sitting at zero.
644+ let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db)
645+ .await
646+ .unwrap()
647+ .unwrap();
648+ late.delete(&db).await.unwrap().unwrap();
649+ assert_eq!(counters(&user, &db).await, (1, 1));
650+
651+ // ... and withdrawing the punctual one gives back exactly that credit.
652+ let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db)
653+ .await
654+ .unwrap()
655+ .unwrap();
656+ kept.delete(&db).await.unwrap().unwrap();
657+ assert_eq!(counters(&user, &db).await, (0, 0));
658+ }
659+
660+ /// A row from before `counted_on_time` existed carries no verdict β€” it was
661+ /// credited by a comparison that left no trace, and cannot be given one
662+ /// retroactively. Withdrawing it falls back to that same comparison, so the
663+ /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did.
664+ ///
665+ /// Bite check: an absent verdict read as `false` rather than falling through
666+ /// (`??` binding the wrong side of the `<=`) leaves the last assertion at
667+ /// `(0, 1)` β€” on time above submitted, the shape the stored verdict exists
668+ /// to prevent.
669+ #[tokio::test]
670+ async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() {
671+ let db = crate::database::init_mem().await.unwrap();
672+ let punctual = a_homework(far_future(), &db).await;
673+ let overdue = a_homework(Timestamp::from_millis(1), &db).await;
674+ let user = a_student("ogrenci", &db).await;
675+
676+ HomeworkSubmission::upsert(&punctual, &user, None, &db)
677+ .await
678+ .unwrap()
679+ .unwrap();
680+ HomeworkSubmission::upsert(&overdue, &user, None, &db)
681+ .await
682+ .unwrap()
683+ .unwrap();
684+ assert_eq!(counters(&user, &db).await, (2, 1));
685+ // Aged into legacy rows: the counters keep the credit, the rows lose the
686+ // verdict β€” the exact state of every submission on an existing volume.
687+ db.query("UPDATE homework_submission UNSET counted_on_time")
688+ .await
689+ .unwrap()
690+ .check()
691+ .unwrap();
692+
693+ let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db)
694+ .await
695+ .unwrap()
696+ .unwrap();
697+ late.delete(&db).await.unwrap().unwrap();
698+ assert_eq!(counters(&user, &db).await, (1, 1));
699+
700+ let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db)
701+ .await
702+ .unwrap()
703+ .unwrap();
704+ kept.delete(&db).await.unwrap().unwrap();
705+ assert_eq!(counters(&user, &db).await, (0, 0));
706+ }
398 }707 }
src/domain/mod.rsmodified+1 -0
@@ -6,6 +6,7 @@ pub mod answer_image;
6 pub mod appointment;6 pub mod appointment;
7 pub mod appointment_slot;7 pub mod appointment_slot;
8 pub mod attendance;8 pub mod attendance;
9+pub mod badge;
9 pub mod bank_question;10 pub mod bank_question;
10 pub mod bank_question_image;11 pub mod bank_question_image;
11 pub mod board;12 pub mod board;
src/domain/pomodoro.rsmodified+120 -10
@@ -1,7 +1,10 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::POMODORO_SESSION_TABLE;3+use crate::constant::{
4+ POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE,
5+};
4 use crate::database::{Database, transaction_with_retry};6 use crate::database::{Database, transaction_with_retry};
7+use crate::domain::badge;
5 use crate::domain::monotonic_id::next_ulid;8 use crate::domain::monotonic_id::next_ulid;
6 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
7 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
@@ -116,23 +119,41 @@ impl PomodoroSession {
116 /// student did not cause; recording a zero-length stint keeps the session119 /// student did not cause; recording a zero-length stint keeps the session
117 /// count honest and its duration merely understated. Nothing downstream may120 /// count honest and its duration merely understated. Nothing downstream may
118 /// then read a negative duration (`ProfileStats::load` sums these).121 /// then read a negative duration (`ProfileStats::load` sums these).
122+ ///
123+ /// The lifetime badge counters on the user row move in this same
124+ /// transaction, so they can never count a stint the log does not hold (nor
125+ /// miss one it does), and a retried round re-applies nothing β€” the abort
126+ /// rolled the increment back with the rest. They are written field-scoped:
127+ /// the row also carries admin-owned data (`role`), which a whole-row save
128+ /// would silently revert. The clamped duration is the *same* expression the
129+ /// `CREATE` stores, so the counter can never take a negative summand and
130+ /// nothing downstream needs a floor. Only *finished* stints reach here β€” an
131+ /// open row is a `pomodoro_session` row and nothing else β€” and there is no
132+ /// student-facing delete for a stint, so neither counter ever decrements.
119 pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> {133 pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> {
120 let (mut result, mut errors) = transaction_with_retry(134 let (mut result, mut errors) = transaction_with_retry(
121 db,135 db,
122- "BEGIN TRANSACTION;136+ &format!(
137+ "BEGIN TRANSACTION;
123 LET $before = (DELETE $open RETURN BEFORE);138 LET $before = (DELETE $open RETURN BEFORE);
124- IF array::len($before) = 0 { THROW 'no_pomodoro_running' };139+ IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }};
125- CREATE $closed CONTENT {140+ UPDATE $usr SET
141+ {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1,
142+ {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)
143+ + (math::max([$before[0].started_at, $done]) - $before[0].started_at);
144+ CREATE $closed CONTENT {{
126 user: $before[0].user,145 user: $before[0].user,
127 started_at: $before[0].started_at,146 started_at: $before[0].started_at,
128 finished_at: math::max([$before[0].started_at, $done]),147 finished_at: math::max([$before[0].started_at, $done]),
129- };148+ }};
130- COMMIT TRANSACTION;",149+ COMMIT TRANSACTION;"
150+ ),
131 &[151 &[
132 (152 (
133 "open".into(),153 "open".into(),
134 PomodoroSessionId::open_for(user).record().into_value(),154 PomodoroSessionId::open_for(user).record().into_value(),
135 ),155 ),
156+ ("usr".into(), user.record().into_value()),
136 (157 (
137 "closed".into(),158 "closed".into(),
138 PomodoroSessionId::generate().record().into_value(),159 PomodoroSessionId::generate().record().into_value(),
@@ -154,10 +175,26 @@ impl PomodoroSession {
154 if let Some(error) = errors.drain().map(|(_, error)| error).next() {175 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
155 return Err(error.into());176 return Err(error.into());
156 }177 }
157- // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3.178+ // The `CREATE` is deliberately kept the last statement before `COMMIT`
158- let saved: Option<PomodoroSession> =179+ // (the counter `UPDATE` sits ahead of it β€” same transaction, so the
159- result.take::<Vec<PomodoroSession>>(3)?.into_iter().next();180+ // order is free), which is what lets its slot follow the statement
160- saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))181+ // count instead of a hand-kept number: `num_statements` counts `BEGIN`
182+ // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a
183+ // hand-kept slot caused.
184+ let slot = result.num_statements().saturating_sub(2);
185+ let saved: Option<PomodoroSession> = result
186+ .take::<Vec<PomodoroSession>>(slot)?
187+ .into_iter()
188+ .next();
189+ let saved =
190+ saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?;
191+ // A badge is a decoration on top of the stint: losing one to a
192+ // transient database error must never fail the finish, and the next
193+ // counter move re-runs this and heals it.
194+ if let Err(err) = badge::sync(user, db).await {
195+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
196+ }
197+ Ok(saved)
161 }198 }
162 199
163 /// Every session of `user`, newest first β€” the running one (if any)200 /// Every session of `user`, newest first β€” the running one (if any)
@@ -186,6 +223,79 @@ mod tests {
186 use super::*;223 use super::*;
187 use crate::database;224 use crate::database;
188 225
226+ /// A real `user` row: the counters land with `UPDATE`, which only ever
227+ /// touches a record that exists, so a fabricated id would silently store
228+ /// nothing. The tests above need no row β€” they read only the stint log.
229+ async fn a_user(db: &Database) -> UserId {
230+ let user = UserId::from_key(&Ulid::new().to_string());
231+ db.query("CREATE $usr SET username = $name, password_hash = 'x'")
232+ .bind(("usr", user.record()))
233+ .bind(("name", user.key().to_string()))
234+ .await
235+ .unwrap()
236+ .check()
237+ .unwrap();
238+ user
239+ }
240+
241+ /// `(finished_total, focus_ms_total)` re-read from the store β€” never off
242+ /// what `finish` returned, which proves nothing about what was written.
243+ async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
244+ let mut result = db
245+ .query(format!(
246+ "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0),
247+ ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr"
248+ ))
249+ .bind(("usr", user.record()))
250+ .await
251+ .unwrap()
252+ .check()
253+ .unwrap();
254+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
255+ let row = rows.into_iter().next().expect("the user row");
256+ (row[0], row[1])
257+ }
258+
259+ #[tokio::test]
260+ async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
261+ let db = database::init_mem().await.unwrap();
262+ let user = a_user(&db).await;
263+ assert_eq!(counters(&user, &db).await, (0, 0));
264+
265+ // An open stint is not a finished one: neither counter moves until it
266+ // closes.
267+ PomodoroSession::start(&user, &db).await.unwrap();
268+ assert_eq!(counters(&user, &db).await, (0, 0));
269+
270+ let mut focus_ms = 0;
271+ for _ in 0..2 {
272+ let closed = PomodoroSession::finish(&user, &db).await.unwrap();
273+ focus_ms +=
274+ closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis();
275+ PomodoroSession::start(&user, &db).await.unwrap();
276+ }
277+ // Three starts, two finishes β€” the third is still running.
278+ assert_eq!(counters(&user, &db).await, (2, focus_ms));
279+ }
280+
281+ #[tokio::test]
282+ async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
283+ let db = database::init_mem().await.unwrap();
284+ let user = a_user(&db).await;
285+
286+ PomodoroSession::start(&user, &db).await.unwrap();
287+ db.query("UPDATE $open SET started_at = $future")
288+ .bind(("open", PomodoroSessionId::open_for(&user).record()))
289+ .bind(("future", Timestamp::now().as_millis() + 3_600_000))
290+ .await
291+ .unwrap()
292+ .check()
293+ .unwrap();
294+
295+ PomodoroSession::finish(&user, &db).await.unwrap();
296+ assert_eq!(counters(&user, &db).await, (1, 0));
297+ }
298+
189 #[tokio::test]299 #[tokio::test]
190 async fn restart_replaces_the_open_session_and_finish_closes_it() {300 async fn restart_replaces_the_open_session_and_finish_closes_it() {
191 let db = database::init_mem().await.unwrap();301 let db = database::init_mem().await.unwrap();
src/domain/profile.rsmodified+72 -7
@@ -5,6 +5,7 @@ use surrealdb::types::SurrealValue;
5 5
6 use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN};6 use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN};
7 use crate::database::Database;7 use crate::database::Database;
8+use crate::domain::badge::{BadgeStat, BadgeStats};
8 use crate::domain::timestamp::Timestamp;9 use crate::domain::timestamp::Timestamp;
9 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
10 use crate::error::{AppError, ValidationError};11 use crate::error::{AppError, ValidationError};
@@ -143,6 +144,7 @@ pub struct ProfileStats {
143 pomodoro_focus_ms: i64,144 pomodoro_focus_ms: i64,
144 courses: i64,145 courses: i64,
145 classes: i64,146 classes: i64,
147+ totals: BadgeStats,
146 }148 }
147 149
148 impl ProfileStats {150 impl ProfileStats {
@@ -162,16 +164,29 @@ impl ProfileStats {
162 self.classes164 self.classes
163 }165 }
164 166
165- /// One query, and only one: `courses` and `classes` arrive from the caller,167+ /// The stored lifetime counters β€” the same numbers [`crate::domain::badge`]
166- /// which already holds them as the `total` of the paged class and course168+ /// decides an award from, so a profile read can check the shelf without a
167- /// readers it ran for the profile's own blocks β€” re-counting them here169+ /// second load of them.
168- /// would be two extra reads for numbers already in hand.170+ pub fn get_totals(&self) -> &BadgeStats {
171+ &self.totals
172+ }
173+
174+ /// One round trip, and only one: `courses` and `classes` arrive from the
175+ /// caller, which already holds them as the `total` of the paged class and
176+ /// course readers it ran for the profile's own blocks β€” re-counting them
177+ /// here would be two extra reads for numbers already in hand.
169 ///178 ///
170 /// The pomodoro aggregate rides the per-user index, so it is a lookup and179 /// The pomodoro aggregate rides the per-user index, so it is a lookup and
171 /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a180 /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a
172 /// bare truthiness test would also drop a stint that finished at epoch. An181 /// bare truthiness test would also drop a stint that finished at epoch. An
173 /// open stint contributes to neither the count nor the sum β€” unfinished182 /// open stint contributes to neither the count nor the sum β€” unfinished
174 /// focus has no honest duration to add.183 /// focus has no honest duration to add.
184+ ///
185+ /// The lifetime counters ride along as a second statement in the *same*
186+ /// query rather than a [`BadgeStats::load`] call, which would be a second
187+ /// round trip for one record lookup. It repeats that projection β€” `?? 0`
188+ /// per column, because the columns are `option<int>` and a row predating
189+ /// them carries none β€” so the two must move together if the shape changes.
175 pub async fn load(190 pub async fn load(
176 user: &UserId,191 user: &UserId,
177 courses: i64,192 courses: i64,
@@ -179,17 +194,35 @@ impl ProfileStats {
179 db: &Database,194 db: &Database,
180 ) -> Result<ProfileStats, AppError> {195 ) -> Result<ProfileStats, AppError> {
181 let mut result = db196 let mut result = db
182- .query(197+ .query(format!(
183 "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms198 "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms
184- FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL",199+ FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL;
185- )200+ SELECT ({homework_submitted} ?? 0) AS homework_submitted,
201+ ({homework_on_time} ?? 0) AS homework_on_time,
202+ ({exam_sat} ?? 0) AS exam_sat,
203+ ({pomodoro_finished} ?? 0) AS pomodoro_finished,
204+ ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms
205+ FROM $usr;",
206+ homework_submitted = BadgeStat::HomeworkSubmitted.field(),
207+ homework_on_time = BadgeStat::HomeworkOnTime.field(),
208+ exam_sat = BadgeStat::ExamSat.field(),
209+ pomodoro_finished = BadgeStat::PomodoroFinished.field(),
210+ pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(),
211+ ))
186 .bind(("usr", user.record()))212 .bind(("usr", user.record()))
187 .await?213 .await?
188 .check()?;214 .check()?;
189 // `GROUP ALL` yields no row at all when nothing matched β€” that is the215 // `GROUP ALL` yields no row at all when nothing matched β€” that is the
190 // zero case, not a missing one.216 // zero case, not a missing one.
191 let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next();217 let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next();
218+ // A vanished user row reads as five zeros, same as a fresh account.
219+ let totals = result
220+ .take::<Vec<BadgeStats>>(1)?
221+ .into_iter()
222+ .next()
223+ .unwrap_or_default();
192 Ok(ProfileStats {224 Ok(ProfileStats {
225+ totals,
193 pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions),226 pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions),
194 // Floored at zero: a stint stamped by a wall clock that stepped227 // Floored at zero: a stint stamped by a wall clock that stepped
195 // backwards mid-session sums as negative time, and "you focused for228 // backwards mid-session sums as negative time, and "you focused for
@@ -308,6 +341,38 @@ mod tests {
308 // The passed-in counts survive untouched.341 // The passed-in counts survive untouched.
309 assert_eq!(stats.get_courses(), 3);342 assert_eq!(stats.get_courses(), 3);
310 assert_eq!(stats.get_classes(), 1);343 assert_eq!(stats.get_classes(), 1);
344+ // No user row at all β€” the lifetime counters still read as zeros.
345+ assert_eq!(stats.get_totals().get_homework_submitted(), 0);
346+ assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0);
347+ }
348+
349+ /// The second statement of the same query: the stored counters, straight off
350+ /// the user row, with the columns an older row is missing read as zero.
351+ #[tokio::test]
352+ async fn lifetime_totals_ride_the_same_query() {
353+ let db = crate::database::init_mem().await.unwrap();
354+ let user = UserId::from_key(&ulid::Ulid::new().to_string());
355+ db.query(format!(
356+ "CREATE $usr SET username = $name, password_hash = 'x',
357+ {} = 4, {} = 3",
358+ crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD,
359+ crate::constant::EXAM_SAT_TOTAL_FIELD,
360+ ))
361+ .bind(("usr", user.record()))
362+ .bind(("name", user.key().to_string()))
363+ .await
364+ .unwrap()
365+ .check()
366+ .unwrap();
367+
368+ let totals = ProfileStats::load(&user, 0, 0, &db).await.unwrap();
369+ let totals = totals.get_totals();
370+ assert_eq!(totals.get_homework_submitted(), 4);
371+ assert_eq!(totals.get_exam_sat(), 3);
372+ // Never written on this row: absent must read as 0, not as an error.
373+ assert_eq!(totals.get_homework_on_time(), 0);
374+ assert_eq!(totals.get_pomodoro_finished(), 0);
375+ assert_eq!(totals.get_pomodoro_focus_ms(), 0);
311 }376 }
312 377
313 #[tokio::test]378 #[tokio::test]
src/lib.rsmodified+1 -1
@@ -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 no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `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 no certificate configured the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup. `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 a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. 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 a claimed job rather than an in-process task: whichever backend process holds a `chat.reply` worker picks it up (within ~200ms), dispatches it and stamps the result, so a restart no longer strands an accepted turn and a claim its owner never finishes is retried after 90 seconds. 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). 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`; 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), and stats computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts; `0`, never `null`). 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, and `stats.courses` stays the owner's true total either way. `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). 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`; 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 nine-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 five are stored lifetime tallies maintained at write time (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total`, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), so a tally can outlive the rows behind it β€” a deleted exam does not un-sit it; all nine read `0`, never `null`. **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}`, 13 badges, `stat` being the API's name for the counter rather than the column it is stored in), 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, and `stats.courses` stays the owner's true total either way. `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, 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 teacher demoted after publishing leaves inert slots: they drop 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, 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 teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),
src/migration_sql.rsmodified+113 -0
@@ -65,6 +65,16 @@ pub const MIGRATION: &str = "
65 DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option<int>;65 DEFINE FIELD IF NOT EXISTS avatar_size ON user TYPE option<int>;
66 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;66 DEFINE FIELD IF NOT EXISTS chatbot_thread_count ON user TYPE option<int>;
67 DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>;67 DEFINE FIELD IF NOT EXISTS board_count ON user TYPE option<int>;
68+ -- Lifetime badge counters (2026-08-04). Not caps and never released: each
69+ -- counts something the student *did*, so a badge earned off one stands even
70+ -- if the counter later drops. `option<int>` and absent reads as zero, so a
71+ -- row written before them needs no repair to be *readable* β€” but it does
72+ -- need one to be *right*, which is what the BACKFILL seeding is for.
73+ DEFINE FIELD IF NOT EXISTS homework_submitted_total ON user TYPE option<int>;
74+ DEFINE FIELD IF NOT EXISTS homework_on_time_total ON user TYPE option<int>;
75+ DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option<int>;
76+ DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option<int>;
77+ DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option<int>;
68 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;78 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
69 79
70 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;80 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
@@ -613,6 +623,18 @@ pub const MIGRATION: &str = "
613 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;623 DEFINE FIELD IF NOT EXISTS submitted_at ON homework_submission TYPE int READONLY;
614 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;624 DEFINE FIELD IF NOT EXISTS updated_at ON homework_submission TYPE int;
615 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;625 DEFINE FIELD IF NOT EXISTS file_count ON homework_submission TYPE option<int>;
626+ -- The on-time verdict the badge counter was actually credited with, stamped
627+ -- at the first hand-in and never re-judged. `due_at` is mutable (a teacher
628+ -- moves a deadline with `PATCH /homework/{id}`), so re-deriving the verdict
629+ -- at withdrawal read a *different* deadline than the credit did and gave
630+ -- back the wrong thing in both directions β€” extend the deadline after a late
631+ -- hand-in and the withdrawal debited an on-time credit that was never given;
632+ -- pull it back after a punctual one and it debited nothing, leaving on_time
633+ -- above submitted. `option<>` because every row predating 2026-08-04 has no
634+ -- stored verdict and cannot be given one for a credit that already happened:
635+ -- those fall back to the old comparison (see
636+ -- [`crate::domain::homework_submission::HomeworkSubmission::delete`]).
637+ DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option<bool>;
616 -- The grade that froze this submission, absent while it is still open. The638 -- The grade that froze this submission, absent while it is still open. The
617 -- freeze used to be a cross-table read (does a homework_result exist?)639 -- freeze used to be a cross-table read (does a homework_result exist?)
618 -- followed by a write here, which no lock can hold across replicas; the640 -- followed by a write here, which no lock can hold across replicas; the
@@ -812,6 +834,20 @@ pub const MIGRATION: &str = "
812 DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student;834 DEFINE INDEX IF NOT EXISTS payment_ledger_student ON payment_ledger FIELDS student;
813 DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source;835 DEFINE INDEX IF NOT EXISTS payment_ledger_source ON payment_ledger FIELDS source;
814 836
837+ -- One row per badge a user has earned, keyed `{user}_{badge}` so the award
838+ -- is written by an UPSERT that can never double (domain::badge). `earned_at`
839+ -- is `option<int>` because that is what makes the stamp write-once: the
840+ -- UPSERT carries `WHERE earned_at = NONE`, so a re-sync of a badge already
841+ -- held leaves the original date standing. Awards are permanent β€” nothing
842+ -- deletes a row here β€” so the table needs no repair and no BACKFILL.
843+ DEFINE TABLE IF NOT EXISTS badge_award SCHEMAFULL;
844+ DEFINE FIELD IF NOT EXISTS user ON badge_award TYPE record<user>;
845+ DEFINE FIELD IF NOT EXISTS badge ON badge_award TYPE string;
846+ DEFINE FIELD IF NOT EXISTS earned_at ON badge_award TYPE option<int>;
847+ -- A plain field index, never `FIELDS user[*]`: the per-element form is used
848+ -- by the planner and then returns zero rows (see the `course.teachers` note).
849+ DEFINE INDEX IF NOT EXISTS badge_award_user ON badge_award FIELDS user;
850+
815 -- Reference counters, one row per *name* the settings offer, keyed by the851 -- Reference counters, one row per *name* the settings offer, keyed by the
816 -- name itself (2026-07-27). They are how 'a kind nothing is graded under852 -- name itself (2026-07-27). They are how 'a kind nothing is graded under
817 -- may be removed' survives a second replica: the guard used to be a853 -- may be removed' survives a second replica: the guard used to be a
@@ -1169,6 +1205,83 @@ pub const BACKFILL: &str = "
1169 };1205 };
1170 UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000;1206 UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000;
1171 };1207 };
1208+
1209+ -- The badge counters, seeded from the history that already exists
1210+ -- (2026-08-04). Badges are earned off stored lifetime totals, and every
1211+ -- account on an existing volume predates the columns β€” so starting them all
1212+ -- at zero would not merely lose a number, it would mis-award every student
1213+ -- permanently: someone who really handed in 40 homeworks would owe 10 *more*
1214+ -- than a new account does to reach the same badge. The counts below are the
1215+ -- rows that exist, so the seed says exactly what the student did.
1216+ --
1217+ -- Marked one-time, like the board-roster sweep above and unlike every other
1218+ -- backfill in this file β€” but for the opposite reason. Those recompute a
1219+ -- number the live system does not own; these columns are maintained by the
1220+ -- request path from here on (a submission increments as it lands), so a
1221+ -- second recount would not converge, it would *overwrite* everything earned
1222+ -- since boot. The mark is the only thing that makes that safe.
1223+ --
1224+ -- The reset is inside the mark and comes first, so the whole block is
1225+ -- recompute-from-scratch: a boot killed mid-seed writes no mark and the next
1226+ -- one redoes it from a clean slate, and an operator who clears the mark to
1227+ -- force a re-seed gets the counts as they stand rather than a stale high
1228+ -- water mark. It is the one place a *zero pass* is right: it writes over
1229+ -- whatever a half-finished pass left, and it runs exactly once per volume.
1230+ --
1231+ -- Every counter here has to *mean* what the request path means, or a
1232+ -- pre-existing student diverges from a new one forever. So the on-time cut
1233+ -- is `submitted_at <= due_at`, the stamp both live sites use: the create
1234+ -- credits on the first hand-in and the delete debits by `submitted_at`, so
1235+ -- judging the seed by `updated_at` would let a withdrawal decrement a
1236+ -- submission the seed never credited and drive the counter *below* the
1237+ -- truth β€” and `touch()` moves `updated_at` on every file add or delete, so
1238+ -- merely attaching a file after the deadline would have done it. A dangling
1239+ -- `homework` link still falls out of the pass rather than counting as on
1240+ -- time (the traversal yields no value, so the comparison fails).
1241+ --
1242+ -- The focus sum floors *per row*, like the live close does
1243+ -- (`math::max([started_at, done])`), not per user: a legacy stint written
1244+ -- with a backwards clock is negative, and flooring the total instead would
1245+ -- let one such row swallow the real stints beside it. `math::max` *around*
1246+ -- the aggregate is the spelling that is rejected ('nested aggregate
1247+ -- functions are not supported'); inside it, per row, is fine.
1248+ --
1249+ -- Two counters the seed cannot make whole, for the same reason:
1250+ -- `exam_sat_total` (deleting an exam or a course deletes its `exam_attempt`
1251+ -- rows) and `homework_submitted_total` (deleting a homework cascades its
1252+ -- `homework_submission` rows away). Neither delete decrements β€” deliberate,
1253+ -- a lifetime 'did it' tally must not shrink because a teacher tidied up β€” so
1254+ -- the live count stands where the request path left it while a re-seed of
1255+ -- the same volume would read *lower*: the rows do not exist to be counted.
1256+ -- Do not 'repair' this by making the live path decrement; that breaks the
1257+ -- tally for everyone to patch history for a few.
1258+ --
1259+ -- `counted_on_time` is stamped here too, for every row the pass looks at and
1260+ -- by the very same cut, so a submission that predates this seed debits at
1261+ -- withdrawal exactly what the seed credited it. Absolute like every SET
1262+ -- below, so it converges on a forced re-seed.
1263+ IF array::len((SELECT VALUE id FROM migration_mark:profile_counters)) = 0 {
1264+ UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0,
1265+ exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0;
1266+ FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) {
1267+ UPDATE $row.user SET homework_submitted_total = $row.n;
1268+ };
1269+ FOR $row IN ((SELECT user, count() AS n FROM homework_submission
1270+ WHERE submitted_at <= homework.due_at GROUP BY user) ?? []) {
1271+ UPDATE $row.user SET homework_on_time_total = $row.n;
1272+ };
1273+ UPDATE homework_submission SET counted_on_time = submitted_at <= homework.due_at;
1274+ FOR $row IN ((SELECT user, count() AS n FROM exam_attempt GROUP BY user) ?? []) {
1275+ UPDATE $row.user SET exam_sat_total = $row.n;
1276+ };
1277+ FOR $row IN ((SELECT user, count() AS sessions,
1278+ math::sum(math::max([finished_at - started_at, 0])) AS focus_ms
1279+ FROM pomodoro_session WHERE finished_at != NONE GROUP BY user) ?? []) {
1280+ UPDATE $row.user SET pomodoro_finished_total = $row.sessions,
1281+ pomodoro_focus_ms_total = $row.focus_ms;
1282+ };
1283+ UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000;
1284+ };
1172 ";1285 ";
1173 1286
1174 /// The migration batches, in the order a boot applies them β€” and the *only*1287 /// The migration batches, in the order a boot applies them β€” and the *only*
src/web/homework.rsmodified+30 -4
@@ -17,6 +17,7 @@ use utoipa_axum::routes;
17 17
18 use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};18 use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
19 use crate::database::Database;19 use crate::database::Database;
20+use crate::domain::badge;
20 use crate::domain::course::{Course, CourseId};21 use crate::domain::course::{Course, CourseId};
21 use crate::domain::enrollment::Enrollment;22 use crate::domain::enrollment::Enrollment;
22 use crate::domain::exam_result::Mark;23 use crate::domain::exam_result::Mark;
@@ -654,12 +655,17 @@ async fn submit(
654 .await?655 .await?
655 .is_some();656 .is_some();
656 let Some(submission) =657 let Some(submission) =
657- HomeworkSubmission::upsert(homework.get_id(), user.get_id(), text, &st.db).await?658+ HomeworkSubmission::upsert(&homework, user.get_id(), text, &st.db).await?
658 else {659 else {
659 return Err(AppError::Conflict(660 return Err(AppError::Conflict(
660 "this homework has been graded β€” ask the teacher to remove the grade before editing your submission",661 "this homework has been graded β€” ask the teacher to remove the grade before editing your submission",
661 ));662 ));
662 };663 };
664+ // Only a first hand-in moved a counter, so only a first hand-in can have
665+ // earned anything β€” an edit re-runs nothing.
666+ if !existed {
667+ award_badges(user.get_id(), &st.db).await;
668+ }
663 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;669 let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?;
664 let status = if existed {670 let status = if existed {
665 StatusCode::OK671 StatusCode::OK
@@ -760,12 +766,26 @@ async fn delete_submission(
760 "this homework has been graded β€” ask the teacher to remove the grade before deleting your submission",766 "this homework has been graded β€” ask the teacher to remove the grade before deleting your submission",
761 ));767 ));
762 }768 }
769+ // The counters just came down; a badge already earned stays earned (`sync`
770+ // only ever adds), so this is here to keep the award rows in step with the
771+ // *next* submission rather than to take anything back.
772+ award_badges(user.get_id(), &st.db).await;
763 for file in &files {773 for file in &files {
764 remove_blob(&st.files_path, file.get_file()).await;774 remove_blob(&st.files_path, file.get_file()).await;
765 }775 }
766 Ok(StatusCode::NO_CONTENT)776 Ok(StatusCode::NO_CONTENT)
767 }777 }
768 778
779+/// Bring the student's badge awards up to date after a submission moved their
780+/// counters. Never fails the request it follows: a badge is a decoration on top
781+/// of the work, and losing one to a transient database error is not worth
782+/// refusing a hand-in over β€” the next counter move re-runs this and heals it.
783+async fn award_badges(user: &UserId, db: &Database) {
784+ if let Err(err) = badge::sync(user, db).await {
785+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
786+ }
787+}
788+
769 /// Serve a submission file as a download β€” `Content-Disposition: attachment`,789 /// Serve a submission file as a download β€” `Content-Disposition: attachment`,
770 /// never inline. Homework files take *any* content type (documents, photos β€”790 /// never inline. Homework files take *any* content type (documents, photos β€”
771 /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only,791 /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only,
@@ -857,9 +877,15 @@ async fn upload_submission_file(
857 let submission =877 let submission =
858 match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? {878 match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? {
859 Some(existing) => existing,879 Some(existing) => existing,
860- None => HomeworkSubmission::upsert(homework.get_id(), user.get_id(), None, &st.db)880+ // A photo-only hand-in is a hand-in: it creates the row, so it moves
861- .await?881+ // the counters, so it earns badges exactly as a text submit does.
862- .ok_or(GRADED)?,882+ None => {
883+ let created = HomeworkSubmission::upsert(&homework, user.get_id(), None, &st.db)
884+ .await?
885+ .ok_or(GRADED)?;
886+ award_badges(user.get_id(), &st.db).await;
887+ created
888+ }
863 };889 };
864 890
865 // Blob first, row second β€” a stored row always points at a real blob. The891 // Blob first, row second β€” a stored row always points at a real blob. The
src/web/limits.rsmodified+41 -0
@@ -74,6 +74,36 @@ struct UserLimits {
74 session_duration_days: i64,74 session_duration_days: i64,
75 }75 }
76 76
77+/// The auto-earned badge catalog. A group like every other key here, so a
78+/// client can walk this response uniformly; the catalog itself is the one
79+/// field inside.
80+#[derive(Serialize, ToSchema)]
81+struct BadgeLimits {
82+ /// Every badge the system can auto-award, in catalog order. Hardcoded, so
83+ /// like everything else here it moves only with a deploy.
84+ catalog: Vec<BadgeLimit>,
85+}
86+
87+/// One badge in the auto-earned catalog. The id is the whole contract: a
88+/// profile hands back ids and nothing else, and the label and icon behind one
89+/// live in the client, exactly as they do for a role or a course kind.
90+#[derive(Serialize, ToSchema)]
91+struct BadgeLimit {
92+ /// Stable id, never reused for another meaning. A retired badge simply
93+ /// stops appearing here.
94+ #[schema(example = "homework_submitted_10")]
95+ id: &'static str,
96+ /// The lifetime counter it reads β€” badges sharing one form a ladder. An
97+ /// API-side name, not the column it is stored in, so storage can be
98+ /// renamed without moving this contract.
99+ #[schema(example = "homework_submitted")]
100+ stat: &'static str,
101+ /// Counter value that earns it. Awards are permanent: a counter that later
102+ /// falls back below this does not take the badge away.
103+ #[schema(example = 10)]
104+ threshold: i64,
105+}
106+
77 /// Note bodies and their attachments.107 /// Note bodies and their attachments.
78 #[derive(Serialize, ToSchema)]108 #[derive(Serialize, ToSchema)]
79 struct NoteLimits {109 struct NoteLimits {
@@ -368,6 +398,7 @@ struct RequestLimits {
368 #[derive(Serialize, ToSchema)]398 #[derive(Serialize, ToSchema)]
369 struct LimitsResponse {399 struct LimitsResponse {
370 user: UserLimits,400 user: UserLimits,
401+ badges: BadgeLimits,
371 note: NoteLimits,402 note: NoteLimits,
372 file: FileLimits,403 file: FileLimits,
373 message: MessageLimits,404 message: MessageLimits,
@@ -411,6 +442,16 @@ impl LimitsResponse {
411 palette_color_len: PALETTE_COLOR_LEN,442 palette_color_len: PALETTE_COLOR_LEN,
412 session_duration_days: SESSION_DURATION_DAYS,443 session_duration_days: SESSION_DURATION_DAYS,
413 },444 },
445+ badges: BadgeLimits {
446+ catalog: BADGES
447+ .iter()
448+ .map(|(id, stat, threshold)| BadgeLimit {
449+ id,
450+ stat: stat.as_str(),
451+ threshold: *threshold,
452+ })
453+ .collect(),
454+ },
414 note: NoteLimits {455 note: NoteLimits {
415 max_title_len: MAX_NOTE_TITLE_LEN,456 max_title_len: MAX_NOTE_TITLE_LEN,
416 max_content_len: MAX_NOTE_CONTENT_LEN,457 max_content_len: MAX_NOTE_CONTENT_LEN,
src/web/users.rsmodified+88 -1
@@ -12,6 +12,7 @@ use crate::constant::{
12 MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES,12 MAX_MAX_FILE_BYTES, MAX_PROFILE_CLASSES, MAX_PROFILE_COURSES, UPLOAD_BODY_OVERHEAD_BYTES,
13 };13 };
14 use crate::database::Database;14 use crate::database::Database;
15+use crate::domain::badge::{self, BadgeAward};
15 use crate::domain::class_group::{ClassGroup, ClassGroupId};16 use crate::domain::class_group::{ClassGroup, ClassGroupId};
16 use crate::domain::class_member::ClassMember;17 use crate::domain::class_member::ClassMember;
17 use crate::domain::course::Course;18 use crate::domain::course::Course;
@@ -689,9 +690,26 @@ struct ProfileResponse {
689 /// block, the owner and manager+ see it whole. The full list is at690 /// block, the owner and manager+ see it whole. The full list is at
690 /// `GET /courses/me`.691 /// `GET /courses/me`.
691 courses: Vec<ProfileCourseRef>,692 courses: Vec<ProfileCourseRef>,
693+ /// Every badge this account has earned, oldest first. Ids and stamps only β€”
694+ /// the label and the icon are the client's, keyed by id off the `badges`
695+ /// catalog at `GET /limits`.
696+ badges: Vec<ProfileBadge>,
692 stats: ProfileStatsResponse,697 stats: ProfileStatsResponse,
693 }698 }
694 699
700+/// One earned badge. Permanent: once it appears here it never leaves, even if
701+/// the counter behind it falls back below the threshold that earned it.
702+#[derive(Serialize, ToSchema)]
703+struct ProfileBadge {
704+ /// A catalog id from `GET /limits` β€” `badges.catalog[].id`.
705+ #[schema(example = "pomodoro_finished_10")]
706+ id: String,
707+ /// When it was *first* earned, UTC unix-milliseconds. Later syncs never
708+ /// move it.
709+ #[schema(example = 1_759_000_000_000_i64)]
710+ earned_at: i64,
711+}
712+
695 /// What a stored avatar is, without its bytes.713 /// What a stored avatar is, without its bytes.
696 #[derive(Serialize, ToSchema)]714 #[derive(Serialize, ToSchema)]
697 struct ProfileAvatar {715 struct ProfileAvatar {
@@ -729,6 +747,14 @@ struct ProfileCourseRef {
729 747
730 /// The motivational counters. Derived, never settable, and never `null`: an748 /// The motivational counters. Derived, never settable, and never `null`: an
731 /// account with no rows behind a counter reads a true `0`.749 /// account with no rows behind a counter reads a true `0`.
750+///
751+/// Two kinds live here. The first four are **computed at read time** from the
752+/// rows that exist right now, so deleting the rows moves them down. The five
753+/// `*_total` ones are **stored lifetime counters**, incremented as the work
754+/// happens and never recomputed β€” they can therefore outlive the rows behind
755+/// them (an exam deleted by its teacher still counts as sat), which is exactly
756+/// why a badge earned off them stays earned. Each is named for a `stat` of the
757+/// badge catalog at `GET /limits`, plus `_total`.
732 #[derive(Serialize, ToSchema)]758 #[derive(Serialize, ToSchema)]
733 struct ProfileStatsResponse {759 struct ProfileStatsResponse {
734 /// Finished pomodoro stints; an open one counts for nothing.760 /// Finished pomodoro stints; an open one counts for nothing.
@@ -739,6 +765,18 @@ struct ProfileStatsResponse {
739 courses: i64,765 courses: i64,
740 /// Every class behind the `classes` block, not just the embedded window.766 /// Every class behind the `classes` block, not just the embedded window.
741 classes: i64,767 classes: i64,
768+ /// Lifetime homework hand-ins. Withdrawing a submission gives one back;
769+ /// editing one moves nothing.
770+ homework_submitted_total: i64,
771+ /// Lifetime hand-ins made before their deadline, judged at hand-in.
772+ homework_on_time_total: i64,
773+ /// Lifetime exam sittings, counted once per attempt β€” retakes included, and
774+ /// deleting the exam does not take them back.
775+ exam_sat_total: i64,
776+ /// Lifetime finished pomodoro stints.
777+ pomodoro_finished_total: i64,
778+ /// Lifetime focused milliseconds.
779+ pomodoro_focus_ms_total: i64,
742 }780 }
743 781
744 /// Build one profile as `viewer` may see it. The course block is chosen off the782 /// Build one profile as `viewer` may see it. The course block is chosen off the
@@ -796,6 +834,7 @@ async fn profile_of(
796 // Both totals are the full counts, not the windowed ones β€” the blocks are a834 // Both totals are the full counts, not the windowed ones β€” the blocks are a
797 // preview, the stats are the truth.835 // preview, the stats are the truth.
798 let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?;836 let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?;
837+ let badges = badges_of(st, id, &stats).await?;
799 Ok(ProfileResponse {838 Ok(ProfileResponse {
800 id: id.key().to_string(),839 id: id.key().to_string(),
801 username: user.get_username().as_str().to_string(),840 username: user.get_username().as_str().to_string(),
@@ -828,15 +867,61 @@ async fn profile_of(
828 kind: course.get_kind().as_str().to_string(),867 kind: course.get_kind().as_str().to_string(),
829 })868 })
830 .collect(),869 .collect(),
870+ badges: badges
871+ .iter()
872+ .map(|award| ProfileBadge {
873+ id: award.get_badge().to_string(),
874+ earned_at: award.get_earned_at().as_millis(),
875+ })
876+ .collect(),
831 stats: ProfileStatsResponse {877 stats: ProfileStatsResponse {
832 pomodoro_sessions: stats.get_pomodoro_sessions(),878 pomodoro_sessions: stats.get_pomodoro_sessions(),
833 pomodoro_focus_ms: stats.get_pomodoro_focus_ms(),879 pomodoro_focus_ms: stats.get_pomodoro_focus_ms(),
834 courses: stats.get_courses(),880 courses: stats.get_courses(),
835 classes: stats.get_classes(),881 classes: stats.get_classes(),
882+ homework_submitted_total: stats.get_totals().get_homework_submitted(),
883+ homework_on_time_total: stats.get_totals().get_homework_on_time(),
884+ exam_sat_total: stats.get_totals().get_exam_sat(),
885+ pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(),
886+ pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(),
836 },887 },
837 })888 })
838 }889 }
839 890
891+/// The owner's earned badges, and the backstop that keeps them honest.
892+///
893+/// Every write that moves a counter syncs the badges behind it, so in the
894+/// steady state the earned set holds nothing the award rows do not already
895+/// carry and this is one read and **no write at all**. Only a threshold crossed
896+/// by a path whose sync was lost β€” a transient database error, which those
897+/// callers log and swallow on purpose β€” leaves a gap, and that heals here on
898+/// the next profile read of that account.
899+///
900+/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has
901+/// since fallen back below its threshold leaves the badge standing. The sync's
902+/// own error is logged and dropped, and the awards already read are served β€”
903+/// a decoration may not fail the profile it decorates.
904+async fn badges_of(
905+ st: &AppState,
906+ user: &UserId,
907+ stats: &ProfileStats,
908+) -> Result<Vec<BadgeAward>, AppError> {
909+ let awards = BadgeAward::list_for(user, &st.db).await?;
910+ let complete = badge::earned(stats.get_totals())
911+ .iter()
912+ .all(|id| awards.iter().any(|award| award.get_badge() == *id));
913+ if complete {
914+ return Ok(awards);
915+ }
916+ if let Err(err) = badge::sync(user, &st.db).await {
917+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
918+ return Ok(awards);
919+ }
920+ // Re-read so the badge just healed appears on *this* response, stamp and
921+ // all, rather than only on the next one.
922+ BadgeAward::list_for(user, &st.db).await
923+}
924+
840 /// The profile gate: any authenticated account reads any profile β€” except a925 /// The profile gate: any authenticated account reads any profile β€” except a
841 /// parent, who is an observer of their own children and of nobody else. The926 /// parent, who is an observer of their own children and of nobody else. The
842 /// link alone is not the grant either; [`ensure_can_observe`] re-reads the927 /// link alone is not the grant either; [`ensure_can_observe`] re-reads the
@@ -878,7 +963,9 @@ async fn my_profile(
878 }963 }
879 964
880 /// One user's public profile: display name, bio, avatar meta, their class and965 /// One user's public profile: display name, bio, avatar meta, their class and
881-/// course blocks, and the motivational counters. Readable by every966+/// course blocks, the badges they have earned, and the motivational counters.
967+/// Badges carry an id and the instant they were first earned; their labels and
968+/// icons come from the `badges` catalog at `GET /limits`. Readable by every
882 /// authenticated account β€” except a parent, who reads only their own and their969 /// authenticated account β€” except a parent, who reads only their own and their
883 /// linked students'. Never carries email, phone, or birth date; those stay on970 /// linked students'. Never carries email, phone, or birth date; those stay on
884 /// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped971 /// `GET /users/{id}` (admin) and `GET /auth/me`. The embedded blocks are capped
tests/regress_profile.rsmodified+553 -3
@@ -12,8 +12,13 @@ mod common;
12 12
13 use axum::Router;13 use axum::Router;
14 use axum::http::StatusCode;14 use axum::http::StatusCode;
15-use common::{app_and_db, create_course, enroll, login, login_as, me_id, send, set_role};15+use common::{
16+ app_and_db, create_course, create_exam_with, create_homework, create_subject, enroll, id_of,
17+ login, login_as, me_id, send, set_role,
18+};
16 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};19 use hezarfen_backend::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN};
20+use hezarfen_backend::database::Database;
21+use hezarfen_backend::domain::timestamp::Timestamp;
17 use serde_json::{Value, json};22 use serde_json::{Value, json};
18 23
19 const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary";24 const BOUNDARY: &str = "multipart/form-data; boundary=hezarfen-test-boundary";
@@ -102,13 +107,16 @@ async fn a_peer_profile_carries_no_contact_fields() {
102 let seen = profile(&app, &peer, &ada_id).await;107 let seen = profile(&app, &peer, &ada_id).await;
103 assert_eq!(seen.status, StatusCode::OK, "{}", seen.body);108 assert_eq!(seen.status, StatusCode::OK, "{}", seen.body);
104 assert_eq!(seen.body["username"], "ada");109 assert_eq!(seen.body["username"], "ada");
105- for private in ["email", "phone", "birth_date", "badges"] {110+ for private in ["email", "phone", "birth_date"] {
106 assert!(111 assert!(
107 seen.body.get(private).is_none(),112 seen.body.get(private).is_none(),
108 "{private} must not ride on a profile: {}",113 "{private} must not ride on a profile: {}",
109 seen.body114 seen.body
110 );115 );
111 }116 }
117+ // Badges are public, unlike the contact fields β€” and an account that has
118+ // earned none says so with an empty list, never with a missing key.
119+ assert_eq!(seen.body["badges"], json!([]), "{}", seen.body);
112 }120 }
113 121
114 /// A parent is an observer of their own children and of nobody else: the122 /// A parent is an observer of their own children and of nobody else: the
@@ -238,6 +246,75 @@ async fn display_name_falls_back_to_the_legal_name_then_null() {
238 );246 );
239 }247 }
240 248
249+/// The read-time badge backstop, and the write it must not make.
250+///
251+/// A counter is moved behind the API's back β€” exactly what a lost `badge::sync`
252+/// leaves behind, since every counter writer logs and swallows that error. The
253+/// first profile read must heal it and serve the badges with their stamps; the
254+/// second must serve the identical shelf and write *nothing*, which is what the
255+/// `badge_award` write probe counts. Zero extra writes on a read is the whole
256+/// point: a profile is a read endpoint.
257+#[tokio::test]
258+async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
259+ let (app, db) = app_and_db().await;
260+ let ada = login(&app, "ada").await;
261+ let ada_id = me_id(&app, &ada).await;
262+
263+ // Fires inside any write to the award table, so a write this read should
264+ // not make cannot hide behind an unchanged-looking response.
265+ db.query(
266+ "DEFINE EVENT award_write ON badge_award WHEN true THEN {
267+ UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1;
268+ };",
269+ )
270+ .await
271+ .unwrap()
272+ .check()
273+ .unwrap();
274+ let writes = || async {
275+ db.query("SELECT VALUE n FROM award_write_probe:n")
276+ .await
277+ .unwrap()
278+ .take::<Vec<i64>>(0)
279+ .unwrap()
280+ .first()
281+ .copied()
282+ .unwrap_or(0)
283+ };
284+
285+ db.query("UPDATE type::record('user', $id) SET homework_submitted_total = 10")
286+ .bind(("id", ada_id.clone()))
287+ .await
288+ .unwrap()
289+ .check()
290+ .unwrap();
291+
292+ let healed = profile(&app, &ada, &ada_id).await;
293+ assert_eq!(healed.status, StatusCode::OK, "{}", healed.body);
294+ let ids: Vec<&str> = healed.body["badges"]
295+ .as_array()
296+ .expect("badges array")
297+ .iter()
298+ .map(|badge| badge["id"].as_str().expect("badge id"))
299+ .collect();
300+ assert_eq!(ids, vec!["homework_submitted_1", "homework_submitted_10"]);
301+ assert!(
302+ healed.body["badges"][0]["earned_at"].as_i64().unwrap_or(0) > 0,
303+ "a badge carries when it was earned: {}",
304+ healed.body
305+ );
306+ assert_eq!(healed.body["stats"]["homework_submitted_total"], 10);
307+ let after_heal = writes().await;
308+ assert!(after_heal > 0, "the heal wrote the awards");
309+
310+ // Steady state: everything earned is already held, so this read must not
311+ // touch the award table at all.
312+ let again = profile(&app, &ada, &ada_id).await;
313+ assert_eq!(again.status, StatusCode::OK, "{}", again.body);
314+ assert_eq!(again.body["badges"], healed.body["badges"], "same shelf");
315+ assert_eq!(writes().await, after_heal, "a profile read wrote something");
316+}
317+
241 /// The counters are derived, so a fresh account reads a true `0` on all four β€”318 /// The counters are derived, so a fresh account reads a true `0` on all four β€”
242 /// never `null`, never an absent key a client would have to guard.319 /// never `null`, never an absent key a client would have to guard.
243 #[tokio::test]320 #[tokio::test]
@@ -253,6 +330,13 @@ async fn fresh_stats_read_zero_on_every_field() {
253 "pomodoro_focus_ms",330 "pomodoro_focus_ms",
254 "courses",331 "courses",
255 "classes",332 "classes",
333+ // The stored lifetime counters: a row that predates the columns carries
334+ // none of them, and absent must still read as a numeric 0.
335+ "homework_submitted_total",
336+ "homework_on_time_total",
337+ "exam_sat_total",
338+ "pomodoro_finished_total",
339+ "pomodoro_focus_ms_total",
256 ] {340 ] {
257 assert_eq!(341 assert_eq!(
258 stats.get(field).and_then(Value::as_i64),342 stats.get(field).and_then(Value::as_i64),
@@ -261,7 +345,7 @@ async fn fresh_stats_read_zero_on_every_field() {
261 stats.get(field)345 stats.get(field)
262 );346 );
263 }347 }
264- assert_eq!(stats.len(), 4, "no fifth counter shipped: {stats:?}");348+ assert_eq!(stats.len(), 9, "no tenth counter shipped: {stats:?}");
265 assert!(mine.body["avatar"].is_null());349 assert!(mine.body["avatar"].is_null());
266 assert_eq!(mine.body["classes"], json!([]));350 assert_eq!(mine.body["classes"], json!([]));
267 assert_eq!(mine.body["courses"], json!([]));351 assert_eq!(mine.body["courses"], json!([]));
@@ -685,6 +769,472 @@ async fn stats_courses_stays_the_owners_true_total() {
685 assert_eq!(peer.body["stats"]["courses"], 2);769 assert_eq!(peer.body["stats"]["courses"], 2);
686 }770 }
687 771
772+// --- Badges ---------------------------------------------------------------
773+//
774+// Badges are *permanent*: an award row is stamped once and nothing ever moves
775+// or removes it, while the counters underneath it move both ways. Every test
776+// below is written against that split β€” the award, not the counter, is what
777+// carries the promise β€” and the counter tests read off the profile rather than
778+// the database, because the profile is the only surface a client has.
779+
780+/// A course with a subject and one enrolled student: the smallest cast that
781+/// can move a homework counter.
782+struct Classroom {
783+ app: Router,
784+ db: Database,
785+ teacher: String,
786+ student: String,
787+ student_id: String,
788+ course: String,
789+ subject: String,
790+}
791+
792+async fn classroom() -> Classroom {
793+ let (app, db) = app_and_db().await;
794+ let teacher = login_as(&app, &db, "teach", "teacher").await;
795+ let student = login(&app, "stu").await;
796+ let student_id = me_id(&app, &student).await;
797+ let course = create_course(&app, &teacher, "Algebra").await;
798+ enroll(&app, &teacher, &course, &student_id).await;
799+ let subject = create_subject(&app, &teacher, &course, "Fractions").await;
800+ Classroom {
801+ app,
802+ db,
803+ teacher,
804+ student,
805+ student_id,
806+ course,
807+ subject,
808+ }
809+}
810+
811+/// A homework due `in_ms` from now. Negative backdates it *inside* the
812+/// scheduling grace β€” the only way to hand something in late in one test.
813+async fn homework(c: &Classroom, title: &str, in_ms: i64) -> String {
814+ let due = Timestamp::now().as_millis() + in_ms;
815+ create_homework(&c.app, &c.teacher, &c.course, &c.subject, title, due).await
816+}
817+
818+/// Move `homework`'s deadline to `in_ms` from now, as the teacher who set it.
819+/// Negative backdates it *inside* the scheduling grace, which is legal β€” the
820+/// deadline is mutable in both directions, which is what the two tests below
821+/// are about.
822+async fn move_deadline(c: &Classroom, homework: &str, in_ms: i64) {
823+ let due = Timestamp::now().as_millis() + in_ms;
824+ let res = send(
825+ &c.app,
826+ "PATCH",
827+ &format!("/homework/{homework}"),
828+ Some(&c.teacher),
829+ Some(json!({ "due_at": due })),
830+ )
831+ .await;
832+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
833+}
834+
835+/// Hand in `homework` as `cookie`, asserting the first-hand-in `201`.
836+async fn hand_in(app: &Router, cookie: &str, homework: &str) {
837+ let res = send(
838+ app,
839+ "POST",
840+ &format!("/homework/{homework}/submission"),
841+ Some(cookie),
842+ Some(json!({ "text": "done" })),
843+ )
844+ .await;
845+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
846+}
847+
848+/// Withdraw the caller's own submission, asserting the `204`.
849+async fn withdraw(app: &Router, cookie: &str, homework: &str) {
850+ let res = send(
851+ app,
852+ "DELETE",
853+ &format!("/homework/{homework}/submission"),
854+ Some(cookie),
855+ None,
856+ )
857+ .await;
858+ assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
859+}
860+
861+/// The caller's own profile body (asserts the `200`).
862+async fn my_profile(app: &Router, cookie: &str) -> Value {
863+ let res = send(app, "GET", "/users/me/profile", Some(cookie), None).await;
864+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
865+ res.body
866+}
867+
868+/// When `id` was earned, off a profile body β€” `None` if the shelf lacks it.
869+fn stamp_of(profile: &Value, id: &str) -> Option<i64> {
870+ profile["badges"]
871+ .as_array()
872+ .expect("badges array")
873+ .iter()
874+ .find(|badge| badge["id"] == id)
875+ .map(|badge| badge["earned_at"].as_i64().expect("earned_at millis"))
876+}
877+
878+/// The badge ids on a profile, in the order served.
879+fn badge_ids(profile: &Value) -> Vec<&str> {
880+ profile["badges"]
881+ .as_array()
882+ .expect("badges array")
883+ .iter()
884+ .map(|badge| badge["id"].as_str().expect("badge id"))
885+ .collect()
886+}
887+
888+/// Crossing a threshold earns the badge there and then, stamped with the
889+/// moment it happened β€” not at some later sweep. The window is taken around
890+/// the request, so a stamp copied from anywhere else fails.
891+#[tokio::test]
892+async fn a_badge_lands_the_moment_its_threshold_is_crossed() {
893+ let c = classroom().await;
894+ let first = homework(&c, "Fractions I", 600_000).await;
895+
896+ let before = my_profile(&c.app, &c.student).await;
897+ assert_eq!(badge_ids(&before), Vec::<&str>::new(), "nothing earned yet");
898+
899+ let opened = Timestamp::now().as_millis();
900+ hand_in(&c.app, &c.student, &first).await;
901+ let closed = Timestamp::now().as_millis();
902+
903+ let mine = my_profile(&c.app, &c.student).await;
904+ assert_eq!(badge_ids(&mine), ["homework_submitted_1"], "{mine}");
905+ let earned = stamp_of(&mine, "homework_submitted_1").expect("the badge");
906+ assert!(
907+ (opened..=closed).contains(&earned),
908+ "earned_at {earned} is outside the request window {opened}..={closed}: {mine}"
909+ );
910+ // One hand-in is one submission, and the ten-badge is nine away.
911+ assert_eq!(mine["stats"]["homework_submitted_total"], 1);
912+ assert_eq!(mine["stats"]["homework_on_time_total"], 1);
913+}
914+
915+/// The permanence guarantee, at the stamp: crossing again re-runs the sync,
916+/// and the sync's `WHERE earned_at = NONE` must leave the original stamp
917+/// standing. The clock is given room to move between the two hand-ins, so a
918+/// sync that *did* overwrite would write a demonstrably later value.
919+#[tokio::test]
920+async fn a_second_crossing_never_moves_the_stamp() {
921+ let c = classroom().await;
922+ let first = homework(&c, "Fractions I", 600_000).await;
923+ let second = homework(&c, "Fractions II", 600_000).await;
924+
925+ hand_in(&c.app, &c.student, &first).await;
926+ let earned = stamp_of(
927+ &my_profile(&c.app, &c.student).await,
928+ "homework_submitted_1",
929+ )
930+ .expect("the badge");
931+
932+ // Any overwrite from here on is strictly later than this instant.
933+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
934+ let moved_on = Timestamp::now().as_millis();
935+ assert!(earned < moved_on, "the clock never moved β€” test is vacuous");
936+
937+ hand_in(&c.app, &c.student, &second).await;
938+ let after = my_profile(&c.app, &c.student).await;
939+ assert_eq!(after["stats"]["homework_submitted_total"], 2, "{after}");
940+ assert_eq!(
941+ stamp_of(&after, "homework_submitted_1"),
942+ Some(earned),
943+ "a re-sync moved a permanent stamp: {after}"
944+ );
945+}
946+
947+/// The whole point of an award row: permanence lives at the award, not at the
948+/// counter. Withdrawing the submission takes the counter back to zero β€” and
949+/// the badge it earned stays on the shelf, stamp untouched.
950+#[tokio::test]
951+async fn a_badge_outlives_the_counter_that_earned_it() {
952+ let c = classroom().await;
953+ let only = homework(&c, "Fractions I", 600_000).await;
954+
955+ hand_in(&c.app, &c.student, &only).await;
956+ let earned_it = my_profile(&c.app, &c.student).await;
957+ let earned = stamp_of(&earned_it, "homework_submitted_1").expect("the badge");
958+ assert_eq!(earned_it["stats"]["homework_submitted_total"], 1);
959+
960+ withdraw(&c.app, &c.student, &only).await;
961+
962+ let after = my_profile(&c.app, &c.student).await;
963+ assert_eq!(
964+ after["stats"]["homework_submitted_total"], 0,
965+ "the counter must come back down: {after}"
966+ );
967+ assert_eq!(after["stats"]["homework_on_time_total"], 0, "{after}");
968+ assert_eq!(
969+ stamp_of(&after, "homework_submitted_1"),
970+ Some(earned),
971+ "a badge is never taken back: {after}"
972+ );
973+}
974+
975+/// The farm hole, closed at the counter: withdrawing gives the credit back, so
976+/// submit β†’ withdraw β†’ submit is worth exactly one submission however many
977+/// times it is run. Without the decrement, one homework mints unlimited ones.
978+#[tokio::test]
979+async fn submit_withdraw_submit_is_worth_one_submission() {
980+ let c = classroom().await;
981+ let only = homework(&c, "Fractions I", 600_000).await;
982+
983+ for _ in 0..3 {
984+ hand_in(&c.app, &c.student, &only).await;
985+ withdraw(&c.app, &c.student, &only).await;
986+ }
987+ hand_in(&c.app, &c.student, &only).await;
988+
989+ let mine = my_profile(&c.app, &c.student).await;
990+ assert_eq!(
991+ mine["stats"]["homework_submitted_total"], 1,
992+ "one homework handed in once, whatever the churn: {mine}"
993+ );
994+ assert_eq!(mine["stats"]["homework_on_time_total"], 1, "{mine}");
995+}
996+
997+/// The two homework counters part company at the deadline: everything handed
998+/// in counts as submitted, only what beat `due_at` counts as on time. The
999+/// on-time hand-in in the same test is what proves the counter still moves at
1000+/// all, so a permanently-stuck `on_time` cannot pass as "the late one".
1001+#[tokio::test]
1002+async fn a_late_submission_moves_submitted_but_not_on_time() {
1003+ let c = classroom().await;
1004+ // Backdated inside the scheduling grace: already due, still creatable.
1005+ let overdue = homework(&c, "Yesterday's", -30_000).await;
1006+ let punctual = homework(&c, "Next week's", 600_000).await;
1007+
1008+ hand_in(&c.app, &c.student, &overdue).await;
1009+ let late = my_profile(&c.app, &c.student).await;
1010+ assert_eq!(late["stats"]["homework_submitted_total"], 1, "{late}");
1011+ assert_eq!(
1012+ late["stats"]["homework_on_time_total"], 0,
1013+ "a submission past due_at earns no on-time credit: {late}"
1014+ );
1015+
1016+ hand_in(&c.app, &c.student, &punctual).await;
1017+ let both = my_profile(&c.app, &c.student).await;
1018+ assert_eq!(both["stats"]["homework_submitted_total"], 2, "{both}");
1019+ assert_eq!(both["stats"]["homework_on_time_total"], 1, "{both}");
1020+}
1021+
1022+/// A withdrawal gives back what the hand-in was credited with, not what the
1023+/// deadline says *now*: a teacher who extends `due_at` after a late hand-in has
1024+/// not made it on time retroactively. Re-judging at withdrawal debited an
1025+/// on-time credit that was never given, and the zero floor hid it β€” so a
1026+/// genuinely on-time submission is held throughout, and it is that one's credit
1027+/// the late withdrawal used to eat.
1028+#[tokio::test]
1029+async fn extending_a_deadline_never_debits_an_on_time_credit_it_never_gave() {
1030+ let c = classroom().await;
1031+ let punctual = homework(&c, "Next week's", 600_000).await;
1032+ // Backdated inside the scheduling grace: already due, still creatable.
1033+ let overdue = homework(&c, "Yesterday's", -30_000).await;
1034+
1035+ hand_in(&c.app, &c.student, &punctual).await;
1036+ hand_in(&c.app, &c.student, &overdue).await;
1037+ let both = my_profile(&c.app, &c.student).await;
1038+ assert_eq!(both["stats"]["homework_submitted_total"], 2, "{both}");
1039+ assert_eq!(both["stats"]["homework_on_time_total"], 1, "{both}");
1040+
1041+ // The teacher relents and moves the deadline out. The hand-in that was late
1042+ // when it landed was still late when it landed.
1043+ move_deadline(&c, &overdue, 600_000).await;
1044+ let moved = my_profile(&c.app, &c.student).await;
1045+ assert_eq!(moved["stats"]["homework_on_time_total"], 1, "{moved}");
1046+
1047+ withdraw(&c.app, &c.student, &overdue).await;
1048+ let after = my_profile(&c.app, &c.student).await;
1049+ assert_eq!(after["stats"]["homework_submitted_total"], 1, "{after}");
1050+ assert_eq!(
1051+ after["stats"]["homework_on_time_total"], 1,
1052+ "withdrawing the late one took the punctual one's credit: {after}"
1053+ );
1054+
1055+ // ... and the punctual one still has exactly its own credit to give back.
1056+ withdraw(&c.app, &c.student, &punctual).await;
1057+ let empty = my_profile(&c.app, &c.student).await;
1058+ assert_eq!(empty["stats"]["homework_submitted_total"], 0, "{empty}");
1059+ assert_eq!(empty["stats"]["homework_on_time_total"], 0, "{empty}");
1060+}
1061+
1062+/// The other direction, where the floor cannot hide it: pulling `due_at` back
1063+/// after a punctual hand-in used to make the withdrawal debit *nothing* on
1064+/// time, leaving `on_time` standing above `submitted` β€” a student credited with
1065+/// more punctual hand-ins than hand-ins. The invariant is checked at every step,
1066+/// not just at the end.
1067+#[tokio::test]
1068+async fn pulling_a_deadline_back_leaves_on_time_no_higher_than_submitted() {
1069+ let c = classroom().await;
1070+ let only = homework(&c, "Next week's", 600_000).await;
1071+
1072+ let counted = |profile: &Value| -> (i64, i64) {
1073+ let submitted = profile["stats"]["homework_submitted_total"]
1074+ .as_i64()
1075+ .unwrap_or_else(|| panic!("submitted total: {profile}"));
1076+ let on_time = profile["stats"]["homework_on_time_total"]
1077+ .as_i64()
1078+ .unwrap_or_else(|| panic!("on-time total: {profile}"));
1079+ assert!(
1080+ on_time <= submitted,
1081+ "on_time {on_time} exceeds submitted {submitted}: {profile}"
1082+ );
1083+ (submitted, on_time)
1084+ };
1085+
1086+ hand_in(&c.app, &c.student, &only).await;
1087+ assert_eq!(counted(&my_profile(&c.app, &c.student).await), (1, 1));
1088+
1089+ // Backdating inside the grace is a legal PATCH, and it moves the very cut
1090+ // the credit was judged by.
1091+ move_deadline(&c, &only, -30_000).await;
1092+ assert_eq!(
1093+ counted(&my_profile(&c.app, &c.student).await),
1094+ (1, 1),
1095+ "moving a deadline re-judges nothing already credited"
1096+ );
1097+
1098+ withdraw(&c.app, &c.student, &only).await;
1099+ assert_eq!(
1100+ counted(&my_profile(&c.app, &c.student).await),
1101+ (0, 0),
1102+ "the withdrawal gave back the on-time credit it took"
1103+ );
1104+}
1105+
1106+/// `exam_sat_total` counts sittings, not requests: re-posting a running
1107+/// attempt resumes it (`200`, same clock) and must leave the counter alone.
1108+#[tokio::test]
1109+async fn a_resumed_exam_attempt_counts_once() {
1110+ let c = classroom().await;
1111+ let now = Timestamp::now().as_millis();
1112+ let res = create_exam_with(
1113+ &c.app,
1114+ &c.teacher,
1115+ &c.course,
1116+ json!({ "title": "Midterm", "kind": "quiz", "mode": "sync",
1117+ "starts_at": now - 1_000, "ends_at": now + 600_000 }),
1118+ )
1119+ .await;
1120+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1121+ let exam = id_of(&res.body);
1122+
1123+ let started = send(
1124+ &c.app,
1125+ "POST",
1126+ &format!("/exams/{exam}/attempt"),
1127+ Some(&c.student),
1128+ None,
1129+ )
1130+ .await;
1131+ assert_eq!(started.status, StatusCode::CREATED, "{}", started.body);
1132+
1133+ let resumed = send(
1134+ &c.app,
1135+ "POST",
1136+ &format!("/exams/{exam}/attempt"),
1137+ Some(&c.student),
1138+ None,
1139+ )
1140+ .await;
1141+ assert_eq!(
1142+ resumed.status,
1143+ StatusCode::OK,
1144+ "the second post must resume, not start: {}",
1145+ resumed.body
1146+ );
1147+
1148+ let mine = my_profile(&c.app, &c.student).await;
1149+ assert_eq!(
1150+ mine["stats"]["exam_sat_total"], 1,
1151+ "a resume is not a second sitting: {mine}"
1152+ );
1153+ assert_eq!(badge_ids(&mine), ["exam_sat_1"], "{mine}");
1154+}
1155+
1156+/// The catalog a client renders badges from, end to end. `stat` is a **wire**
1157+/// name: a domain test pins that it differs from the user-row column, and this
1158+/// pins that what ships is the wire one β€” and that appending `_total` to it
1159+/// lands on a real key of a real profile's stats, which is the only thing that
1160+/// lets a client join the two surfaces at all.
1161+#[tokio::test]
1162+async fn the_badge_catalog_is_reachable_and_wire_named() {
1163+ let (app, _db) = app_and_db().await;
1164+ let fresh = login(&app, "fresh").await;
1165+ let stats = my_profile(&app, &fresh).await["stats"]
1166+ .as_object()
1167+ .expect("stats object")
1168+ .clone();
1169+
1170+ // Unauthenticated: the form that renders a badge needs no session.
1171+ let res = send(&app, "GET", "/limits", None, None).await;
1172+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1173+ let catalog = res.body["badges"]["catalog"]
1174+ .as_array()
1175+ .unwrap_or_else(|| panic!("badges.catalog array: {}", res.body));
1176+ assert!(!catalog.is_empty(), "an empty catalog awards nothing");
1177+
1178+ for badge in catalog {
1179+ let id = badge["id"]
1180+ .as_str()
1181+ .unwrap_or_else(|| panic!("id: {badge}"));
1182+ let stat = badge["stat"]
1183+ .as_str()
1184+ .unwrap_or_else(|| panic!("stat: {badge}"));
1185+ let threshold = badge["threshold"]
1186+ .as_i64()
1187+ .unwrap_or_else(|| panic!("threshold: {badge}"));
1188+ assert!(threshold > 0, "{id} is earned by doing nothing");
1189+ assert!(
1190+ !stat.ends_with("_total"),
1191+ "{id} serves the database column {stat}, not a wire name: renaming \
1192+ the column would break the API"
1193+ );
1194+ assert!(
1195+ stats.contains_key(&format!("{stat}_total")),
1196+ "{id}'s stat {stat} joins no profile stats key: {stats:?}"
1197+ );
1198+ }
1199+ assert!(
1200+ catalog
1201+ .iter()
1202+ .any(|badge| badge["id"] == "homework_submitted_1" && badge["threshold"] == 1),
1203+ "the first-homework badge left the catalog: {res_body}",
1204+ res_body = res.body
1205+ );
1206+}
1207+
1208+/// Badges are public β€” they are a decoration, not a record β€” so they ride the
1209+/// profile's existing gate and open no door of their own: a peer reads them,
1210+/// and a parent with no link to the student is still refused the whole
1211+/// profile, badges included.
1212+#[tokio::test]
1213+async fn badges_ride_the_profile_gate_and_open_no_new_door() {
1214+ let c = classroom().await;
1215+ let only = homework(&c, "Fractions I", 600_000).await;
1216+ hand_in(&c.app, &c.student, &only).await;
1217+
1218+ let peer = login(&c.app, "peer").await;
1219+ let seen = profile(&c.app, &peer, &c.student_id).await;
1220+ assert_eq!(seen.status, StatusCode::OK, "{}", seen.body);
1221+ assert_eq!(
1222+ badge_ids(&seen.body),
1223+ ["homework_submitted_1"],
1224+ "a peer sees the shelf: {}",
1225+ seen.body
1226+ );
1227+
1228+ let stranger = login_as(&c.app, &c.db, "mom", "parent").await;
1229+ let blocked = profile(&c.app, &stranger, &c.student_id).await;
1230+ assert_eq!(
1231+ blocked.status,
1232+ StatusCode::FORBIDDEN,
1233+ "an unlinked parent reads no profile, badges included: {}",
1234+ blocked.body
1235+ );
1236+}
1237+
688 /// A profile that was never there is a 404, at any role β€” the id is not an1238 /// A profile that was never there is a 404, at any role β€” the id is not an
689 /// existence oracle wearing a 403.1239 /// existence oracle wearing a 403.
690 #[tokio::test]1240 #[tokio::test]
tests/spec_bounds.rsmodified+34 -0
@@ -1045,6 +1045,40 @@ fn expectations_cover_every_annotation() {
1045 );1045 );
1046 }1046 }
1047 1047
1048+/// README.md quotes how many bounds this suite checks β€” a hand-kept copy of
1049+/// [`expectations`]`.len()`, and one that had already gone stale twice before
1050+/// anything watched it. This is that watcher.
1051+#[test]
1052+fn the_readme_states_the_real_bound_count() {
1053+ // Anchored on the sentence itself, not a line number or a loose digit
1054+ // scan: the README is 73KB and full of other numbers.
1055+ const ANCHOR: &str = "`tests/spec_bounds.rs` builds the OpenAPI document, reads all ";
1056+ let readme = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))
1057+ .expect("read README.md");
1058+ let at = readme.find(ANCHOR).unwrap_or_else(|| {
1059+ panic!(
1060+ "README.md no longer contains the sentence this test reads:\n \"{ANCHOR}…\"\n\n\
1061+ It states how many published bounds this suite checks ({} today). Restore that \
1062+ wording, or move the count and re-anchor this test on its new phrasing.",
1063+ expectations().len()
1064+ )
1065+ });
1066+ let stated: String = readme[at + ANCHOR.len()..]
1067+ .chars()
1068+ .take_while(char::is_ascii_digit)
1069+ .collect();
1070+
1071+ assert_eq!(
1072+ stated.parse::<usize>().ok(),
1073+ Some(expectations().len()),
1074+ "README.md says this suite checks {stated:?} published bounds, but the expectations \
1075+ table has {} rows.\n\nEdit README.md so that sentence reads \"reads all {} published \
1076+ bounds\" β€” the table is the truth, the README is the copy.",
1077+ expectations().len(),
1078+ expectations().len()
1079+ );
1080+}
1081+
1048 /// The three image-meta bodies β€” exam question images, bank template images,1082 /// The three image-meta bodies β€” exam question images, bank template images,
1049 /// and pool question/solution photos β€” are hand-kept copies of one shape,1083 /// and pool question/solution photos β€” are hand-kept copies of one shape,
1050 /// `{content_type, size}`. The write half behind them is shared1084 /// `{content_type, size}`. The write half behind them is shared