diff --git a/README.md b/README.md index acebc02..fb1aa9a 100644 --- a/README.md +++ b/README.md @@ -117,10 +117,12 @@ preference (or, for the accent, its own default). Every account also has a **public profile** (`/users/{id}/profile`): a self-chosen `display_name` and `bio`, one **avatar**, the classes and courses it belongs to, counters computed at read (finished pomodoro stints, course and -class totals) beside stored lifetime tallies of homework handed in, exams sat -and focus time, and the **badges** those tallies have earned — auto-earned -only, no route awards or revokes one, and permanent once earned even if the -counter later falls. Contact details are deliberately not part of it — email, +class totals) beside stored lifetime tallies of what the account has done — +homework handed in, exams sat and focus time, lessons attended, high exam +marks and the longest run of consecutive study days for a student; grades +given, lessons held and question-pool approvals for a teacher — and the +**badges** those tallies have earned — auto-earned only, no route awards or +revokes one, and permanent once earned even if the counter later falls. Contact details are deliberately not part of it — email, phone and birth date keep the gate they already have — and any authenticated account reads any profile, except a `parent`, who reads their own and their linked students' only (see "User profiles & avatars"). @@ -339,7 +341,8 @@ response in the same commit. "session_duration_days": 7 }, "badges": { "catalog": [ { "id": "homework_submitted_10", "stat": "homework_submitted", "threshold": 10 }, - { "…": 0 } ] }, + { "…": 0 } ], + "high_mark_min": 90 }, "note": { "max_title_len": 200, "max_content_len": 10000, "max_files": 10 }, "file": { "max_name_len": 255, "max_content_type_len": 100, "min_max_file_bytes": 1024, "max_max_file_bytes": 26214400, @@ -442,18 +445,28 @@ Notes: uploadable `image_content_types` are the exact accepted spellings — build pickers from these rather than from a literal list. - **The badge catalog rides here too.** `badges.catalog[]` is every badge the - system can auto-award — `{id, stat, threshold}`, 13 of them, in catalog + system can auto-award — `{id, stat, threshold}`, 34 of them, in catalog order. It is a group (an object with one `catalog` key) rather than a bare array because every key of this document is a group, and that uniformity is what lets a client walk the response generically. `stat` is the API's name for the lifetime counter behind the badge (`homework_submitted`, - `homework_on_time`, `exam_sat`, `pomodoro_finished`, `pomodoro_focus_ms`), - deliberately not the database column it is stored in, so storage can be - renamed without moving a published contract; badges sharing a `stat` form a - ladder. The catalog is compiled in, so a threshold moves only with a deploy — - the rules stay reviewable in a diff instead of editable in a settings row. - Labels and icons are **not** here: like `roles` and course `kinds`, the id is - the whole contract and the client owns what it looks like. + `homework_on_time`, `exam_sat`, `pomodoro_finished`, `pomodoro_focus_ms`, + `marks_given`, `lessons_held`, `pool_approved`, `pool_published`, + `lessons_attended`, `high_mark`, `study_streak` — twelve counters over the + 34 badges), deliberately not the database column it is stored in, so storage + can be renamed without moving a published contract; badges sharing a `stat` + form a ladder. Every one of them joins the profile's `stats` key of the same + name plus `_total`, mechanically and without exception — including + `study_streak_total`, which is a *longest run* rather than a sum and keeps + the suffix anyway so the join needs no special case. The catalog is compiled + in, so a threshold moves only with a deploy — the rules stay reviewable in a + diff instead of editable in a settings row. Labels and icons are **not** + here: like `roles` and course `kinds`, the id is the whole contract and the + client owns what it looks like. Beside it, `badges.high_mark_min` (90) is the + exam mark the `high_mark` ladder counts from — published because + `high_mark_10` does not say what a high mark is, and deliberately not the + school's grade bands, whose labels a school renames at will while a badge id + must mean the same thing in every deployment forever. **`422` versus `400`.** The two refusals mean different things and a client 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, "courses": 7, "classes": 1, "homework_submitted_total": 12, "homework_on_time_total": 11, "exam_sat_total": 5, "pomodoro_finished_total": 44, - "pomodoro_focus_ms_total": 65400000 } + "pomodoro_focus_ms_total": 65400000, + "marks_given_total": 0, "lessons_held_total": 0, + "pool_approved_total": 0, "pool_published_total": 3, + "lessons_attended_total": 58, "high_mark_total": 2, + "study_streak_total": 9 } } ``` @@ -1192,21 +1209,33 @@ owner's true total on purpose — it is the motivational counter, a per-reader number would be meaningless, and a magnitude names no course. One consequence, by design: a teacher you share nothing with has an empty `courses` block. -**`stats` holds nine numbers of two different kinds, and the difference is +**`stats` holds sixteen numbers of two different kinds, and the difference is worth knowing.** `pomodoro_sessions`, `pomodoro_focus_ms`, `courses` and `classes` are **computed at read**: they are recounted from the live rows on -every call, so no column can drift out of sync with what is behind it. The five -`*_total` keys are **stored lifetime tallies**, maintained at write time (see -below), so a tally can outlive the rows behind it — a student's +every call, so no column can drift out of sync with what is behind it. The +twelve `*_total` keys are **stored lifetime tallies**, maintained at write time +(see below), so a tally can outlive the rows behind it — a student's `exam_sat_total` still counts an exam a teacher has since deleted, which is the point of a lifetime counter. Either kind reads a true `0` on a fresh account, never `null`. Only *finished* pomodoro stints count on either side — a timer left running is not study time. Exam averages, homework-done rates and attendance rates are deliberately absent: those tables are indexed for their own reads, so a per-user aggregate over them is a full table scan, and a -profile is far too cheap a page to pay for one — which is also why the five +profile is far too cheap a page to pay for one — which is also why the twelve lifetime counters are tallied at write rather than recounted here. +**Every key is unconditional, whatever the role.** Some counters are a +student's (`exam_sat_total`, `lessons_attended_total`, `high_mark_total`, +`study_streak_total`, the two homework ones), some a teacher's +(`marks_given_total`, `lessons_held_total`, `pool_approved_total`), and a role +that never does the work simply reads `0` — no key appears or disappears with a +role, so a client renders one shape. Each `*_total` is the badge catalog's +`stat` name plus `_total` and nothing else, which is how a client joins a +profile to `badges.catalog[]` at `/limits` without a lookup table. +`study_streak_total` keeps that suffix even though it is a **longest run and +not a sum** — the mechanical spelling is worth more than the accurate one, so +do not "fix" it. + **The avatar** is one picture per account, uploaded as `multipart/form-data` with the image under a `file` field. Raster types only (`image/png`, `image/jpeg`, `image/webp`, `image/gif`) — an SVG can carry script, and these @@ -1241,7 +1270,8 @@ oldest first. **Ids only.** Each entry is `{id, earned_at}`. The label, the icon and the description are the frontend's, keyed by the id — the same deal `roles` and course `kinds` already have. The catalog behind the ids is at `GET /limits` as -`badges.catalog[]` (`{id, stat, threshold}`, 13 badges); it is compiled into +`badges.catalog[]` (`{id, stat, threshold}`, 34 badges over twelve counters, +alongside `badges.high_mark_min`); it is compiled into the binary, so changing a threshold is a deploy, not a settings edit. An id is never reused for another meaning, and retiring a badge just drops it from the catalog — awards carrying it stop being served, no migration. @@ -1262,6 +1292,50 @@ catalog — awards carrying it stop being served, no migration. - **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its duration into `pomodoro_focus_ms_total`. An open stint counts for neither — unfinished focus has no honest duration to add. +- **Study streak.** Finishing a stint also extends `study_streak_total`, the + **longest** run of consecutive days on which the student finished one. A + second stint the same day extends nothing; a gap of any length starts the run + over at 1. The badge reads the longest run ever held, never the run in + progress, so a broken streak takes no badge away and the counter never comes + down. A day is a **UTC calendar day**: this API stores no school timezone + anywhere, and the boundary is midnight UTC, the same one every other day + calculation here uses (meal cutoffs, menu dates, birth dates). +- **Grades given.** `+1 marks_given_total` for the **grader**, the first time + they record a grade for a given exam sitting or homework submission — exam + and homework alike, since grading is grading. A regrade of the same pair moves + nothing: the counter counts work judged, not times the mark was edited. +- **High marks.** `+1 high_mark_total` for the **student** whenever an exam + mark lands at or above `badges.high_mark_min` (90, published at `/limits`), + once per sitting — a retake is another sitting and can earn another. Homework + marks never count here: a homework mark is optional and most grades are + status-only, so counting them would reward a teacher's habit rather than a + student's work. The cut is compiled in rather than read from the school's + grade bands, which are renameable display labels — `high_mark_10` has to mean + the same thing in every school, forever. +- **Lessons held.** `+1 lessons_held_total` for the **session's teacher**, once + per lesson, credited by the **first roll call taken for it**. It means "a + lesson whose roll call was taken", not "a lesson on the timetable" — + scheduling two hundred lessons and cancelling them all earns nothing. The + thirtieth student marked in that lesson credits nothing further (a stamp on + the session row is the guard), and taking one student back off the roll does + not un-hold the lesson. +- **Lessons attended.** `+1 lessons_attended_total` for a **student** marked + `present` or `late` at lesson roll call — the same cut the attendance report's + `rate` uses, so a student's badge and their attendance rate never disagree + about what attending is; `excused` and every school-added status are neutral. + It is a **delta, not a tally**: a teacher correcting `present` → `absent` + moves it back down (floored at 0), and clearing the row does too. Student-only + — a teacher marked present in their own lesson moves nothing — and course + roll call only: the daily/event attendance at `/attendance` earns none of it. +- **The question pool.** One pending → approved transition credits two people: + `+1 pool_approved_total` for the **approver** and `+1 pool_published_total` + for the **asker** whose question reached the pool. The asker is credited at + approval and never at asking, because asking is self-service — delete and + re-ask would farm it — which is why the counter is named `published` rather + than `asked`. And a teacher **approving their own question** earns neither: + the approval itself is unchanged (same `200`, same freeze), but a counter + moves only where one person's work was judged by somebody else, which closes + the ask-approve-delete farm from the other end too. **Existing accounts are seeded once.** The first boot of this version tallies 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 — and the fix is not to make deletion decrement, which would break the tally for everyone in order to patch it for a few. +**The seven newer counters are not seeded at all**, deliberately: +`marks_given_total`, `high_mark_total`, `lessons_held_total`, +`lessons_attended_total`, `pool_approved_total`, `pool_published_total` and +`study_streak_total` **begin at this deploy**, at zero, and no history is +reconstructed for them. The columns are defined and absent reads `0`, so an +account written before them is indistinguishable from a fresh one; the first +grade recorded, roll call taken, approval landed or stint finished after the +upgrade is what starts each of them counting. + ## Appointments 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. Re-marking overwrites: one row per session+user, by construction. Deleting a session (or its course) cascades its roll-call rows. +**Roll call is also what credits two badge counters** (see "Badges"). The +**first** mark taken for a lesson credits its teacher's `lessons_held_total`, +once — a lesson counts as held when its roll call is taken, so one merely +scheduled (and then cancelled) counts for nothing, and the marks after that +first one credit nothing further. And a **student** marked `present` or `late` +gains a `lessons_attended_total`, using the same cut the attendance `rate` +below uses; correcting that mark to any other status, or clearing the row, gives +it back. The session teacher's own presence row moves neither counter — the +attendance one is a student's badge, and a teacher does not attend their own +lesson. + The **work log** (`/work`) is the staff timesheet, for teachers and above. `POST /work/check-in` opens a stint and `POST /work/check-out` closes it, both 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 every finished session's duration: `GET /pomodoro/me` for your own, `GET /pomodoro/{user}` for teacher+ (study oversight). Only students start sessions — pomodoro is the study tool, the work log is the staff timesheet. +Finishing a stint also feeds the **study streak** behind the `study_streak` +badges: consecutive **UTC** days on which one was finished, kept as the longest +run ever held (see "Badges"). **Attendance reports** mirror the marks report: `GET /attendance/me` for any logged-in user, `GET /attendance/{user}` for teacher+ — narrowed to the diff --git a/src/constant.rs b/src/constant.rs index 4d0fe20..493b0ad 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -875,6 +875,43 @@ pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total"; pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; pub const POMODORO_FINISHED_TOTAL_FIELD: &str = "pomodoro_finished_total"; pub const POMODORO_FOCUS_MS_TOTAL_FIELD: &str = "pomodoro_focus_ms_total"; +/// The staff-side and second student-side totals, same shape and same rules: +/// lifetime, floored at zero, absent reads as zero. `MARKS_GIVEN` and +/// `LESSONS_HELD` are what a teacher accumulates; `POOL_APPROVED` counts the +/// approvals a teacher hands out and `POOL_PUBLISHED` the questions whose +/// author got approved — credited at approval, which is why the name says +/// published rather than asked. +pub const MARKS_GIVEN_TOTAL_FIELD: &str = "marks_given_total"; +pub const LESSONS_HELD_TOTAL_FIELD: &str = "lessons_held_total"; +pub const POOL_APPROVED_TOTAL_FIELD: &str = "pool_approved_total"; +pub const POOL_PUBLISHED_TOTAL_FIELD: &str = "pool_published_total"; +pub const LESSONS_ATTENDED_TOTAL_FIELD: &str = "lessons_attended_total"; +pub const HIGH_MARK_TOTAL_FIELD: &str = "high_mark_total"; +/// The longest run of consecutive days the student has studied, and the two +/// bookkeeping columns the write site needs to compute it: the run in progress +/// and the last day counted (both plain day numbers, midnight UTC — the same +/// boundary every other day calculation here uses). +/// +/// Only the longest is a badge counter: it never comes down, which is what +/// keeps it on the ordinary `>=` rule with no second catalog shape. The other +/// two are internal state — no badge reads them, `/limits` never names them, +/// and no profile key serves them. +pub const STUDY_STREAK_LONGEST_FIELD: &str = "study_streak_longest"; +pub const STUDY_STREAK_CURRENT_FIELD: &str = "study_streak_current"; +pub const STUDY_STREAK_LAST_DAY_FIELD: &str = "study_streak_last_day"; +/// When a lesson was first counted towards its teacher's `lessons_held_total`, +/// stamped on the `course_session` row by the first roll call taken for it. +/// Bookkeeping like the two streak columns above: no badge reads it, `/limits` +/// never names it, no profile key serves it. Its only job is the once-per- +/// session guard — a lesson is credited when it is *taken*, and the thirtieth +/// student marked must credit nothing further. +pub const LESSON_COUNTED_AT_FIELD: &str = "held_counted_at"; +/// What counts as a high mark, out of `MAX_MARK`. Hardcoded next to the badge +/// thresholds rather than read from the school's grade bands: those are +/// renameable display labels, and a badge id must never depend on a value a +/// school can change at runtime — `high_mark_10` has to mean the same thing in +/// every deployment, forever. +pub const HIGH_MARK_MIN: i64 = 90; /// The badge catalog: every badge the system can award, as /// `(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"; /// carry it simply stop being served (no data migration — /// [`crate::domain::badge::BadgeAward::list_for`] filters to the live /// catalog). -pub const BADGES: [(&str, BadgeStat, i64); 13] = [ +pub const BADGES: [(&str, BadgeStat, i64); 34] = [ ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), ("homework_submitted_10", BadgeStat::HomeworkSubmitted, 10), ("homework_submitted_50", BadgeStat::HomeworkSubmitted, 50), @@ -911,6 +948,30 @@ pub const BADGES: [(&str, BadgeStat, i64); 13] = [ BadgeStat::PomodoroFocusMs, 180_000_000, ), + ("marks_given_10", BadgeStat::MarksGiven, 10), + ("marks_given_50", BadgeStat::MarksGiven, 50), + ("marks_given_250", BadgeStat::MarksGiven, 250), + ("lessons_held_10", BadgeStat::LessonsHeld, 10), + ("lessons_held_50", BadgeStat::LessonsHeld, 50), + ("lessons_held_200", BadgeStat::LessonsHeld, 200), + ("pool_approved_5", BadgeStat::PoolApproved, 5), + ("pool_approved_25", BadgeStat::PoolApproved, 25), + ("pool_approved_100", BadgeStat::PoolApproved, 100), + ("pool_published_1", BadgeStat::PoolPublished, 1), + ("pool_published_10", BadgeStat::PoolPublished, 10), + ("pool_published_50", BadgeStat::PoolPublished, 50), + ("lessons_attended_10", BadgeStat::LessonsAttended, 10), + ("lessons_attended_50", BadgeStat::LessonsAttended, 50), + ("lessons_attended_200", BadgeStat::LessonsAttended, 200), + // Exam marks at or above `HIGH_MARK_MIN`, counted per graded sitting. + ("high_mark_1", BadgeStat::HighMark, 1), + ("high_mark_10", BadgeStat::HighMark, 10), + ("high_mark_25", BadgeStat::HighMark, 25), + // Consecutive study days, read off the longest run ever held — so these + // are earned once and never lost when the run breaks. + ("study_streak_3", BadgeStat::StudyStreak, 3), + ("study_streak_7", BadgeStat::StudyStreak, 7), + ("study_streak_30", BadgeStat::StudyStreak, 30), ]; /// The two stroke counters on a board row. `epoch_stroke_count` is reset to /// zero by a clear and capped at `MAX_EPOCH_STROKES` — a full epoch is diff --git a/src/domain/badge.rs b/src/domain/badge.rs index 761d14e..f75a6a3 100644 --- a/src/domain/badge.rs +++ b/src/domain/badge.rs @@ -16,8 +16,11 @@ use surrealdb::types::SurrealValue; use crate::constant::{ - BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, - HOMEWORK_SUBMITTED_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, + BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, + LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, + POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, + STUDY_STREAK_LONGEST_FIELD, }; use crate::database::Database; use crate::domain::timestamp::Timestamp; @@ -35,6 +38,17 @@ pub enum BadgeStat { ExamSat, PomodoroFinished, PomodoroFocusMs, + MarksGiven, + LessonsHeld, + PoolApproved, + PoolPublished, + LessonsAttended, + HighMark, + /// The *longest* run of study days, not the run in progress: the two + /// bookkeeping columns behind it are not counters and are deliberately not + /// variants here, because nothing may award a badge off a number that comes + /// back down. + StudyStreak, } impl BadgeStat { @@ -48,6 +62,13 @@ impl BadgeStat { BadgeStat::ExamSat => EXAM_SAT_TOTAL_FIELD, BadgeStat::PomodoroFinished => POMODORO_FINISHED_TOTAL_FIELD, BadgeStat::PomodoroFocusMs => POMODORO_FOCUS_MS_TOTAL_FIELD, + BadgeStat::MarksGiven => MARKS_GIVEN_TOTAL_FIELD, + BadgeStat::LessonsHeld => LESSONS_HELD_TOTAL_FIELD, + BadgeStat::PoolApproved => POOL_APPROVED_TOTAL_FIELD, + BadgeStat::PoolPublished => POOL_PUBLISHED_TOTAL_FIELD, + BadgeStat::LessonsAttended => LESSONS_ATTENDED_TOTAL_FIELD, + BadgeStat::HighMark => HIGH_MARK_TOTAL_FIELD, + BadgeStat::StudyStreak => STUDY_STREAK_LONGEST_FIELD, } } @@ -65,6 +86,13 @@ impl BadgeStat { BadgeStat::ExamSat => "exam_sat", BadgeStat::PomodoroFinished => "pomodoro_finished", BadgeStat::PomodoroFocusMs => "pomodoro_focus_ms", + BadgeStat::MarksGiven => "marks_given", + BadgeStat::LessonsHeld => "lessons_held", + BadgeStat::PoolApproved => "pool_approved", + BadgeStat::PoolPublished => "pool_published", + BadgeStat::LessonsAttended => "lessons_attended", + BadgeStat::HighMark => "high_mark", + BadgeStat::StudyStreak => "study_streak", } } } @@ -79,6 +107,15 @@ pub struct BadgeStats { exam_sat: i64, pomodoro_finished: i64, pomodoro_focus_ms: i64, + marks_given: i64, + lessons_held: i64, + pool_approved: i64, + pool_published: i64, + lessons_attended: i64, + high_mark: i64, + /// The longest study run, off `study_streak_longest`. Named for the wire, + /// like every field here, and never the run in progress. + study_streak: i64, } impl BadgeStats { @@ -102,14 +139,42 @@ impl BadgeStats { self.pomodoro_focus_ms } - /// All five counters off the user row, in one statement — a record lookup, - /// not a scan. + pub fn get_marks_given(&self) -> i64 { + self.marks_given + } + + pub fn get_lessons_held(&self) -> i64 { + self.lessons_held + } + + pub fn get_pool_approved(&self) -> i64 { + self.pool_approved + } + + pub fn get_pool_published(&self) -> i64 { + self.pool_published + } + + pub fn get_lessons_attended(&self) -> i64 { + self.lessons_attended + } + + pub fn get_high_mark(&self) -> i64 { + self.high_mark + } + + pub fn get_study_streak(&self) -> i64 { + self.study_streak + } + + /// Every counter off the user row, in one statement — a record lookup, not + /// a scan. /// /// Each projection is `(column ?? 0)`, parenthesized because `??` binds /// loosely, and it is the whole stale-data story: the columns are /// `option`, a row written before they existed carries none of them, /// and absent must read as zero rather than as a null or an error. A user - /// row that is gone entirely reads as five zeros too — a badge sync is not + /// row that is gone entirely reads as all zeros too — a badge sync is not /// the place to discover a deleted account. pub async fn load(user: &UserId, db: &Database) -> Result { let mut result = db @@ -118,13 +183,27 @@ impl BadgeStats { ({homework_on_time} ?? 0) AS homework_on_time, ({exam_sat} ?? 0) AS exam_sat, ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, + ({marks_given} ?? 0) AS marks_given, + ({lessons_held} ?? 0) AS lessons_held, + ({pool_approved} ?? 0) AS pool_approved, + ({pool_published} ?? 0) AS pool_published, + ({lessons_attended} ?? 0) AS lessons_attended, + ({high_mark} ?? 0) AS high_mark, + ({study_streak} ?? 0) AS study_streak FROM $usr", homework_submitted = BadgeStat::HomeworkSubmitted.field(), homework_on_time = BadgeStat::HomeworkOnTime.field(), exam_sat = BadgeStat::ExamSat.field(), pomodoro_finished = BadgeStat::PomodoroFinished.field(), pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), + marks_given = BadgeStat::MarksGiven.field(), + lessons_held = BadgeStat::LessonsHeld.field(), + pool_approved = BadgeStat::PoolApproved.field(), + pool_published = BadgeStat::PoolPublished.field(), + lessons_attended = BadgeStat::LessonsAttended.field(), + high_mark = BadgeStat::HighMark.field(), + study_streak = BadgeStat::StudyStreak.field(), )) .bind(("usr", user.record())) .await? @@ -153,6 +232,13 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { BadgeStat::ExamSat => stats.exam_sat, BadgeStat::PomodoroFinished => stats.pomodoro_finished, BadgeStat::PomodoroFocusMs => stats.pomodoro_focus_ms, + BadgeStat::MarksGiven => stats.marks_given, + BadgeStat::LessonsHeld => stats.lessons_held, + BadgeStat::PoolApproved => stats.pool_approved, + BadgeStat::PoolPublished => stats.pool_published, + BadgeStat::LessonsAttended => stats.lessons_attended, + BadgeStat::HighMark => stats.high_mark, + BadgeStat::StudyStreak => stats.study_streak, }; value >= *threshold }) @@ -258,6 +344,7 @@ pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> { #[cfg(test)] mod tests { use super::*; + use crate::constant::{STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD}; /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled /// with the same `IF NOT EXISTS` guards the migration uses, so it is a @@ -269,6 +356,15 @@ mod tests { DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option; DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option; DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option; DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record; DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; @@ -326,6 +422,13 @@ mod tests { (BadgeStat::ExamSat, "exam_sat"), (BadgeStat::PomodoroFinished, "pomodoro_finished"), (BadgeStat::PomodoroFocusMs, "pomodoro_focus_ms"), + (BadgeStat::MarksGiven, "marks_given"), + (BadgeStat::LessonsHeld, "lessons_held"), + (BadgeStat::PoolApproved, "pool_approved"), + (BadgeStat::PoolPublished, "pool_published"), + (BadgeStat::LessonsAttended, "lessons_attended"), + (BadgeStat::HighMark, "high_mark"), + (BadgeStat::StudyStreak, "study_streak"), ] { assert_eq!(stat.as_str(), wire, "the published name is frozen"); assert_ne!(stat.as_str(), stat.field(), "{stat:?} collapsed the two"); @@ -333,7 +436,7 @@ mod tests { } #[tokio::test] - async fn a_row_without_the_columns_loads_as_five_zeros() { + async fn a_row_without_the_columns_loads_as_zeros() { let db = crate::database::init_mem().await.unwrap(); schema(&db).await; // The stale-data case: an account written before the counters existed @@ -345,6 +448,13 @@ mod tests { assert_eq!(stats.get_exam_sat(), 0); assert_eq!(stats.get_pomodoro_finished(), 0); assert_eq!(stats.get_pomodoro_focus_ms(), 0); + assert_eq!(stats.get_marks_given(), 0); + assert_eq!(stats.get_lessons_held(), 0); + assert_eq!(stats.get_pool_approved(), 0); + assert_eq!(stats.get_pool_published(), 0); + assert_eq!(stats.get_lessons_attended(), 0); + assert_eq!(stats.get_high_mark(), 0); + assert_eq!(stats.get_study_streak(), 0); assert!(earned(&stats).is_empty(), "zero earns nothing"); } } @@ -357,6 +467,10 @@ mod tests { exam_sat: 0, pomodoro_finished: 200, pomodoro_focus_ms: 36_000_000, + high_mark: 1, + // The longest run, so 7 keeps the 3 even once the run breaks. + study_streak: 7, + ..BadgeStats::default() }; assert_eq!( earned(&stats), @@ -370,6 +484,9 @@ mod tests { "pomodoro_finished_200", // Exactly at the threshold earns it. "pomodoro_focus_ms_36000000", + "high_mark_1", + "study_streak_3", + "study_streak_7", ] ); } diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index 26c259f..a327501 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -3,7 +3,8 @@ use std::collections::HashMap; use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, KIND_REF_TABLE, REF_COUNT_FIELD, REF_RETIRED_FIELD, + EXAM_RESULT_COUNT_FIELD, EXAM_RESULT_TABLE, HIGH_MARK_MIN, HIGH_MARK_TOTAL_FIELD, + KIND_REF_TABLE, MARKS_GIVEN_TOTAL_FIELD, REF_COUNT_FIELD, REF_RETIRED_FIELD, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::cap; @@ -201,6 +202,14 @@ impl ExamResult { /// one mark, one reference, so the branch that finds a row simply leaves /// both counters where they are — there is no claim to give back, and so no /// window in which a crash could fail to give it. + /// + /// The two badge counters ride that same first-time branch: the grader's + /// `marks_given_total`, and — only when the mark clears + /// [`HIGH_MARK_MIN`] — the student's `high_mark_total`. So a regrade of a + /// sitting moves neither however often it is run, while a retake, being a + /// distinct `seq` and so a distinct row, counts on its own. They are + /// written field-scoped: a user row also carries admin-owned data (`role`) + /// that a whole-row save would revert. pub async fn grade( exam: &ExamId, user: &UserId, @@ -246,6 +255,17 @@ impl ExamResult { // the index entry can only ever point at the row the id already names // and the write resolves onto it. A lost round aborts having written // nothing, counters included. + // Below the line the student's counter is left out of the statement + // list entirely, rather than added to by a zero: a low mark is most + // marks, and it must not write the student's row at all. + let high_mark = if mark.as_i64() >= HIGH_MARK_MIN { + format!( + "UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} = + ({HIGH_MARK_TOTAL_FIELD} ?? 0) + 1;" + ) + } else { + String::new() + }; let _guard = cap::counter_lock().await; let (mut written, mut errors) = transaction_with_retry( db, @@ -260,6 +280,9 @@ impl ExamResult { IF array::len($kind) = 0 {{ THROW '{RETIRED_MARK}' }}; UPDATE $exam SET {EXAM_RESULT_COUNT_FIELD} = ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1; + {high_mark} }}; LET $after = (UPSERT $id CONTENT $result RETURN AFTER); RETURN $after[0]; @@ -269,6 +292,8 @@ impl ExamResult { ("exam".into(), exam.record().into_value()), ("id".into(), result.id.record().into_value()), ("kref".into(), kind_ref(kind).into_value()), + ("grader".into(), graded_by.record().into_value()), + ("student".into(), user.record().into_value()), ("result".into(), result.into_value()), ], &["exam_missing", "exam_draft", RETIRED_MARK], @@ -570,6 +595,9 @@ mod tests { .unwrap(); } + const STUDENT: &str = "01TESTSTUDENTAAAAAAAAAAAAA"; + const TEACHER: &str = "01TESTTEACHERAAAAAAAAAAAAA"; + async fn grade( db: &Database, exam: &ExamId, @@ -579,10 +607,10 @@ mod tests { ) -> Result { ExamResult::grade( exam, - &UserId::from_key("01TESTSTUDENTAAAAAAAAAAAAA"), + &UserId::from_key(STUDENT), seq, Mark::try_new(mark).unwrap(), - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), + &UserId::from_key(TEACHER), kind, db, ) @@ -612,6 +640,86 @@ mod tests { assert_eq!(counters(&db, "midterm").await, (2, 2)); } + /// The two badge counters, re-read out of the store: the grader's marks + /// given and the student's high marks. + async fn badge_counters(db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $grader; + SELECT VALUE ({HIGH_MARK_TOTAL_FIELD} ?? 0) FROM $student;" + )) + .bind(("grader", UserId::from_key(TEACHER).record())) + .bind(("student", UserId::from_key(STUDENT).record())) + .await + .unwrap() + .check() + .unwrap(); + let given: Vec = result.take(0).unwrap(); + let high: Vec = result.take(1).unwrap(); + ( + given.into_iter().next().unwrap_or(0), + high.into_iter().next().unwrap_or(0), + ) + } + + /// The rows a counter needs to land on — `UPDATE` writes nothing to a user + /// that does not exist, so the badge tests must make both real. + async fn the_two_people(db: &Database) { + for key in [TEACHER, STUDENT] { + db.query("CREATE $usr SET username = $name, password_hash = 'x'") + .bind(("usr", UserId::from_key(key).record())) + .bind(("name", key.to_string())) + .await + .unwrap() + .check() + .unwrap(); + } + } + + /// A first grade credits the grader once and the student only when the mark + /// clears the line; a regrade of the same sitting credits neither again, + /// while a retake — a distinct seq, so a distinct row — counts on its own. + #[tokio::test] + async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMBADGEAAAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + + grade(&db, &exam, 1, 90, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it"); + + // Same sitting graded again: neither counter may move, however high. + grade(&db, &exam, 1, 100, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing"); + + // A retake below the line: the grader is credited, the student is not. + grade(&db, &exam, 2, 89, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line"); + + // …and a high-scoring retake counts as its own sitting. + grade(&db, &exam, 3, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (3, 2)); + } + + /// A refused mark leaves the badge counters where the other two are left. + #[tokio::test] + async fn a_refused_mark_credits_nobody() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMBADGEDRAFTAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + db.query("UPDATE $ex SET draft = true") + .bind(("ex", exam.record())) + .await + .unwrap() + .check() + .unwrap(); + + assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err()); + assert_eq!(badge_counters(&db).await, (0, 0)); + } + /// A retired kind refuses the claim from inside the transaction, which /// takes the mark and the exam's counter down with it — the settings guard /// enforcing the same invariant from the other side. diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 6025eee..1aa0634 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -13,7 +13,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{HOMEWORK_RESULT_TABLE, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; +use crate::constant::{ + HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, +}; use crate::database::Database; use crate::domain::course::CourseId; use crate::domain::exam_result::Mark; @@ -164,22 +166,47 @@ impl HomeworkResult { graded_by: graded_by.clone(), created_at: Timestamp::now(), }; + // Whether the pair was already graded is read one statement ahead of + // the write, inside the same transaction — it is what keeps a regrade + // from crediting the grader a second time. No mark counter here: a + // homework mark is optional and most grades are status-only, so + // `high_mark` is an exam-only family. + // + // ponytail: this is a plain query, not `transaction_with_retry`, so a + // store conflict on the grader's row — another domain writing the same + // user row in the same instant — comes back as a 500 rather than a + // re-send. Rare (grading is serialised by `HOMEWORK_LOCK` and a + // teacher's row moves nowhere else but exam grading), and the upgrade + // is the shape `HomeworkSubmission::upsert` already uses: the whole + // transaction is re-sendable, since nothing in it can legitimately + // answer "already exists". let mut saved = db .query(format!( "BEGIN TRANSACTION; - UPSERT $id CONTENT $row RETURN AFTER; + LET $before = (SELECT VALUE id FROM ONLY $id); + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ WHERE {SUBMISSION_OPEN_GUARD}; + IF $before = NONE {{ + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 + }}; + RETURN $after; COMMIT TRANSACTION;" )) .bind(("id", id.record())) .bind(("sub", submission.record())) + .bind(("grader", graded_by.record())) .bind(("row", result.into_value())) .await? .check()?; - // BEGIN is slot 0; the result's UPSERT is slot 1, the stamp slot 2. + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count instead of a hand-kept + // number — which the counter statement above would otherwise have + // shifted, silently handing back the stamp's row. + let slot = saved.num_statements().saturating_sub(2); saved - .take::>(1)? + .take::>(slot)? .into_iter() .next() .ok_or_else(|| AppError::Internal("failed to record homework result".into())) @@ -339,4 +366,59 @@ mod tests { .is_none() ); } + + /// The grader is credited once per graded pair: a regrade lands on the same + /// row, so it is not a mark given twice. The student's counters are not + /// touched at all — a homework grade is not a homework submission. + #[tokio::test] + async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWBADGEAAAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + // `UPDATE` writes nothing to a user row that does not exist. + db.query("CREATE $usr SET username = 't', password_hash = 'x'") + .bind(("usr", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); + + for status in ["incomplete", "done"] { + HomeworkResult::grade( + &homework, + &user, + HomeworkStatus::try_new(status).unwrap(), + None, + &teacher, + &db, + ) + .await + .unwrap(); + } + assert_eq!( + marks_given(&teacher, &db).await, + 1, + "one graded pair, one mark given" + ); + } + + /// The grader's badge counter, re-read out of the store. + async fn marks_given(user: &UserId, db: &Database) -> i64 { + let mut result = db + .query(format!( + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + result + .take::>(0) + .unwrap() + .into_iter() + .next() + .unwrap_or(0) + } } diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 223dae7..f07b593 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -2,6 +2,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, POMODORO_SESSION_TABLE, + STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, }; use crate::database::{Database, transaction_with_retry}; use crate::domain::badge; @@ -130,7 +131,51 @@ impl PomodoroSession { /// nothing downstream needs a floor. Only *finished* stints reach here — an /// open row is a `pomodoro_session` row and nothing else — and there is no /// student-facing delete for a stint, so neither counter ever decrements. + /// + /// The **study streak** rides the same transaction. A study day is a UTC + /// calendar day on which a stint was *finished* (midnight UTC, like every + /// other day calculation here — no timezone is stored anywhere): the same + /// day again changes nothing, the next day extends the run, any other gap + /// starts a new one at 1. It is written as **two** statements, not one: + /// every field reference on the right-hand side of a `SET` resolves + /// against the row as it was *before* that statement, so a single + /// `SET current = …, longest = math::max([longest, current])` would take + /// the *old* `current` and lag one write behind forever (probed on a real + /// 3.2.3 server: day two left `current = 2, longest = 1`). Across + /// statements *inside a transaction* the read does see the prior write, so + /// the pair is correct and still atomic. Absent columns are read through + /// `?? 0` (and `?? -1` for the day — a sentinel no real day number + /// reaches), because `math::max` errors outright on a `NONE` argument and + /// every account older than these columns carries none of them. + /// + /// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two + /// lines up: a plain `UPDATE` hands back an array, so a user row that is + /// missing (a `record` column checks only the table of the id) simply + /// yields nothing to index and the second statement matches no row either. + /// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero + /// rows; it errors on *many* — but a `null` is a shape the read then has to + /// special-case, so the file's existing idiom wins. + /// + /// No `cap::counter_lock` is taken, deliberately. The pair cannot tear: + /// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts + /// a rival that touched the row in between — `transaction_with_retry` then + /// re-sends the whole round. And `longest` is written as + /// `max(longest, current)`, which cannot come down under *any* + /// interleaving, so even a torn pair could only under-count `current`, + /// never lower the high-water mark the badges read. The lock would only + /// serialize this process's writers (its other job, keeping the in-memory + /// test engine deterministic, is moot here — these tests are sequential). + /// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent + /// finishes for one user left `current = 60, longest = 60` with no + /// anomaly; a rival write forced *between* the two statements (a `sleep` + /// wedged into the batch) aborted the whole cascade with a write conflict, + /// wrote nothing, and left the rival's value standing. + /// + /// Streaks begin at this deploy: nothing reconstructs history from the + /// stint log, so every account starts with no streak columns and its first + /// finish sets a run of 1. pub async fn finish(user: &UserId, db: &Database) -> Result { + let done = Timestamp::now(); let (mut result, mut errors) = transaction_with_retry( db, &format!( @@ -141,6 +186,18 @@ impl PomodoroSession { {POMODORO_FINISHED_TOTAL_FIELD} = ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, {POMODORO_FOCUS_MS_TOTAL_FIELD} = ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + (math::max([$before[0].started_at, $done]) - $before[0].started_at); + LET $streak = (UPDATE $usr SET + {STUDY_STREAK_CURRENT_FIELD} = + IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day + THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) + ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) + THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) + ELSE 1 END, + {STUDY_STREAK_LAST_DAY_FIELD} = $day + RETURN AFTER); + UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), + ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]); CREATE $closed CONTENT {{ user: $before[0].user, started_at: $before[0].started_at, @@ -158,7 +215,8 @@ impl PomodoroSession { "closed".into(), PomodoroSessionId::generate().record().into_value(), ), - ("done".into(), Timestamp::now().into_value()), + ("done".into(), done.into_value()), + ("day".into(), done.day_number().into_value()), ], &["no_pomodoro_running"], ) @@ -256,6 +314,197 @@ mod tests { (row[0], row[1]) } + /// `(current, longest, last_day)` re-read from the store. + async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0), + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), + ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + let row = rows.into_iter().next().expect("the user row"); + (row[0], row[1], row[2]) + } + + /// Age the streak bookkeeping by `days`, so the *next* finish lands that + /// many days later on the calendar. The day is injected into the stored + /// state rather than into the clock, which keeps `Timestamp::now` the sole + /// clock read and the test free of sleeping. + /// + /// Known flake, left as-is: every caller assumes the UTC day does not turn + /// over mid-test — a crossing between two stints shifts the real day under + /// the injected one and reddens the run. That is one ~ms-wide window per + /// day (~5e-6 per run), and the alternative is a clock seam in production + /// code to serve a test. Re-run before believing a failure that only ever + /// happens near midnight UTC. + async fn age_by_days(user: &UserId, db: &Database, days: i64) { + db.query(format!( + "UPDATE $usr SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days" + )) + .bind(("usr", user.record())) + .bind(("days", days)) + .await + .unwrap() + .check() + .unwrap(); + } + + /// Start and close one stint. + async fn one_stint(user: &UserId, db: &Database) { + PomodoroSession::start(user, db).await.unwrap(); + PomodoroSession::finish(user, db).await.unwrap(); + } + + #[tokio::test] + async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + // The stale-data case: a row that predates all three columns reads as + // no streak at all, and its first finish opens a run of one. + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + + one_stint(&user, &db).await; + let today = Timestamp::now().day_number(); + assert_eq!(streak(&user, &db).await, (1, 1, today)); + + // A second stint the same day is not a second day. + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await, (1, 1, today)); + + // Days N+1 and N+2. + for day in 2..=3 { + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await, (day, day, today)); + } + } + + #[tokio::test] + async fn a_gap_resets_the_run_but_never_the_high_water_mark() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + one_stint(&user, &db).await; + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await.0, 2); + + // Skip a day: the run restarts at one, the longest stays where it got. + age_by_days(&user, &db, 2).await; + one_stint(&user, &db).await; + let (current, longest, _) = streak(&user, &db).await; + assert_eq!((current, longest), (1, 2)); + + // A backwards day (a clock stepped back over a boundary) is a gap too, + // and still cannot lower the mark. + age_by_days(&user, &db, -5).await; + one_stint(&user, &db).await; + assert_eq!( + streak(&user, &db).await, + (1, 2, Timestamp::now().day_number()) + ); + } + + /// The transaction boundary itself, on a real server: the streak pair and + /// the counters must commit with the stint or not at all, under real + /// contention on one user row. + /// + /// Multi-threaded and off the embedded engine for the reason + /// [`crate::domain::cap`] spells out: the in-memory engine does not + /// conflict-check two concurrent writes to one record, so it would answer + /// `Ok` to a write it dropped and *forge* the integrity failure this test + /// exists to catch. + /// + /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT` + /// pair from the batch turns all 20 rounds red. A `THROW` then errors only + /// its own statement, so the losers of the open-row race run the rest of + /// the cascade anyway — they bump the counters for a stint they never + /// closed and `CREATE` a session row out of an empty `$before`, which comes + /// back as `500 … Expected record, got none` (the `errors` assertion below + /// fires first; `finished_total` running ahead of the `Ok` finishes is the + /// same wound one statement later). What it does *not* pin is the + /// streak arithmetic under concurrency: same-day finishes all compute the + /// same value, so that stays green either way — it is + /// `max(longest, current)` that makes that robust, not the isolation. + /// + /// The shape of the contention, measured rather than assumed: four racers + /// per round is four `start`s collapsing onto *one* open row (the id is + /// deterministic per user), so typically exactly one `finish` commits and + /// three lose the `DELETE` and abort their whole cascade — 20 finishes and + /// 60 conflicts over 20 rounds, measured. That is the contention: the + /// losers' cascades are live against the same user row, which is precisely + /// what must leave nothing behind. Two commits in one round are possible + /// (a racer scheduled entirely after another's finish frees the slot) and + /// the assertions allow it — the day count is per round, not per stint. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { + let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await; + let user = a_user(&db).await; + let (mut finished, mut conflicts, mut errors) = (0, 0, 0); + let mut last_error = String::new(); + for round in 1..=20 { + let racers: Vec<_> = (0..4) + .map(|_| { + let (user, db) = (user.clone(), db.clone()); + tokio::spawn(async move { + PomodoroSession::start(&user, &db).await?; + PomodoroSession::finish(&user, &db).await + }) + }) + .collect(); + let mut won = 0; + for racer in racers { + match racer.await.unwrap() { + Ok(_) => won += 1, + // Losing the open row is the correct answer for a racer + // whose stint someone else closed; only `Db` is a defect. + Err(AppError::Conflict(_)) => conflicts += 1, + Err(err) => { + errors += 1; + last_error = format!("{err:?}"); + } + } + } + finished += won; + // One day per round, however many stints landed in it, and the + // mark never lags the run in progress. + let (current, longest, _) = streak(&user, &db).await; + assert_eq!( + (current, longest), + (round, round), + "round {round} counted {won} finishes as {current} days" + ); + age_by_days(&user, &db, 1).await; + } + // The atomicity claim: the counter counts exactly the stints that were + // closed, never a loser's aborted round. + let (counted, _) = counters(&user, &db).await; + eprintln!( + "PomodoroSession::finish raced: {finished} finishes over 20 days, \ + {conflicts} rivals refused, {errors} 500s" + ); + assert_eq!( + errors, 0, + "a raced finish must conflict, not 500: {last_error}" + ); + assert_eq!( + counted, finished, + "the counter counted {counted} stints for {finished} finishes" + ); + assert!( + conflicts > 0, + "every racer won its own round, so no cascade was ever aborted mid-flight \ + and this run proves nothing about the transaction boundary" + ); + } + #[tokio::test] async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { let db = database::init_mem().await.unwrap(); diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 3083483..39d31c2 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -13,10 +13,10 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, - STATUS_PENDING, + MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_APPROVED_TOTAL_FIELD, + POOL_PUBLISHED_TOTAL_FIELD, POOL_QUESTION_TABLE, STATUS_APPROVED, STATUS_PENDING, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; use crate::domain::solution::Solution; @@ -202,23 +202,76 @@ impl PoolQuestion { /// racing approvals exactly one wins, and an approve can never land on a /// question deleted mid-flight. `None` = the question wasn't pending /// (already approved, or gone) — the caller sorts out which. + /// + /// Two lifetime badge counters ride that same guard, inside this + /// transaction: the approver's `pool_approved_total` and the *asker's* + /// `pool_published_total`. Both hang off `array::len($done) > 0` — the + /// guard's own verdict — so the pair moves once per real transition and + /// never on a second approve of an already-approved question. + /// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that + /// holds.) The second conjunct is the self-approval rule below. + /// + /// Two rules keep the pair unfarmable, one per side of the transition. + /// + /// The asker is credited at *approval*, not at asking: a bare + /// [`insert`](PoolQuestion::insert) is self-service and the author can + /// delete their own question and ask again forever, so a counter moved + /// there is farmable. Approval is teacher-gated and one-way, which is why + /// the family is named `pool_published` and not `pool_asked`. That closes + /// the student side. + /// + /// And a *self*-approval — a teacher+ approving a question they asked + /// themselves, which the route deliberately still allows — moves neither + /// counter, hence the `$done[0].asker != $by` half of the condition. It is + /// the same farm from the other end (ask, approve, delete, repeat, with no + /// second person involved), and the two together are why a counter can only + /// move when one person's work was judged by another's. Nothing else about + /// a self-approval changes: same 200, same freeze, same stamp — this skips + /// the credit, not the approval. + /// + /// Re-sent while the store answers "conflict, retry": the guard reads a + /// column a rival approve writes, and both counters sit on user rows every + /// other counter site writes too. Sound to re-send — every statement is an + /// `UPDATE`, none of which can legitimately answer "already exists" — and a + /// lost round aborts having written nothing, increments included. pub async fn approve( id: &PoolQuestionId, approver: &UserId, db: &Database, ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET status = $approved, approved_by = $by \ - WHERE status = $pending RETURN AFTER", - ) - .bind(("q", id.record())) - .bind(("approved", STATUS_APPROVED)) - .bind(("by", approver.record())) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $done = (UPDATE $q SET status = $approved, approved_by = $by + WHERE status = $pending RETURN AFTER); + IF array::len($done) > 0 AND $done[0].asker != $by {{ + UPDATE $by SET + {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; + LET $asker = $done[0].asker; + UPDATE $asker SET + {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; + }}; + RETURN $done; + COMMIT TRANSACTION;" + ), + &[ + ("q".into(), id.record().into_value()), + ("approved".into(), STATUS_APPROVED.to_string().into_value()), + ("by".into(), approver.record().into_value()), + ("pending".into(), STATUS_PENDING.to_string().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count rather than a hand-kept + // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). + let slot = result.num_statements().saturating_sub(2); + Ok(result.take::>(slot)?.into_iter().next()) } /// Point the question at a freshly written image blob. Guarded on @@ -303,6 +356,45 @@ mod tests { use crate::database; use crate::domain::solution::{Solution, SolutionBody}; + /// The two counter columns plus a row to carry them: the `user` table is + /// SCHEMAFULL in production, and the counters are `option` there. + async fn a_user(db: &Database) -> UserId { + let user = UserId::from_key(&Ulid::new().to_string()); + db.query(format!( + "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; + CREATE $usr SET username = $name, password_hash = 'x';" + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// `(pool_approved_total, pool_published_total)` as stored — absent reads + /// zero, the way `BadgeStats::load` reads it. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), + ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows = result.take::>>(0).unwrap(); + let row = rows.into_iter().next().unwrap_or_default(); + ( + row.first().copied().unwrap_or(0), + row.get(1).copied().unwrap_or(0), + ) + } + fn question(asker: &UserId) -> PoolQuestion { PoolQuestion::new( asker, @@ -344,6 +436,77 @@ mod tests { ); } + /// The publish counters ride the guard, so they move exactly once per real + /// transition: the approver's on the approve side, the asker's on the + /// published side, and neither on a second approve of the same question. + #[tokio::test] + async fn approval_moves_both_counters_once_and_only_once() { + let db = database::init_mem().await.unwrap(); + let asker = a_user(&db).await; + let teacher = a_user(&db).await; + + let q = question(&asker).insert(&db).await.unwrap(); + assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); + + PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); + assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); + + // The guard finds nothing pending, so neither counter may move — this + // is what stops an approve loop from farming either one. + assert!( + PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .is_none() + ); + assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); + assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); + + // And an approve that lands on nothing at all writes nothing. + assert!( + PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) + .await + .unwrap() + .is_none() + ); + assert_eq!(counters(&teacher, &db).await, (1, 0)); + } + + /// A teacher may ask a question and the route does not bar them from + /// approving it — that still works, unchanged. What it does not do is pay + /// for itself: ask, approve, delete, repeat is the staff-side farm, and + /// neither counter moves when one person is both ends of the transition. + #[tokio::test] + async fn self_approval_still_approves_but_moves_neither_counter() { + let db = database::init_mem().await.unwrap(); + let teacher = a_user(&db).await; + + let q = question(&teacher).insert(&db).await.unwrap(); + let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + // The approval itself is untouched: published, stamped, frozen. + assert!(approved.is_approved()); + assert_eq!(approved.get_approved_by(), Some(&teacher)); + assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); + + // And the skip is about the *pair*, not about the teacher: approving + // somebody else's question right after still pays. + let asker = a_user(&db).await; + let other = question(&asker).insert(&db).await.unwrap(); + PoolQuestion::approve(other.get_id(), &teacher, &db) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&teacher, &db).await, (1, 0)); + assert_eq!(counters(&asker, &db).await, (0, 1)); + } + #[tokio::test] async fn visibility_hides_others_pending_questions() { let db = database::init_mem().await.unwrap(); diff --git a/src/domain/profile.rs b/src/domain/profile.rs index 9ee003c..71ff2e8 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -201,13 +201,27 @@ impl ProfileStats { ({homework_on_time} ?? 0) AS homework_on_time, ({exam_sat} ?? 0) AS exam_sat, ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, + ({marks_given} ?? 0) AS marks_given, + ({lessons_held} ?? 0) AS lessons_held, + ({pool_approved} ?? 0) AS pool_approved, + ({pool_published} ?? 0) AS pool_published, + ({lessons_attended} ?? 0) AS lessons_attended, + ({high_mark} ?? 0) AS high_mark, + ({study_streak} ?? 0) AS study_streak FROM $usr;", homework_submitted = BadgeStat::HomeworkSubmitted.field(), homework_on_time = BadgeStat::HomeworkOnTime.field(), exam_sat = BadgeStat::ExamSat.field(), pomodoro_finished = BadgeStat::PomodoroFinished.field(), pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), + marks_given = BadgeStat::MarksGiven.field(), + lessons_held = BadgeStat::LessonsHeld.field(), + pool_approved = BadgeStat::PoolApproved.field(), + pool_published = BadgeStat::PoolPublished.field(), + lessons_attended = BadgeStat::LessonsAttended.field(), + high_mark = BadgeStat::HighMark.field(), + study_streak = BadgeStat::StudyStreak.field(), )) .bind(("usr", user.record())) .await? @@ -215,7 +229,7 @@ impl ProfileStats { // `GROUP ALL` yields no row at all when nothing matched — that is the // zero case, not a missing one. let row = result.take::>(0)?.into_iter().next(); - // A vanished user row reads as five zeros, same as a fresh account. + // A vanished user row reads as all zeros, same as a fresh account. let totals = result .take::>(1)? .into_iter() diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 6c2a14b..eed3e50 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -1,11 +1,15 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::SESSION_ATTENDANCE_TABLE; +use crate::constant::{ + LESSON_COUNTED_AT_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, + SESSION_ATTENDANCE_TABLE, +}; use crate::database::{Database, transaction_with_retry}; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; use crate::domain::page::PagedList; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -36,6 +40,22 @@ impl SessionAttendanceId { } } +/// Whether a status means the person was *there*, for the `lessons_attended` +/// badge counter. Exactly the rule `GET /attendance/me` already publishes — +/// `StatusCounts::tally` in `src/web/attendance.rs` puts `present` and `late` +/// over the line and leaves `excused` and every school-added status neutral — +/// so a student's badge and their attendance rate never disagree about what +/// attending is. +/// +/// Hardcoding the two literals is safe by construction: statuses are the +/// school's to extend, but [`crate::domain::settings`] refuses any write that +/// drops one of the core four, so `present` and `late` can never be renamed +/// away. The SQL below repeats them — they are one rule in two languages, and +/// the transition test is what pins them together. +fn counts_as_attended(status: &AttendanceStatus) -> bool { + matches!(status.as_str(), "present" | "late") +} + /// One person's roll-call state for one lesson. `course` is denormalized from /// the session so the per-course attendance report is a single indexed query /// (`WHERE user = $u`) with no join. @@ -86,13 +106,42 @@ impl SessionAttendance { /// route 404ing on the vanished session while the attendance report went /// on counting it. A deleted session reads NONE, which is falsy, so the /// gate is written as an explicit `IS NONE` (see - /// [`crate::domain::exam_result::ExamResult::grade`]). + /// [`crate::domain::exam_result::ExamResult::grade`]). It reads the + /// session's `teacher` — required on every row, so NONE means "no row" just + /// as `id` did — because the counter below needs that teacher anyway, and + /// one read serves both. /// /// Sound to re-send while the store answers "conflict, retry": the gate /// reads the record a delete writes, so the two contend by design, and the /// UPSERT cannot legitimately answer "already exists" — its composite id is /// bijective with the `session_attendance_session_user` unique tuple, so /// the index entry can only point at the row the id already names. + /// + /// Two badge counters move in this same transaction, both of them read + /// from the store rather than taken on the caller's word: + /// + /// - `lessons_attended_total`, on the person marked, as a *delta* rather + /// than an increment, because this is an upsert: a re-mark that changes + /// nothing must change nothing, and a teacher's correction must move it + /// back down. `$was` is read before the upsert overwrites it (`NONE` when + /// the pair has no row yet), so it writes only on a real crossing of the + /// attended line, and only for a **student** — attending lessons is a + /// student's badge, the same student-only rule enrolling and sitting an + /// exam already carry, so a teacher marked present in their own lesson + /// moves it in neither direction. The live `role` decides that, not the + /// role someone held when the row was written. + /// - `lessons_held_total`, on the *session's* teacher, exactly once per + /// session: the first roll call taken stamps + /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees + /// the stamp and credits nothing. It counts lessons that actually + /// happened — scheduling one and cancelling it earns nothing, which is + /// why the credit does not live in `CourseSession::create`. Two + /// simultaneous first marks both write the lesson row, so the store's own + /// conflict detection (and `transaction_with_retry` behind it) is what + /// keeps the stamp from being set twice. + /// + /// Both are floored/guarded rather than trusting the column to exist: a row + /// written before these columns carries none of them. pub async fn mark( session: &CourseSession, user: &UserId, @@ -100,6 +149,8 @@ impl SessionAttendance { marked_by: &UserId, db: &Database, ) -> Result { + let attended = counts_as_attended(&status); + let delta: i64 = if attended { 1 } else { -1 }; let attendance = SessionAttendance { id: SessionAttendanceId::composite(session.get_id(), user), session: session.get_id().clone(), @@ -110,16 +161,35 @@ impl SessionAttendance { }; let (mut written, mut errors) = transaction_with_retry( db, - "BEGIN TRANSACTION; - IF (SELECT VALUE id FROM ONLY $sess) IS NONE { THROW 'session_missing' }; + &format!( + "BEGIN TRANSACTION; + LET $teacher = (SELECT VALUE teacher FROM ONLY $sess); + IF $teacher IS NONE {{ THROW 'session_missing' }}; + LET $counted = (SELECT VALUE {LESSON_COUNTED_AT_FIELD} FROM ONLY $sess); + LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); + LET $was = ((SELECT VALUE status FROM ONLY $id) IN ['present', 'late']); LET $after = (UPSERT $id CONTENT $row RETURN AFTER); + IF $student AND $was != $now {{ + UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = + math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) + $delta, 0]) + }}; + IF $counted IS NONE {{ + UPDATE $sess SET {LESSON_COUNTED_AT_FIELD} = $stamp; + UPDATE $teacher SET {LESSONS_HELD_TOTAL_FIELD} = + ({LESSONS_HELD_TOTAL_FIELD} ?? 0) + 1 + }}; RETURN $after; - COMMIT TRANSACTION;", + COMMIT TRANSACTION;" + ), &[ // `$session` is SurrealDB's own protected variable (the auth // session): binding that name errors the whole query. ("sess".into(), session.get_id().record().into_value()), ("id".into(), attendance.id.record().into_value()), + ("usr".into(), user.record().into_value()), + ("now".into(), attended.into_value()), + ("delta".into(), delta.into_value()), + ("stamp".into(), Timestamp::now().into_value()), ("row".into(), attendance.into_value()), ], &["session_missing"], @@ -175,17 +245,361 @@ impl SessionAttendance { Ok(result.take::>(0)?) } + /// Clearing a row the student was counted for gives the count back, in the + /// delete's own transaction — the other direction of the delta in + /// [`SessionAttendance::mark`], so a row that never existed and a row that + /// was withdrawn leave the same number behind. Only *this* route decrements: + /// [`CourseSession::delete`]'s cascade sweeps the rows with a `DELETE` of + /// its own and never comes through here, which is the ruling + /// `exam_sat_total` already carries — deleting the lesson does not un-attend + /// it. `lessons_held_total` is never given back either: the lesson was + /// taken, and clearing one student's row does not un-take it. + /// + /// Student-only on the same terms as the mark, and read from the store for + /// the same reason. + /// + /// Sound to re-send: neither statement can answer "already exists". + // + // ponytail: both ends read the *live* role, so a student promoted between + // being marked present and having that row corrected leaves the counter one + // high (the credit landed as a student, the refund is refused as staff). + // Upgrade path is stamping the credit on the roll-call row itself and + // refunding off that stamp, the way `counted_on_time` works for homework — + // not worth a column until a promotion mid-term is a real complaint. pub async fn remove( session: &CourseSessionId, user: &UserId, db: &Database, ) -> Result, AppError> { - let mut result = db - .query("DELETE session_attendance WHERE session = $s AND user = $usr RETURN BEFORE") - .bind(("s", session.record())) + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $student = ((SELECT VALUE role FROM ONLY $usr) = 'student'); + LET $gone = (DELETE session_attendance + WHERE session = $s AND user = $usr RETURN BEFORE); + IF $student AND array::len($gone) > 0 AND $gone[0].status IN ['present', 'late'] {{ + UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = + math::max([({LESSONS_ATTENDED_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; + COMMIT TRANSACTION;" + ), + &[ + ("s".into(), session.record().into_value()), + ("usr".into(), user.record().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`. + let slot = result.num_statements().saturating_sub(2); + Ok(result + .take::>(slot)? + .into_iter() + .next()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::DEFAULT_ATTENDANCE_STATUSES; + use crate::database::init_mem; + use crate::domain::badge::BadgeStats; + use crate::domain::course_session::SessionTopic; + use crate::domain::role::Role; + + /// A user row carrying its role — the counters are `UPDATE`s on one (which + /// writes nothing at all to a record that does not exist), and the live + /// role is what decides whether the attended counter moves. + async fn a_user(key: &str, role: Role, db: &Database) -> UserId { + let user = UserId::from_key(key); + db.query("CREATE $usr SET username = $name, password_hash = 'x', role = $role") .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + .bind(("name", key.to_string())) + .bind(("role", role)) + .await + .unwrap() + .check() + .unwrap(); + user + } + + async fn a_student(key: &str, db: &Database) -> UserId { + a_user(key, Role::Student, db).await + } + + async fn a_teacher(key: &str, db: &Database) -> UserId { + a_user(key, Role::Teacher, db).await + } + + async fn a_session(teacher: &UserId, db: &Database) -> CourseSession { + CourseSession::create( + &CourseId::from_key("c"), + teacher, + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(1), + None, + db, + ) + .await + .unwrap() + } + + /// A status this school allows — the four core ones plus a school-added + /// `online`, which is exactly the open half of the set. + fn status(value: &str) -> AttendanceStatus { + let allowed: Vec = DEFAULT_ATTENDANCE_STATUSES + .iter() + .map(|s| s.to_string()) + .chain(["online".to_string()]) + .collect(); + AttendanceStatus::try_new(value, &allowed).unwrap() + } + + /// The two counters as the badge rules read them, off the stored row. + async fn attended(user: &UserId, db: &Database) -> i64 { + BadgeStats::load(user, db) + .await + .unwrap() + .get_lessons_attended() + } + + async fn held(user: &UserId, db: &Database) -> i64 { + BadgeStats::load(user, db).await.unwrap().get_lessons_held() + } + + /// The whole transition table in one pass: an upsert may only move the + /// counter when the mark crosses the attended line, in either direction, so + /// a re-mark and a swap within the same class are both no-ops. + #[tokio::test] + async fn the_counter_follows_every_crossing_and_no_other_move() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + let mark = async |value: &str, db: &Database| { + SessionAttendance::mark(&session, &student, status(value), &teacher, db) + .await + .unwrap(); + }; + + for (value, expected, why) in [ + ("present", 1, "first mark counts"), + ("present", 1, "re-marking the same status changes nothing"), + ("late", 1, "late is attending too, so no crossing"), + ("absent", 0, "a correction gives the count back"), + ("absent", 0, "and does not keep giving it back"), + ("late", 1, "absent -> late crosses back up"), + ("excused", 0, "excused is neutral: a crossing down"), + ("online", 0, "a school-added status stays neutral"), + ("present", 1, "…and crossing up from one still counts"), + ("online", 0, "…as does crossing down to one"), + ] { + mark(value, &db).await; + assert_eq!(attended(&student, &db).await, expected, "{why}"); + } + assert_eq!(attended(&teacher, &db).await, 0, "credited the marker"); + // Ten marks, one lesson: correcting a roll call is not holding another. + assert_eq!(held(&teacher, &db).await, 1, "the lesson was counted twice"); + } + + /// The lesson is credited to its teacher when the roll call is *taken*, and + /// once: the whole roster, and every later correction, ride the same stamp. + #[tokio::test] + async fn the_first_roll_call_counts_the_lesson_once() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let other = a_teacher("o", &db).await; + let session = a_session(&teacher, &db).await; + assert_eq!(held(&teacher, &db).await, 0, "scheduling counts nothing"); + + for key in ["s1", "s2", "s3"] { + let student = a_student(key, &db).await; + SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 1, "{key} counted it again"); + } + assert_eq!(held(&other, &db).await, 0, "credited the wrong teacher"); + + // A second lesson is a second count — the stamp is per session. + let second = a_session(&teacher, &db).await; + let student = a_student("s4", &db).await; + SessionAttendance::mark(&second, &student, status("present"), &teacher, &db) + .await + .unwrap(); + assert_eq!(held(&teacher, &db).await, 2); + } + + /// Attending lessons is a student's badge. A teacher marked present in + /// their own lesson (which management does, not the teacher) moves nothing + /// for them as an attendee — while the roll call itself still counts as a + /// lesson held. + #[tokio::test] + async fn a_teacher_marked_present_earns_nothing_for_attending() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let session = a_session(&teacher, &db).await; + + SessionAttendance::mark(&session, &teacher, status("present"), &teacher, &db) + .await + .unwrap(); + assert_eq!(attended(&teacher, &db).await, 0, "staff attended a lesson"); + assert_eq!(held(&teacher, &db).await, 1, "the roll call was taken"); + + // And the correction direction is just as closed: nothing was taken, so + // nothing may be given back. + SessionAttendance::mark(&session, &teacher, status("absent"), &teacher, &db) + .await + .unwrap(); + assert_eq!(attended(&teacher, &db).await, 0); + SessionAttendance::remove(session.get_id(), &teacher, &db) + .await + .unwrap() + .expect("the row was there"); + assert_eq!(attended(&teacher, &db).await, 0); + assert_eq!(held(&teacher, &db).await, 1, "the lesson still happened"); + } + + /// Two lessons are two counts — the counter is per row, not per student. + #[tokio::test] + async fn each_lesson_counts_once_for_the_student_marked() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let other = a_student("o", &db).await; + for _ in 0..2 { + let session = a_session(&teacher, &db).await; + SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) + .await + .unwrap(); + } + assert_eq!(attended(&student, &db).await, 2); + assert_eq!(attended(&other, &db).await, 0, "credited the wrong student"); + } + + /// Removing the row is the other direction of the delta, and only for a row + /// that was counted. + #[tokio::test] + async fn removing_a_row_gives_back_only_what_it_took() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + + let counted = a_session(&teacher, &db).await; + SessionAttendance::mark(&counted, &student, status("present"), &teacher, &db) + .await + .unwrap(); + let neutral = a_session(&teacher, &db).await; + SessionAttendance::mark(&neutral, &student, status("absent"), &teacher, &db) + .await + .unwrap(); + assert_eq!(attended(&student, &db).await, 1); + + SessionAttendance::remove(neutral.get_id(), &student, &db) + .await + .unwrap() + .expect("the absent row was there"); + assert_eq!(attended(&student, &db).await, 1, "absent took nothing"); + SessionAttendance::remove(counted.get_id(), &student, &db) + .await + .unwrap() + .expect("the present row was there"); + assert_eq!(attended(&student, &db).await, 0); + assert!( + SessionAttendance::remove(counted.get_id(), &student, &db) + .await + .unwrap() + .is_none(), + "nothing left to remove" + ); + assert_eq!(attended(&student, &db).await, 0, "and nothing to give back"); + assert_eq!( + held(&teacher, &db).await, + 2, + "clearing a row un-held a lesson" + ); + } + + /// The floor: however the corrections and removals interleave, and whatever + /// a stale row starts from, the counter never goes negative. + #[tokio::test] + async fn the_counter_never_goes_below_zero() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + + // Ten counted lessons whose counter was never credited — the stale-data + // case, an account that predates the column. Every one of them is now + // corrected away, which is ten decrements against a zero. + let mut sessions = Vec::new(); + for _ in 0..10 { + let session = a_session(&teacher, &db).await; + SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) + .await + .unwrap(); + sessions.push(session); + } + db.query(format!( + "UPDATE $usr SET {LESSONS_ATTENDED_TOTAL_FIELD} = 0" + )) + .bind(("usr", student.record())) + .await + .unwrap() + .check() + .unwrap(); + + for session in &sessions { + SessionAttendance::mark(session, &student, status("absent"), &teacher, &db) + .await + .unwrap(); + SessionAttendance::remove(session.get_id(), &student, &db) + .await + .unwrap(); + assert!(attended(&student, &db).await >= 0); + } + assert_eq!(attended(&student, &db).await, 0, "floored, never negative"); + } + + /// Deleting the lesson sweeps its roll-call rows with a `DELETE` of its own + /// — it never reaches [`SessionAttendance::remove`] — so the count stands, + /// the ruling every other counter here carries. + #[tokio::test] + async fn deleting_the_session_leaves_the_counters_alone() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + SessionAttendance::mark(&session, &student, status("present"), &teacher, &db) + .await + .unwrap(); + + session.delete(&db).await.unwrap(); + assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); + assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); + } + + /// A mark on a session that is already gone is refused, so it cannot leave + /// a count behind either. + #[tokio::test] + async fn a_refused_mark_moves_nothing() { + let db = init_mem().await.unwrap(); + let teacher = a_teacher("t", &db).await; + let student = a_student("s", &db).await; + let session = a_session(&teacher, &db).await; + let ghost = session.clone(); + session.delete(&db).await.unwrap(); + + assert!(matches!( + SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await, + Err(AppError::NotFound) + )); + assert_eq!(attended(&student, &db).await, 0); + assert_eq!(held(&teacher, &db).await, 0, "a refused mark held a lesson"); } } diff --git a/src/domain/timestamp.rs b/src/domain/timestamp.rs index 62672be..b93460f 100644 --- a/src/domain/timestamp.rs +++ b/src/domain/timestamp.rs @@ -11,6 +11,7 @@ //! - Durations that only pace things (rate limiter) use the monotonic //! `Instant` clock instead, which NTP adjustments cannot move backwards. +use chrono::Datelike; use surrealdb::types::SurrealValue; use crate::constant::MILLIS_PER_DAY; @@ -69,6 +70,26 @@ impl Timestamp { .expect("current time is within chrono's representable range") .date_naive() } + + /// *This* instant's UTC calendar day as a stable integer (days since the + /// Common Era epoch). The day a stored value can be compared and + /// incremented as an `int` — `day == stored + 1` is exactly "the next + /// day", with no string parsing and no month/year arithmetic. + /// + /// Takes the instant instead of reading the clock, which is what makes a + /// day-boundary rule testable without sleeping: [`Timestamp::now`] stays + /// the single clock read, and the caller derives the day from the same + /// stamp it already took. Midnight UTC is the boundary, like every other + /// day calculation here ([`Timestamp::today_utc`], menu dates, the meal + /// cutoff) — no timezone is stored anywhere, deliberately. + pub fn day_number(&self) -> i64 { + chrono::DateTime::from_timestamp_millis(self.0) + // Reachable only for an instant ±262 000 years from the epoch; the + // callers derive this from a server clock read. + .expect("timestamp is within chrono's representable range") + .date_naive() + .num_days_from_ce() as i64 + } } #[cfg(test)] @@ -108,6 +129,27 @@ mod tests { assert_eq!(Timestamp::in_days(i64::MAX).as_millis(), i64::MAX); } + #[tokio::test] + async fn day_number_is_a_midnight_utc_day_counter() { + // The unix epoch, pinned: a drifting origin would silently shift every + // stored streak day. + let epoch = Timestamp::from_millis(0); + assert_eq!(epoch.day_number(), 719_163); + // Same UTC day, different hours — one day number. + assert_eq!(Timestamp::from_millis(86_399_999).day_number(), 719_163); + // The next millisecond is the next day, and a whole day is +1. + assert_eq!(Timestamp::from_millis(86_400_000).day_number(), 719_164); + assert_eq!( + Timestamp::from_millis(1_700_000_000_000 + MILLIS_PER_DAY).day_number(), + Timestamp::from_millis(1_700_000_000_000).day_number() + 1 + ); + // Before the epoch still counts forward. + assert_eq!(Timestamp::from_millis(-1).day_number(), 719_162); + // And it agrees with the crate's other day calculation. Not flaky: a + // day boundary between the two clock reads still leaves `<=`. + assert!(Timestamp::now().day_number() <= Timestamp::today_utc().num_days_from_ce() as i64); + } + #[tokio::test] async fn today_utc_matches_now() { let today = Timestamp::today_utc(); diff --git a/src/lib.rs b/src/lib.rs index 14ce0dc..df5ebda 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,14 +44,14 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With 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"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is 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"), - (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`"), + (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`"), (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"), (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"), (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked, 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"), (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"), (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"), (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 `/ \\ ? # %`"), - (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher)"), + (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"), (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"), (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"), (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)"), diff --git a/src/migration_sql.rs b/src/migration_sql.rs index a01b098..f080e66 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -75,6 +75,21 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS exam_sat_total ON user TYPE option; DEFINE FIELD IF NOT EXISTS pomodoro_finished_total ON user TYPE option; DEFINE FIELD IF NOT EXISTS pomodoro_focus_ms_total ON user TYPE option; + -- Pass 3 (2026-08-04): the staff-side counters, two more student ones, and + -- the study streak. `study_streak_longest` is the badge counter; the other + -- two streak columns are bookkeeping the write site needs to compute it and + -- are read by nothing else. Definitions only — the seeding of the + -- row-derivable ones is a BACKFILL under its own migration mark, never in + -- this batch (same-batch DDL + backfill reads a stale schema). + DEFINE FIELD IF NOT EXISTS marks_given_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS lessons_held_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS pool_approved_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS pool_published_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS lessons_attended_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS high_mark_total ON user TYPE option; + DEFINE FIELD IF NOT EXISTS study_streak_longest ON user TYPE option; + DEFINE FIELD IF NOT EXISTS study_streak_current ON user TYPE option; + DEFINE FIELD IF NOT EXISTS study_streak_last_day ON user TYPE option; DEFINE INDEX IF NOT EXISTS user_username ON user FIELDS username UNIQUE; DEFINE TABLE IF NOT EXISTS session SCHEMAFULL; @@ -369,6 +384,12 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS topic ON course_session TYPE string; DEFINE FIELD IF NOT EXISTS starts_at ON course_session TYPE int; DEFINE FIELD IF NOT EXISTS ends_at ON course_session TYPE option; + -- The once-per-session guard behind `lessons_held_total` (2026-08-04): + -- stamped by the first roll call taken for the lesson, read by nothing but + -- that guard. Definition only, and deliberately no backfill — a session + -- that predates it carries no stamp, so the next roll call taken on it + -- credits its teacher once, which is the rule this column encodes anyway. + DEFINE FIELD IF NOT EXISTS held_counted_at ON course_session TYPE option; DEFINE INDEX IF NOT EXISTS course_session_course ON course_session FIELDS course; DEFINE TABLE IF NOT EXISTS session_attendance SCHEMAFULL; diff --git a/src/web/courses.rs b/src/web/courses.rs index 41b7b90..62ddade 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -1350,6 +1350,52 @@ mod tests { assert!(!can_manage_course(&course, &demoted)); } + /// A manager may schedule a lesson on a teacher's behalf, and the session + /// belongs to the teacher they named — not to the caller. Everything hung + /// off that column (who may take the roll call, and who the roll call + /// credits) follows it, so a handler that stored the caller instead would + /// hand the office staff somebody else's lesson. + #[tokio::test] + async fn a_manager_scheduling_a_lesson_names_the_teacher_not_themselves() { + let db = init_mem().await.unwrap(); + let manager = user("manager", Role::Manager, &db).await; + let teacher = user("teacher", Role::Teacher, &db).await; + let course = course(&manager, &db).await; + let st = AppState { + db: db.clone(), + files_path: std::env::temp_dir(), + cookie_secure: false, + rate_limit: crate::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + db_up: Default::default(), + ai: None, + }; + + let (status, Json(session)) = create_session_in_course( + State(st), + RequireTeacher(manager.clone()), + Path(course.get_id().key().to_string()), + Json(CreateSessionInCourse { + topic: None, + teacher_id: Some(teacher.get_id().key().to_string()), + starts_at: Timestamp::now().as_millis() + 60_000, + ends_at: None, + }), + ) + .await + .unwrap(); + assert_eq!(status, StatusCode::CREATED); + // Read back off the stored row, which is what `SessionResponse` names. + assert_eq!(session.teacher.id, teacher.get_id().key()); + assert_ne!( + session.teacher.id, + manager.get_id().key(), + "the caller took the lesson instead of the teacher they named" + ); + } + /// No course is left orphaned by the floor: manager+ reaches a course whose /// creator was demoted and which has no assigned teachers. #[tokio::test] diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index c15c06f..a7242e7 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -12,6 +12,7 @@ use utoipa_axum::routes; use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; +use crate::domain::badge; use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::course::Course; @@ -723,6 +724,15 @@ async fn grade( &st.db, ) .await?; + // Both sides of the grade moved a counter — the grader's `marks_given`, + // the student's `high_mark` — so both are brought up to date. A badge is a + // decoration on top of the mark: losing one to a transient database error + // must never fail the grading, and the next counter move heals it. + for person in [teacher.get_id(), &target] { + if let Err(err) = badge::sync(person, &st.db).await { + tracing::warn!("failed to sync badges for {}: {err}", person.key()); + } + } let people = PersonRef::map_of(&[&target_user, &teacher]); Ok(Json(ExamResultResponse::new(&result, &people))) } diff --git a/src/web/homework.rs b/src/web/homework.rs index 1b1b4e5..7a68697 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -776,8 +776,9 @@ async fn delete_submission( Ok(StatusCode::NO_CONTENT) } -/// Bring the student's badge awards up to date after a submission moved their -/// counters. Never fails the request it follows: a badge is a decoration on top +/// Bring one user's badge awards up to date after a write moved their counters +/// — the student's after a submission, the grader's after a grade. Never fails +/// the request it follows: a badge is a decoration on top /// of the work, and losing one to a transient database error is not worth /// refusing a hand-in over — the next counter move re-runs this and heals it. async fn award_badges(user: &UserId, db: &Database) { @@ -1135,6 +1136,9 @@ async fn grade_homework( &st.db, ) .await?; + // The grade credited the *grader*'s `marks_given`, not the student's — a + // homework grade moves no counter of the student's at all. + award_badges(teacher.get_id(), &st.db).await; Ok(Json(HomeworkResultResponse::new(&result))) } diff --git a/src/web/limits.rs b/src/web/limits.rs index d7ed80f..4015007 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -82,6 +82,11 @@ struct BadgeLimits { /// Every badge the system can auto-award, in catalog order. Hardcoded, so /// like everything else here it moves only with a deploy. catalog: Vec, + /// The exam mark that counts as a high one, out of `mark.max_mark`, behind + /// the `high_mark` ladder. Published because the id alone does not say it: + /// deliberately not the school's grade bands, which are renameable labels. + #[schema(example = 90)] + high_mark_min: i64, } /// One badge in the auto-earned catalog. The id is the whole contract: a @@ -451,6 +456,7 @@ impl LimitsResponse { threshold: *threshold, }) .collect(), + high_mark_min: HIGH_MARK_MIN, }, note: NoteLimits { max_title_len: MAX_NOTE_TITLE_LEN, diff --git a/src/web/questions.rs b/src/web/questions.rs index f72d26d..e4b7a80 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -18,6 +18,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::domain::badge; use crate::domain::pool_question::{ PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, }; @@ -386,6 +387,16 @@ async fn approve_question( return Err(AppError::Conflict("the question is already approved")); } }; + // Both counters moved inside the approval's own transaction; the badges + // they may have earned are a decoration on top of it. Losing one to a + // transient database error must never fail the approval behind it, and the + // next counter move re-runs this and heals it. Two users, because the + // transition credits the approver and the asker alike. + for earner in [user.get_id(), question.get_asker()] { + if let Err(err) = badge::sync(earner, &st.db).await { + tracing::warn!("failed to sync badges for {}: {err}", earner.key()); + } + } let responses = question_responses(std::slice::from_ref(&question), &st).await?; let response = responses .into_iter() diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 290ca0b..7e0e378 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -10,6 +10,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::AttendanceStatus; +use crate::domain::badge; use crate::domain::course::Course; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; use crate::domain::enrollment::Enrollment; @@ -354,6 +355,20 @@ async fn mark_roll_call( let attendance = SessionAttendance::mark(&session, &target, status, user.get_id(), &st.db).await?; + // A badge is a decoration on top of the roll call: losing one to a + // transient database error must never fail the mark, and the next counter + // move re-runs this and heals it. Both people the mark can credit are + // synced — the person marked (`lessons_attended`) and the lesson's teacher + // (`lessons_held`, on the first roll call only). The teacher's runs on every + // mark rather than only that first one: `sync` is add-only and idempotent, + // so the extra calls cost one record read and are what heals a first sync + // that failed, and knowing here whether the credit landed would mean + // widening `mark`'s return type for nothing. + for who in [&target, session.get_teacher()] { + if let Err(err) = badge::sync(who, &st.db).await { + tracing::warn!("failed to sync badges for {}: {err}", who.key()); + } + } let people = PersonRef::map_of(&[&target_user, &user]); Ok(Json(SessionAttendanceResponse::new(&attendance, &people))) } diff --git a/src/web/users.rs b/src/web/users.rs index 7d265bd..4309a42 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -749,12 +749,18 @@ struct ProfileCourseRef { /// account with no rows behind a counter reads a true `0`. /// /// Two kinds live here. The first four are **computed at read time** from the -/// rows that exist right now, so deleting the rows moves them down. The five -/// `*_total` ones are **stored lifetime counters**, incremented as the work +/// rows that exist right now, so deleting the rows moves them down. Every +/// `*_total` one is a **stored lifetime counter**, incremented as the work /// happens and never recomputed — they can therefore outlive the rows behind /// them (an exam deleted by its teacher still counts as sat), which is exactly /// why a badge earned off them stays earned. Each is named for a `stat` of the -/// badge catalog at `GET /limits`, plus `_total`. +/// badge catalog at `GET /limits`, plus `_total`, and that spelling is the join +/// a client makes between the two surfaces — so the suffix is on the key even +/// where the counter is not a running total (`study_streak_total` is a longest, +/// not a sum). +/// +/// Some are staff counters and some student ones; a role that never does the +/// work simply reads zero, which is why no key is conditional. #[derive(Serialize, ToSchema)] struct ProfileStatsResponse { /// Finished pomodoro stints; an open one counts for nothing. @@ -777,6 +783,28 @@ struct ProfileStatsResponse { pomodoro_finished_total: i64, /// Lifetime focused milliseconds. pomodoro_focus_ms_total: i64, + /// Lifetime grades this teacher recorded — exam sittings and homework + /// submissions alike, once per pair: a regrade moves nothing. + marks_given_total: i64, + /// Lifetime lessons this teacher held, credited at the **first roll call** + /// taken for one — a lesson scheduled and cancelled counts for nothing. + lessons_held_total: i64, + /// Lifetime pool questions this teacher approved. + pool_approved_total: i64, + /// Lifetime questions of this author that reached the school-wide pool, + /// counted when the approval lands. + pool_published_total: i64, + /// Lifetime lesson roll calls that put this **student** `present` or + /// `late`; a correction to any other status takes one back. Daily and event + /// attendance moves it not at all. + lessons_attended_total: i64, + /// Lifetime exam marks at or above the high-mark cut published as + /// `badges.high_mark_min` on `GET /limits`, one per graded sitting. + /// Homework marks never count — they are optional and often status-only. + high_mark_total: i64, + /// Longest run of consecutive study days ever held — a high-water mark, so + /// breaking the run never brings it down. Days end at midnight UTC. + study_streak_total: i64, } /// Build one profile as `viewer` may see it. The course block is chosen off the @@ -884,6 +912,13 @@ async fn profile_of( exam_sat_total: stats.get_totals().get_exam_sat(), pomodoro_finished_total: stats.get_totals().get_pomodoro_finished(), pomodoro_focus_ms_total: stats.get_totals().get_pomodoro_focus_ms(), + marks_given_total: stats.get_totals().get_marks_given(), + lessons_held_total: stats.get_totals().get_lessons_held(), + pool_approved_total: stats.get_totals().get_pool_approved(), + pool_published_total: stats.get_totals().get_pool_published(), + lessons_attended_total: stats.get_totals().get_lessons_attended(), + high_mark_total: stats.get_totals().get_high_mark(), + study_streak_total: stats.get_totals().get_study_streak(), }, }) } diff --git a/tests/regress_badges.rs b/tests/regress_badges.rs new file mode 100644 index 0000000..7374f62 --- /dev/null +++ b/tests/regress_badges.rs @@ -0,0 +1,639 @@ +//! The badge families this pass added, driven over the routes that earn them: +//! `marks_given`, `high_mark`, `pool_approved` / `pool_published`, +//! `lessons_held` and `lessons_attended`. +//! +//! Each counter is unit-tested inside its own domain module; what lives here is +//! the whole path — a real request moves the counter, the write site syncs the +//! award, and the badge comes back on a profile a client can actually read. +//! Two rules the suite exists to defend: +//! +//! * a badge is **permanent** — a counter falling back below its threshold +//! never takes the award away, and a later sync never moves `earned_at`; +//! * a counter moves only for the person who did the work, once per piece of +//! work: a regrade, a re-mark, and a self-approval all move nothing. +//! +//! Every test that reads a counter drives a real registered user through the +//! API, never a fabricated id: `UPDATE` on a record that does not exist writes +//! nothing at all, so a counter assertion against a made-up key passes as +//! `0 == 0` whatever the implementation does. + +mod common; + +use axum::Router; +use axum::http::StatusCode; +use common::{ + app_and_db, create_course, create_exam, create_session, enroll, id_of, login, login_as, me_id, + send, set_role, +}; +use hezarfen_backend::constant::{BADGES, HIGH_MARK_MIN, STUDY_STREAK_LAST_DAY_FIELD}; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::timestamp::Timestamp; +use serde_json::{Value, json}; + +/// One profile body as `cookie` may see it (asserts the `200`). +async fn profile_of(app: &Router, cookie: &str, id: &str) -> Value { + let res = send( + app, + "GET", + &format!("/users/{id}/profile"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body +} + +/// The caller's own profile body (asserts the `200`). +async fn my_profile(app: &Router, cookie: &str) -> Value { + let res = send(app, "GET", "/users/me/profile", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body +} + +/// One `stats` counter off a profile body. Panics rather than defaulting: a +/// missing key is a renamed counter, not a zero. +fn stat(profile: &Value, key: &str) -> i64 { + profile["stats"][key] + .as_i64() + .unwrap_or_else(|| panic!("stats.{key} is not a number: {profile}")) +} + +/// The badge ids on a profile, in the order served. +fn badge_ids(profile: &Value) -> Vec<&str> { + profile["badges"] + .as_array() + .expect("badges array") + .iter() + .map(|badge| badge["id"].as_str().expect("badge id")) + .collect() +} + +/// When `id` was earned, off a profile body — `None` if the shelf lacks it. +fn stamp_of(profile: &Value, id: &str) -> Option { + profile["badges"] + .as_array() + .expect("badges array") + .iter() + .find(|badge| badge["id"] == id) + .map(|badge| badge["earned_at"].as_i64().expect("earned_at millis")) +} + +// --- grading --------------------------------------------------------------- + +/// A teacher, one enrolled student, and `n` exams in one course. +/// +/// `marks_given` counts one mark per *sitting*, so ten first grades need ten +/// exams or ten students — and an exam is a single cheap request while a +/// student costs two argon2 hashes to register and log in. +struct Marking { + app: Router, + teacher: String, + student: String, + student_id: String, + exams: Vec, +} + +async fn marking(exams: usize) -> Marking { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let student = login(&app, "stu").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Algebra").await; + enroll(&app, &teacher, &course, &student_id).await; + let mut ids = Vec::with_capacity(exams); + for n in 0..exams { + ids.push(create_exam(&app, &teacher, &course, &format!("Quiz {n}"), "quiz").await); + } + Marking { + app, + teacher, + student, + student_id, + exams: ids, + } +} + +/// Record `mark` for `student` on `exam` as `teacher` (asserts the `200`). +async fn grade(app: &Router, teacher: &str, exam: &str, student: &str, mark: i64) { + let res = send( + app, + "POST", + &format!("/exams/{exam}/results"), + Some(teacher), + Some(json!({ "user_id": student, "mark": mark })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "grade {mark}: {}", res.body); +} + +/// The grader's side, end to end: ten marks recorded through the exam route +/// put `marks_given_10` on the teacher's profile — and on the *public* one a +/// student reads, which is the only surface a client has. +#[tokio::test] +async fn ten_marks_put_the_graders_badge_on_a_profile() { + let m = marking(10).await; + let teacher_id = me_id(&m.app, &m.teacher).await; + + for exam in &m.exams { + grade(&m.app, &m.teacher, exam, &m.student_id, 70).await; + } + + let mine = my_profile(&m.app, &m.teacher).await; + assert_eq!(stat(&mine, "marks_given_total"), 10, "{mine}"); + assert_eq!(badge_ids(&mine), ["marks_given_10"], "{mine}"); + // Badges are public: the student whose work was marked sees the same shelf. + let seen = profile_of(&m.app, &m.student, &teacher_id).await; + assert_eq!(badge_ids(&seen), ["marks_given_10"], "{seen}"); + // Grading is the teacher's work, not the student's — 70 is under the line, + // so the student's own counters never moved. + let theirs = my_profile(&m.app, &m.student).await; + assert_eq!(stat(&theirs, "high_mark_total"), 0, "{theirs}"); + assert_eq!(stat(&theirs, "marks_given_total"), 0, "{theirs}"); +} + +/// A mark is credited at the *first* grade of a sitting, so correcting one is +/// free: the counter stays, and — the permanence rule at the stamp — the badge +/// it already earned keeps the `earned_at` it was first given. The regrade is +/// deliberately pushed over the high-mark line, which a re-judging +/// implementation would mint a `high_mark` for. +#[tokio::test] +async fn a_regrade_moves_neither_the_counter_nor_the_stamp() { + let m = marking(10).await; + for exam in &m.exams { + grade(&m.app, &m.teacher, exam, &m.student_id, 70).await; + } + let earned = stamp_of(&my_profile(&m.app, &m.teacher).await, "marks_given_10") + .expect("the tenth mark earned the badge"); + + // Any overwrite from here on would be strictly later than this instant. + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + assert!( + earned < Timestamp::now().as_millis(), + "the clock never moved — the stamp assertion below is vacuous" + ); + + grade(&m.app, &m.teacher, &m.exams[0], &m.student_id, 100).await; + + let after = my_profile(&m.app, &m.teacher).await; + assert_eq!( + stat(&after, "marks_given_total"), + 10, + "a regrade is not an eleventh mark: {after}" + ); + assert_eq!( + stamp_of(&after, "marks_given_10"), + Some(earned), + "a re-sync moved a permanent stamp: {after}" + ); + let theirs = my_profile(&m.app, &m.student).await; + assert_eq!( + stat(&theirs, "high_mark_total"), + 0, + "a regrade re-judged the sitting and minted a high mark: {theirs}" + ); + assert_eq!(badge_ids(&theirs), Vec::<&str>::new(), "{theirs}"); +} + +/// The high-mark cut, from both sides of the line in one student's history: +/// the mark at `HIGH_MARK_MIN` earns `high_mark_1`, and the one below it earns +/// nothing — the counter that stays put is what proves the cut is a `>=` and +/// not "every mark counts". +#[tokio::test] +async fn a_mark_at_the_cut_earns_the_badge_and_one_below_it_earns_nothing() { + let m = marking(2).await; + + grade( + &m.app, + &m.teacher, + &m.exams[0], + &m.student_id, + HIGH_MARK_MIN, + ) + .await; + let high = my_profile(&m.app, &m.student).await; + assert_eq!(stat(&high, "high_mark_total"), 1, "{high}"); + assert_eq!(badge_ids(&high), ["high_mark_1"], "{high}"); + + grade( + &m.app, + &m.teacher, + &m.exams[1], + &m.student_id, + HIGH_MARK_MIN - 1, + ) + .await; + let after = my_profile(&m.app, &m.student).await; + assert_eq!( + stat(&after, "high_mark_total"), + 1, + "a mark under the cut was counted as a high one: {after}" + ); + // The grader's own counter moved twice, which is what proves the second + // grade landed at all rather than being refused. + assert_eq!( + stat(&my_profile(&m.app, &m.teacher).await, "marks_given_total"), + 2 + ); +} + +// --- the question pool ----------------------------------------------------- + +/// Ask a pool question as `cookie` (asserts the `201`); returns its id. +async fn ask(app: &Router, cookie: &str, title: &str) -> String { + let res = send( + app, + "POST", + "/questions", + Some(cookie), + Some(json!({ "title": title, "body": "Nasıl çözülür?" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + id_of(&res.body) +} + +/// Approve `question` as `cookie` (asserts the `200`); returns the body. +async fn approve(app: &Router, cookie: &str, question: &str) -> Value { + let res = send( + app, + "POST", + &format!("/questions/{question}/approve"), + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + res.body +} + +/// One approval, two people credited: the approver's `pool_approved` and the +/// asker's `pool_published`, which is a badge on its first one. And the farm +/// this closes — approving a question you asked yourself moves *neither* +/// counter, while the approval itself is untouched: same `200`, same +/// `approved` status, same stamp. +#[tokio::test] +async fn a_two_party_approval_credits_both_and_a_self_approval_credits_neither() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let asker = login(&app, "stu").await; + // Asking is student-only, so the self-approver asks first and is promoted + // afterwards — the one route onto a self-approval the API actually has. + let selfie = login(&app, "selfie").await; + + let theirs = ask(&app, &asker, "Integral").await; + let own = ask(&app, &selfie, "Türev").await; + + approve(&app, &teacher, &theirs).await; + let judge = my_profile(&app, &teacher).await; + assert_eq!(stat(&judge, "pool_approved_total"), 1, "{judge}"); + // Five approvals earn the first badge, so this one is a counter move only. + assert_eq!(badge_ids(&judge), Vec::<&str>::new(), "{judge}"); + let author = my_profile(&app, &asker).await; + assert_eq!(stat(&author, "pool_published_total"), 1, "{author}"); + assert_eq!(badge_ids(&author), ["pool_published_1"], "{author}"); + + set_role(&db, "selfie", "teacher").await; + let approved = approve(&app, &selfie, &own).await; + assert_eq!(approved["status"], "approved", "{approved}"); + assert_eq!( + approved["approved_by"]["id"], + Value::from(me_id(&app, &selfie).await), + "{approved}" + ); + + let mine = my_profile(&app, &selfie).await; + assert_eq!( + ( + stat(&mine, "pool_approved_total"), + stat(&mine, "pool_published_total") + ), + (0, 0), + "judging your own question credited you: {mine}" + ); + assert_eq!(badge_ids(&mine), Vec::<&str>::new(), "{mine}"); +} + +// --- roll call ------------------------------------------------------------- + +/// Mark `user` `status` for `session` as `cookie` (asserts the `200`). +async fn roll_call(app: &Router, cookie: &str, session: &str, user: &str, status: &str) { + let res = send( + app, + "POST", + &format!("/sessions/{session}/attendance"), + Some(cookie), + Some(json!({ "user_id": user, "status": status })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "mark {status}: {}", res.body); +} + +fn soon() -> i64 { + Timestamp::now().as_millis() + 3_600_000 +} + +/// A lesson is credited to its teacher when the roll call is *taken*, once: +/// the first student marked stamps it, and the second and third credit nothing +/// further however many are on the roster. +/// +/// And attending is a student's badge alone — the manager marking the lesson's +/// own teacher present (the one staff roll-call row the API allows) moves no +/// `lessons_attended` at all. +#[tokio::test] +async fn the_first_roll_call_credits_the_lesson_once_and_only_students_attend() { + let (app, db) = app_and_db().await; + let boss = login_as(&app, &db, "mudur", "manager").await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + let course = create_course(&app, &teacher, "Algebra").await; + + let mut students = Vec::new(); + for name in ["ali", "veli", "ayse"] { + let cookie = login(&app, name).await; + let id = me_id(&app, &cookie).await; + enroll(&app, &teacher, &course, &id).await; + students.push((cookie, id)); + } + let session = create_session(&app, &teacher, &course, soon()).await; + + roll_call(&app, &teacher, &session, &students[0].1, "present").await; + let held = my_profile(&app, &teacher).await; + assert_eq!( + stat(&held, "lessons_held_total"), + 1, + "taking the roll call is what holds a lesson: {held}" + ); + + roll_call(&app, &teacher, &session, &students[1].1, "present").await; + roll_call(&app, &teacher, &session, &students[2].1, "late").await; + let after = my_profile(&app, &teacher).await; + assert_eq!( + stat(&after, "lessons_held_total"), + 1, + "the third student marked held the same lesson again: {after}" + ); + + for (cookie, _) in &students { + let theirs = my_profile(&app, cookie).await; + // `late` is attendance too — the same rule `GET /attendance/me` uses. + assert_eq!(stat(&theirs, "lessons_attended_total"), 1, "{theirs}"); + } + + // Management records the teacher's own presence: a roll-call row like any + // other, and no `lessons_attended` for a person who is not a student. + roll_call(&app, &boss, &session, &teacher_id, "present").await; + let staff = my_profile(&app, &teacher).await; + assert_eq!( + stat(&staff, "lessons_attended_total"), + 0, + "the teacher attended their own lesson: {staff}" + ); + assert_eq!(stat(&staff, "lessons_held_total"), 1, "{staff}"); +} + +/// **The permanence rule.** A correction takes the counter back down — that is +/// what a roll call being editable means — and the badge it already earned +/// stays on the shelf with the stamp it was first given. Badges are auto-earned +/// and never revoked; nothing in the system removes an award row, and this is +/// the test that would notice if something started to. +/// +/// The tenth lesson is what earns `lessons_attended_10`, and it is that very +/// tenth mark the correction withdraws — so the counter ends *below* the +/// threshold the badge was earned at, which is the only state that tells a +/// permanent award apart from one recomputed on every read. +#[tokio::test] +async fn a_correction_lowers_the_counter_but_never_takes_the_badge_back() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let student = login(&app, "stu").await; + let student_id = me_id(&app, &student).await; + let course = create_course(&app, &teacher, "Algebra").await; + enroll(&app, &teacher, &course, &student_id).await; + + let mut sessions = Vec::new(); + for lesson in 0..10 { + let starts_at = soon() + lesson * 3_600_000; + let session = create_session(&app, &teacher, &course, starts_at).await; + roll_call(&app, &teacher, &session, &student_id, "present").await; + sessions.push(session); + } + + let earned_it = my_profile(&app, &student).await; + assert_eq!( + stat(&earned_it, "lessons_attended_total"), + 10, + "{earned_it}" + ); + let earned = stamp_of(&earned_it, "lessons_attended_10").expect("the tenth lesson earns it"); + + // The teacher corrects the last roll call: the student was not there. + roll_call( + &app, + &teacher, + sessions.last().unwrap(), + &student_id, + "absent", + ) + .await; + + let after = my_profile(&app, &student).await; + assert_eq!( + stat(&after, "lessons_attended_total"), + 9, + "a correction must give the count back: {after}" + ); + assert_eq!( + stamp_of(&after, "lessons_attended_10"), + Some(earned), + "a badge was taken back when its counter fell: {after}" + ); + // Correcting one student's row does not un-hold the lesson either. + assert_eq!( + stat(&my_profile(&app, &teacher).await, "lessons_held_total"), + 10 + ); +} + +// --- the study streak ------------------------------------------------------ + +/// Start and finish one focus stint as `cookie` (asserts both statuses). +async fn stint(app: &Router, cookie: &str) { + let started = send(app, "POST", "/pomodoro/start", Some(cookie), None).await; + assert_eq!(started.status, StatusCode::CREATED, "{}", started.body); + let finished = send(app, "POST", "/pomodoro/finish", Some(cookie), None).await; + assert_eq!(finished.status, StatusCode::OK, "{}", finished.body); +} + +/// Wind `user`'s streak bookkeeping back one day, so the *next* finish lands on +/// the next calendar day. +/// +/// This manipulates **stored state, never the clock**: `Timestamp::now` stays +/// the one clock read in the process and nothing sleeps. It is the same trick +/// the domain tests use (`age_by_days` in `src/domain/pomodoro.rs`), reached +/// here through the harness's own database handle because no route can move a +/// day boundary — the streak's day arithmetic itself is the domain suite's to +/// pin, and what this buys is the *badge* arriving on a real profile. +async fn age_one_day(db: &Database, user: &str) { + db.query(format!( + "UPDATE type::record('user', $id) + SET {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - 1" + )) + .bind(("id", user.to_string())) + .await + .unwrap() + .check() + .unwrap(); +} + +/// The streak's whole path, in the one shape a client sees it: a student +/// finishes a stint and their profile says `study_streak_total: 1`. +/// +/// That single number is worth more than it looks — it is written by the +/// pomodoro transaction into `study_streak_longest`, projected by +/// `BadgeStats::load`, projected *again* by the parallel hand-kept reader in +/// `src/domain/profile.rs` (the two carry doc comments saying they move +/// together, and nothing but a test notices when they stop), and finally +/// served under a key deliberately spelled `study_streak_total` although the +/// counter is a longest and not a sum. Break any one of those and this reads +/// `0` or panics on a missing key. +/// +/// Three consecutive days then earn `study_streak_3` off a real profile read. +#[tokio::test] +async fn a_finished_stint_reaches_the_profile_and_three_days_earn_the_badge() { + let (app, db) = app_and_db().await; + let student = login(&app, "stu").await; + let student_id = me_id(&app, &student).await; + + stint(&app, &student).await; + + let first = profile_of(&app, &student, &student_id).await; + assert_eq!( + stat(&first, "study_streak_total"), + 1, + "one finished stint is a one-day run: {first}" + ); + // The stint landed at all — so a zero above would be the streak's own + // projection, not a pomodoro route that never ran. + assert_eq!(stat(&first, "pomodoro_finished_total"), 1, "{first}"); + assert_eq!(badge_ids(&first), Vec::<&str>::new(), "three days away"); + + for _ in 0..2 { + age_one_day(&db, &student_id).await; + stint(&app, &student).await; + } + + let after = profile_of(&app, &student, &student_id).await; + assert_eq!( + stat(&after, "study_streak_total"), + 3, + "three consecutive days are a run of three: {after}" + ); + // Ten finished stints earn the pomodoro badge, so three days earn exactly + // one thing. + assert_eq!(badge_ids(&after), ["study_streak_3"], "{after}"); +} + +// --- the read side --------------------------------------------------------- + +/// A profile is a read endpoint. The write site behind a badge already ran +/// `badge::sync`, so by the time anyone reads the profile there is nothing +/// owed — and the read must therefore touch the award table exactly zero +/// times, however many badges the shelf carries. +/// +/// The probe is a `DEFINE EVENT` on the award table itself: it fires inside any +/// write to it — creates and updates alike, checked with a hand-run `UPDATE` +/// while this was written — so a write this read should not make cannot hide +/// behind an unchanged-looking response. +/// +/// What this bites on, precisely: a read path that writes an award row at all. +/// Two things stop it today and either one alone is enough — `badges_of` skips +/// the sync while the shelf is complete, and `sync`'s own +/// `WHERE earned_at = NONE` makes a re-write a no-op — so dropping *only* the +/// second leaves this green. The frozen stamp is pinned by +/// `a_regrade_moves_neither_the_counter_nor_the_stamp` instead. +#[tokio::test] +async fn a_profile_read_owes_nothing_the_write_site_already_paid() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teach", "teacher").await; + let asker = login(&app, "stu").await; + let asker_id = me_id(&app, &asker).await; + let bystander = login(&app, "nobody").await; + + // The counter row is seeded so the probe reads a real zero: selecting from + // a table nothing has written yet is an error, not an empty answer. + db.query( + "UPSERT type::record('award_write_probe', 'n') SET n = 0; + DEFINE EVENT award_write ON badge_award WHEN true THEN { + UPSERT type::record('award_write_probe', 'n') SET n = (n ?? 0) + 1; + };", + ) + .await + .unwrap() + .check() + .unwrap(); + let writes = || async { + db.query("SELECT VALUE n FROM award_write_probe:n") + .await + .unwrap() + .take::>(0) + .unwrap() + .first() + .copied() + .unwrap_or(0) + }; + assert_eq!(writes().await, 0, "nothing has been awarded yet"); + + // One approval, and `pool_published_1` is earned — by the route, not by + // any later read. + let question = ask(&app, &asker, "Integral").await; + approve(&app, &teacher, &question).await; + let written = writes().await; + assert!(written > 0, "the approval never wrote the asker's award"); + + let mine = my_profile(&app, &asker).await; + assert_eq!(badge_ids(&mine), ["pool_published_1"], "{mine}"); + assert_eq!( + writes().await, + written, + "a profile read wrote to the award table" + ); + + // Same again from another reader, and from an account that has earned + // nothing at all — the shelf is empty, so there is not even a statement to + // send. + profile_of(&app, &bystander, &asker_id).await; + let empty = my_profile(&app, &bystander).await; + assert_eq!(badge_ids(&empty), Vec::<&str>::new(), "{empty}"); + assert_eq!( + writes().await, + written, + "reading a profile that owes nothing still wrote" + ); +} + +/// The catalog `GET /limits` publishes is the whole of `BADGES` — a family +/// added to the constant and forgotten at the wire is a badge no client can +/// ever render — and it carries the high-mark cut, which no id spells out. +#[tokio::test] +async fn the_limits_badge_block_serves_the_whole_catalog_and_the_high_mark_cut() { + let (app, _db) = app_and_db().await; + + let res = send(&app, "GET", "/limits", None, None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let served: Vec<&str> = res.body["badges"]["catalog"] + .as_array() + .unwrap_or_else(|| panic!("badges.catalog array: {}", res.body)) + .iter() + .map(|badge| badge["id"].as_str().expect("badge id")) + .collect(); + let known: Vec<&str> = BADGES.iter().map(|(id, _, _)| *id).collect(); + assert_eq!(served, known, "the catalog and the wire disagree"); + + assert_eq!( + res.body["badges"]["high_mark_min"], + Value::from(HIGH_MARK_MIN), + "the high-mark cut is not published: {}", + res.body + ); +} diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 5cdbfc1..ac59101 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -315,8 +315,9 @@ async fn a_profile_read_heals_a_missed_badge_then_writes_nothing() { assert_eq!(writes().await, after_heal, "a profile read wrote something"); } -/// The counters are derived, so a fresh account reads a true `0` on all four — -/// never `null`, never an absent key a client would have to guard. +/// A fresh account reads a true `0` on every counter — never `null`, never an +/// absent key a client would have to guard. Both kinds: the four derived ones +/// have no rows behind them, and the stored ones have no columns on the row. #[tokio::test] async fn fresh_stats_read_zero_on_every_field() { let (app, _db) = app_and_db().await; @@ -337,6 +338,15 @@ async fn fresh_stats_read_zero_on_every_field() { "exam_sat_total", "pomodoro_finished_total", "pomodoro_focus_ms_total", + "marks_given_total", + "lessons_held_total", + "pool_approved_total", + "pool_published_total", + "lessons_attended_total", + "high_mark_total", + // A longest, not a running total — the key still carries `_total` + // because that suffix is how a client joins a badge `stat` to a stat. + "study_streak_total", ] { assert_eq!( stats.get(field).and_then(Value::as_i64), @@ -345,7 +355,7 @@ async fn fresh_stats_read_zero_on_every_field() { stats.get(field) ); } - assert_eq!(stats.len(), 9, "no tenth counter shipped: {stats:?}"); + assert_eq!(stats.len(), 16, "an unlisted counter shipped: {stats:?}"); assert!(mine.body["avatar"].is_null()); assert_eq!(mine.body["classes"], json!([])); assert_eq!(mine.body["courses"], json!([]));