forge
Explore
Log in

Don't you dare go Hollow

πŸŽ–οΈ earn badges on both sides of the classroom

Browse files at this commit

46c76f5155040c9a462c63db2d49953682d094e5Ahmet Kaan GümüşParent: a00880e
  • feat
    • πŸŽ–οΈ earn badges on both sides of the classroom
Show full message
feat: πŸŽ–οΈ earn badges on both sides of the classroom

Pass 2 gave badges only to students doing their own homework. Seven new
families cover the rest of the school and the two shapes a plain tally
could not express.

Teachers earn `marks_given` (a grade recorded, once per pair β€” a regrade
moves nothing), `lessons_held` (credited at the first roll call taken for
a session, so a lesson scheduled and cancelled counts for nothing), and
`pool_approved`. Students earn `pool_published`, `high_mark` (an exam
mark at or above 90, once per sitting), `lessons_attended` (marked
present or late at roll call, moved back down by a correction), and
`study_streak` β€” the longest run of consecutive days finishing a
pomodoro, read as a high-water mark so breaking it never takes the badge
back. Days end at midnight UTC, like every other day calculation here.

Both counters of the question pool skip a self-approval: a counter moves
only when one person's work was judged by somebody else, which closes the
ask-approve-delete farm on the staff side the way crediting at approval
closes it on the student side.

Every counter moves inside the transaction of the write that causes it.
The streak needs two statements rather than one because sibling SET
clauses read the row's before-state, so `longest` would lag `current`
forever; the pair sits in one transaction, and `max` keeps it monotone
under every interleaving, verified on a real 3.2.3 server. No backfill
and no migration mark: every counter starts at zero at this deploy.
README.mdmodified+117 -20
@@ -117,10 +117,12 @@ preference (or, for the accent, its own default).
117117 Every account also has a **public profile** (`/users/{id}/profile`): a
118118 self-chosen `display_name` and `bio`, one **avatar**, the classes and courses
119119 it belongs to, counters computed at read (finished pomodoro stints, course and
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,
120+class totals) beside stored lifetime tallies of what the account has done β€”
121+homework handed in, exams sat and focus time, lessons attended, high exam
122+marks and the longest run of consecutive study days for a student; grades
123+given, lessons held and question-pool approvals for a teacher β€” and the
124+**badges** those tallies have earned β€” auto-earned only, no route awards or
125+revokes one, and permanent once earned even if the counter later falls. Contact details are deliberately not part of it β€” email,
124126 phone and birth date keep the gate they already have β€” and any authenticated
125127 account reads any profile, except a `parent`, who reads their own and their
126128 linked students' only (see "User profiles & avatars").
@@ -339,7 +341,8 @@ response in the same commit.
339341 "session_duration_days": 7 },
340342 "badges": { "catalog": [ { "id": "homework_submitted_10",
341343 "stat": "homework_submitted", "threshold": 10 },
342- { "…": 0 } ] },
344+ { "…": 0 } ],
345+ "high_mark_min": 90 },
343346 "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 },
344347 "file": { "max_name_len": 255, "max_content_type_len": 100,
345348 "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400,
@@ -442,18 +445,28 @@ Notes:
442445 uploadable `image_content_types` are the exact accepted spellings β€” build
443446 pickers from these rather than from a literal list.
444447 - **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
448+ system can auto-award β€” `{id, stat, threshold}`, 34 of them, in catalog
446449 order. It is a group (an object with one `catalog` key) rather than a bare
447450 array because every key of this document is a group, and that uniformity is
448451 what lets a client walk the response generically. `stat` is the API's name
449452 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.
453+ `homework_on_time`, `exam_sat`, `pomodoro_finished`, `pomodoro_focus_ms`,
454+ `marks_given`, `lessons_held`, `pool_approved`, `pool_published`,
455+ `lessons_attended`, `high_mark`, `study_streak` β€” twelve counters over the
456+ 34 badges), deliberately not the database column it is stored in, so storage
457+ can be renamed without moving a published contract; badges sharing a `stat`
458+ form a ladder. Every one of them joins the profile's `stats` key of the same
459+ name plus `_total`, mechanically and without exception β€” including
460+ `study_streak_total`, which is a *longest run* rather than a sum and keeps
461+ the suffix anyway so the join needs no special case. The catalog is compiled
462+ in, so a threshold moves only with a deploy β€” the rules stay reviewable in a
463+ diff instead of editable in a settings row. Labels and icons are **not**
464+ here: like `roles` and course `kinds`, the id is the whole contract and the
465+ client owns what it looks like. Beside it, `badges.high_mark_min` (90) is the
466+ exam mark the `high_mark` ladder counts from β€” published because
467+ `high_mark_10` does not say what a high mark is, and deliberately not the
468+ school's grade bands, whose labels a school renames at will while a badge id
469+ must mean the same thing in every deployment forever.
457470
458471 **`422` versus `400`.** The two refusals mean different things and a client
459472 must not treat them alike. Every JSON-bodied route can answer **`422`**: the
@@ -1140,7 +1153,11 @@ the school. `GET /users/me/profile` is the caller's own copy of it,
11401153 "courses": 7, "classes": 1,
11411154 "homework_submitted_total": 12, "homework_on_time_total": 11,
11421155 "exam_sat_total": 5, "pomodoro_finished_total": 44,
1143- "pomodoro_focus_ms_total": 65400000 }
1156+ "pomodoro_focus_ms_total": 65400000,
1157+ "marks_given_total": 0, "lessons_held_total": 0,
1158+ "pool_approved_total": 0, "pool_published_total": 3,
1159+ "lessons_attended_total": 58, "high_mark_total": 2,
1160+ "study_streak_total": 9 }
11441161 }
11451162 ```
11461163
@@ -1192,21 +1209,33 @@ owner's true total on purpose β€” it is the motivational counter, a per-reader
11921209 number would be meaningless, and a magnitude names no course. One consequence,
11931210 by design: a teacher you share nothing with has an empty `courses` block.
11941211
1195-**`stats` holds nine numbers of two different kinds, and the difference is
1212+**`stats` holds sixteen numbers of two different kinds, and the difference is
11961213 worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and
11971214 `classes` are **computed at read**: they are recounted from the live rows on
1198-every call, so no column can drift out of sync with what is behind it. The five
1199-`*_total` keys are **stored lifetime tallies**, maintained at write time (see
1200-below), so a tally can outlive the rows behind it β€” a student's
1215+every call, so no column can drift out of sync with what is behind it. The
1216+twelve `*_total` keys are **stored lifetime tallies**, maintained at write time
1217+(see below), so a tally can outlive the rows behind it β€” a student's
12011218 `exam_sat_total` still counts an exam a teacher has since deleted, which is the
12021219 point of a lifetime counter. Either kind reads a true `0` on a fresh account,
12031220 never `null`. Only *finished* pomodoro stints count on either side β€” a timer
12041221 left running is not study time. Exam averages, homework-done rates and
12051222 attendance rates are deliberately absent: those tables are indexed for their
12061223 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
1224+profile is far too cheap a page to pay for one β€” which is also why the twelve
12081225 lifetime counters are tallied at write rather than recounted here.
12091226
1227+**Every key is unconditional, whatever the role.** Some counters are a
1228+student's (`exam_sat_total`, `lessons_attended_total`, `high_mark_total`,
1229+`study_streak_total`, the two homework ones), some a teacher's
1230+(`marks_given_total`, `lessons_held_total`, `pool_approved_total`), and a role
1231+that never does the work simply reads `0` β€” no key appears or disappears with a
1232+role, so a client renders one shape. Each `*_total` is the badge catalog's
1233+`stat` name plus `_total` and nothing else, which is how a client joins a
1234+profile to `badges.catalog[]` at `/limits` without a lookup table.
1235+`study_streak_total` keeps that suffix even though it is a **longest run and
1236+not a sum** β€” the mechanical spelling is worth more than the accurate one, so
1237+do not "fix" it.
1238+
12101239 **The avatar** is one picture per account, uploaded as `multipart/form-data`
12111240 with the image under a `file` field. Raster types only (`image/png`,
12121241 `image/jpeg`, `image/webp`, `image/gif`) β€” an SVG can carry script, and these
@@ -1241,7 +1270,8 @@ oldest first.
12411270 **Ids only.** Each entry is `{id, earned_at}`. The label, the icon and the
12421271 description are the frontend's, keyed by the id β€” the same deal `roles` and
12431272 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
1273+`badges.catalog[]` (`{id, stat, threshold}`, 34 badges over twelve counters,
1274+alongside `badges.high_mark_min`); it is compiled into
12451275 the binary, so changing a threshold is a deploy, not a settings edit. An id is
12461276 never reused for another meaning, and retiring a badge just drops it from the
12471277 catalog β€” awards carrying it stop being served, no migration.
@@ -1262,6 +1292,50 @@ catalog β€” awards carrying it stop being served, no migration.
12621292 - **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its
12631293 duration into `pomodoro_focus_ms_total`. An open stint counts for neither β€”
12641294 unfinished focus has no honest duration to add.
1295+- **Study streak.** Finishing a stint also extends `study_streak_total`, the
1296+ **longest** run of consecutive days on which the student finished one. A
1297+ second stint the same day extends nothing; a gap of any length starts the run
1298+ over at 1. The badge reads the longest run ever held, never the run in
1299+ progress, so a broken streak takes no badge away and the counter never comes
1300+ down. A day is a **UTC calendar day**: this API stores no school timezone
1301+ anywhere, and the boundary is midnight UTC, the same one every other day
1302+ calculation here uses (meal cutoffs, menu dates, birth dates).
1303+- **Grades given.** `+1 marks_given_total` for the **grader**, the first time
1304+ they record a grade for a given exam sitting or homework submission β€” exam
1305+ and homework alike, since grading is grading. A regrade of the same pair moves
1306+ nothing: the counter counts work judged, not times the mark was edited.
1307+- **High marks.** `+1 high_mark_total` for the **student** whenever an exam
1308+ mark lands at or above `badges.high_mark_min` (90, published at `/limits`),
1309+ once per sitting β€” a retake is another sitting and can earn another. Homework
1310+ marks never count here: a homework mark is optional and most grades are
1311+ status-only, so counting them would reward a teacher's habit rather than a
1312+ student's work. The cut is compiled in rather than read from the school's
1313+ grade bands, which are renameable display labels β€” `high_mark_10` has to mean
1314+ the same thing in every school, forever.
1315+- **Lessons held.** `+1 lessons_held_total` for the **session's teacher**, once
1316+ per lesson, credited by the **first roll call taken for it**. It means "a
1317+ lesson whose roll call was taken", not "a lesson on the timetable" β€”
1318+ scheduling two hundred lessons and cancelling them all earns nothing. The
1319+ thirtieth student marked in that lesson credits nothing further (a stamp on
1320+ the session row is the guard), and taking one student back off the roll does
1321+ not un-hold the lesson.
1322+- **Lessons attended.** `+1 lessons_attended_total` for a **student** marked
1323+ `present` or `late` at lesson roll call β€” the same cut the attendance report's
1324+ `rate` uses, so a student's badge and their attendance rate never disagree
1325+ about what attending is; `excused` and every school-added status are neutral.
1326+ It is a **delta, not a tally**: a teacher correcting `present` β†’ `absent`
1327+ moves it back down (floored at 0), and clearing the row does too. Student-only
1328+ β€” a teacher marked present in their own lesson moves nothing β€” and course
1329+ roll call only: the daily/event attendance at `/attendance` earns none of it.
1330+- **The question pool.** One pending β†’ approved transition credits two people:
1331+ `+1 pool_approved_total` for the **approver** and `+1 pool_published_total`
1332+ for the **asker** whose question reached the pool. The asker is credited at
1333+ approval and never at asking, because asking is self-service β€” delete and
1334+ re-ask would farm it β€” which is why the counter is named `published` rather
1335+ than `asked`. And a teacher **approving their own question** earns neither:
1336+ the approval itself is unchanged (same `200`, same freeze), but a counter
1337+ moves only where one person's work was judged by somebody else, which closes
1338+ the ask-approve-delete farm from the other end too.
12651339
12661340 **Existing accounts are seeded once.** The first boot of this version tallies
12671341 every account from its real history, so nobody starts at zero for work they
@@ -1273,6 +1347,15 @@ seed (count what is there) simply cannot agree about history that is gone β€”
12731347 and the fix is not to make deletion decrement, which would break the tally for
12741348 everyone in order to patch it for a few.
12751349
1350+**The seven newer counters are not seeded at all**, deliberately:
1351+`marks_given_total`, `high_mark_total`, `lessons_held_total`,
1352+`lessons_attended_total`, `pool_approved_total`, `pool_published_total` and
1353+`study_streak_total` **begin at this deploy**, at zero, and no history is
1354+reconstructed for them. The columns are defined and absent reads `0`, so an
1355+account written before them is indistinguishable from a fresh one; the first
1356+grade recorded, roll call taken, approval landed or stint finished after the
1357+upgrade is what starts each of them counting.
1358+
12761359 ## Appointments
12771360
12781361 Office hours and parent-teacher conferences, booked instead of arranged by
@@ -2521,6 +2604,17 @@ it; a student reads their own tallies through the attendance report instead.
25212604 Re-marking overwrites: one row per session+user, by construction. Deleting a
25222605 session (or its course) cascades its roll-call rows.
25232606
2607+**Roll call is also what credits two badge counters** (see "Badges"). The
2608+**first** mark taken for a lesson credits its teacher's `lessons_held_total`,
2609+once β€” a lesson counts as held when its roll call is taken, so one merely
2610+scheduled (and then cancelled) counts for nothing, and the marks after that
2611+first one credit nothing further. And a **student** marked `present` or `late`
2612+gains a `lessons_attended_total`, using the same cut the attendance `rate`
2613+below uses; correcting that mark to any other status, or clearing the row, gives
2614+it back. The session teacher's own presence row moves neither counter β€” the
2615+attendance one is a student's badge, and a teacher does not attend their own
2616+lesson.
2617+
25242618 The **work log** (`/work`) is the staff timesheet, for teachers and above.
25252619 `POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both
25262620 stamped by the **server clock** β€” a request never carries an instant, so a
@@ -2546,6 +2640,9 @@ Logs return the usual page envelope plus `total_focus_ms`, the unpaged sum of
25462640 every finished session's duration: `GET /pomodoro/me` for your own,
25472641 `GET /pomodoro/{user}` for teacher+ (study oversight). Only students start
25482642 sessions β€” pomodoro is the study tool, the work log is the staff timesheet.
2643+Finishing a stint also feeds the **study streak** behind the `study_streak`
2644+badges: consecutive **UTC** days on which one was finished, kept as the longest
2645+run ever held (see "Badges").
25492646
25502647 **Attendance reports** mirror the marks report: `GET /attendance/me` for any
25512648 logged-in user, `GET /attendance/{user}` for teacher+ β€” narrowed to the
src/constant.rsmodified+62 -1
@@ -875,6 +875,43 @@ pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
875875 pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
876876 pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total";
877877 pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
878+/// The staff-side and second student-side totals, same shape and same rules:
879+/// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and
880+/// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the
881+/// approvals a teacher hands out and `POOL_PUBLISHED` the questions whose
882+/// author got approved β€” credited at approval, which is why the name says
883+/// published rather than asked.
884+pub const MARKS_GIVEN_TOTAL_FIELD: &str = "marks_given_total";
885+pub const LESSONS_HELD_TOTAL_FIELD: &str = "lessons_held_total";
886+pub const POOL_APPROVED_TOTAL_FIELD: &str = "pool_approved_total";
887+pub const POOL_PUBLISHED_TOTAL_FIELD: &str = "pool_published_total";
888+pub const LESSONS_ATTENDED_TOTAL_FIELD: &str = "lessons_attended_total";
889+pub const HIGH_MARK_TOTAL_FIELD: &str = "high_mark_total";
890+/// The longest run of consecutive days the student has studied, and the two
891+/// bookkeeping columns the write site needs to compute it: the run in progress
892+/// and the last day counted (both plain day numbers, midnight UTC β€” the same
893+/// boundary every other day calculation here uses).
894+///
895+/// Only the longest is a badge counter: it never comes down, which is what
896+/// keeps it on the ordinary `>=` rule with no second catalog shape. The other
897+/// two are internal state β€” no badge reads them, `/limits` never names them,
898+/// and no profile key serves them.
899+pub const STUDY_STREAK_LONGEST_FIELD: &str = "study_streak_longest";
900+pub const STUDY_STREAK_CURRENT_FIELD: &str = "study_streak_current";
901+pub const STUDY_STREAK_LAST_DAY_FIELD: &str = "study_streak_last_day";
902+/// When a lesson was first counted towards its teacher's `lessons_held_total`,
903+/// stamped on the `course_session` row by the first roll call taken for it.
904+/// Bookkeeping like the two streak columns above: no badge reads it, `/limits`
905+/// never names it, no profile key serves it. Its only job is the once-per-
906+/// session guard β€” a lesson is credited when it is *taken*, and the thirtieth
907+/// student marked must credit nothing further.
908+pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at";
909+/// What counts as a high mark, out of `MAX_MARK`. Hardcoded next to the badge
910+/// thresholds rather than read from the school's grade bands: those are
911+/// renameable display labels, and a badge id must never depend on a value a
912+/// school can change at runtime β€” `high_mark_10` has to mean the same thing in
913+/// every deployment, forever.
914+pub const HIGH_MARK_MIN: i64 = 90;
878915
879916 /// The badge catalog: every badge the system can award, as
880917 /// `(id, the counter it reads, the value that earns it)`. Hardcoded on
@@ -888,7 +925,7 @@ pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total";
888925 /// carry it simply stop being served (no data migration β€”
889926 /// [`crate::domain::badge::BadgeAward::list_for`] filters to the live
890927 /// catalog).
891-pub const BADGES: [(&str, BadgeStat, i64); 13] = [
928+pub const BADGES: [(&str, BadgeStat, i64); 34] = [
892929 ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1),
893930 ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10),
894931 ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50),
@@ -911,6 +948,30 @@ pub const BADGES: [(&str, BadgeStat, i64); 13] = [
911948 BadgeStat::PomodoroFocusMs,
912949 180_000_000,
913950 ),
951+ ("marks_given_10", BadgeStat::MarksGiven, 10),
952+ ("marks_given_50", BadgeStat::MarksGiven, 50),
953+ ("marks_given_250", BadgeStat::MarksGiven, 250),
954+ ("lessons_held_10", BadgeStat::LessonsHeld, 10),
955+ ("lessons_held_50", BadgeStat::LessonsHeld, 50),
956+ ("lessons_held_200", BadgeStat::LessonsHeld, 200),
957+ ("pool_approved_5", BadgeStat::PoolApproved, 5),
958+ ("pool_approved_25", BadgeStat::PoolApproved, 25),
959+ ("pool_approved_100", BadgeStat::PoolApproved, 100),
960+ ("pool_published_1", BadgeStat::PoolPublished, 1),
961+ ("pool_published_10", BadgeStat::PoolPublished, 10),
962+ ("pool_published_50", BadgeStat::PoolPublished, 50),
963+ ("lessons_attended_10", BadgeStat::LessonsAttended, 10),
964+ ("lessons_attended_50", BadgeStat::LessonsAttended, 50),
965+ ("lessons_attended_200", BadgeStat::LessonsAttended, 200),
966+ // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting.
967+ ("high_mark_1", BadgeStat::HighMark, 1),
968+ ("high_mark_10", BadgeStat::HighMark, 10),
969+ ("high_mark_25", BadgeStat::HighMark, 25),
970+ // Consecutive study days, read off the longest run ever held β€” so these
971+ // are earned once and never lost when the run breaks.
972+ ("study_streak_3", BadgeStat::StudyStreak, 3),
973+ ("study_streak_7", BadgeStat::StudyStreak, 7),
974+ ("study_streak_30", BadgeStat::StudyStreak, 30),
914975 ];
915976 /// The two stroke counters on a board row. `epoch_stroke_count` is reset to
916977 /// zero by a clear and capped at `MAX_EPOCH_STROKES` β€” a full epoch is
src/domain/badge.rsmodified+124 -7
@@ -16,8 +16,11 @@
1616 use surrealdb::types::SurrealValue;
1717
1818 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,
19+ BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD,
20+ HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD,
21+ LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD,
22+ POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD,
23+ STUDY_STREAK_LONGEST_FIELD,
2124 };
2225 use crate::database::Database;
2326 use crate::domain::timestamp::Timestamp;
@@ -35,6 +38,17 @@ pub enum BadgeStat {
3538 ExamSat,
3639 PomodoroFinished,
3740 PomodoroFocusMs,
41+ MarksGiven,
42+ LessonsHeld,
43+ PoolApproved,
44+ PoolPublished,
45+ LessonsAttended,
46+ HighMark,
47+ /// The *longest* run of study days, not the run in progress: the two
48+ /// bookkeeping columns behind it are not counters and are deliberately not
49+ /// variants here, because nothing may award a badge off a number that comes
50+ /// back down.
51+ StudyStreak,
3852 }
3953
4054 impl BadgeStat {
@@ -48,6 +62,13 @@ impl BadgeStat {
4862 BadgeStat::ExamSat => EXAM_SAT_TOTAL_FIELD,
4963 BadgeStat::PomodoroFinished => POMODORO_FINISHED_TOTAL_FIELD,
5064 BadgeStat::PomodoroFocusMs => POMODORO_FOCUS_MS_TOTAL_FIELD,
65+ BadgeStat::MarksGiven => MARKS_GIVEN_TOTAL_FIELD,
66+ BadgeStat::LessonsHeld => LESSONS_HELD_TOTAL_FIELD,
67+ BadgeStat::PoolApproved => POOL_APPROVED_TOTAL_FIELD,
68+ BadgeStat::PoolPublished => POOL_PUBLISHED_TOTAL_FIELD,
69+ BadgeStat::LessonsAttended => LESSONS_ATTENDED_TOTAL_FIELD,
70+ BadgeStat::HighMark => HIGH_MARK_TOTAL_FIELD,
71+ BadgeStat::StudyStreak => STUDY_STREAK_LONGEST_FIELD,
5172 }
5273 }
5374
@@ -65,6 +86,13 @@ impl BadgeStat {
6586 BadgeStat::ExamSat => "exam_sat",
6687 BadgeStat::PomodoroFinished => "pomodoro_finished",
6788 BadgeStat::PomodoroFocusMs => "pomodoro_focus_ms",
89+ BadgeStat::MarksGiven => "marks_given",
90+ BadgeStat::LessonsHeld => "lessons_held",
91+ BadgeStat::PoolApproved => "pool_approved",
92+ BadgeStat::PoolPublished => "pool_published",
93+ BadgeStat::LessonsAttended => "lessons_attended",
94+ BadgeStat::HighMark => "high_mark",
95+ BadgeStat::StudyStreak => "study_streak",
6896 }
6997 }
7098 }
@@ -79,6 +107,15 @@ pub struct BadgeStats {
79107 exam_sat: i64,
80108 pomodoro_finished: i64,
81109 pomodoro_focus_ms: i64,
110+ marks_given: i64,
111+ lessons_held: i64,
112+ pool_approved: i64,
113+ pool_published: i64,
114+ lessons_attended: i64,
115+ high_mark: i64,
116+ /// The longest study run, off `study_streak_longest`. Named for the wire,
117+ /// like every field here, and never the run in progress.
118+ study_streak: i64,
82119 }
83120
84121 impl BadgeStats {
@@ -102,14 +139,42 @@ impl BadgeStats {
102139 self.pomodoro_focus_ms
103140 }
104141
105- /// All five counters off the user row, in one statement β€” a record lookup,
106- /// not a scan.
142+ pub fn get_marks_given(&self) -> i64 {
143+ self.marks_given
144+ }
145+
146+ pub fn get_lessons_held(&self) -> i64 {
147+ self.lessons_held
148+ }
149+
150+ pub fn get_pool_approved(&self) -> i64 {
151+ self.pool_approved
152+ }
153+
154+ pub fn get_pool_published(&self) -> i64 {
155+ self.pool_published
156+ }
157+
158+ pub fn get_lessons_attended(&self) -> i64 {
159+ self.lessons_attended
160+ }
161+
162+ pub fn get_high_mark(&self) -> i64 {
163+ self.high_mark
164+ }
165+
166+ pub fn get_study_streak(&self) -> i64 {
167+ self.study_streak
168+ }
169+
170+ /// Every counter off the user row, in one statement β€” a record lookup, not
171+ /// a scan.
107172 ///
108173 /// Each projection is `(column ?? 0)`, parenthesized because `??` binds
109174 /// loosely, and it is the whole stale-data story: the columns are
110175 /// `option<int>`, a row written before they existed carries none of them,
111176 /// 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
177+ /// row that is gone entirely reads as all zeros too β€” a badge sync is not
113178 /// the place to discover a deleted account.
114179 pub async fn load(user: &UserId, db: &Database) -> Result<BadgeStats, AppError> {
115180 let mut result = db
@@ -118,13 +183,27 @@ impl BadgeStats {
118183 ({homework_on_time} ?? 0) AS homework_on_time,
119184 ({exam_sat} ?? 0) AS exam_sat,
120185 ({pomodoro_finished} ?? 0) AS pomodoro_finished,
121- ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms
186+ ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms,
187+ ({marks_given} ?? 0) AS marks_given,
188+ ({lessons_held} ?? 0) AS lessons_held,
189+ ({pool_approved} ?? 0) AS pool_approved,
190+ ({pool_published} ?? 0) AS pool_published,
191+ ({lessons_attended} ?? 0) AS lessons_attended,
192+ ({high_mark} ?? 0) AS high_mark,
193+ ({study_streak} ?? 0) AS study_streak
122194 FROM $usr",
123195 homework_submitted = BadgeStat::HomeworkSubmitted.field(),
124196 homework_on_time = BadgeStat::HomeworkOnTime.field(),
125197 exam_sat = BadgeStat::ExamSat.field(),
126198 pomodoro_finished = BadgeStat::PomodoroFinished.field(),
127199 pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(),
200+ marks_given = BadgeStat::MarksGiven.field(),
201+ lessons_held = BadgeStat::LessonsHeld.field(),
202+ pool_approved = BadgeStat::PoolApproved.field(),
203+ pool_published = BadgeStat::PoolPublished.field(),
204+ lessons_attended = BadgeStat::LessonsAttended.field(),
205+ high_mark = BadgeStat::HighMark.field(),
206+ study_streak = BadgeStat::StudyStreak.field(),
128207 ))
129208 .bind(("usr", user.record()))
130209 .await?
@@ -153,6 +232,13 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> {
153232 BadgeStat::ExamSat => stats.exam_sat,
154233 BadgeStat::PomodoroFinished => stats.pomodoro_finished,
155234 BadgeStat::PomodoroFocusMs => stats.pomodoro_focus_ms,
235+ BadgeStat::MarksGiven => stats.marks_given,
236+ BadgeStat::LessonsHeld => stats.lessons_held,
237+ BadgeStat::PoolApproved => stats.pool_approved,
238+ BadgeStat::PoolPublished => stats.pool_published,
239+ BadgeStat::LessonsAttended => stats.lessons_attended,
240+ BadgeStat::HighMark => stats.high_mark,
241+ BadgeStat::StudyStreak => stats.study_streak,
156242 };
157243 value >= *threshold
158244 })
@@ -258,6 +344,7 @@ pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> {
258344 #[cfg(test)]
259345 mod tests {
260346 use super::*;
347+ use crate::constant::{STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD};
261348
262349 /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled
263350 /// with the same `IF NOT EXISTS` guards the migration uses, so it is a
@@ -269,6 +356,15 @@ mod tests {
269356 DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option<int>;
270357 DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option<int>;
271358 DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option<int>;
359+ DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option<int>;
360+ DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option<int>;
361+ DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>;
362+ DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>;
363+ DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option<int>;
364+ DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option<int>;
365+ DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option<int>;
366+ DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option<int>;
367+ DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option<int>;
272368 DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL;
273369 DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record<user>;
274370 DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string;
@@ -326,6 +422,13 @@ mod tests {
326422 (BadgeStat::ExamSat, "exam_sat"),
327423 (BadgeStat::PomodoroFinished, "pomodoro_finished"),
328424 (BadgeStat::PomodoroFocusMs, "pomodoro_focus_ms"),
425+ (BadgeStat::MarksGiven, "marks_given"),
426+ (BadgeStat::LessonsHeld, "lessons_held"),
427+ (BadgeStat::PoolApproved, "pool_approved"),
428+ (BadgeStat::PoolPublished, "pool_published"),
429+ (BadgeStat::LessonsAttended, "lessons_attended"),
430+ (BadgeStat::HighMark, "high_mark"),
431+ (BadgeStat::StudyStreak, "study_streak"),
329432 ] {
330433 assert_eq!(stat.as_str(), wire, "the published name is frozen");
331434 assert_ne!(stat.as_str(), stat.field(), "{stat:?} collapsed the two");
@@ -333,7 +436,7 @@ mod tests {
333436 }
334437
335438 #[tokio::test]
336- async fn a_row_without_the_columns_loads_as_five_zeros() {
439+ async fn a_row_without_the_columns_loads_as_zeros() {
337440 let db = crate::database::init_mem().await.unwrap();
338441 schema(&db).await;
339442 // The stale-data case: an account written before the counters existed
@@ -345,6 +448,13 @@ mod tests {
345448 assert_eq!(stats.get_exam_sat(), 0);
346449 assert_eq!(stats.get_pomodoro_finished(), 0);
347450 assert_eq!(stats.get_pomodoro_focus_ms(), 0);
451+ assert_eq!(stats.get_marks_given(), 0);
452+ assert_eq!(stats.get_lessons_held(), 0);
453+ assert_eq!(stats.get_pool_approved(), 0);
454+ assert_eq!(stats.get_pool_published(), 0);
455+ assert_eq!(stats.get_lessons_attended(), 0);
456+ assert_eq!(stats.get_high_mark(), 0);
457+ assert_eq!(stats.get_study_streak(), 0);
348458 assert!(earned(&stats).is_empty(), "zero earns nothing");
349459 }
350460 }
@@ -357,6 +467,10 @@ mod tests {
357467 exam_sat: 0,
358468 pomodoro_finished: 200,
359469 pomodoro_focus_ms: 36_000_000,
470+ high_mark: 1,
471+ // The longest run, so 7 keeps the 3 even once the run breaks.
472+ study_streak: 7,
473+ ..BadgeStats::default()
360474 };
361475 assert_eq!(
362476 earned(&stats),
@@ -370,6 +484,9 @@ mod tests {
370484 "pomodoro_finished_200",
371485 // Exactly at the threshold earns it.
372486 "pomodoro_focus_ms_36000000",
487+ "high_mark_1",
488+ "study_streak_3",
489+ "study_streak_7",
373490 ]
374491 );
375492 }
src/domain/exam_result.rsmodified+111 -3
@@ -3,7 +3,8 @@ use std::collections::HashMap;
33 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
44
55 use crate::constant::{
6- EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, REF_RETIRED_FIELD,
6+ EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD,
7+ KIND_REF_TABLE, MARKS_GIVEN_TOTAL_FIELD, REF_COUNT_FIELD, REF_RETIRED_FIELD,
78 };
89 use crate::database::{Database, transaction_with_retry};
910 use crate::domain::cap;
@@ -201,6 +202,14 @@ impl ExamResult {
201202 /// one mark, one reference, so the branch that finds a row simply leaves
202203 /// both counters where they are β€” there is no claim to give back, and so no
203204 /// window in which a crash could fail to give it.
205+ ///
206+ /// The two badge counters ride that same first-time branch: the grader's
207+ /// `marks_given_total`, and β€” only when the mark clears
208+ /// [`HIGH_MARK_MIN`] β€” the student's `high_mark_total`. So a regrade of a
209+ /// sitting moves neither however often it is run, while a retake, being a
210+ /// distinct `seq` and so a distinct row, counts on its own. They are
211+ /// written field-scoped: a user row also carries admin-owned data (`role`)
212+ /// that a whole-row save would revert.
204213 pub async fn grade(
205214 exam: &ExamId,
206215 user: &UserId,
@@ -246,6 +255,17 @@ impl ExamResult {
246255 // the index entry can only ever point at the row the id already names
247256 // and the write resolves onto it. A lost round aborts having written
248257 // nothing, counters included.
258+ // Below the line the student's counter is left out of the statement
259+ // list entirely, rather than added to by a zero: a low mark is most
260+ // marks, and it must not write the student's row at all.
261+ let high_mark = if mark.as_i64() >= HIGH_MARK_MIN {
262+ format!(
263+ "UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} =
264+ ({HIGH_MARK_TOTAL_FIELD} ?? 0) + 1;"
265+ )
266+ } else {
267+ String::new()
268+ };
249269 let _guard = cap::counter_lock().await;
250270 let (mut written, mut errors) = transaction_with_retry(
251271 db,
@@ -260,6 +280,9 @@ impl ExamResult {
260280 IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }};
261281 UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} =
262282 ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1;
283+ UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
284+ ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1;
285+ {high_mark}
263286 }};
264287 LET $after = (UPSERT $id CONTENT $result RETURN AFTER);
265288 RETURN $after[0];
@@ -269,6 +292,8 @@ impl ExamResult {
269292 ("exam".into(), exam.record().into_value()),
270293 ("id".into(), result.id.record().into_value()),
271294 ("kref".into(), kind_ref(kind).into_value()),
295+ ("grader".into(), graded_by.record().into_value()),
296+ ("student".into(), user.record().into_value()),
272297 ("result".into(), result.into_value()),
273298 ],
274299 &["exam_missing", "exam_draft", RETIRED_MARK],
@@ -570,6 +595,9 @@ mod tests {
570595 .unwrap();
571596 }
572597
598+ const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA";
599+ const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA";
600+
573601 async fn grade(
574602 db: &Database,
575603 exam: &ExamId,
@@ -579,10 +607,10 @@ mod tests {
579607 ) -> Result<ExamResult, AppError> {
580608 ExamResult::grade(
581609 exam,
582- &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"),
610+ &UserId::from_key(STUDENT),
583611 seq,
584612 Mark::try_new(mark).unwrap(),
585- &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"),
613+ &UserId::from_key(TEACHER),
586614 kind,
587615 db,
588616 )
@@ -612,6 +640,86 @@ mod tests {
612640 assert_eq!(counters(&db, "midterm").await, (2, 2));
613641 }
614642
643+ /// The two badge counters, re-read out of the store: the grader's marks
644+ /// given and the student's high marks.
645+ async fn badge_counters(db: &Database) -> (i64, i64) {
646+ let mut result = db
647+ .query(format!(
648+ "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader;
649+ SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;"
650+ ))
651+ .bind(("grader", UserId::from_key(TEACHER).record()))
652+ .bind(("student", UserId::from_key(STUDENT).record()))
653+ .await
654+ .unwrap()
655+ .check()
656+ .unwrap();
657+ let given: Vec<i64> = result.take(0).unwrap();
658+ let high: Vec<i64> = result.take(1).unwrap();
659+ (
660+ given.into_iter().next().unwrap_or(0),
661+ high.into_iter().next().unwrap_or(0),
662+ )
663+ }
664+
665+ /// The rows a counter needs to land on β€” `UPDATE` writes nothing to a user
666+ /// that does not exist, so the badge tests must make both real.
667+ async fn the_two_people(db: &Database) {
668+ for key in [TEACHER, STUDENT] {
669+ db.query("CREATE $usr SET username = $name, password_hash = 'x'")
670+ .bind(("usr", UserId::from_key(key).record()))
671+ .bind(("name", key.to_string()))
672+ .await
673+ .unwrap()
674+ .check()
675+ .unwrap();
676+ }
677+ }
678+
679+ /// A first grade credits the grader once and the student only when the mark
680+ /// clears the line; a regrade of the same sitting credits neither again,
681+ /// while a retake β€” a distinct seq, so a distinct row β€” counts on its own.
682+ #[tokio::test]
683+ async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() {
684+ let db = init_mem().await.unwrap();
685+ let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA");
686+ an_exam(&db, &exam, "midterm").await;
687+ the_two_people(&db).await;
688+
689+ grade(&db, &exam, 1, 90, "midterm").await.unwrap();
690+ assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it");
691+
692+ // Same sitting graded again: neither counter may move, however high.
693+ grade(&db, &exam, 1, 100, "midterm").await.unwrap();
694+ assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing");
695+
696+ // A retake below the line: the grader is credited, the student is not.
697+ grade(&db, &exam, 2, 89, "midterm").await.unwrap();
698+ assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line");
699+
700+ // …and a high-scoring retake counts as its own sitting.
701+ grade(&db, &exam, 3, 95, "midterm").await.unwrap();
702+ assert_eq!(badge_counters(&db).await, (3, 2));
703+ }
704+
705+ /// A refused mark leaves the badge counters where the other two are left.
706+ #[tokio::test]
707+ async fn a_refused_mark_credits_nobody() {
708+ let db = init_mem().await.unwrap();
709+ let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA");
710+ an_exam(&db, &exam, "midterm").await;
711+ the_two_people(&db).await;
712+ db.query("UPDATE $ex SET draft = true")
713+ .bind(("ex", exam.record()))
714+ .await
715+ .unwrap()
716+ .check()
717+ .unwrap();
718+
719+ assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err());
720+ assert_eq!(badge_counters(&db).await, (0, 0));
721+ }
722+
615723 /// A retired kind refuses the claim from inside the transaction, which
616724 /// takes the mark and the exam's counter down with it β€” the settings guard
617725 /// enforcing the same invariant from the other side.
src/domain/homework_result.rsmodified+86 -4
@@ -13,7 +13,9 @@
1313
1414 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1515
16-use crate::constant::{HOMEWORK_RESULT_TABLE, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD};
16+use crate::constant::{
17+ HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD,
18+};
1719 use crate::database::Database;
1820 use crate::domain::course::CourseId;
1921 use crate::domain::exam_result::Mark;
@@ -164,22 +166,47 @@ impl HomeworkResult {
164166 graded_by: graded_by.clone(),
165167 created_at: Timestamp::now(),
166168 };
169+ // Whether the pair was already graded is read one statement ahead of
170+ // the write, inside the same transaction β€” it is what keeps a regrade
171+ // from crediting the grader a second time. No mark counter here: a
172+ // homework mark is optional and most grades are status-only, so
173+ // `high_mark` is an exam-only family.
174+ //
175+ // ponytail: this is a plain query, not `transaction_with_retry`, so a
176+ // store conflict on the grader's row β€” another domain writing the same
177+ // user row in the same instant β€” comes back as a 500 rather than a
178+ // re-send. Rare (grading is serialised by `HOMEWORK_LOCK` and a
179+ // teacher's row moves nowhere else but exam grading), and the upgrade
180+ // is the shape `HomeworkSubmission::upsert` already uses: the whole
181+ // transaction is re-sendable, since nothing in it can legitimately
182+ // answer "already exists".
167183 let mut saved = db
168184 .query(format!(
169185 "BEGIN TRANSACTION;
170- UPSERT $id CONTENT $row RETURN AFTER;
186+ LET $before = (SELECT VALUE id FROM ONLY $id);
187+ LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
171188 UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \
172189 WHERE {SUBMISSION_OPEN_GUARD};
190+ IF $before = NONE {{
191+ UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
192+ ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1
193+ }};
194+ RETURN $after;
173195 COMMIT TRANSACTION;"
174196 ))
175197 .bind(("id", id.record()))
176198 .bind(("sub", submission.record()))
199+ .bind(("grader", graded_by.record()))
177200 .bind(("row", result.into_value()))
178201 .await?
179202 .check()?;
180- // BEGIN is slot 0; the result's UPSERT is slot 1, the stamp slot 2.
203+ // The trailing `RETURN` is always the last statement before `COMMIT`,
204+ // so its slot follows the statement count instead of a hand-kept
205+ // number β€” which the counter statement above would otherwise have
206+ // shifted, silently handing back the stamp's row.
207+ let slot = saved.num_statements().saturating_sub(2);
181208 saved
182- .take::<Vec<HomeworkResult>>(1)?
209+ .take::<Vec<HomeworkResult>>(slot)?
183210 .into_iter()
184211 .next()
185212 .ok_or_else(|| AppError::Internal("failed to record homework result".into()))
@@ -339,4 +366,59 @@ mod tests {
339366 .is_none()
340367 );
341368 }
369+
370+ /// The grader is credited once per graded pair: a regrade lands on the same
371+ /// row, so it is not a mark given twice. The student's counters are not
372+ /// touched at all β€” a homework grade is not a homework submission.
373+ #[tokio::test]
374+ async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() {
375+ let db = crate::database::init_mem().await.unwrap();
376+ let homework = HomeworkId::from_key("01TESTHWBADGEAAAAAAAAAAAAA");
377+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
378+ let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
379+ // `UPDATE` writes nothing to a user row that does not exist.
380+ db.query("CREATE $usr SET username = 't', password_hash = 'x'")
381+ .bind(("usr", teacher.record()))
382+ .await
383+ .unwrap()
384+ .check()
385+ .unwrap();
386+
387+ for status in ["incomplete", "done"] {
388+ HomeworkResult::grade(
389+ &homework,
390+ &user,
391+ HomeworkStatus::try_new(status).unwrap(),
392+ None,
393+ &teacher,
394+ &db,
395+ )
396+ .await
397+ .unwrap();
398+ }
399+ assert_eq!(
400+ marks_given(&teacher, &db).await,
401+ 1,
402+ "one graded pair, one mark given"
403+ );
404+ }
405+
406+ /// The grader's badge counter, re-read out of the store.
407+ async fn marks_given(user: &UserId, db: &Database) -> i64 {
408+ let mut result = db
409+ .query(format!(
410+ "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr"
411+ ))
412+ .bind(("usr", user.record()))
413+ .await
414+ .unwrap()
415+ .check()
416+ .unwrap();
417+ result
418+ .take::<Vec<i64>>(0)
419+ .unwrap()
420+ .into_iter()
421+ .next()
422+ .unwrap_or(0)
423+ }
342424 }
src/domain/pomodoro.rsmodified+250 -1
@@ -2,6 +2,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
33 use crate::constant::{
44 POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE,
5+ STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD,
56 };
67 use crate::database::{Database, transaction_with_retry};
78 use crate::domain::badge;
@@ -130,7 +131,51 @@ impl PomodoroSession {
130131 /// nothing downstream needs a floor. Only *finished* stints reach here β€” an
131132 /// open row is a `pomodoro_session` row and nothing else β€” and there is no
132133 /// student-facing delete for a stint, so neither counter ever decrements.
134+ ///
135+ /// The **study streak** rides the same transaction. A study day is a UTC
136+ /// calendar day on which a stint was *finished* (midnight UTC, like every
137+ /// other day calculation here β€” no timezone is stored anywhere): the same
138+ /// day again changes nothing, the next day extends the run, any other gap
139+ /// starts a new one at 1. It is written as **two** statements, not one:
140+ /// every field reference on the right-hand side of a `SET` resolves
141+ /// against the row as it was *before* that statement, so a single
142+ /// `SET current = …, longest = math::max([longest, current])` would take
143+ /// the *old* `current` and lag one write behind forever (probed on a real
144+ /// 3.2.3 server: day two left `current = 2, longest = 1`). Across
145+ /// statements *inside a transaction* the read does see the prior write, so
146+ /// the pair is correct and still atomic. Absent columns are read through
147+ /// `?? 0` (and `?? -1` for the day β€” a sentinel no real day number
148+ /// reaches), because `math::max` errors outright on a `NONE` argument and
149+ /// every account older than these columns carries none of them.
150+ ///
151+ /// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two
152+ /// lines up: a plain `UPDATE` hands back an array, so a user row that is
153+ /// missing (a `record<user>` column checks only the table of the id) simply
154+ /// yields nothing to index and the second statement matches no row either.
155+ /// `UPDATE ONLY` would work too β€” it answers `null`, not an error, on zero
156+ /// rows; it errors on *many* β€” but a `null` is a shape the read then has to
157+ /// special-case, so the file's existing idiom wins.
158+ ///
159+ /// No `cap::counter_lock` is taken, deliberately. The pair cannot tear:
160+ /// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts
161+ /// a rival that touched the row in between β€” `transaction_with_retry` then
162+ /// re-sends the whole round. And `longest` is written as
163+ /// `max(longest, current)`, which cannot come down under *any*
164+ /// interleaving, so even a torn pair could only under-count `current`,
165+ /// never lower the high-water mark the badges read. The lock would only
166+ /// serialize this process's writers (its other job, keeping the in-memory
167+ /// test engine deterministic, is moot here β€” these tests are sequential).
168+ /// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent
169+ /// finishes for one user left `current = 60, longest = 60` with no
170+ /// anomaly; a rival write forced *between* the two statements (a `sleep`
171+ /// wedged into the batch) aborted the whole cascade with a write conflict,
172+ /// wrote nothing, and left the rival's value standing.
173+ ///
174+ /// Streaks begin at this deploy: nothing reconstructs history from the
175+ /// stint log, so every account starts with no streak columns and its first
176+ /// finish sets a run of 1.
133177 pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> {
178+ let done = Timestamp::now();
134179 let (mut result, mut errors) = transaction_with_retry(
135180 db,
136181 &format!(
@@ -141,6 +186,18 @@ impl PomodoroSession {
141186 {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1,
142187 {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)
143188 + (math::max([$before[0].started_at, $done]) - $before[0].started_at);
189+ LET $streak = (UPDATE $usr SET
190+ {STUDY_STREAK_CURRENT_FIELD} =
191+ IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day
192+ THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0)
193+ ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1)
194+ THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1)
195+ ELSE 1 END,
196+ {STUDY_STREAK_LAST_DAY_FIELD} = $day
197+ RETURN AFTER);
198+ UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([
199+ ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
200+ ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]);
144201 CREATE $closed CONTENT {{
145202 user: $before[0].user,
146203 started_at: $before[0].started_at,
@@ -158,7 +215,8 @@ impl PomodoroSession {
158215 "closed".into(),
159216 PomodoroSessionId::generate().record().into_value(),
160217 ),
161- ("done".into(), Timestamp::now().into_value()),
218+ ("done".into(), done.into_value()),
219+ ("day".into(), done.day_number().into_value()),
162220 ],
163221 &["no_pomodoro_running"],
164222 )
@@ -256,6 +314,197 @@ mod tests {
256314 (row[0], row[1])
257315 }
258316
317+ /// `(current, longest, last_day)` re-read from the store.
318+ async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
319+ let mut result = db
320+ .query(format!(
321+ "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0),
322+ ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
323+ ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr"
324+ ))
325+ .bind(("usr", user.record()))
326+ .await
327+ .unwrap()
328+ .check()
329+ .unwrap();
330+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
331+ let row = rows.into_iter().next().expect("the user row");
332+ (row[0], row[1], row[2])
333+ }
334+
335+ /// Age the streak bookkeeping by `days`, so the *next* finish lands that
336+ /// many days later on the calendar. The day is injected into the stored
337+ /// state rather than into the clock, which keeps `Timestamp::now` the sole
338+ /// clock read and the test free of sleeping.
339+ ///
340+ /// Known flake, left as-is: every caller assumes the UTC day does not turn
341+ /// over mid-test β€” a crossing between two stints shifts the real day under
342+ /// the injected one and reddens the run. That is one ~ms-wide window per
343+ /// day (~5e-6 per run), and the alternative is a clock seam in production
344+ /// code to serve a test. Re-run before believing a failure that only ever
345+ /// happens near midnight UTC.
346+ async fn age_by_days(user: &UserId, db: &Database, days: i64) {
347+ db.query(format!(
348+ "UPDATE $usr SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days"
349+ ))
350+ .bind(("usr", user.record()))
351+ .bind(("days", days))
352+ .await
353+ .unwrap()
354+ .check()
355+ .unwrap();
356+ }
357+
358+ /// Start and close one stint.
359+ async fn one_stint(user: &UserId, db: &Database) {
360+ PomodoroSession::start(user, db).await.unwrap();
361+ PomodoroSession::finish(user, db).await.unwrap();
362+ }
363+
364+ #[tokio::test]
365+ async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
366+ let db = database::init_mem().await.unwrap();
367+ let user = a_user(&db).await;
368+ // The stale-data case: a row that predates all three columns reads as
369+ // no streak at all, and its first finish opens a run of one.
370+ assert_eq!(streak(&user, &db).await, (0, 0, -1));
371+
372+ one_stint(&user, &db).await;
373+ let today = Timestamp::now().day_number();
374+ assert_eq!(streak(&user, &db).await, (1, 1, today));
375+
376+ // A second stint the same day is not a second day.
377+ one_stint(&user, &db).await;
378+ assert_eq!(streak(&user, &db).await, (1, 1, today));
379+
380+ // Days N+1 and N+2.
381+ for day in 2..=3 {
382+ age_by_days(&user, &db, 1).await;
383+ one_stint(&user, &db).await;
384+ assert_eq!(streak(&user, &db).await, (day, day, today));
385+ }
386+ }
387+
388+ #[tokio::test]
389+ async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
390+ let db = database::init_mem().await.unwrap();
391+ let user = a_user(&db).await;
392+
393+ one_stint(&user, &db).await;
394+ age_by_days(&user, &db, 1).await;
395+ one_stint(&user, &db).await;
396+ assert_eq!(streak(&user, &db).await.0, 2);
397+
398+ // Skip a day: the run restarts at one, the longest stays where it got.
399+ age_by_days(&user, &db, 2).await;
400+ one_stint(&user, &db).await;
401+ let (current, longest, _) = streak(&user, &db).await;
402+ assert_eq!((current, longest), (1, 2));
403+
404+ // A backwards day (a clock stepped back over a boundary) is a gap too,
405+ // and still cannot lower the mark.
406+ age_by_days(&user, &db, -5).await;
407+ one_stint(&user, &db).await;
408+ assert_eq!(
409+ streak(&user, &db).await,
410+ (1, 2, Timestamp::now().day_number())
411+ );
412+ }
413+
414+ /// The transaction boundary itself, on a real server: the streak pair and
415+ /// the counters must commit with the stint or not at all, under real
416+ /// contention on one user row.
417+ ///
418+ /// Multi-threaded and off the embedded engine for the reason
419+ /// [`crate::domain::cap`] spells out: the in-memory engine does not
420+ /// conflict-check two concurrent writes to one record, so it would answer
421+ /// `Ok` to a write it dropped and *forge* the integrity failure this test
422+ /// exists to catch.
423+ ///
424+ /// It bites β€” proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT`
425+ /// pair from the batch turns all 20 rounds red. A `THROW` then errors only
426+ /// its own statement, so the losers of the open-row race run the rest of
427+ /// the cascade anyway β€” they bump the counters for a stint they never
428+ /// closed and `CREATE` a session row out of an empty `$before`, which comes
429+ /// back as `500 … Expected record, got none` (the `errors` assertion below
430+ /// fires first; `finished_total` running ahead of the `Ok` finishes is the
431+ /// same wound one statement later). What it does *not* pin is the
432+ /// streak arithmetic under concurrency: same-day finishes all compute the
433+ /// same value, so that stays green either way β€” it is
434+ /// `max(longest, current)` that makes that robust, not the isolation.
435+ ///
436+ /// The shape of the contention, measured rather than assumed: four racers
437+ /// per round is four `start`s collapsing onto *one* open row (the id is
438+ /// deterministic per user), so typically exactly one `finish` commits and
439+ /// three lose the `DELETE` and abort their whole cascade β€” 20 finishes and
440+ /// 60 conflicts over 20 rounds, measured. That is the contention: the
441+ /// losers' cascades are live against the same user row, which is precisely
442+ /// what must leave nothing behind. Two commits in one round are possible
443+ /// (a racer scheduled entirely after another's finish frees the slot) and
444+ /// the assertions allow it β€” the day count is per round, not per stint.
445+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
446+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
447+ async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
448+ let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await;
449+ let user = a_user(&db).await;
450+ let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
451+ let mut last_error = String::new();
452+ for round in 1..=20 {
453+ let racers: Vec<_> = (0..4)
454+ .map(|_| {
455+ let (user, db) = (user.clone(), db.clone());
456+ tokio::spawn(async move {
457+ PomodoroSession::start(&user, &db).await?;
458+ PomodoroSession::finish(&user, &db).await
459+ })
460+ })
461+ .collect();
462+ let mut won = 0;
463+ for racer in racers {
464+ match racer.await.unwrap() {
465+ Ok(_) => won += 1,
466+ // Losing the open row is the correct answer for a racer
467+ // whose stint someone else closed; only `Db` is a defect.
468+ Err(AppError::Conflict(_)) => conflicts += 1,
469+ Err(err) => {
470+ errors += 1;
471+ last_error = format!("{err:?}");
472+ }
473+ }
474+ }
475+ finished += won;
476+ // One day per round, however many stints landed in it, and the
477+ // mark never lags the run in progress.
478+ let (current, longest, _) = streak(&user, &db).await;
479+ assert_eq!(
480+ (current, longest),
481+ (round, round),
482+ "round {round} counted {won} finishes as {current} days"
483+ );
484+ age_by_days(&user, &db, 1).await;
485+ }
486+ // The atomicity claim: the counter counts exactly the stints that were
487+ // closed, never a loser's aborted round.
488+ let (counted, _) = counters(&user, &db).await;
489+ eprintln!(
490+ "PomodoroSession::finish raced: {finished} finishes over 20 days, \
491+ {conflicts} rivals refused, {errors} 500s"
492+ );
493+ assert_eq!(
494+ errors, 0,
495+ "a raced finish must conflict, not 500: {last_error}"
496+ );
497+ assert_eq!(
498+ counted, finished,
499+ "the counter counted {counted} stints for {finished} finishes"
500+ );
501+ assert!(
502+ conflicts > 0,
503+ "every racer won its own round, so no cascade was ever aborted mid-flight \
504+ and this run proves nothing about the transaction boundary"
505+ );
506+ }
507+
259508 #[tokio::test]
260509 async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
261510 let db = database::init_mem().await.unwrap();
src/domain/pool_question.rsmodified+178 -15
@@ -13,10 +13,10 @@
1313 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
1414
1515 use crate::constant::{
16- MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED,
17- STATUS_PENDING,
16+ MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_APPROVED_TOTAL_FIELD,
17+ POOL_PUBLISHED_TOTAL_FIELD, POOL_QUESTION_TABLE, STATUS_APPROVED, STATUS_PENDING,
1818 };
19-use crate::database::Database;
19+use crate::database::{Database, transaction_with_retry};
2020 use crate::domain::monotonic_id::next_ulid;
2121 use crate::domain::note_file::FileContentType;
2222 use crate::domain::solution::Solution;
@@ -202,23 +202,76 @@ impl PoolQuestion {
202202 /// racing approvals exactly one wins, and an approve can never land on a
203203 /// question deleted mid-flight. `None` = the question wasn't pending
204204 /// (already approved, or gone) β€” the caller sorts out which.
205+ ///
206+ /// Two lifetime badge counters ride that same guard, inside this
207+ /// transaction: the approver's `pool_approved_total` and the *asker's*
208+ /// `pool_published_total`. Both hang off `array::len($done) > 0` β€” the
209+ /// guard's own verdict β€” so the pair moves once per real transition and
210+ /// never on a second approve of an already-approved question.
211+ /// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that
212+ /// holds.) The second conjunct is the self-approval rule below.
213+ ///
214+ /// Two rules keep the pair unfarmable, one per side of the transition.
215+ ///
216+ /// The asker is credited at *approval*, not at asking: a bare
217+ /// [`insert`](PoolQuestion::insert) is self-service and the author can
218+ /// delete their own question and ask again forever, so a counter moved
219+ /// there is farmable. Approval is teacher-gated and one-way, which is why
220+ /// the family is named `pool_published` and not `pool_asked`. That closes
221+ /// the student side.
222+ ///
223+ /// And a *self*-approval β€” a teacher+ approving a question they asked
224+ /// themselves, which the route deliberately still allows β€” moves neither
225+ /// counter, hence the `$done[0].asker != $by` half of the condition. It is
226+ /// the same farm from the other end (ask, approve, delete, repeat, with no
227+ /// second person involved), and the two together are why a counter can only
228+ /// move when one person's work was judged by another's. Nothing else about
229+ /// a self-approval changes: same 200, same freeze, same stamp β€” this skips
230+ /// the credit, not the approval.
231+ ///
232+ /// Re-sent while the store answers "conflict, retry": the guard reads a
233+ /// column a rival approve writes, and both counters sit on user rows every
234+ /// other counter site writes too. Sound to re-send β€” every statement is an
235+ /// `UPDATE`, none of which can legitimately answer "already exists" β€” and a
236+ /// lost round aborts having written nothing, increments included.
205237 pub async fn approve(
206238 id: &PoolQuestionId,
207239 approver: &UserId,
208240 db: &Database,
209241 ) -> Result<Option<PoolQuestion>, AppError> {
210- let mut result = db
211- .query(
212- "UPDATE $q SET status = $approved, approved_by = $by \
213- WHERE status = $pending RETURN AFTER",
214- )
215- .bind(("q", id.record()))
216- .bind(("approved", STATUS_APPROVED))
217- .bind(("by", approver.record()))
218- .bind(("pending", STATUS_PENDING))
219- .await?
220- .check()?;
221- Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next())
242+ let (mut result, mut errors) = transaction_with_retry(
243+ db,
244+ &format!(
245+ "BEGIN TRANSACTION;
246+ LET $done = (UPDATE $q SET status = $approved, approved_by = $by
247+ WHERE status = $pending RETURN AFTER);
248+ IF array::len($done) > 0 AND $done[0].asker != $by {{
249+ UPDATE $by SET
250+ {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1;
251+ LET $asker = $done[0].asker;
252+ UPDATE $asker SET
253+ {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1;
254+ }};
255+ RETURN $done;
256+ COMMIT TRANSACTION;"
257+ ),
258+ &[
259+ ("q".into(), id.record().into_value()),
260+ ("approved".into(), STATUS_APPROVED.to_string().into_value()),
261+ ("by".into(), approver.record().into_value()),
262+ ("pending".into(), STATUS_PENDING.to_string().into_value()),
263+ ],
264+ &[],
265+ )
266+ .await?;
267+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
268+ return Err(error.into());
269+ }
270+ // The trailing `RETURN` is always the last statement before `COMMIT`,
271+ // so its slot follows the statement count rather than a hand-kept
272+ // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2).
273+ let slot = result.num_statements().saturating_sub(2);
274+ Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next())
222275 }
223276
224277 /// Point the question at a freshly written image blob. Guarded on
@@ -303,6 +356,45 @@ mod tests {
303356 use crate::database;
304357 use crate::domain::solution::{Solution, SolutionBody};
305358
359+ /// The two counter columns plus a row to carry them: the `user` table is
360+ /// SCHEMAFULL in production, and the counters are `option<int>` there.
361+ async fn a_user(db: &Database) -> UserId {
362+ let user = UserId::from_key(&Ulid::new().to_string());
363+ db.query(format!(
364+ "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>;
365+ DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>;
366+ CREATE $usr SET username = $name, password_hash = 'x';"
367+ ))
368+ .bind(("usr", user.record()))
369+ .bind(("name", user.key().to_string()))
370+ .await
371+ .unwrap()
372+ .check()
373+ .unwrap();
374+ user
375+ }
376+
377+ /// `(pool_approved_total, pool_published_total)` as stored β€” absent reads
378+ /// zero, the way `BadgeStats::load` reads it.
379+ async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
380+ let mut result = db
381+ .query(format!(
382+ "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0),
383+ ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr"
384+ ))
385+ .bind(("usr", user.record()))
386+ .await
387+ .unwrap()
388+ .check()
389+ .unwrap();
390+ let rows = result.take::<Vec<Vec<i64>>>(0).unwrap();
391+ let row = rows.into_iter().next().unwrap_or_default();
392+ (
393+ row.first().copied().unwrap_or(0),
394+ row.get(1).copied().unwrap_or(0),
395+ )
396+ }
397+
306398 fn question(asker: &UserId) -> PoolQuestion {
307399 PoolQuestion::new(
308400 asker,
@@ -344,6 +436,77 @@ mod tests {
344436 );
345437 }
346438
439+ /// The publish counters ride the guard, so they move exactly once per real
440+ /// transition: the approver's on the approve side, the asker's on the
441+ /// published side, and neither on a second approve of the same question.
442+ #[tokio::test]
443+ async fn approval_moves_both_counters_once_and_only_once() {
444+ let db = database::init_mem().await.unwrap();
445+ let asker = a_user(&db).await;
446+ let teacher = a_user(&db).await;
447+
448+ let q = question(&asker).insert(&db).await.unwrap();
449+ assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero");
450+
451+ PoolQuestion::approve(q.get_id(), &teacher, &db)
452+ .await
453+ .unwrap()
454+ .unwrap();
455+ assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver");
456+ assert_eq!(counters(&asker, &db).await, (0, 1), "the asker");
457+
458+ // The guard finds nothing pending, so neither counter may move β€” this
459+ // is what stops an approve loop from farming either one.
460+ assert!(
461+ PoolQuestion::approve(q.get_id(), &teacher, &db)
462+ .await
463+ .unwrap()
464+ .is_none()
465+ );
466+ assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve");
467+ assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish");
468+
469+ // And an approve that lands on nothing at all writes nothing.
470+ assert!(
471+ PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db)
472+ .await
473+ .unwrap()
474+ .is_none()
475+ );
476+ assert_eq!(counters(&teacher, &db).await, (1, 0));
477+ }
478+
479+ /// A teacher may ask a question and the route does not bar them from
480+ /// approving it β€” that still works, unchanged. What it does not do is pay
481+ /// for itself: ask, approve, delete, repeat is the staff-side farm, and
482+ /// neither counter moves when one person is both ends of the transition.
483+ #[tokio::test]
484+ async fn self_approval_still_approves_but_moves_neither_counter() {
485+ let db = database::init_mem().await.unwrap();
486+ let teacher = a_user(&db).await;
487+
488+ let q = question(&teacher).insert(&db).await.unwrap();
489+ let approved = PoolQuestion::approve(q.get_id(), &teacher, &db)
490+ .await
491+ .unwrap()
492+ .unwrap();
493+ // The approval itself is untouched: published, stamped, frozen.
494+ assert!(approved.is_approved());
495+ assert_eq!(approved.get_approved_by(), Some(&teacher));
496+ assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit");
497+
498+ // And the skip is about the *pair*, not about the teacher: approving
499+ // somebody else's question right after still pays.
500+ let asker = a_user(&db).await;
501+ let other = question(&asker).insert(&db).await.unwrap();
502+ PoolQuestion::approve(other.get_id(), &teacher, &db)
503+ .await
504+ .unwrap()
505+ .unwrap();
506+ assert_eq!(counters(&teacher, &db).await, (1, 0));
507+ assert_eq!(counters(&asker, &db).await, (0, 1));
508+ }
509+
347510 #[tokio::test]
348511 async fn visibility_hides_others_pending_questions() {
349512 let db = database::init_mem().await.unwrap();
src/domain/profile.rsmodified+16 -2
@@ -201,13 +201,27 @@ impl ProfileStats {
201201 ({homework_on_time} ?? 0) AS homework_on_time,
202202 ({exam_sat} ?? 0) AS exam_sat,
203203 ({pomodoro_finished} ?? 0) AS pomodoro_finished,
204- ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms
204+ ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms,
205+ ({marks_given} ?? 0) AS marks_given,
206+ ({lessons_held} ?? 0) AS lessons_held,
207+ ({pool_approved} ?? 0) AS pool_approved,
208+ ({pool_published} ?? 0) AS pool_published,
209+ ({lessons_attended} ?? 0) AS lessons_attended,
210+ ({high_mark} ?? 0) AS high_mark,
211+ ({study_streak} ?? 0) AS study_streak
205212 FROM $usr;",
206213 homework_submitted = BadgeStat::HomeworkSubmitted.field(),
207214 homework_on_time = BadgeStat::HomeworkOnTime.field(),
208215 exam_sat = BadgeStat::ExamSat.field(),
209216 pomodoro_finished = BadgeStat::PomodoroFinished.field(),
210217 pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(),
218+ marks_given = BadgeStat::MarksGiven.field(),
219+ lessons_held = BadgeStat::LessonsHeld.field(),
220+ pool_approved = BadgeStat::PoolApproved.field(),
221+ pool_published = BadgeStat::PoolPublished.field(),
222+ lessons_attended = BadgeStat::LessonsAttended.field(),
223+ high_mark = BadgeStat::HighMark.field(),
224+ study_streak = BadgeStat::StudyStreak.field(),
211225 ))
212226 .bind(("usr", user.record()))
213227 .await?
@@ -215,7 +229,7 @@ impl ProfileStats {
215229 // `GROUP ALL` yields no row at all when nothing matched β€” that is the
216230 // zero case, not a missing one.
217231 let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next();
218- // A vanished user row reads as five zeros, same as a fresh account.
232+ // A vanished user row reads as all zeros, same as a fresh account.
219233 let totals = result
220234 .take::<Vec<BadgeStats>>(1)?
221235 .into_iter()
src/domain/session_attendance.rsmodified+425 -11
@@ -1,11 +1,15 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
3-use crate::constant::SESSION_ATTENDANCE_TABLE;
3+use crate::constant::{
4+ LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD,
5+ SESSION_ATTENDANCE_TABLE,
6+};
47 use crate::database::{Database, transaction_with_retry};
58 use crate::domain::attendance::AttendanceStatus;
69 use crate::domain::course::CourseId;
710 use crate::domain::course_session::{CourseSession, CourseSessionId};
811 use crate::domain::page::PagedList;
12+use crate::domain::timestamp::Timestamp;
913 use crate::domain::user::UserId;
1014 use crate::error::AppError;
1115
@@ -36,6 +40,22 @@ impl SessionAttendanceId {
3640 }
3741 }
3842
43+/// Whether a status means the person was *there*, for the `lessons_attended`
44+/// badge counter. Exactly the rule `GET /attendance/me` already publishes β€”
45+/// `StatusCounts::tally` in `src/web/attendance.rs` puts `present` and `late`
46+/// over the line and leaves `excused` and every school-added status neutral β€”
47+/// so a student's badge and their attendance rate never disagree about what
48+/// attending is.
49+///
50+/// Hardcoding the two literals is safe by construction: statuses are the
51+/// school's to extend, but [`crate::domain::settings`] refuses any write that
52+/// drops one of the core four, so `present` and `late` can never be renamed
53+/// away. The SQL below repeats them β€” they are one rule in two languages, and
54+/// the transition test is what pins them together.
55+fn counts_as_attended(status: &AttendanceStatus) -> bool {
56+ matches!(status.as_str(), "present" | "late")
57+}
58+
3959 /// One person's roll-call state for one lesson. `course` is denormalized from
4060 /// the session so the per-course attendance report is a single indexed query
4161 /// (`WHERE user = $u`) with no join.
@@ -86,13 +106,42 @@ impl SessionAttendance {
86106 /// route 404ing on the vanished session while the attendance report went
87107 /// on counting it. A deleted session reads NONE, which is falsy, so the
88108 /// gate is written as an explicit `IS NONE` (see
89- /// [`crate::domain::exam_result::ExamResult::grade`]).
109+ /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the
110+ /// session's `teacher` β€” required on every row, so NONE means "no row" just
111+ /// as `id` did β€” because the counter below needs that teacher anyway, and
112+ /// one read serves both.
90113 ///
91114 /// Sound to re-send while the store answers "conflict, retry": the gate
92115 /// reads the record a delete writes, so the two contend by design, and the
93116 /// UPSERT cannot legitimately answer "already exists" β€” its composite id is
94117 /// bijective with the `session_attendance_session_user` unique tuple, so
95118 /// the index entry can only point at the row the id already names.
119+ ///
120+ /// Two badge counters move in this same transaction, both of them read
121+ /// from the store rather than taken on the caller's word:
122+ ///
123+ /// - `lessons_attended_total`, on the person marked, as a *delta* rather
124+ /// than an increment, because this is an upsert: a re-mark that changes
125+ /// nothing must change nothing, and a teacher's correction must move it
126+ /// back down. `$was` is read before the upsert overwrites it (`NONE` when
127+ /// the pair has no row yet), so it writes only on a real crossing of the
128+ /// attended line, and only for a **student** β€” attending lessons is a
129+ /// student's badge, the same student-only rule enrolling and sitting an
130+ /// exam already carry, so a teacher marked present in their own lesson
131+ /// moves it in neither direction. The live `role` decides that, not the
132+ /// role someone held when the row was written.
133+ /// - `lessons_held_total`, on the *session's* teacher, exactly once per
134+ /// session: the first roll call taken stamps
135+ /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
136+ /// the stamp and credits nothing. It counts lessons that actually
137+ /// happened β€” scheduling one and cancelling it earns nothing, which is
138+ /// why the credit does not live in `CourseSession::create`. Two
139+ /// simultaneous first marks both write the lesson row, so the store's own
140+ /// conflict detection (and `transaction_with_retry` behind it) is what
141+ /// keeps the stamp from being set twice.
142+ ///
143+ /// Both are floored/guarded rather than trusting the column to exist: a row
144+ /// written before these columns carries none of them.
96145 pub async fn mark(
97146 session: &CourseSession,
98147 user: &UserId,
@@ -100,6 +149,8 @@ impl SessionAttendance {
100149 marked_by: &UserId,
101150 db: &Database,
102151 ) -> Result<SessionAttendance, AppError> {
152+ let attended = counts_as_attended(&status);
153+ let delta: i64 = if attended { 1 } else { -1 };
103154 let attendance = SessionAttendance {
104155 id: SessionAttendanceId::composite(session.get_id(), user),
105156 session: session.get_id().clone(),
@@ -110,16 +161,35 @@ impl SessionAttendance {
110161 };
111162 let (mut written, mut errors) = transaction_with_retry(
112163 db,
113- "BEGIN TRANSACTION;
114- IF (SELECT VALUE id FROM ONLY $sess) IS NONE { THROW 'session_missing' };
164+ &format!(
165+ "BEGIN TRANSACTION;
166+ LET $teacher = (SELECT VALUE teacher FROM ONLY $sess);
167+ IF $teacher IS NONE {{ THROW 'session_missing' }};
168+ LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess);
169+ LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
170+ LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']);
115171 LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
172+ IF $student AND $was != $now {{
173+ UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
174+ math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0])
175+ }};
176+ IF $counted IS NONE {{
177+ UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp;
178+ UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} =
179+ ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1
180+ }};
116181 RETURN $after;
117- COMMIT TRANSACTION;",
182+ COMMIT TRANSACTION;"
183+ ),
118184 &[
119185 // `$session` is SurrealDB's own protected variable (the auth
120186 // session): binding that name errors the whole query.
121187 ("sess".into(), session.get_id().record().into_value()),
122188 ("id".into(), attendance.id.record().into_value()),
189+ ("usr".into(), user.record().into_value()),
190+ ("now".into(), attended.into_value()),
191+ ("delta".into(), delta.into_value()),
192+ ("stamp".into(), Timestamp::now().into_value()),
123193 ("row".into(), attendance.into_value()),
124194 ],
125195 &["session_missing"],
@@ -175,17 +245,361 @@ impl SessionAttendance {
175245 Ok(result.take::<Vec<SessionAttendance>>(0)?)
176246 }
177247
248+ /// Clearing a row the student was counted for gives the count back, in the
249+ /// delete's own transaction β€” the other direction of the delta in
250+ /// [`SessionAttendance::mark`], so a row that never existed and a row that
251+ /// was withdrawn leave the same number behind. Only *this* route decrements:
252+ /// [`CourseSession::delete`]'s cascade sweeps the rows with a `DELETE` of
253+ /// its own and never comes through here, which is the ruling
254+ /// `exam_sat_total` already carries β€” deleting the lesson does not un-attend
255+ /// it. `lessons_held_total` is never given back either: the lesson was
256+ /// taken, and clearing one student's row does not un-take it.
257+ ///
258+ /// Student-only on the same terms as the mark, and read from the store for
259+ /// the same reason.
260+ ///
261+ /// Sound to re-send: neither statement can answer "already exists".
262+ //
263+ // ponytail: both ends read the *live* role, so a student promoted between
264+ // being marked present and having that row corrected leaves the counter one
265+ // high (the credit landed as a student, the refund is refused as staff).
266+ // Upgrade path is stamping the credit on the roll-call row itself and
267+ // refunding off that stamp, the way `counted_on_time` works for homework β€”
268+ // not worth a column until a promotion mid-term is a real complaint.
178269 pub async fn remove(
179270 session: &CourseSessionId,
180271 user: &UserId,
181272 db: &Database,
182273 ) -> Result<Option<SessionAttendance>, AppError> {
183- let mut result = db
184- .query("DELETE session_attendance WHERE session = $s AND user = $usr RETURN BEFORE")
185- .bind(("s", session.record()))
274+ let (mut result, mut errors) = transaction_with_retry(
275+ db,
276+ &format!(
277+ "BEGIN TRANSACTION;
278+ LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student');
279+ LET $gone = (DELETE session_attendance
280+ WHERE session = $s AND user = $usr RETURN BEFORE);
281+ IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{
282+ UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} =
283+ math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0])
284+ }};
285+ RETURN $gone;
286+ COMMIT TRANSACTION;"
287+ ),
288+ &[
289+ ("s".into(), session.record().into_value()),
290+ ("usr".into(), user.record().into_value()),
291+ ],
292+ &[],
293+ )
294+ .await?;
295+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
296+ return Err(error.into());
297+ }
298+ // The trailing `RETURN` is always the last statement before `COMMIT`.
299+ let slot = result.num_statements().saturating_sub(2);
300+ Ok(result
301+ .take::<Vec<SessionAttendance>>(slot)?
302+ .into_iter()
303+ .next())
304+ }
305+}
306+
307+#[cfg(test)]
308+mod tests {
309+ use super::*;
310+ use crate::constant::DEFAULT_ATTENDANCE_STATUSES;
311+ use crate::database::init_mem;
312+ use crate::domain::badge::BadgeStats;
313+ use crate::domain::course_session::SessionTopic;
314+ use crate::domain::role::Role;
315+
316+ /// A user row carrying its role β€” the counters are `UPDATE`s on one (which
317+ /// writes nothing at all to a record that does not exist), and the live
318+ /// role is what decides whether the attended counter moves.
319+ async fn a_user(key: &str, role: Role, db: &Database) -> UserId {
320+ let user = UserId::from_key(key);
321+ db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role")
186322 .bind(("usr", user.record()))
187- .await?
188- .check()?;
189- Ok(result.take::<Vec<SessionAttendance>>(0)?.into_iter().next())
323+ .bind(("name", key.to_string()))
324+ .bind(("role", role))
325+ .await
326+ .unwrap()
327+ .check()
328+ .unwrap();
329+ user
330+ }
331+
332+ async fn a_student(key: &str, db: &Database) -> UserId {
333+ a_user(key, Role::Student, db).await
334+ }
335+
336+ async fn a_teacher(key: &str, db: &Database) -> UserId {
337+ a_user(key, Role::Teacher, db).await
338+ }
339+
340+ async fn a_session(teacher: &UserId, db: &Database) -> CourseSession {
341+ CourseSession::create(
342+ &CourseId::from_key("c"),
343+ teacher,
344+ SessionTopic::try_new("limits").unwrap(),
345+ Timestamp::from_millis(1),
346+ None,
347+ db,
348+ )
349+ .await
350+ .unwrap()
351+ }
352+
353+ /// A status this school allows β€” the four core ones plus a school-added
354+ /// `online`, which is exactly the open half of the set.
355+ fn status(value: &str) -> AttendanceStatus {
356+ let allowed: Vec<String> = DEFAULT_ATTENDANCE_STATUSES
357+ .iter()
358+ .map(|s| s.to_string())
359+ .chain(["online".to_string()])
360+ .collect();
361+ AttendanceStatus::try_new(value, &allowed).unwrap()
362+ }
363+
364+ /// The two counters as the badge rules read them, off the stored row.
365+ async fn attended(user: &UserId, db: &Database) -> i64 {
366+ BadgeStats::load(user, db)
367+ .await
368+ .unwrap()
369+ .get_lessons_attended()
370+ }
371+
372+ async fn held(user: &UserId, db: &Database) -> i64 {
373+ BadgeStats::load(user, db).await.unwrap().get_lessons_held()
374+ }
375+
376+ /// The whole transition table in one pass: an upsert may only move the
377+ /// counter when the mark crosses the attended line, in either direction, so
378+ /// a re-mark and a swap within the same class are both no-ops.
379+ #[tokio::test]
380+ async fn the_counter_follows_every_crossing_and_no_other_move() {
381+ let db = init_mem().await.unwrap();
382+ let teacher = a_teacher("t", &db).await;
383+ let student = a_student("s", &db).await;
384+ let session = a_session(&teacher, &db).await;
385+ let mark = async |value: &str, db: &Database| {
386+ SessionAttendance::mark(&session, &student, status(value), &teacher, db)
387+ .await
388+ .unwrap();
389+ };
390+
391+ for (value, expected, why) in [
392+ ("present", 1, "first mark counts"),
393+ ("present", 1, "re-marking the same status changes nothing"),
394+ ("late", 1, "late is attending too, so no crossing"),
395+ ("absent", 0, "a correction gives the count back"),
396+ ("absent", 0, "and does not keep giving it back"),
397+ ("late", 1, "absent -> late crosses back up"),
398+ ("excused", 0, "excused is neutral: a crossing down"),
399+ ("online", 0, "a school-added status stays neutral"),
400+ ("present", 1, "…and crossing up from one still counts"),
401+ ("online", 0, "…as does crossing down to one"),
402+ ] {
403+ mark(value, &db).await;
404+ assert_eq!(attended(&student, &db).await, expected, "{why}");
405+ }
406+ assert_eq!(attended(&teacher, &db).await, 0, "credited the marker");
407+ // Ten marks, one lesson: correcting a roll call is not holding another.
408+ assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice");
409+ }
410+
411+ /// The lesson is credited to its teacher when the roll call is *taken*, and
412+ /// once: the whole roster, and every later correction, ride the same stamp.
413+ #[tokio::test]
414+ async fn the_first_roll_call_counts_the_lesson_once() {
415+ let db = init_mem().await.unwrap();
416+ let teacher = a_teacher("t", &db).await;
417+ let other = a_teacher("o", &db).await;
418+ let session = a_session(&teacher, &db).await;
419+ assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing");
420+
421+ for key in ["s1", "s2", "s3"] {
422+ let student = a_student(key, &db).await;
423+ SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
424+ .await
425+ .unwrap();
426+ assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again");
427+ }
428+ assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher");
429+
430+ // A second lesson is a second count β€” the stamp is per session.
431+ let second = a_session(&teacher, &db).await;
432+ let student = a_student("s4", &db).await;
433+ SessionAttendance::mark(&second, &student, status("present"), &teacher, &db)
434+ .await
435+ .unwrap();
436+ assert_eq!(held(&teacher, &db).await, 2);
437+ }
438+
439+ /// Attending lessons is a student's badge. A teacher marked present in
440+ /// their own lesson (which management does, not the teacher) moves nothing
441+ /// for them as an attendee β€” while the roll call itself still counts as a
442+ /// lesson held.
443+ #[tokio::test]
444+ async fn a_teacher_marked_present_earns_nothing_for_attending() {
445+ let db = init_mem().await.unwrap();
446+ let teacher = a_teacher("t", &db).await;
447+ let session = a_session(&teacher, &db).await;
448+
449+ SessionAttendance::mark(&session, &teacher, status("present"), &teacher, &db)
450+ .await
451+ .unwrap();
452+ assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson");
453+ assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken");
454+
455+ // And the correction direction is just as closed: nothing was taken, so
456+ // nothing may be given back.
457+ SessionAttendance::mark(&session, &teacher, status("absent"), &teacher, &db)
458+ .await
459+ .unwrap();
460+ assert_eq!(attended(&teacher, &db).await, 0);
461+ SessionAttendance::remove(session.get_id(), &teacher, &db)
462+ .await
463+ .unwrap()
464+ .expect("the row was there");
465+ assert_eq!(attended(&teacher, &db).await, 0);
466+ assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened");
467+ }
468+
469+ /// Two lessons are two counts β€” the counter is per row, not per student.
470+ #[tokio::test]
471+ async fn each_lesson_counts_once_for_the_student_marked() {
472+ let db = init_mem().await.unwrap();
473+ let teacher = a_teacher("t", &db).await;
474+ let student = a_student("s", &db).await;
475+ let other = a_student("o", &db).await;
476+ for _ in 0..2 {
477+ let session = a_session(&teacher, &db).await;
478+ SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
479+ .await
480+ .unwrap();
481+ }
482+ assert_eq!(attended(&student, &db).await, 2);
483+ assert_eq!(attended(&other, &db).await, 0, "credited the wrong student");
484+ }
485+
486+ /// Removing the row is the other direction of the delta, and only for a row
487+ /// that was counted.
488+ #[tokio::test]
489+ async fn removing_a_row_gives_back_only_what_it_took() {
490+ let db = init_mem().await.unwrap();
491+ let teacher = a_teacher("t", &db).await;
492+ let student = a_student("s", &db).await;
493+
494+ let counted = a_session(&teacher, &db).await;
495+ SessionAttendance::mark(&counted, &student, status("present"), &teacher, &db)
496+ .await
497+ .unwrap();
498+ let neutral = a_session(&teacher, &db).await;
499+ SessionAttendance::mark(&neutral, &student, status("absent"), &teacher, &db)
500+ .await
501+ .unwrap();
502+ assert_eq!(attended(&student, &db).await, 1);
503+
504+ SessionAttendance::remove(neutral.get_id(), &student, &db)
505+ .await
506+ .unwrap()
507+ .expect("the absent row was there");
508+ assert_eq!(attended(&student, &db).await, 1, "absent took nothing");
509+ SessionAttendance::remove(counted.get_id(), &student, &db)
510+ .await
511+ .unwrap()
512+ .expect("the present row was there");
513+ assert_eq!(attended(&student, &db).await, 0);
514+ assert!(
515+ SessionAttendance::remove(counted.get_id(), &student, &db)
516+ .await
517+ .unwrap()
518+ .is_none(),
519+ "nothing left to remove"
520+ );
521+ assert_eq!(attended(&student, &db).await, 0, "and nothing to give back");
522+ assert_eq!(
523+ held(&teacher, &db).await,
524+ 2,
525+ "clearing a row un-held a lesson"
526+ );
527+ }
528+
529+ /// The floor: however the corrections and removals interleave, and whatever
530+ /// a stale row starts from, the counter never goes negative.
531+ #[tokio::test]
532+ async fn the_counter_never_goes_below_zero() {
533+ let db = init_mem().await.unwrap();
534+ let teacher = a_teacher("t", &db).await;
535+ let student = a_student("s", &db).await;
536+
537+ // Ten counted lessons whose counter was never credited β€” the stale-data
538+ // case, an account that predates the column. Every one of them is now
539+ // corrected away, which is ten decrements against a zero.
540+ let mut sessions = Vec::new();
541+ for _ in 0..10 {
542+ let session = a_session(&teacher, &db).await;
543+ SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
544+ .await
545+ .unwrap();
546+ sessions.push(session);
547+ }
548+ db.query(format!(
549+ "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0"
550+ ))
551+ .bind(("usr", student.record()))
552+ .await
553+ .unwrap()
554+ .check()
555+ .unwrap();
556+
557+ for session in &sessions {
558+ SessionAttendance::mark(session, &student, status("absent"), &teacher, &db)
559+ .await
560+ .unwrap();
561+ SessionAttendance::remove(session.get_id(), &student, &db)
562+ .await
563+ .unwrap();
564+ assert!(attended(&student, &db).await >= 0);
565+ }
566+ assert_eq!(attended(&student, &db).await, 0, "floored, never negative");
567+ }
568+
569+ /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own
570+ /// β€” it never reaches [`SessionAttendance::remove`] β€” so the count stands,
571+ /// the ruling every other counter here carries.
572+ #[tokio::test]
573+ async fn deleting_the_session_leaves_the_counters_alone() {
574+ let db = init_mem().await.unwrap();
575+ let teacher = a_teacher("t", &db).await;
576+ let student = a_student("s", &db).await;
577+ let session = a_session(&teacher, &db).await;
578+ SessionAttendance::mark(&session, &student, status("present"), &teacher, &db)
579+ .await
580+ .unwrap();
581+
582+ session.delete(&db).await.unwrap();
583+ assert_eq!(attended(&student, &db).await, 1, "the cascade decremented");
584+ assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented");
585+ }
586+
587+ /// A mark on a session that is already gone is refused, so it cannot leave
588+ /// a count behind either.
589+ #[tokio::test]
590+ async fn a_refused_mark_moves_nothing() {
591+ let db = init_mem().await.unwrap();
592+ let teacher = a_teacher("t", &db).await;
593+ let student = a_student("s", &db).await;
594+ let session = a_session(&teacher, &db).await;
595+ let ghost = session.clone();
596+ session.delete(&db).await.unwrap();
597+
598+ assert!(matches!(
599+ SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await,
600+ Err(AppError::NotFound)
601+ ));
602+ assert_eq!(attended(&student, &db).await, 0);
603+ assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson");
190604 }
191605 }
src/domain/timestamp.rsmodified+42 -0
@@ -11,6 +11,7 @@
1111 //! - Durations that only pace things (rate limiter) use the monotonic
1212 //! `Instant` clock instead, which NTP adjustments cannot move backwards.
1313
14+use chrono::Datelike;
1415 use surrealdb::types::SurrealValue;
1516
1617 use crate::constant::MILLIS_PER_DAY;
@@ -69,6 +70,26 @@ impl Timestamp {
6970 .expect("current time is within chrono's representable range")
7071 .date_naive()
7172 }
73+
74+ /// *This* instant's UTC calendar day as a stable integer (days since the
75+ /// Common Era epoch). The day a stored value can be compared and
76+ /// incremented as an `int` β€” `day == stored + 1` is exactly "the next
77+ /// day", with no string parsing and no month/year arithmetic.
78+ ///
79+ /// Takes the instant instead of reading the clock, which is what makes a
80+ /// day-boundary rule testable without sleeping: [`Timestamp::now`] stays
81+ /// the single clock read, and the caller derives the day from the same
82+ /// stamp it already took. Midnight UTC is the boundary, like every other
83+ /// day calculation here ([`Timestamp::today_utc`], menu dates, the meal
84+ /// cutoff) β€” no timezone is stored anywhere, deliberately.
85+ pub fn day_number(&self) -> i64 {
86+ chrono::DateTime::from_timestamp_millis(self.0)
87+ // Reachable only for an instant Β±262 000 years from the epoch; the
88+ // callers derive this from a server clock read.
89+ .expect("timestamp is within chrono's representable range")
90+ .date_naive()
91+ .num_days_from_ce() as i64
92+ }
7293 }
7394
7495 #[cfg(test)]
@@ -108,6 +129,27 @@ mod tests {
108129 assert_eq!(Timestamp::in_days(i64::MAX).as_millis(), i64::MAX);
109130 }
110131
132+ #[tokio::test]
133+ async fn day_number_is_a_midnight_utc_day_counter() {
134+ // The unix epoch, pinned: a drifting origin would silently shift every
135+ // stored streak day.
136+ let epoch = Timestamp::from_millis(0);
137+ assert_eq!(epoch.day_number(), 719_163);
138+ // Same UTC day, different hours β€” one day number.
139+ assert_eq!(Timestamp::from_millis(86_399_999).day_number(), 719_163);
140+ // The next millisecond is the next day, and a whole day is +1.
141+ assert_eq!(Timestamp::from_millis(86_400_000).day_number(), 719_164);
142+ assert_eq!(
143+ Timestamp::from_millis(1_700_000_000_000 + MILLIS_PER_DAY).day_number(),
144+ Timestamp::from_millis(1_700_000_000_000).day_number() + 1
145+ );
146+ // Before the epoch still counts forward.
147+ assert_eq!(Timestamp::from_millis(-1).day_number(), 719_162);
148+ // And it agrees with the crate's other day calculation. Not flaky: a
149+ // day boundary between the two clock reads still leaves `<=`.
150+ assert!(Timestamp::now().day_number() <= Timestamp::today_utc().num_days_from_ce() as i64);
151+ }
152+
111153 #[tokio::test]
112154 async fn today_utc_matches_now() {
113155 let today = Timestamp::today_utc();
src/lib.rsmodified+2 -2
@@ -44,14 +44,14 @@ use crate::state::AppState;
4444 (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"),
4545 (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`"),
4646 (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), 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`"),
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 sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it β€” a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total`, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair β€” a regrade moves nothing), `lessons_held_total` (a session teacher's lessons, credited at the **first roll call** taken for one, so a lesson scheduled and cancelled counts for nothing), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pendingβ†’approved transition β€” a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting; homework marks are optional and often status-only, so they never count), and `study_streak_total` β€” the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** β€” no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile β€” except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created β€” and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter, 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`"),
4848 (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`)"),
4949 (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"),
5050 (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"),
5151 (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),
5252 (name = "courses", description = "Courses β€” kind `course` (a regular taught course), `study` (etΓΌt, a supervised study session), or `club` (kulΓΌp, a student club; same behavior, different label) β€” optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) β€” empty the roster first"),
5353 (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership β€” adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class β€” the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept β€” and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent β€” the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sΔ±nΔ±f âğretmeni) with `teacher_id` β€” any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role β€” staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. Creating or editing one retro-pumps every class already at the grade, and does so best-effort β€” a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list), but a course a human attached to a class by hand carries no blueprint tag and always survives β€” the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),
54- (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"),
54+ (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson credits its teacher's `lessons_held_total` once, and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"),
5555 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
5656 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend β€” the backend records only focus stints"),
5757 (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` β€” raster types only, ≀ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image β€” moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` β€” author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),
src/migration_sql.rsmodified+21 -0
@@ -75,6 +75,21 @@ pub const MIGRATION: &str = "
7575 DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option<int>;
7676 DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option<int>;
7777 DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option<int>;
78+ -- Pass 3 (2026-08-04): the staff-side counters, two more student ones, and
79+ -- the study streak. `study_streak_longest` is the badge counter; the other
80+ -- two streak columns are bookkeeping the write site needs to compute it and
81+ -- are read by nothing else. Definitions only β€” the seeding of the
82+ -- row-derivable ones is a BACKFILL under its own migration mark, never in
83+ -- this batch (same-batch DDL + backfill reads a stale schema).
84+ DEFINE FIELD IF NOT EXISTS marks_given_total ON user TYPE option<int>;
85+ DEFINE FIELD IF NOT EXISTS lessons_held_total ON user TYPE option<int>;
86+ DEFINE FIELD IF NOT EXISTS pool_approved_total ON user TYPE option<int>;
87+ DEFINE FIELD IF NOT EXISTS pool_published_total ON user TYPE option<int>;
88+ DEFINE FIELD IF NOT EXISTS lessons_attended_total ON user TYPE option<int>;
89+ DEFINE FIELD IF NOT EXISTS high_mark_total ON user TYPE option<int>;
90+ DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option<int>;
91+ DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option<int>;
92+ DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option<int>;
7893 DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE;
7994
8095 DEFINE TABLE IF NOT EXISTS session SCHEMAFULL;
@@ -369,6 +384,12 @@ pub const MIGRATION: &str = "
369384 DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string;
370385 DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int;
371386 DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option<int>;
387+ -- The once-per-session guard behind `lessons_held_total` (2026-08-04):
388+ -- stamped by the first roll call taken for the lesson, read by nothing but
389+ -- that guard. Definition only, and deliberately no backfill β€” a session
390+ -- that predates it carries no stamp, so the next roll call taken on it
391+ -- credits its teacher once, which is the rule this column encodes anyway.
392+ DEFINE FIELD IF NOT EXISTS held_counted_at ON course_session TYPE option<int>;
372393 DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course;
373394
374395 DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL;
src/web/courses.rsmodified+46 -0
@@ -1350,6 +1350,52 @@ mod tests {
13501350 assert!(!can_manage_course(&course, &demoted));
13511351 }
13521352
1353+ /// A manager may schedule a lesson on a teacher's behalf, and the session
1354+ /// belongs to the teacher they named β€” not to the caller. Everything hung
1355+ /// off that column (who may take the roll call, and who the roll call
1356+ /// credits) follows it, so a handler that stored the caller instead would
1357+ /// hand the office staff somebody else's lesson.
1358+ #[tokio::test]
1359+ async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() {
1360+ let db = init_mem().await.unwrap();
1361+ let manager = user("manager", Role::Manager, &db).await;
1362+ let teacher = user("teacher", Role::Teacher, &db).await;
1363+ let course = course(&manager, &db).await;
1364+ let st = AppState {
1365+ db: db.clone(),
1366+ files_path: std::env::temp_dir(),
1367+ cookie_secure: false,
1368+ rate_limit: crate::rate_limit::RateLimitConfig::unlimited(),
1369+ chatbot_limit: Default::default(),
1370+ exam_presence: Default::default(),
1371+ board_hub: Default::default(),
1372+ db_up: Default::default(),
1373+ ai: None,
1374+ };
1375+
1376+ let (status, Json(session)) = create_session_in_course(
1377+ State(st),
1378+ RequireTeacher(manager.clone()),
1379+ Path(course.get_id().key().to_string()),
1380+ Json(CreateSessionInCourse {
1381+ topic: None,
1382+ teacher_id: Some(teacher.get_id().key().to_string()),
1383+ starts_at: Timestamp::now().as_millis() + 60_000,
1384+ ends_at: None,
1385+ }),
1386+ )
1387+ .await
1388+ .unwrap();
1389+ assert_eq!(status, StatusCode::CREATED);
1390+ // Read back off the stored row, which is what `SessionResponse` names.
1391+ assert_eq!(session.teacher.id, teacher.get_id().key());
1392+ assert_ne!(
1393+ session.teacher.id,
1394+ manager.get_id().key(),
1395+ "the caller took the lesson instead of the teacher they named"
1396+ );
1397+ }
1398+
13531399 /// No course is left orphaned by the floor: manager+ reaches a course whose
13541400 /// creator was demoted and which has no assigned teachers.
13551401 #[tokio::test]
src/web/exams/mod.rsmodified+10 -0
@@ -12,6 +12,7 @@ use utoipa_axum::routes;
1212 use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES};
1313 use crate::database::Database;
1414 use crate::domain::answer_image::AnswerImage;
15+use crate::domain::badge;
1516 use crate::domain::bank_question::{BankQuestion, BankQuestionId};
1617 use crate::domain::bank_question_image::BankQuestionImage;
1718 use crate::domain::course::Course;
@@ -723,6 +724,15 @@ async fn grade(
723724 &st.db,
724725 )
725726 .await?;
727+ // Both sides of the grade moved a counter β€” the grader's `marks_given`,
728+ // the student's `high_mark` β€” so both are brought up to date. A badge is a
729+ // decoration on top of the mark: losing one to a transient database error
730+ // must never fail the grading, and the next counter move heals it.
731+ for person in [teacher.get_id(), &target] {
732+ if let Err(err) = badge::sync(person, &st.db).await {
733+ tracing::warn!("failed to sync badges for {}: {err}", person.key());
734+ }
735+ }
726736 let people = PersonRef::map_of(&[&target_user, &teacher]);
727737 Ok(Json(ExamResultResponse::new(&result, &people)))
728738 }
src/web/homework.rsmodified+6 -2
@@ -776,8 +776,9 @@ async fn delete_submission(
776776 Ok(StatusCode::NO_CONTENT)
777777 }
778778
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
779+/// Bring one user's badge awards up to date after a write moved their counters
780+/// β€” the student's after a submission, the grader's after a grade. Never fails
781+/// the request it follows: a badge is a decoration on top
781782 /// of the work, and losing one to a transient database error is not worth
782783 /// refusing a hand-in over β€” the next counter move re-runs this and heals it.
783784 async fn award_badges(user: &UserId, db: &Database) {
@@ -1135,6 +1136,9 @@ async fn grade_homework(
11351136 &st.db,
11361137 )
11371138 .await?;
1139+ // The grade credited the *grader*'s `marks_given`, not the student's β€” a
1140+ // homework grade moves no counter of the student's at all.
1141+ award_badges(teacher.get_id(), &st.db).await;
11381142 Ok(Json(HomeworkResultResponse::new(&result)))
11391143 }
11401144
src/web/limits.rsmodified+6 -0
@@ -82,6 +82,11 @@ struct BadgeLimits {
8282 /// Every badge the system can auto-award, in catalog order. Hardcoded, so
8383 /// like everything else here it moves only with a deploy.
8484 catalog: Vec<BadgeLimit>,
85+ /// The exam mark that counts as a high one, out of `mark.max_mark`, behind
86+ /// the `high_mark` ladder. Published because the id alone does not say it:
87+ /// deliberately not the school's grade bands, which are renameable labels.
88+ #[schema(example = 90)]
89+ high_mark_min: i64,
8590 }
8691
8792 /// One badge in the auto-earned catalog. The id is the whole contract: a
@@ -451,6 +456,7 @@ impl LimitsResponse {
451456 threshold: *threshold,
452457 })
453458 .collect(),
459+ high_mark_min: HIGH_MARK_MIN,
454460 },
455461 note: NoteLimits {
456462 max_title_len: MAX_NOTE_TITLE_LEN,
src/web/questions.rsmodified+11 -0
@@ -18,6 +18,7 @@ use utoipa_axum::router::OpenApiRouter;
1818 use utoipa_axum::routes;
1919
2020 use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES};
21+use crate::domain::badge;
2122 use crate::domain::pool_question::{
2223 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,
2324 };
@@ -386,6 +387,16 @@ async fn approve_question(
386387 return Err(AppError::Conflict("the question is already approved"));
387388 }
388389 };
390+ // Both counters moved inside the approval's own transaction; the badges
391+ // they may have earned are a decoration on top of it. Losing one to a
392+ // transient database error must never fail the approval behind it, and the
393+ // next counter move re-runs this and heals it. Two users, because the
394+ // transition credits the approver and the asker alike.
395+ for earner in [user.get_id(), question.get_asker()] {
396+ if let Err(err) = badge::sync(earner, &st.db).await {
397+ tracing::warn!("failed to sync badges for {}: {err}", earner.key());
398+ }
399+ }
389400 let responses = question_responses(std::slice::from_ref(&question), &st).await?;
390401 let response = responses
391402 .into_iter()
src/web/sessions.rsmodified+15 -0
@@ -10,6 +10,7 @@ use utoipa_axum::routes;
1010
1111 use crate::database::Database;
1212 use crate::domain::attendance::AttendanceStatus;
13+use crate::domain::badge;
1314 use crate::domain::course::Course;
1415 use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic};
1516 use crate::domain::enrollment::Enrollment;
@@ -354,6 +355,20 @@ async fn mark_roll_call(
354355
355356 let attendance =
356357 SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?;
358+ // A badge is a decoration on top of the roll call: losing one to a
359+ // transient database error must never fail the mark, and the next counter
360+ // move re-runs this and heals it. Both people the mark can credit are
361+ // synced β€” the person marked (`lessons_attended`) and the lesson's teacher
362+ // (`lessons_held`, on the first roll call only). The teacher's runs on every
363+ // mark rather than only that first one: `sync` is add-only and idempotent,
364+ // so the extra calls cost one record read and are what heals a first sync
365+ // that failed, and knowing here whether the credit landed would mean
366+ // widening `mark`'s return type for nothing.
367+ for who in [&target, session.get_teacher()] {
368+ if let Err(err) = badge::sync(who, &st.db).await {
369+ tracing::warn!("failed to sync badges for {}: {err}", who.key());
370+ }
371+ }
357372 let people = PersonRef::map_of(&[&target_user, &user]);
358373 Ok(Json(SessionAttendanceResponse::new(&attendance, &people)))
359374 }
src/web/users.rsmodified+38 -3
@@ -749,12 +749,18 @@ struct ProfileCourseRef {
749749 /// account with no rows behind a counter reads a true `0`.
750750 ///
751751 /// 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
752+/// rows that exist right now, so deleting the rows moves them down. Every
753+/// `*_total` one is a **stored lifetime counter**, incremented as the work
754754 /// happens and never recomputed β€” they can therefore outlive the rows behind
755755 /// them (an exam deleted by its teacher still counts as sat), which is exactly
756756 /// why a badge earned off them stays earned. Each is named for a `stat` of the
757-/// badge catalog at `GET /limits`, plus `_total`.
757+/// badge catalog at `GET /limits`, plus `_total`, and that spelling is the join
758+/// a client makes between the two surfaces β€” so the suffix is on the key even
759+/// where the counter is not a running total (`study_streak_total` is a longest,
760+/// not a sum).
761+///
762+/// Some are staff counters and some student ones; a role that never does the
763+/// work simply reads zero, which is why no key is conditional.
758764 #[derive(Serialize, ToSchema)]
759765 struct ProfileStatsResponse {
760766 /// Finished pomodoro stints; an open one counts for nothing.
@@ -777,6 +783,28 @@ struct ProfileStatsResponse {
777783 pomodoro_finished_total: i64,
778784 /// Lifetime focused milliseconds.
779785 pomodoro_focus_ms_total: i64,
786+ /// Lifetime grades this teacher recorded β€” exam sittings and homework
787+ /// submissions alike, once per pair: a regrade moves nothing.
788+ marks_given_total: i64,
789+ /// Lifetime lessons this teacher held, credited at the **first roll call**
790+ /// taken for one β€” a lesson scheduled and cancelled counts for nothing.
791+ lessons_held_total: i64,
792+ /// Lifetime pool questions this teacher approved.
793+ pool_approved_total: i64,
794+ /// Lifetime questions of this author that reached the school-wide pool,
795+ /// counted when the approval lands.
796+ pool_published_total: i64,
797+ /// Lifetime lesson roll calls that put this **student** `present` or
798+ /// `late`; a correction to any other status takes one back. Daily and event
799+ /// attendance moves it not at all.
800+ lessons_attended_total: i64,
801+ /// Lifetime exam marks at or above the high-mark cut published as
802+ /// `badges.high_mark_min` on `GET /limits`, one per graded sitting.
803+ /// Homework marks never count β€” they are optional and often status-only.
804+ high_mark_total: i64,
805+ /// Longest run of consecutive study days ever held β€” a high-water mark, so
806+ /// breaking the run never brings it down. Days end at midnight UTC.
807+ study_streak_total: i64,
780808 }
781809
782810 /// Build one profile as `viewer` may see it. The course block is chosen off the
@@ -884,6 +912,13 @@ async fn profile_of(
884912 exam_sat_total: stats.get_totals().get_exam_sat(),
885913 pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(),
886914 pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(),
915+ marks_given_total: stats.get_totals().get_marks_given(),
916+ lessons_held_total: stats.get_totals().get_lessons_held(),
917+ pool_approved_total: stats.get_totals().get_pool_approved(),
918+ pool_published_total: stats.get_totals().get_pool_published(),
919+ lessons_attended_total: stats.get_totals().get_lessons_attended(),
920+ high_mark_total: stats.get_totals().get_high_mark(),
921+ study_streak_total: stats.get_totals().get_study_streak(),
887922 },
888923 })
889924 }
tests/regress_badges.rsadded+639 -0
@@ -0,0 +1,639 @@
1+//! The badge families this pass added, driven over the routes that earn them:
2+//! `marks_given`, `high_mark`, `pool_approved` / `pool_published`,
3+//! `lessons_held` and `lessons_attended`.
4+//!
5+//! Each counter is unit-tested inside its own domain module; what lives here is
6+//! the whole path β€” a real request moves the counter, the write site syncs the
7+//! award, and the badge comes back on a profile a client can actually read.
8+//! Two rules the suite exists to defend:
9+//!
10+//! * a badge is **permanent** β€” a counter falling back below its threshold
11+//! never takes the award away, and a later sync never moves `earned_at`;
12+//! * a counter moves only for the person who did the work, once per piece of
13+//! work: a regrade, a re-mark, and a self-approval all move nothing.
14+//!
15+//! Every test that reads a counter drives a real registered user through the
16+//! API, never a fabricated id: `UPDATE` on a record that does not exist writes
17+//! nothing at all, so a counter assertion against a made-up key passes as
18+//! `0 == 0` whatever the implementation does.
19+
20+mod common;
21+
22+use axum::Router;
23+use axum::http::StatusCode;
24+use common::{
25+ app_and_db, create_course, create_exam, create_session, enroll, id_of, login, login_as, me_id,
26+ send, set_role,
27+};
28+use hezarfen_backend::constant::{BADGES, HIGH_MARK_MIN, STUDY_STREAK_LAST_DAY_FIELD};
29+use hezarfen_backend::database::Database;
30+use hezarfen_backend::domain::timestamp::Timestamp;
31+use serde_json::{Value, json};
32+
33+/// One profile body as `cookie` may see it (asserts the `200`).
34+async fn profile_of(app: &Router, cookie: &str, id: &str) -> Value {
35+ let res = send(
36+ app,
37+ "GET",
38+ &format!("/users/{id}/profile"),
39+ Some(cookie),
40+ None,
41+ )
42+ .await;
43+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
44+ res.body
45+}
46+
47+/// The caller's own profile body (asserts the `200`).
48+async fn my_profile(app: &Router, cookie: &str) -> Value {
49+ let res = send(app, "GET", "/users/me/profile", Some(cookie), None).await;
50+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
51+ res.body
52+}
53+
54+/// One `stats` counter off a profile body. Panics rather than defaulting: a
55+/// missing key is a renamed counter, not a zero.
56+fn stat(profile: &Value, key: &str) -> i64 {
57+ profile["stats"][key]
58+ .as_i64()
59+ .unwrap_or_else(|| panic!("stats.{key} is not a number: {profile}"))
60+}
61+
62+/// The badge ids on a profile, in the order served.
63+fn badge_ids(profile: &Value) -> Vec<&str> {
64+ profile["badges"]
65+ .as_array()
66+ .expect("badges array")
67+ .iter()
68+ .map(|badge| badge["id"].as_str().expect("badge id"))
69+ .collect()
70+}
71+
72+/// When `id` was earned, off a profile body β€” `None` if the shelf lacks it.
73+fn stamp_of(profile: &Value, id: &str) -> Option<i64> {
74+ profile["badges"]
75+ .as_array()
76+ .expect("badges array")
77+ .iter()
78+ .find(|badge| badge["id"] == id)
79+ .map(|badge| badge["earned_at"].as_i64().expect("earned_at millis"))
80+}
81+
82+// --- grading ---------------------------------------------------------------
83+
84+/// A teacher, one enrolled student, and `n` exams in one course.
85+///
86+/// `marks_given` counts one mark per *sitting*, so ten first grades need ten
87+/// exams or ten students β€” and an exam is a single cheap request while a
88+/// student costs two argon2 hashes to register and log in.
89+struct Marking {
90+ app: Router,
91+ teacher: String,
92+ student: String,
93+ student_id: String,
94+ exams: Vec<String>,
95+}
96+
97+async fn marking(exams: usize) -> Marking {
98+ let (app, db) = app_and_db().await;
99+ let teacher = login_as(&app, &db, "teach", "teacher").await;
100+ let student = login(&app, "stu").await;
101+ let student_id = me_id(&app, &student).await;
102+ let course = create_course(&app, &teacher, "Algebra").await;
103+ enroll(&app, &teacher, &course, &student_id).await;
104+ let mut ids = Vec::with_capacity(exams);
105+ for n in 0..exams {
106+ ids.push(create_exam(&app, &teacher, &course, &format!("Quiz {n}"), "quiz").await);
107+ }
108+ Marking {
109+ app,
110+ teacher,
111+ student,
112+ student_id,
113+ exams: ids,
114+ }
115+}
116+
117+/// Record `mark` for `student` on `exam` as `teacher` (asserts the `200`).
118+async fn grade(app: &Router, teacher: &str, exam: &str, student: &str, mark: i64) {
119+ let res = send(
120+ app,
121+ "POST",
122+ &format!("/exams/{exam}/results"),
123+ Some(teacher),
124+ Some(json!({ "user_id": student, "mark": mark })),
125+ )
126+ .await;
127+ assert_eq!(res.status, StatusCode::OK, "grade {mark}: {}", res.body);
128+}
129+
130+/// The grader's side, end to end: ten marks recorded through the exam route
131+/// put `marks_given_10` on the teacher's profile β€” and on the *public* one a
132+/// student reads, which is the only surface a client has.
133+#[tokio::test]
134+async fn ten_marks_put_the_graders_badge_on_a_profile() {
135+ let m = marking(10).await;
136+ let teacher_id = me_id(&m.app, &m.teacher).await;
137+
138+ for exam in &m.exams {
139+ grade(&m.app, &m.teacher, exam, &m.student_id, 70).await;
140+ }
141+
142+ let mine = my_profile(&m.app, &m.teacher).await;
143+ assert_eq!(stat(&mine, "marks_given_total"), 10, "{mine}");
144+ assert_eq!(badge_ids(&mine), ["marks_given_10"], "{mine}");
145+ // Badges are public: the student whose work was marked sees the same shelf.
146+ let seen = profile_of(&m.app, &m.student, &teacher_id).await;
147+ assert_eq!(badge_ids(&seen), ["marks_given_10"], "{seen}");
148+ // Grading is the teacher's work, not the student's β€” 70 is under the line,
149+ // so the student's own counters never moved.
150+ let theirs = my_profile(&m.app, &m.student).await;
151+ assert_eq!(stat(&theirs, "high_mark_total"), 0, "{theirs}");
152+ assert_eq!(stat(&theirs, "marks_given_total"), 0, "{theirs}");
153+}
154+
155+/// A mark is credited at the *first* grade of a sitting, so correcting one is
156+/// free: the counter stays, and β€” the permanence rule at the stamp β€” the badge
157+/// it already earned keeps the `earned_at` it was first given. The regrade is
158+/// deliberately pushed over the high-mark line, which a re-judging
159+/// implementation would mint a `high_mark` for.
160+#[tokio::test]
161+async fn a_regrade_moves_neither_the_counter_nor_the_stamp() {
162+ let m = marking(10).await;
163+ for exam in &m.exams {
164+ grade(&m.app, &m.teacher, exam, &m.student_id, 70).await;
165+ }
166+ let earned = stamp_of(&my_profile(&m.app, &m.teacher).await, "marks_given_10")
167+ .expect("the tenth mark earned the badge");
168+
169+ // Any overwrite from here on would be strictly later than this instant.
170+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
171+ assert!(
172+ earned < Timestamp::now().as_millis(),
173+ "the clock never moved β€” the stamp assertion below is vacuous"
174+ );
175+
176+ grade(&m.app, &m.teacher, &m.exams[0], &m.student_id, 100).await;
177+
178+ let after = my_profile(&m.app, &m.teacher).await;
179+ assert_eq!(
180+ stat(&after, "marks_given_total"),
181+ 10,
182+ "a regrade is not an eleventh mark: {after}"
183+ );
184+ assert_eq!(
185+ stamp_of(&after, "marks_given_10"),
186+ Some(earned),
187+ "a re-sync moved a permanent stamp: {after}"
188+ );
189+ let theirs = my_profile(&m.app, &m.student).await;
190+ assert_eq!(
191+ stat(&theirs, "high_mark_total"),
192+ 0,
193+ "a regrade re-judged the sitting and minted a high mark: {theirs}"
194+ );
195+ assert_eq!(badge_ids(&theirs), Vec::<&str>::new(), "{theirs}");
196+}
197+
198+/// The high-mark cut, from both sides of the line in one student's history:
199+/// the mark at `HIGH_MARK_MIN` earns `high_mark_1`, and the one below it earns
200+/// nothing β€” the counter that stays put is what proves the cut is a `>=` and
201+/// not "every mark counts".
202+#[tokio::test]
203+async fn a_mark_at_the_cut_earns_the_badge_and_one_below_it_earns_nothing() {
204+ let m = marking(2).await;
205+
206+ grade(
207+ &m.app,
208+ &m.teacher,
209+ &m.exams[0],
210+ &m.student_id,
211+ HIGH_MARK_MIN,
212+ )
213+ .await;
214+ let high = my_profile(&m.app, &m.student).await;
215+ assert_eq!(stat(&high, "high_mark_total"), 1, "{high}");
216+ assert_eq!(badge_ids(&high), ["high_mark_1"], "{high}");
217+
218+ grade(
219+ &m.app,
220+ &m.teacher,
221+ &m.exams[1],
222+ &m.student_id,
223+ HIGH_MARK_MIN - 1,
224+ )
225+ .await;
226+ let after = my_profile(&m.app, &m.student).await;
227+ assert_eq!(
228+ stat(&after, "high_mark_total"),
229+ 1,
230+ "a mark under the cut was counted as a high one: {after}"
231+ );
232+ // The grader's own counter moved twice, which is what proves the second
233+ // grade landed at all rather than being refused.
234+ assert_eq!(
235+ stat(&my_profile(&m.app, &m.teacher).await, "marks_given_total"),
236+ 2
237+ );
238+}
239+
240+// --- the question pool -----------------------------------------------------
241+
242+/// Ask a pool question as `cookie` (asserts the `201`); returns its id.
243+async fn ask(app: &Router, cookie: &str, title: &str) -> String {
244+ let res = send(
245+ app,
246+ "POST",
247+ "/questions",
248+ Some(cookie),
249+ Some(json!({ "title": title, "body": "NasΔ±l Γ§ΓΆzΓΌlΓΌr?" })),
250+ )
251+ .await;
252+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
253+ id_of(&res.body)
254+}
255+
256+/// Approve `question` as `cookie` (asserts the `200`); returns the body.
257+async fn approve(app: &Router, cookie: &str, question: &str) -> Value {
258+ let res = send(
259+ app,
260+ "POST",
261+ &format!("/questions/{question}/approve"),
262+ Some(cookie),
263+ None,
264+ )
265+ .await;
266+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
267+ res.body
268+}
269+
270+/// One approval, two people credited: the approver's `pool_approved` and the
271+/// asker's `pool_published`, which is a badge on its first one. And the farm
272+/// this closes β€” approving a question you asked yourself moves *neither*
273+/// counter, while the approval itself is untouched: same `200`, same
274+/// `approved` status, same stamp.
275+#[tokio::test]
276+async fn a_two_party_approval_credits_both_and_a_self_approval_credits_neither() {
277+ let (app, db) = app_and_db().await;
278+ let teacher = login_as(&app, &db, "teach", "teacher").await;
279+ let asker = login(&app, "stu").await;
280+ // Asking is student-only, so the self-approver asks first and is promoted
281+ // afterwards β€” the one route onto a self-approval the API actually has.
282+ let selfie = login(&app, "selfie").await;
283+
284+ let theirs = ask(&app, &asker, "Integral").await;
285+ let own = ask(&app, &selfie, "TΓΌrev").await;
286+
287+ approve(&app, &teacher, &theirs).await;
288+ let judge = my_profile(&app, &teacher).await;
289+ assert_eq!(stat(&judge, "pool_approved_total"), 1, "{judge}");
290+ // Five approvals earn the first badge, so this one is a counter move only.
291+ assert_eq!(badge_ids(&judge), Vec::<&str>::new(), "{judge}");
292+ let author = my_profile(&app, &asker).await;
293+ assert_eq!(stat(&author, "pool_published_total"), 1, "{author}");
294+ assert_eq!(badge_ids(&author), ["pool_published_1"], "{author}");
295+
296+ set_role(&db, "selfie", "teacher").await;
297+ let approved = approve(&app, &selfie, &own).await;
298+ assert_eq!(approved["status"], "approved", "{approved}");
299+ assert_eq!(
300+ approved["approved_by"]["id"],
301+ Value::from(me_id(&app, &selfie).await),
302+ "{approved}"
303+ );
304+
305+ let mine = my_profile(&app, &selfie).await;
306+ assert_eq!(
307+ (
308+ stat(&mine, "pool_approved_total"),
309+ stat(&mine, "pool_published_total")
310+ ),
311+ (0, 0),
312+ "judging your own question credited you: {mine}"
313+ );
314+ assert_eq!(badge_ids(&mine), Vec::<&str>::new(), "{mine}");
315+}
316+
317+// --- roll call -------------------------------------------------------------
318+
319+/// Mark `user` `status` for `session` as `cookie` (asserts the `200`).
320+async fn roll_call(app: &Router, cookie: &str, session: &str, user: &str, status: &str) {
321+ let res = send(
322+ app,
323+ "POST",
324+ &format!("/sessions/{session}/attendance"),
325+ Some(cookie),
326+ Some(json!({ "user_id": user, "status": status })),
327+ )
328+ .await;
329+ assert_eq!(res.status, StatusCode::OK, "mark {status}: {}", res.body);
330+}
331+
332+fn soon() -> i64 {
333+ Timestamp::now().as_millis() + 3_600_000
334+}
335+
336+/// A lesson is credited to its teacher when the roll call is *taken*, once:
337+/// the first student marked stamps it, and the second and third credit nothing
338+/// further however many are on the roster.
339+///
340+/// And attending is a student's badge alone β€” the manager marking the lesson's
341+/// own teacher present (the one staff roll-call row the API allows) moves no
342+/// `lessons_attended` at all.
343+#[tokio::test]
344+async fn the_first_roll_call_credits_the_lesson_once_and_only_students_attend() {
345+ let (app, db) = app_and_db().await;
346+ let boss = login_as(&app, &db, "mudur", "manager").await;
347+ let teacher = login_as(&app, &db, "teach", "teacher").await;
348+ let teacher_id = me_id(&app, &teacher).await;
349+ let course = create_course(&app, &teacher, "Algebra").await;
350+
351+ let mut students = Vec::new();
352+ for name in ["ali", "veli", "ayse"] {
353+ let cookie = login(&app, name).await;
354+ let id = me_id(&app, &cookie).await;
355+ enroll(&app, &teacher, &course, &id).await;
356+ students.push((cookie, id));
357+ }
358+ let session = create_session(&app, &teacher, &course, soon()).await;
359+
360+ roll_call(&app, &teacher, &session, &students[0].1, "present").await;
361+ let held = my_profile(&app, &teacher).await;
362+ assert_eq!(
363+ stat(&held, "lessons_held_total"),
364+ 1,
365+ "taking the roll call is what holds a lesson: {held}"
366+ );
367+
368+ roll_call(&app, &teacher, &session, &students[1].1, "present").await;
369+ roll_call(&app, &teacher, &session, &students[2].1, "late").await;
370+ let after = my_profile(&app, &teacher).await;
371+ assert_eq!(
372+ stat(&after, "lessons_held_total"),
373+ 1,
374+ "the third student marked held the same lesson again: {after}"
375+ );
376+
377+ for (cookie, _) in &students {
378+ let theirs = my_profile(&app, cookie).await;
379+ // `late` is attendance too β€” the same rule `GET /attendance/me` uses.
380+ assert_eq!(stat(&theirs, "lessons_attended_total"), 1, "{theirs}");
381+ }
382+
383+ // Management records the teacher's own presence: a roll-call row like any
384+ // other, and no `lessons_attended` for a person who is not a student.
385+ roll_call(&app, &boss, &session, &teacher_id, "present").await;
386+ let staff = my_profile(&app, &teacher).await;
387+ assert_eq!(
388+ stat(&staff, "lessons_attended_total"),
389+ 0,
390+ "the teacher attended their own lesson: {staff}"
391+ );
392+ assert_eq!(stat(&staff, "lessons_held_total"), 1, "{staff}");
393+}
394+
395+/// **The permanence rule.** A correction takes the counter back down β€” that is
396+/// what a roll call being editable means β€” and the badge it already earned
397+/// stays on the shelf with the stamp it was first given. Badges are auto-earned
398+/// and never revoked; nothing in the system removes an award row, and this is
399+/// the test that would notice if something started to.
400+///
401+/// The tenth lesson is what earns `lessons_attended_10`, and it is that very
402+/// tenth mark the correction withdraws β€” so the counter ends *below* the
403+/// threshold the badge was earned at, which is the only state that tells a
404+/// permanent award apart from one recomputed on every read.
405+#[tokio::test]
406+async fn a_correction_lowers_the_counter_but_never_takes_the_badge_back() {
407+ let (app, db) = app_and_db().await;
408+ let teacher = login_as(&app, &db, "teach", "teacher").await;
409+ let student = login(&app, "stu").await;
410+ let student_id = me_id(&app, &student).await;
411+ let course = create_course(&app, &teacher, "Algebra").await;
412+ enroll(&app, &teacher, &course, &student_id).await;
413+
414+ let mut sessions = Vec::new();
415+ for lesson in 0..10 {
416+ let starts_at = soon() + lesson * 3_600_000;
417+ let session = create_session(&app, &teacher, &course, starts_at).await;
418+ roll_call(&app, &teacher, &session, &student_id, "present").await;
419+ sessions.push(session);
420+ }
421+
422+ let earned_it = my_profile(&app, &student).await;
423+ assert_eq!(
424+ stat(&earned_it, "lessons_attended_total"),
425+ 10,
426+ "{earned_it}"
427+ );
428+ let earned = stamp_of(&earned_it, "lessons_attended_10").expect("the tenth lesson earns it");
429+
430+ // The teacher corrects the last roll call: the student was not there.
431+ roll_call(
432+ &app,
433+ &teacher,
434+ sessions.last().unwrap(),
435+ &student_id,
436+ "absent",
437+ )
438+ .await;
439+
440+ let after = my_profile(&app, &student).await;
441+ assert_eq!(
442+ stat(&after, "lessons_attended_total"),
443+ 9,
444+ "a correction must give the count back: {after}"
445+ );
446+ assert_eq!(
447+ stamp_of(&after, "lessons_attended_10"),
448+ Some(earned),
449+ "a badge was taken back when its counter fell: {after}"
450+ );
451+ // Correcting one student's row does not un-hold the lesson either.
452+ assert_eq!(
453+ stat(&my_profile(&app, &teacher).await, "lessons_held_total"),
454+ 10
455+ );
456+}
457+
458+// --- the study streak ------------------------------------------------------
459+
460+/// Start and finish one focus stint as `cookie` (asserts both statuses).
461+async fn stint(app: &Router, cookie: &str) {
462+ let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await;
463+ assert_eq!(started.status, StatusCode::CREATED, "{}", started.body);
464+ let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await;
465+ assert_eq!(finished.status, StatusCode::OK, "{}", finished.body);
466+}
467+
468+/// Wind `user`'s streak bookkeeping back one day, so the *next* finish lands on
469+/// the next calendar day.
470+///
471+/// This manipulates **stored state, never the clock**: `Timestamp::now` stays
472+/// the one clock read in the process and nothing sleeps. It is the same trick
473+/// the domain tests use (`age_by_days` in `src/domain/pomodoro.rs`), reached
474+/// here through the harness's own database handle because no route can move a
475+/// day boundary β€” the streak's day arithmetic itself is the domain suite's to
476+/// pin, and what this buys is the *badge* arriving on a real profile.
477+async fn age_one_day(db: &Database, user: &str) {
478+ db.query(format!(
479+ "UPDATE type::record('user', $id)
480+ SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - 1"
481+ ))
482+ .bind(("id", user.to_string()))
483+ .await
484+ .unwrap()
485+ .check()
486+ .unwrap();
487+}
488+
489+/// The streak's whole path, in the one shape a client sees it: a student
490+/// finishes a stint and their profile says `study_streak_total: 1`.
491+///
492+/// That single number is worth more than it looks β€” it is written by the
493+/// pomodoro transaction into `study_streak_longest`, projected by
494+/// `BadgeStats::load`, projected *again* by the parallel hand-kept reader in
495+/// `src/domain/profile.rs` (the two carry doc comments saying they move
496+/// together, and nothing but a test notices when they stop), and finally
497+/// served under a key deliberately spelled `study_streak_total` although the
498+/// counter is a longest and not a sum. Break any one of those and this reads
499+/// `0` or panics on a missing key.
500+///
501+/// Three consecutive days then earn `study_streak_3` off a real profile read.
502+#[tokio::test]
503+async fn a_finished_stint_reaches_the_profile_and_three_days_earn_the_badge() {
504+ let (app, db) = app_and_db().await;
505+ let student = login(&app, "stu").await;
506+ let student_id = me_id(&app, &student).await;
507+
508+ stint(&app, &student).await;
509+
510+ let first = profile_of(&app, &student, &student_id).await;
511+ assert_eq!(
512+ stat(&first, "study_streak_total"),
513+ 1,
514+ "one finished stint is a one-day run: {first}"
515+ );
516+ // The stint landed at all β€” so a zero above would be the streak's own
517+ // projection, not a pomodoro route that never ran.
518+ assert_eq!(stat(&first, "pomodoro_finished_total"), 1, "{first}");
519+ assert_eq!(badge_ids(&first), Vec::<&str>::new(), "three days away");
520+
521+ for _ in 0..2 {
522+ age_one_day(&db, &student_id).await;
523+ stint(&app, &student).await;
524+ }
525+
526+ let after = profile_of(&app, &student, &student_id).await;
527+ assert_eq!(
528+ stat(&after, "study_streak_total"),
529+ 3,
530+ "three consecutive days are a run of three: {after}"
531+ );
532+ // Ten finished stints earn the pomodoro badge, so three days earn exactly
533+ // one thing.
534+ assert_eq!(badge_ids(&after), ["study_streak_3"], "{after}");
535+}
536+
537+// --- the read side ---------------------------------------------------------
538+
539+/// A profile is a read endpoint. The write site behind a badge already ran
540+/// `badge::sync`, so by the time anyone reads the profile there is nothing
541+/// owed β€” and the read must therefore touch the award table exactly zero
542+/// times, however many badges the shelf carries.
543+///
544+/// The probe is a `DEFINE EVENT` on the award table itself: it fires inside any
545+/// write to it β€” creates and updates alike, checked with a hand-run `UPDATE`
546+/// while this was written β€” so a write this read should not make cannot hide
547+/// behind an unchanged-looking response.
548+///
549+/// What this bites on, precisely: a read path that writes an award row at all.
550+/// Two things stop it today and either one alone is enough β€” `badges_of` skips
551+/// the sync while the shelf is complete, and `sync`'s own
552+/// `WHERE earned_at = NONE` makes a re-write a no-op β€” so dropping *only* the
553+/// second leaves this green. The frozen stamp is pinned by
554+/// `a_regrade_moves_neither_the_counter_nor_the_stamp` instead.
555+#[tokio::test]
556+async fn a_profile_read_owes_nothing_the_write_site_already_paid() {
557+ let (app, db) = app_and_db().await;
558+ let teacher = login_as(&app, &db, "teach", "teacher").await;
559+ let asker = login(&app, "stu").await;
560+ let asker_id = me_id(&app, &asker).await;
561+ let bystander = login(&app, "nobody").await;
562+
563+ // The counter row is seeded so the probe reads a real zero: selecting from
564+ // a table nothing has written yet is an error, not an empty answer.
565+ db.query(
566+ "UPSERT type::record('award_write_probe', 'n') SET n = 0;
567+ DEFINE EVENT award_write ON badge_award WHEN true THEN {
568+ UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1;
569+ };",
570+ )
571+ .await
572+ .unwrap()
573+ .check()
574+ .unwrap();
575+ let writes = || async {
576+ db.query("SELECT VALUE n FROM award_write_probe:n")
577+ .await
578+ .unwrap()
579+ .take::<Vec<i64>>(0)
580+ .unwrap()
581+ .first()
582+ .copied()
583+ .unwrap_or(0)
584+ };
585+ assert_eq!(writes().await, 0, "nothing has been awarded yet");
586+
587+ // One approval, and `pool_published_1` is earned β€” by the route, not by
588+ // any later read.
589+ let question = ask(&app, &asker, "Integral").await;
590+ approve(&app, &teacher, &question).await;
591+ let written = writes().await;
592+ assert!(written > 0, "the approval never wrote the asker's award");
593+
594+ let mine = my_profile(&app, &asker).await;
595+ assert_eq!(badge_ids(&mine), ["pool_published_1"], "{mine}");
596+ assert_eq!(
597+ writes().await,
598+ written,
599+ "a profile read wrote to the award table"
600+ );
601+
602+ // Same again from another reader, and from an account that has earned
603+ // nothing at all β€” the shelf is empty, so there is not even a statement to
604+ // send.
605+ profile_of(&app, &bystander, &asker_id).await;
606+ let empty = my_profile(&app, &bystander).await;
607+ assert_eq!(badge_ids(&empty), Vec::<&str>::new(), "{empty}");
608+ assert_eq!(
609+ writes().await,
610+ written,
611+ "reading a profile that owes nothing still wrote"
612+ );
613+}
614+
615+/// The catalog `GET /limits` publishes is the whole of `BADGES` β€” a family
616+/// added to the constant and forgotten at the wire is a badge no client can
617+/// ever render β€” and it carries the high-mark cut, which no id spells out.
618+#[tokio::test]
619+async fn the_limits_badge_block_serves_the_whole_catalog_and_the_high_mark_cut() {
620+ let (app, _db) = app_and_db().await;
621+
622+ let res = send(&app, "GET", "/limits", None, None).await;
623+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
624+ let served: Vec<&str> = res.body["badges"]["catalog"]
625+ .as_array()
626+ .unwrap_or_else(|| panic!("badges.catalog array: {}", res.body))
627+ .iter()
628+ .map(|badge| badge["id"].as_str().expect("badge id"))
629+ .collect();
630+ let known: Vec<&str> = BADGES.iter().map(|(id, _, _)| *id).collect();
631+ assert_eq!(served, known, "the catalog and the wire disagree");
632+
633+ assert_eq!(
634+ res.body["badges"]["high_mark_min"],
635+ Value::from(HIGH_MARK_MIN),
636+ "the high-mark cut is not published: {}",
637+ res.body
638+ );
639+}
tests/regress_profile.rsmodified+13 -3
@@ -315,8 +315,9 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() {
315315 assert_eq!(writes().await, after_heal, "a profile read wrote something");
316316 }
317317
318-/// The counters are derived, so a fresh account reads a true `0` on all four β€”
319-/// never `null`, never an absent key a client would have to guard.
318+/// A fresh account reads a true `0` on every counter β€” never `null`, never an
319+/// absent key a client would have to guard. Both kinds: the four derived ones
320+/// have no rows behind them, and the stored ones have no columns on the row.
320321 #[tokio::test]
321322 async fn fresh_stats_read_zero_on_every_field() {
322323 let (app, _db) = app_and_db().await;
@@ -337,6 +338,15 @@ async fn fresh_stats_read_zero_on_every_field() {
337338 "exam_sat_total",
338339 "pomodoro_finished_total",
339340 "pomodoro_focus_ms_total",
341+ "marks_given_total",
342+ "lessons_held_total",
343+ "pool_approved_total",
344+ "pool_published_total",
345+ "lessons_attended_total",
346+ "high_mark_total",
347+ // A longest, not a running total β€” the key still carries `_total`
348+ // because that suffix is how a client joins a badge `stat` to a stat.
349+ "study_streak_total",
340350 ] {
341351 assert_eq!(
342352 stats.get(field).and_then(Value::as_i64),
@@ -345,7 +355,7 @@ async fn fresh_stats_read_zero_on_every_field() {
345355 stats.get(field)
346356 );
347357 }
348- assert_eq!(stats.len(), 9, "no tenth counter shipped: {stats:?}");
358+ assert_eq!(stats.len(), 16, "an unlisted counter shipped: {stats:?}");
349359 assert!(mine.body["avatar"].is_null());
350360 assert_eq!(mine.body["classes"], json!([]));
351361 assert_eq!(mine.body["courses"], json!([]));