From c62e54a0a42e6cae0af902bc33c355895a62e2a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 5 Aug 2026 21:06:24 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9A=20docs:=20move=20the=20doc=20surfa?= =?UTF-8?q?ces=20these=20fixes=20changed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit utoipa annotations, lib.rs tag descriptions and README (intro, route table and the relevant sections) for everything this sweep changed: the review gate's new 409, the narrowed homework roster, the canteen's authorise-before-lookup and cutoff rules, the payments ceilings, the last-admin floor and the live-role filter on the student lists. /limits gains payment.max_assign_writes, payment.max_applied_lines and meal.max_booking_attempts. --- README.md | 160 ++++++++++++++++++++++++++++++++++------------ src/lib.rs | 14 ++-- src/web/limits.rs | 17 +++++ 3 files changed, 144 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index 38626d7..44b37bd 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,8 @@ watch attendance, per-student remaining time, sittings, walk-outs, no-shows (`absent` once the window closes), submissions, and marks land live on a monitor endpoint (snapshot or SSE stream). Courses also hand out **homework**: assigned to the whole course or a named subset (the unnamed never -even see it), tagged with a course subject, due by a required future `due_at` +even see it, and the named see only themselves in it), tagged with a course +subject, due by a required future `due_at` — students hand in text and/or **files of any type** (same size cap, 10 per submission, served back only as forced downloads), editable until the teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark @@ -175,7 +176,10 @@ units and a due date that may sit in the past) and **assigns** it to students, which appends every installment as a `charge` at once — there is no scheduler, and "overdue" is derived at read time. Payments are recorded against one named charge, refunds against one named payment, and nothing is ever edited or -deleted: a mistake is corrected by appending the opposing line. **There is no +deleted: a mistake is corrected by appending the opposing line. Both bulk +operations are bounded: one assignment request may raise at most 3 000 charges +(`400` past that, nothing written), and one ledger line may carry at most 20 +lines applied to it (`409` past that). **There is no online payment integration and none is planned** — no gateway, no card data, `method` is free text. Teachers see no money at all (see "Payments"). @@ -572,11 +576,17 @@ messages, which any role sends and receives (that's how a parent reaches a teacher). A role change off either end of a tie (the parent stops being a `parent`, the student stops being a `student`) drops the tie, exactly like promotion drops -course enrollments. A demotion to `parent` also gives back the seats that +course enrollments. That sweep runs once, so a tie written in the same instant +as the role change can outlive it; a surviving row grants nothing regardless — +every gate re-reads the student's **live** role, and the student list itself +skips anyone who no longer holds the `student` role. A demotion to `parent` also gives back the seats that account holds on still-open **event signup lists** — a parent cannot reach -`DELETE /events/{id}/register/{user}` and no one else may free a non-student's -seat, so those seats would stay claimed forever and a capped event would answer -"full" for good. Every other role change leaves signups alone: staff free their +`DELETE /events/{id}/register/{user}` itself, so an unswept seat would stay +claimed and a capped event would answer "full" for good. Two things keep that +from happening: a registration written while the demotion runs claims the +holder's own row, so either the sweep sees the seat or the seat sees the +`parent` (a `403`); and a teacher+ may free a seat a `parent` holds, which is +the way back for any seat an older build stranded. Every other role change leaves signups alone: staff free their own seats by hand. Seats on lists that have already closed (the event started, or its `ends_at`-only deadline passed) are never touched — that roster is history, and re-registering is refused. @@ -597,7 +607,7 @@ still left exactly as they stand. | Send / read / file / delete messages | (any) | One-to-one, any user to any user (`parent` included — the role's one write); each party only ever touches their own copy | | Mark event attendance; remove attendance rows | teacher | Only users in the event's **audience** can be marked; students never mark — a teacher+ may mark anyone expected, themselves included | | Create events | teacher | The audience (school / role / course / class / registration) is set at creation and editable later | -| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** — never for another staff member. Unregistering mirrors the same rule | +| Register users onto a registration event | teacher | Teachers place **students** (students never register themselves) and take a seat for **themselves** — never for another staff member. Unregistering mirrors the same rule, plus any seat a `parent` was left holding — that account can reach no route to free it itself | | List an event's attendance or its roster report | teacher | Students read their own tallies via the attendance report | | Edit / delete an event | teacher | Only the **creator**, or a `manager`+ for any event — in both cases only while still `teacher`+ | | View a course's sessions | student | Only inside **visible** courses: enrolled, creator, assigned teacher, or `manager`+ | @@ -640,7 +650,7 @@ still left exactly as they stand. | List **own** linked students | parent | Read-only: the list plus each student's mark/attendance/pomodoro/homework reports — a parent changes nothing, anywhere | | Read the school settings and the term list | student | Clients need them to render kind/status pickers, grades, and the calendar | | Edit school settings; create / edit / delete terms | manager | School policy (exam kinds, attendance statuses, grade bands, the note-file size limit) and the academic calendar are management's call | -| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role | +| List users; look up one user; change a user's role; edit **any** user's personal info or UI preferences; tie/untie students to a `parent` account | admin | An admin cannot change **their own** role, and nobody can demote the school's **last** admin (`409`) | ### Bootstrapping the first admin @@ -661,8 +671,14 @@ startup. `compose.yaml` ships with the credentials above for local dev. That admin can then promote everyone else through `PATCH /users/{id}/role`. -Manual fallback (also the recovery path if the seeded name was squatted or the -sole admin locked themselves out): run +The admin set cannot be emptied through the API: an admin never changes their +own role, and a `PATCH /users/{id}/role` that would demote the last admin +answers `409` — including when two admins demote each other at the same +instant, since that guard is serialized school-wide rather than left to the +database (which conflict-checks neither a cross-record count nor a read). + +Manual fallback (the recovery path if the seeded name was squatted, or if an +older build already emptied the admin set): run ```surql UPDATE user SET role = 'admin' WHERE username = 'ada'; @@ -776,18 +792,18 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/users/me/avatar` | student | Upload/replace own avatar: `multipart/form-data`, one `file` part, raster images only, ≤ the school's `max_file_bytes` -> `{content_type, size}` | | GET | `/users/me/avatar` | student | Own avatar bytes (`404` if there is none) — the self alias of `/users/{id}/avatar` | | DELETE | `/users/me/avatar` | student | Remove own avatar (`404` if there is none) | -| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username) · paged | +| GET | `/users/me/students` | parent | The caller's linked students (refs, sorted by username; ties whose student was promoted out are left out) · paged | | GET | `/users/search` | teacher | `?q=&role=` — find users by username/name fragment (pickers); refs only, no contact info · paged | | GET | `/users` | admin | List all users · paged | | GET | `/users/{id}/profile` | student | Any user's public profile — a `parent` reads only their own and their linked students' (`403`) | | GET | `/users/{id}/avatar` | student | The avatar bytes (`nosniff`, `private, no-store`); same reach as the profile | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar — the moderation path | | GET | `/users/{id}` | admin | Get one user | -| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists | +| PATCH | `/users/{id}/role` | admin | `{role}` — set a user's role; promotion out of `student` drops the user's course enrollments (only students enroll), and a demotion to `parent` also frees their seats on still-open event signup lists; demoting the school's **last** admin is refused (`409`) | | PATCH | `/users/{id}/profile` | admin | Update any user's personal info, `display_name` and `bio` included | | PATCH | `/users/{id}/preferences` | admin | Update any user's UI preferences | | POST | `/users/{id}/students` | admin | `{user_id}` — tie a **student** to a **parent** account `{id}` (idempotent); the tie is the parent's read grant | -| GET | `/users/{id}/students` | admin | List a parent's linked students · paged | +| GET | `/users/{id}/students` | admin | List a parent's linked students (same live-role filter as `/users/me/students`) · paged | | DELETE | `/users/{id}/students/{student}` | admin | Untie a student from a parent (student data untouched) | | POST | `/notes` | student | `{title, content?}` | | GET | `/notes` | student | List own notes · paged | @@ -812,7 +828,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/events/{id}/roster` | teacher | Who-missed report: every expected attendee with their status (`null` = never marked) + `marked_by` · paged | | DELETE | `/events/{id}/attendance/{user}` | teacher | Remove a user's attendance | | POST | `/events/{id}/register` | teacher | `{user_id?}` — seat a **student** (or yourself when omitted) on a registration event's signup list; idempotent, `409` once full or started | -| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (same self-or-student rule); `409` once the event started | +| DELETE | `/events/{id}/register/{user}` | teacher | Free a seat (self, a student, or a seat a `parent` was left holding); `409` once the event started | | POST | `/appointments/slots` | teacher | `{starts_at, ends_at, note?, repeat_weekly?, until?}` — publish availability on **own** calendar; always answers an **array** (one element for a one-off, one per weekly occurrence, ≤ 52, sharing a `series`); `400` if a weekly shift would run off the end of time; `409` if the window overlaps one the caller already published (half-open, so back-to-back is fine) — a weekly publish is all-or-nothing | | GET | `/appointments/slots` | student | Teacher+: own calendar (past included). Everyone else: the bookable calendar — slots not yet started (the same bound booking enforces), demoted teachers' slots left out · paged | | DELETE | `/appointments/slots/{id}` | teacher | Withdraw one slot (its teacher, or manager+); `409` while a pending/approved booking sits on it | @@ -908,7 +924,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | One prior sitting's drawn-answer bytes, inline (course manager) | | GET | `/exams/{id}/students/{user}/marks` | teacher | A student's full per-sitting mark history, oldest first — the latest seq is the grade-of-record (course manager) | | GET | `/exams/{id}/review/questions` | student | The exam's question list **with `correct`** — the answer key the caller checks their own sheet against (same review gate) · paged | -| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending — only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise), and `409` while the caller's latest sitting is still in progress (all four review reads share that gate) | +| GET | `/exams/{id}/review/attempts` | student | The caller's **own** sitting numbers (answers ⋃ marks), ascending — only when `allow_review` is on and the caller has been marked (`403`/`404` otherwise), and `409` while the caller can still sit the exam — a sitting in progress, or one still startable under `max_attempts` (all four review reads share that gate) | | GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's **own** sittings, judged: `is_correct` flags + suggested `auto_score` (same review gate) | | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's **own** drawn-answer bytes for a sitting, inline (same review gate) | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | @@ -925,9 +941,9 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | The option picture's bytes (any teacher+) | | DELETE | `/bank-questions/{bid}/choices/{choice_id}/image` | teacher | Remove one option picture (**owner only**, admin bypass) | | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) | -| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) · paged | -| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) · paged | -| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name) | +| GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned, with `assigned` narrowed to themselves) · paged | +| GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned, with `assigned` narrowed to themselves) · paged | +| GET | `/homework/{id}` | student | Get homework (course viewers; a subset homework is a `404` to students it doesn't name, and its `assigned` list comes back narrowed to the caller for anyone without course-management rights) | | PATCH | `/homework/{id}` | teacher | Edit title/description/`due_at`/`subject_id`/`assigned` (course manager; a newly set due date is re-checked; `409` if narrowing `assigned` would strand an existing submission or grade — the blockers are named — or if the `subject_id` it re-tags from changed since the read: nothing written, re-read and retry) | | DELETE | `/homework/{id}` | teacher | Delete homework + its submissions, files, and grades — file blobs included (course manager) | | POST | `/homework/{id}/submission` | student | `{text?}` — hand in / re-edit own work (**students only**, enrolled, assigned): text replaces whole (omit clears), `submitted_at` pins the first hand-in, `updated_at` moves; `409` once graded | @@ -1004,10 +1020,10 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/payments/plans/{id}` | manager | One fee plan with its schedule | | PATCH | `/payments/plans/{id}` | manager | Edit a plan's `name` and/or `installments` (the schedule replaces wholesale); `409` once anyone is on the plan | | DELETE | `/payments/plans/{id}` | manager | Delete a plan; `409` once anyone is on it — its charges name it | -| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≤ 200) — place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` | +| POST | `/payments/plans/{id}/assignments` | manager | `{student_ids}` (≤ 200, and `students × installments` ≤ 3 000 — a bigger batch is a `400` telling you to split it, with nothing written) — place the plan on students, appending **every** installment as a `charge` at once; replay-safe, reported per student as `assigned` / `already_assigned` / `rejected` | | GET | `/payments/plans/{id}/assignments` | manager | Who is on this plan, newest first · paged | -| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` — record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory) and `409` naming the reversal when the charge was reversed. A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` | -| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` — hand money back against one named payment; partials allowed, capped by that credit; same `request_key` retry-safety | +| POST | `/payments/credits` | manager | `{charge_id, amount_minor, method?, note?, request_key?}` — record money received against one named charge; partials are the norm, `409` past what the charge is worth (advisory), `409` naming the reversal when the charge was reversed, and `409` once the charge carries 20 applied lines. A `request_key` makes the call retry-safe: a replay returns the same line, the same key for different money is a `409` | +| POST | `/payments/refunds` | manager | `{credit_id, amount_minor, method?, note?, request_key?}` — hand money back against one named payment; partials allowed, capped by that credit and by the same 20-applied-lines ceiling (`409`); same `request_key` retry-safety | | POST | `/payments/reversals` | manager | `{line_id, note?}` — undo a `charge` or a `refund` for its exact amount (`400` on any other kind); idempotent, at most one reversal per line | | GET | `/payments/ledger/{user}` | student | One student's raw lines — charges, payments, refunds, reversals — newest first · paged · own id always, otherwise manager+ or a parent link (**a teacher gets a `403`**) | | GET | `/payments/statement/me` | student | The caller's own statement: a row per charge with what it collected, what went back out, what is still owed, and whether it is `overdue`. `?limit=&offset=` pages the rows (`entries` is the envelope); `balance_minor` is the same on every page | @@ -1103,9 +1119,11 @@ the moment it passes (register and unregister both). Signup rows survive an audience switch inertly and resurface if the event returns to the registration kind; deleting the event deletes them, in one transaction with the attendance rows. A demotion to `parent` sweeps that user's signups off **still-open** -lists and hands each seat back (`PATCH /users/{id}/role`): unregistering is -student-or-self only, so a parent's seat had no other way out. Staff free their -own, and a closed list is never rewritten. Pre-existing hand-picked (`users`) +lists and hands each seat back (`PATCH /users/{id}/role`), and a registration +racing that demotion is refused rather than left behind. Unregistering is +student-or-self, plus any seat a `parent` holds — that account can free +nothing itself, so a seat stranded before this rule still has a door. Staff +free their own, and a closed list is never rewritten. Pre-existing hand-picked (`users`) audiences convert on boot: each listed user becomes a signup row credited to the event's creator, and the audience becomes an uncapped registration list. Reading a child collection of a missing parent (`/events/{id}/attendance`, @@ -1294,9 +1312,12 @@ catalog — awards carrying it stop being served, no migration. shape in which a counter ever decreases here. Editing an existing submission moves nothing, so the on-time verdict is fixed at the first hand-in and attaching a file after the deadline cannot turn an on-time submission late. -- **Exams.** `+1 exam_sat_total` per attempt created, retakes included — - sitting an exam twice is two sittings. Resuming an attempt already running is - not a new one. Deleting an exam removes the attempt rows but does **not** +- **Exams.** `+1 exam_sat_total` the **first** time a student sits an exam — + the counter is exams sat, not sittings. A **retake moves nothing**: it is the + same exam again, and counting it would make the whole ladder self-serve, since + an `open` exam with `max_attempts: 0` is a start/finish loop a student runs + alone with no teacher in it. Resuming an attempt already running is not a new + sitting either. Deleting an exam removes the attempt rows but does **not** decrement anyone: a teacher tidying up does not un-sit the exam. - **Pomodoro.** Finishing a stint is `+1 pomodoro_finished_total` and its duration into `pomodoro_focus_ms_total`. An open stint counts for neither — @@ -1821,6 +1842,14 @@ teacher or manager ordering a child's lunch is a `403`. cancellation of somebody else's brand-new seat. Unfenced it freed that seat, refunded nothing (the money is keyed to the *older* attempt, already reversed) and burnt the new attempt's reversal id for good. +- **A cancel decides who is asking before it looks the seat up.** An + unauthorised caller gets the same `403` for a booking that exists and one that + never did; only a caller who may cancel it ever sees a `404`. Booking ids are + fully derivable (`{date}_{slot}_{student}`, and both halves are readable), so + reading the row first made the status code answer "did this student book this + meal?" — the whole-school list at `GET /meals/menus/{id}/bookings`, which is + manager+ on purpose, handed out one student at a time to any teacher, and to + any peer who knew a user id. - **A manager+ may cancel anybody's seat.** Booking is student-and-parent only, and cancelling used to be the same door — which left a seat nobody on the API could give back the moment its student was promoted to staff or its @@ -1853,17 +1882,33 @@ teacher or manager ordering a child's lunch is a `403`. at `720` closes at 10:00 UTC that morning, not at 22:00 the night before. **That minute is UTC**: `date` carries no timezone and the backend stores no school timezone — deliberately, it is a rejected feature — so a UTC+3 school - enters `540` (09:00 UTC) for a meal served at noon locally. A slot with no - `serving_minute` falls back to **midnight UTC starting the meal's day**, the - behaviour every booking had before the field existed; the booking is never - refused for want of a serving time. + enters `540` (09:00 UTC) for a meal served at noon locally. A slot with **no + `serving_minute` has no cutoff at all**: there is no instant to count a + deadline back from, so nothing on that slot ever closes until the school sets + the hour. It used to count from midnight UTC of the meal's day, and that took + the canteen offline the moment a school set the one cutoff knob — all three + shipped slots carry no serving hour, so every same-day menu was already past + its deadline: `POST /meals/menus/{today}/bookings` answered `409`, and the + seats already held could no longer be cancelled by the students and parents + holding them, only by a manager. The fallback was chosen to avoid exactly that + and caused it. - **The serving time is read live, not snapshotted onto the menu.** The cutoff minutes are already read live, so freezing the other half of the same deadline would make one policy edit apply and its twin not; a kitchen that moves lunch an hour later wants today's menus to move with it. The menu still snapshots the slot *name* (that is what keeps a retired slot's history - readable), so a menu whose slot has since left the list simply has no - serving time and falls back to midnight UTC. + readable), so a menu whose slot has since left the list simply has no serving + time, and therefore no cutoff. +- **One seat may be taken at most `meal.max_booking_attempts` times** (`GET + /limits`, currently 10) — the first booking plus the re-bookings after a + cancel — and past that `POST /meals/menus/{id}/bookings` is a `409` naming + what happened. This bounds *storage*, not indecision: every cycle appends two + permanent, undeletable ledger lines (the charge and its reversal, both keyed + to the attempt), nothing else bounded them, and every later balance read is + answered over whatever is there. A seat that really must move again is the + canteen's to cancel. Rows already past the ceiling — an upgrade's leftovers — + are untouched: cancelling consults no ceiling, so such a seat and its money + stay reachable, and only one more re-booking is refused. - A menu somebody still holds a seat on **cannot be unpublished** (`409`) — cancel the bookings first, so nothing is left pointing at a deleted meal. @@ -1938,6 +1983,15 @@ in **minor units** (kuruş) as an `i64` — no float, no decimal, at any layer. A *negative* balance means the student owes the school; a positive one is money on account. Amounts are stored positive; the sign lives in the `kind`. +Those three sums are taken **by the database, one per kind**, so a balance read +costs the same on a statement of four lines and one of forty thousand; it used +to decode and fold every line, which made a growing ledger a tax on every later +read. Only the grouping moved: the signs are still applied in Rust by the one +function the formula above is spelled in, because summing `IF kind = 'charge' +THEN -amount` in SQL would fork that rule into a second language where nothing +fails the day the two disagree. A stored running total was the other option and +is a counter that can drift. + - **Booking is what charges, at a price snapshot.** The menu's dishes are summed the moment the seat is taken and that number is frozen onto the charge. Editing a dish's price afterwards moves no existing charge — what a @@ -2043,12 +2097,18 @@ A **fee plan** (`POST /payments/plans`) is a name and 1 to 60 **installments**, each `{amount_minor, due_at}` — minor units (kuruş) as an integer, and unix milliseconds. `due_at` **may be in the past**: a school adopting the app mid-year assigns plans whose first installments were already due, so there is -no future-date rule here. +no future-date rule here. A *negative* `due_at` is a `400` — that is not an +instant, and the charge it billed would read as overdue for ever. Writing a plan bills nobody. **Assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call): that appends *every* installment as a `charge` line right away, each carrying -its own due date. There is no scheduler, no nightly sweep, and nothing that +its own due date. What really bounds one request is therefore the **charges it +would raise**, not the head count: `student_ids × installments` may not exceed +**3 000** (200 students up to a 15-installment plan; 50 at a time on a +60-installment one). A bigger batch is refused whole with a `400` naming the +split — nothing is written, because a money route that billed half a batch and +gave up would leave the office guessing which families were charged. There is no scheduler, no nightly sweep, and nothing that wakes up when a date passes — the whole schedule is written once, and lateness is read off it. @@ -2162,6 +2222,16 @@ account. desk, the outcome is an over-paid charge that is plainly visible in the statement, and it is undone by appending a refund. Both lines are true records of money that really arrived — refusing them would be the worse lie. +- **A line carries at most 20 applied lines.** The cap above is folded one + query per line of the target's subtree, all of them while that single lock is + held, so a charge settled in a thousand pieces would stall every other + payment in the school behind its own arithmetic. Past 20 (payments under a + charge, refunds under a payment, and the reversals among them) a further + payment or refund against that line is a `409` — an installment settled in + more than twenty pieces is pathological, and a plan can always raise a fresh + charge. The ceiling binds **new writes only**: a line that already carries + more (written before the rule) still reads, still refunds through its own + children, and is still reversible. - **There is no payment gateway and no card data, ever**, and none is planned: nothing here talks to a bank, a PSP, or a card network. `method` is free text ("cash", "havale", …) describing how money that already arrived was handed @@ -2232,10 +2302,16 @@ Two per-exam policy knobs ride along, both **live-editable** at any point: reads (`GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]`). A student may review only when this is on **and** the teacher has marked them (an `ExamResult` row exists); own-scoped, so no student reads another's sheet. - All four reads are refused (`409`) while the caller's latest sitting is still - in progress — a mark on sitting 1 must not open the answer key to someone - midway through sitting 2. Submit the sitting first; an expired one reviews - fine. + All four reads are refused (`409`) while the caller can still **write** a + sitting at that exam — one in progress, *or* one they may still start: a mark + on sitting 1 must not open the answer key to someone who can post sitting 2 + with it in hand. Review therefore opens once `max_attempts` is used up (for + the default `max_attempts: 1`, as soon as the single sitting is submitted or + expires), or the exam's `ends_at` has passed, or the exam has no `mode` at all + (offline-graded — nothing to sit, so the mark alone opens it). Consequence, + deliberate: an `open`-mode exam with `max_attempts: 0` (unlimited) never + closes to its students, so its review never opens — cap the attempts or give + the exam an end to hand the key back. That gate is *per exam*, and a second, narrower one covers what it cannot see. Instantiating one question bank template into two exams copies its `correct` @@ -2588,7 +2664,11 @@ grace as every schedule field; late *submissions* are fine — a late like everyone else. `assigned` (at create or PATCH) instead pins a named subset of currently enrolled students (at most 200). The unnamed must not even learn a subset exists: lists omit it, and direct reads and submits answer -`404` — the same no-leak a hidden exam draft gets. Narrowing the subset later +`404` — the same no-leak a hidden exam draft gets. The *named* learn no more +than that they are named: to anyone without course-management rights the +`assigned` field comes back holding their own id alone (`null` still meaning +the whole course), because who else was assigned is roster information and the +roster itself is teacher+-only. Narrowing the subset later is refused with a `409` that names the blockers while any submission or grade belongs to a student the new list would strand. diff --git a/src/lib.rs b/src/lib.rs index a3ed0d9..668be8c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -36,7 +36,7 @@ use crate::state::AppState; info( title = "Hezarfen Backend API", version = env!("CARGO_PKG_VERSION"), - description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak), subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", + description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak) and the named see only themselves in, subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.", ), modifiers(&SecurityAddon), tags( @@ -44,7 +44,7 @@ use crate::state::AppState; (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"), - (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). 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, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's; 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 = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's; 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 — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"), @@ -57,13 +57,13 @@ use crate::state::AppState; (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)"), (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"), (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller's own latest sitting on that exam is in progress, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), - (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with no `serving_minute` set falls back to midnight UTC of that date, the pre-serving-time behaviour. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `_k_`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), - (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), + (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first"), + (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`; the day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `_k_`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"), + (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. One request is bounded by the charges it would raise rather than by the head count alone — `student_ids × installments` may not exceed 3 000 (200 students up to a 15-installment plan, 50 at a time on a 60-installment one) — and a bigger batch is a `400` naming the split, refused whole before anything is written, since a batch billed in part would leave the office guessing which families were charged. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `_k_` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. That sum costs one query per line of the target's subtree, all of them under that lock, so a line carries **at most 20 applied lines** (the payments under a charge, the refunds under a payment, and the reversals among them): past that a further payment or refund against it is a `409`, an installment settled in more than twenty pieces being pathological. The ceiling binds new writes only — a line that already carries more still reads, still refunds through its own children, and is still reversible. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"), (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"), - (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and the cutoff then counts from midnight UTC) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), + (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"), (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"), - (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks); a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), + (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"), (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is left standing — barred to them, unchanged for everyone else. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"), (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. Read: any authenticated user; edit: manager+"), ), diff --git a/src/web/limits.rs b/src/web/limits.rs index 4015007..8db9d2c 100644 --- a/src/web/limits.rs +++ b/src/web/limits.rs @@ -252,6 +252,12 @@ struct MealLimits { max_dish_tags: usize, /// Upper bound for a menu's optional `capacity`; absent = uncapped. max_menu_capacity: i64, + /// How many times one student's seat on one menu may be taken — the first + /// booking plus the re-bookings after a cancel. Past it, `POST + /// /meals/menus/{id}/bookings` is a `409`: every cycle writes two + /// permanent ledger lines, so this bounds the statement, not the mind + /// changing. Only the canteen can free such a seat afterwards. + max_booking_attempts: i64, /// Dietary tags one student's profile may carry, and its kitchen note. max_dietary_tags: usize, max_dietary_note_len: usize, @@ -291,6 +297,14 @@ struct PaymentLimits { max_plan_installments: usize, /// How many students one bulk assignment may name. max_assign_students: usize, + /// How many charge lines one bulk assignment may append — the students it + /// names times the plan's installments. A request past this is a `400` + /// telling the caller to split the batch; nothing is written. + max_assign_writes: usize, + /// How many lines may be applied to one ledger line: the payments under a + /// charge, the refunds under a payment, and the reversals among them. Past + /// it, a further payment or refund against that line is a `409`. + max_applied_lines: usize, /// Ceiling on the optional `request_key` that makes a credit or a refund /// retry-safe; charset `[A-Za-z0-9-]` (no `_`), at least one character. max_request_key_len: usize, @@ -538,6 +552,7 @@ impl LimitsResponse { max_dishes_per_menu: MAX_DISHES_PER_MENU, max_dish_tags: MAX_DISH_TAGS, max_menu_capacity: MAX_MENU_CAPACITY, + max_booking_attempts: MAX_MEAL_BOOKING_ATTEMPTS, max_dietary_tags: MAX_DIETARY_TAGS, max_dietary_note_len: MAX_DIETARY_NOTE_LEN, max_dish_price_minor: MAX_DISH_PRICE_MINOR, @@ -554,6 +569,8 @@ impl LimitsResponse { max_plan_name_len: MAX_FEE_PLAN_NAME_LEN, max_plan_installments: MAX_FEE_PLAN_INSTALLMENTS, max_assign_students: MAX_FEE_PLAN_ASSIGN_STUDENTS, + max_assign_writes: MAX_FEE_PLAN_ASSIGN_WRITES, + max_applied_lines: MAX_LEDGER_APPLIED_LINES, max_request_key_len: MAX_PAYMENT_REQUEST_KEY_LEN, ledger_kinds: PAYMENT_LEDGER_KINDS.to_vec(), },