diff --git a/README.md b/README.md index df194a4..68bc308 100644 --- a/README.md +++ b/README.md @@ -590,8 +590,9 @@ the tie is the parent's whole power — they list their students and homework reports in full. Student-only checks are exact (`role == student`), so a parent can never enroll, sit an exam, be graded, or land on a roll call; and sitting below every staff bar, they can't touch anything else either — except -messages, which any role sends and receives (that's how a parent reaches a -teacher), and their own **notes**, which carry no role bar at all: a note is +messages, which they send *upward* only — to a teacher, manager or admin, +never to a student or another parent (the same bar a student holds, issue +#23) — and their own **notes**, which carry no role bar at all: a note is private to one person, so a role change must not confiscate it. It used to. While the note routes required `student`, a demotion locked the owner out of their own notes permanently — and since nothing else in the crate reads a note @@ -1023,7 +1024,7 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/meals/profiles/{user}` | teacher | One student's dietary profile. Requires teacher+, or a parent link to them — the caller's own id always passes. | | PATCH | `/meals/profiles/{user}` | manager | Record what a student may not eat. **Manager+**, deliberately: an allergen list is a safety record the school keeps on the student's behalf, not a self-service preference — a student editing their own would let a mistyped (or removed) allergy reach the kitchen with the school's authority behind it. Omitted fields keep their value; `tags` replaces the whole list, and `"note": null` clears the note. First write creates the row. | | GET | `/messages` | student | List one of the caller's folders, newest first: `inbox` (default), `sent`, `archive`, or `trash` (`?folder=`). `?read=` narrows by the read flag; `total` counts the filtered folder, so `?folder=inbox&read=false&limit=1` is a cheap unread badge. Paged via `?limit=&offset=`. | -| POST | `/messages` | student | Send a message to another user. Any authenticated user may write to any existing user (parents included — messaging is the one place a parent acts); only messaging yourself is refused. The send is server-stamped and lands in the recipient's inbox unread. | +| POST | `/messages` | student | Send a message to another user. Messaging is upward only below staff: a student or parent may write to a teacher, manager or admin (parents included — messaging is the one place a parent acts), never to another student or parent; staff write to anyone. Messaging yourself is refused. The send is server-stamped and lands in the recipient's inbox unread. | | PATCH | `/messages/{id}` | student | Update the caller's view of a message: flip the read flag (recipient only) and/or move the caller's copy between folders. Each side files independently — archiving or trashing never touches the other party's copy. Filing into `archive`/`trash` records the folder left behind as the copy's `previous_folder`, so restoring is a move back to that value (`inbox`, or `sent` for the sender's copy, when it is `null`). Omitted fields change nothing. | | DELETE | `/messages/{id}` | student | Permanently delete the caller's copy — allowed only from the trash (`PATCH` it to `folder: "trash"` first). The other party's copy lives on; the row disappears for good once both sides have deleted theirs. | | GET | `/notes` | student | List the notes owned by the current user, newest first. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope. | @@ -1086,6 +1087,8 @@ window filtering, before paging; negative values are a `400` naming the field. | GET | `/terms/{id}` | student | Fetch a single term by id. | | PATCH | `/terms/{id}` | manager | Update a term. Requires manager+. Omitted fields keep their value; the merged range must stay ordered. | | DELETE | `/terms/{id}` | manager | Delete a term. Requires manager+. Refused with a 409 while any course still links to it — unlink those courses (`PATCH /courses/{id}` with `"term_id": null`) or delete them first, so a term is never dropped out from under the calendar its courses hang on. | +| POST | `/terms/{id}/archive` | manager | Archive a term. Requires manager+. An archived term is frozen: it takes no edits, no delete, and no new course or class link. Idempotent — archiving an already-archived term answers `200` with the stamp it already had. | +| POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. | | GET | `/users` | admin | List every user with their role, newest first. Admin only. Paged: pass `?limit=&offset=` to take a window (omit `limit` for the whole list); the response is a `{items, total, limit, offset}` envelope where `total` counts every user. | | PATCH | `/users/me` | student | Update the caller's own personal info: name, surname, email, phone, birth date, plus the public-profile pair `display_name` and `bio` (both readable school-wide at `GET /users/{id}/profile`, unlike the contact fields). Any authenticated role. Omitted fields stay as they are; an empty string clears a field. | @@ -1095,7 +1098,7 @@ window filtering, before paging; negative values are a `400` naming the field. | PATCH | `/users/me/preferences` | student | Update the caller's own UI preferences: `theme` (`light`/`dark`), `language` (`tr`/`en`), and `palette_color` (accent color as `#rrggbb`). Any authenticated role. Omitted fields stay as they are; an empty string clears one back to "never chose" (the client then follows the device preference). Read them back on any user response, e.g. `GET /auth/me`. | | GET | `/users/me/profile` | student | The caller's own public profile — what everyone else sees of them. | | GET | `/users/me/students` | parent | The students the calling parent observes, sorted by username. Requires the `parent` role. Each entry's reports live at `GET /marks/{user}`, `GET /attendance/{user}`, and `GET /pomodoro/{user}`. Paged via `?limit=&offset=`. | -| GET | `/users/search` | teacher | Find users by username or name — backs the pickers (enroll, grade, mark attendance). Requires teacher+. `role` narrows to one role (e.g. `role=student` for an enroll picker); a blank `q` with a `role` lists everyone in that role. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | +| GET | `/users/search` | student | Find users by username or name — backs the pickers (enroll, grade, mark attendance) and, for a student or parent, the one way to find the staff member they are allowed to message. Any authenticated user may ask; a caller below teacher only ever sees the roles they may message (teacher, manager, admin), in the items *and* in `total`. `role` narrows to one role (e.g. `role=student` for an enroll picker) — a student or parent naming a role they may not message is refused; a blank `q` with a `role` lists everyone in that role. Paged via `?limit=&offset=` like the other lists (omit `limit` for every match); returns a `{items, total, limit, offset}` envelope carrying only id/username/display name — no contact details. | | GET | `/users/{id}` | admin | Fetch one user with their role and personal info. Admin only. | | GET | `/users/{id}/avatar` | student | The avatar bytes. Same reach as the profile itself: every authenticated account, except a parent, who is limited to their own and their linked students'. | | DELETE | `/users/{id}/avatar` | admin | Remove any user's avatar. Admin only — the moderation path: an offensive picture is a school problem, and no route deletes the account it hangs on. | @@ -1583,8 +1586,9 @@ answers `409`. Every slot carries its teacher's identity (id, username, display name), to a parent as much as to a student: **deliberate**, and not to be tightened. A parent's three direct routes to that identity are all shut (`GET -/users/{id}/profile` is a `403`, `/users/search` is teacher+, `/users` is -admin), but a conference cannot be booked off an anonymous calendar — this list +/users/{id}/profile` is a `403`, `/users` is admin, and `/users/search` names +staff but not *which* of them holds office hours), but a conference cannot be +booked off an anonymous calendar — this list *is* the staff directory for the booking flow, narrowed to whoever published bookable time. The same refs on a booking (`teacher`, `proposed_by`, `decided_by`) read the same way. @@ -1703,9 +1707,14 @@ too — they may still decide any booking by id. ## Messaging One-to-one, mail-style (subject + body + an optional free-text `label` the UI -renders as a badge — "Etüt", "Sınav"; no threads): any user writes to any -user — student to teacher, parent to teacher, teacher to student; only -messaging yourself is refused. A single stored message serves both parties, +renders as a badge — "Etüt", "Sınav"; no threads). Writing is **upward only +below staff**: a student or parent may write to a teacher, manager or admin +(student to teacher, parent to teacher), never to another student or parent — +that is a `403`. Staff write to anyone, in any direction (teacher to student). +Messaging yourself is refused, and only new sends are gated: student↔student +rows sent before the rule stay readable and filable. `GET /users/search` is +how a student or parent finds the staff member to write to — it shows them +staff and nobody else (issue #24). A single stored message serves both parties, but each **owns their copy independently**: the recipient's moves through `inbox` → `archive`/`trash` and carries the `read` flag (the sender sees it as a read receipt); the sender's moves through `sent` → `archive`/`trash`. Filing or @@ -1841,6 +1850,29 @@ under them. Term dates may lie in the past, deliberately: a school adopting the app mid-year backfills its calendar — unlike exam/lesson/event times, which reject backdating. +A finished year is closed with `POST /terms/{id}/archive` and reopened with +`POST /terms/{id}/unarchive` (manager+). Both are idempotent: archiving an +already-archived term answers `200` with the original `archived_at` stamp, and +unarchiving an open one answers `200` as well. While a term is archived it is +read-only — `PATCH`/`DELETE /terms/{id}` are refused, a new course or class may +not link to it, and every write to a course or class already on it, or to +anything hanging off them, is refused too: enrollment, teacher assignment, +class membership and homeroom, class↔course attach/detach and blueprint apply, +sessions and roll call, subjects, exams with their questions, images, attempts +and answers (the exam-room WebSocket door and its `finish` frame included), +marks and grading, homework and submissions, course notes and files. Each +refusal is a `409` with `code: "term_archived"` and the message "this term is +archived — past years are read-only". Reads stay open throughout, so a past +year is still browsable, and unarchiving restores writes. Deliberately outside +the freeze: personal notes, messages, pomodoro, meals, payments, boards, +appointments, the chatbot, the question pool/bank, events (an event only aims +an audience at a course), class blueprint templates, and the staff work log. +Also exempt are the system integrity sweeps — role demotion stripping homeroom +teachers and course teacher assignments, subject delete clearing bank-question +links — which keep the store consistent rather than edit a past year. The +guard is a pre-flight read of the term row, so an archive and a write landing +in the same instant is an accepted race; see `## Concurrency model`. + What stays fixed is deliberate too: the four roles, the `0`–`100` mark scale, validation bounds, and the UTC time policy are invariants, not preferences (rename role labels in the frontend if a school says "principal" instead of @@ -3127,7 +3159,8 @@ newest first, and `total` counts the memberships the window was cut from. Both of them hide one field: **`creator` is `null` below teacher+**. A class is created by manager+ only, so shipping the creator to a student (or to their linked parent) would hand out an office account's username and real name — an -identity `GET /users` (admin-only) and `/users/search` (teacher+) both withhold. +identity `GET /users` (admin-only) withholds outright, and one `/users/search` +hands a student only as the messaging directory — never as class metadata. The homeroom teacher is *not* hidden: naming them is the point of the read. On every staff-facing route (`GET /classes`, `/classes/{id}`, and the create/edit responses) `creator` is populated exactly as before. @@ -4288,7 +4321,7 @@ database itself decides the winner. Three tiers: per (plan, student) — the seat and the row are claimed in one transaction (`cap::claim_and_create`), so a duplicate `CREATE` rolls its own seat back instead of costing a stranger their place. -3. **Two accepted races**, reviewed and deliberately left open: +3. **Three accepted races**, reviewed and deliberately left open: - *Attempt-seq late save* — an exam-room socket writes into the sitting it joined with, a choice made before any lock is taken, so a save racing a retake can stamp an answer onto the just-terminal previous sitting. @@ -4297,6 +4330,10 @@ database itself decides the winner. Three tiers: - *Approved-overlap* — two approvals landing in the same instant can double-book a teacher. Damage: one overlapping half-hour, visible to both parties, fixable by cancelling either side. + - *Archive-vs-write* — the archived-term guard is a pre-flight read on the + term row, so an archive committing in the same instant as a write already + in flight lets that one write through. Damage: one write on a + just-archived term; nothing corrupts, and every later write is refused. In-process locks remain, and they are a *second* line, never the guarantee: `PRESENCE_LOCK` guards in-process socket state (there is no row to conditional diff --git a/src/domain/class_group.rs b/src/domain/class_group.rs index 942e871..d9e4fb2 100644 --- a/src/domain/class_group.rs +++ b/src/domain/class_group.rs @@ -125,6 +125,16 @@ impl ClassGroup { self.term.as_ref() } + /// Refuse the write when this class's term is archived — a pre-flight guard, + /// accepted race (see README concurrency model): a term archived after this + /// read still lets the write through. + pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { + match self.get_term() { + None => Ok(()), + Some(term) => term::Term::require_open(term, db).await, + } + } + /// The homeroom teacher (sınıf öğretmeni), if one is assigned. pub fn get_teacher(&self) -> Option<&UserId> { self.teacher.as_ref() diff --git a/src/domain/course.rs b/src/domain/course.rs index 5aebf4a..6e89298 100644 --- a/src/domain/course.rs +++ b/src/domain/course.rs @@ -144,6 +144,16 @@ impl Course { self.term.as_ref() } + /// Refuse the write when this course's term is archived — a pre-flight guard, + /// accepted race (see README concurrency model): a term archived after this + /// read still lets the write through. + pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { + match self.get_term() { + None => Ok(()), + Some(term) => term::Term::require_open(term, db).await, + } + } + /// The seat cap enforced at enroll time; `None` = unlimited. pub fn get_capacity(&self) -> Option { self.capacity diff --git a/src/domain/role.rs b/src/domain/role.rs index 9a6c612..0e7a512 100644 --- a/src/domain/role.rs +++ b/src/domain/role.rs @@ -65,6 +65,28 @@ impl Role { pub fn at_least(self, min: Role) -> bool { self >= min } + + /// May `self` open a message thread with `recipient`? Messaging is upward + /// only for the two roles below staff: a `Student` or `Parent` writes to + /// teachers and above, never sideways or down (issue #23). Staff + /// (`Teacher`+) write to anyone. [`Role::Ai`] is a service principal with + /// no mailbox, so it neither sends nor receives. + pub fn may_message(self, recipient: Role) -> bool { + if self == Role::Ai || recipient == Role::Ai { + return false; + } + self.at_least(Role::Teacher) || recipient.at_least(Role::Teacher) + } + + /// The roles `self` is allowed to write to, when that set is narrower than + /// "everyone" — `None` means unrestricted. Backs the `/users/search` + /// restriction, which must land in the query so `total` stays right. + pub fn messageable_roles(self) -> Option<&'static [Role]> { + match self.at_least(Role::Teacher) { + true => None, + false => Some(&[Role::Teacher, Role::Manager, Role::Admin]), + } + } } #[cfg(test)] @@ -111,6 +133,31 @@ mod tests { assert_eq!(Role::Ai.as_str(), "ai"); } + #[tokio::test] + async fn messaging_is_upward_only_below_staff() { + // Sideways and downward writes from the two non-staff roles: refused. + for sender in [Role::Student, Role::Parent] { + for recipient in [Role::Student, Role::Parent] { + assert!(!sender.may_message(recipient)); + } + for staff in [Role::Teacher, Role::Manager, Role::Admin] { + assert!(sender.may_message(staff)); + } + assert_eq!( + sender.messageable_roles(), + Some(&[Role::Teacher, Role::Manager, Role::Admin][..]) + ); + } + // Staff write to anyone, in any direction, and are unrestricted in search. + for sender in [Role::Teacher, Role::Manager, Role::Admin] { + assert!(ROLES.iter().all(|&r| sender.may_message(r))); + assert_eq!(sender.messageable_roles(), None); + } + // The service principal has no mailbox in either direction. + assert!(ROLES.iter().all(|&r| !Role::Ai.may_message(r))); + assert!(ROLES.iter().all(|&r| !r.may_message(Role::Ai))); + } + #[tokio::test] async fn str_round_trips() { for role in ROLES { diff --git a/src/domain/term.rs b/src/domain/term.rs index de527fd..d1c1599 100644 --- a/src/domain/term.rs +++ b/src/domain/term.rs @@ -56,6 +56,15 @@ pub fn gone_error() -> AppError { }) } +/// The refusal every write against archived structure gets, coded so a client +/// can tell it from the other 409s on the same route. +pub fn archived_error() -> AppError { + AppError::ConflictCoded { + code: "term_archived", + message: "this term is archived — past years are read-only".into(), + } +} + /// What a PATCH's `term` field owes the refcounts: the term to claim, and the /// one to give back. Covers all three moves — set (none→some), move /// (some→other) and clear (some→none) — and moves nothing for a PATCH that @@ -96,6 +105,11 @@ pub struct Term { name: TermName, starts_at: Timestamp, ends_at: Timestamp, + /// When a manager archived this term; `None` = open. `#[surreal(default)]` + /// for the same reason `BankQuestion::subject` has one: rows written before + /// the column existed still decode, as open terms. + #[surreal(default)] + archived_at: Option, } impl Term { @@ -115,6 +129,14 @@ impl Term { self.ends_at } + pub fn get_archived_at(&self) -> Option { + self.archived_at + } + + pub fn is_archived(&self) -> bool { + self.archived_at.is_some() + } + pub async fn create( name: TermName, starts_at: Timestamp, @@ -126,6 +148,7 @@ impl Term { name, starts_at, ends_at, + archived_at: None, }; let created: Option = db.create(term.id.record()).content(term).await?; created.ok_or_else(|| AppError::Internal("failed to create term".into())) @@ -200,6 +223,58 @@ impl Term { None => Err(AppError::NotFound), } } + + /// Freeze the term. Idempotent by construction: the `WHERE` only matches an + /// open row, so a repeat archive writes nothing and answers with the + /// *original* stamp — the year is not re-dated by a double click. + pub async fn archive(self, db: &Database) -> Result { + self.stamp( + "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", + Some(Timestamp::now()), + db, + ) + .await + } + + /// Re-open the term; idempotent the same way. + pub async fn unarchive(self, db: &Database) -> Result { + self.stamp( + "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", + None, + db, + ) + .await + } + + /// One conditional write, through [`write_with_retry`] like every other + /// guarded single statement here; an empty result is the no-op case, and + /// only that path pays for the read that reports the stored row. + async fn stamp( + self, + sql: &str, + now: Option, + db: &Database, + ) -> Result { + let mut bindings = vec![("term".into(), self.id.record().into_value())]; + if let Some(now) = now { + bindings.push(("now".into(), now.as_millis().into_value())); + } + let written: Vec = write_with_retry(db, sql, &bindings).await?; + if let Some(term) = written.into_iter().next() { + return Ok(term); + } + Self::read(&self.id, db).await?.ok_or(AppError::NotFound) + } + + /// Refuse when the named term is archived. A missing row is `Ok(())`: a + /// dangling link is not this guard's error, and the caller that cares + /// already answers it (see [`gone_error`]). + pub async fn require_open(id: &TermId, db: &Database) -> Result<(), AppError> { + match Self::read(id, db).await? { + Some(term) if term.is_archived() => Err(archived_error()), + _ => Ok(()), + } + } } #[cfg(test)] diff --git a/src/domain/user.rs b/src/domain/user.rs index 0e325d3..4dabec9 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -527,7 +527,11 @@ impl User { /// and surname. Needle and columns both go through /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — /// backs the user pickers. `role` narrows to one role (e.g. only students - /// for an enroll picker); `None` searches everyone. A blank `query` + /// for an enroll picker); `None` searches everyone. `allowed_roles` + /// narrows the *visible* set (the roles a non-staff caller may message — + /// see [`Role::messageable_roles`]); it is part of the query, not a + /// post-filter, so `total` counts only what the caller may see. A blank + /// `query` /// matches everyone, so blank + `role` is a role-scoped listing. Returns /// every match, ordered by username; the HTTP layer pages the result like /// any other list (no built-in cap — an over-broad fragment is windowed @@ -535,6 +539,7 @@ impl User { pub async fn search( query: &str, role: Option, + allowed_roles: Option<&[Role]>, limit: Option, offset: i64, db: &Database, @@ -553,6 +558,9 @@ impl User { if role.is_some() { clauses.push("role = $role"); } + if allowed_roles.is_some() { + clauses.push("role IN $allowed"); + } let where_clause = if clauses.is_empty() { "true".to_string() } else { @@ -563,6 +571,9 @@ impl User { if let Some(role) = role { list = list.bind("role", role); } + if let Some(allowed) = allowed_roles { + list = list.bind("allowed", allowed.to_vec()); + } list.run(limit, offset, db).await } diff --git a/src/lib.rs b/src/lib.rs index b38c381..f8ab659 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,9 +44,9 @@ 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. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `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). 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` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `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 (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), 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` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `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`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"), - (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 = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, 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 demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"), (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"), (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"), @@ -58,7 +58,7 @@ 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; a caller with no mark reads `404` whether review is on or off, so the status code never discloses `allow_review` to someone `GET /exams/{id}` would refuse outright). 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 = "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; a caller with no mark reads `404` whether review is on or off, so the status code never discloses `allow_review` to someone `GET /exams/{id}` would refuse outright). 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. An exam on an archived term is frozen with the rest of that year: the exam-room WebSocket upgrade at `GET /exams/{id}/attempt/ws` is refused with `409` and `code: \"term_archived\"`, and so is a `finish` frame on a socket already open"), (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`. The date is parsed by the same calendar library that computes the serving instant and compared back to the text it came from, so a signed component (`2026-+1-01`, which `\"+1\".parse()` once accepted) is a `400` rather than a **second** menu id for the 1st of January — one with its own capacity and seat counter, invisible to every `?from=&to=` read because `+` sorts below `0`. The day must also not already be over (`400`, measured against the end of the day, so today publishes all day long): a published menu is a bookable one and a booking is what charges, so a menu behind the calendar mints real debt for food nobody can be served. The day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a menu whose **day has already passed** takes no booking at all (`409`), whatever the cutoff is set to and with no role able to bypass it — the booking is the charge, so a seat taken on a day already served bills a meal that cannot be eaten; *cancelling* a seat on such a menu stays open, since money already taken has to stay reversible. A full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `_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"), @@ -66,7 +66,7 @@ use crate::state::AppState; (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), 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 **closed** by that same write: barred to them, still fully readable to everyone else, and refusing every write with the terminal `board_closed` — because clearing, locking, closing and deleting are the creator's alone and nothing lists a board the caller is not on, so a room whose creator was demoted could be ended by nobody at all while its participants kept drawing on it. Nothing is deleted (the marks are the participants' work too) and the seat it holds on `max_boards_per_creator` stays taken, exactly as a manually closed board's does. 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. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `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+"), + (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. A finished year is closed with `POST /terms/{id}/archive` (manager+), reopened with `POST /terms/{id}/unarchive`; both are idempotent — archiving an already-archived term answers 200 with the original `archived_at` stamp, and unarchiving an open one answers 200 too. An archived term is read-only: `PATCH`/`DELETE /terms/{id}` and linking a new course or class to it are refused, as is every write to a course or class already on it and to everything hanging off them — enrollment, teacher assignment, class membership and homeroom, class↔course attach/detach and blueprint apply, sessions and roll call, subjects, exams with their questions, images, attempts and answers, marks and grading, homework and submissions, course notes and files — each with `409` and `code: \"term_archived\"` (\"this term is archived — past years are read-only\"). Reads stay open throughout, and unarchiving restores writes. Read: any authenticated user; edit: manager+"), ), )] struct ApiDoc; diff --git a/src/migration_sql.rs b/src/migration_sql.rs index 4a35470..7b3abf4 100644 --- a/src/migration_sql.rs +++ b/src/migration_sql.rs @@ -306,6 +306,10 @@ pub const MIGRATION: &str = " DEFINE FIELD IF NOT EXISTS name ON term TYPE string; DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; + -- When the term was archived; absent = open. `option` and no + -- BACKFILL: every term that exists predates archiving and is open, which + -- is exactly what an absent stamp already means. + DEFINE FIELD IF NOT EXISTS archived_at ON term TYPE option; -- Courses still linking this term, the stored delete guard that closes -- write-skew between concurrent request tasks (see `crate::domain::cap`). -- Absent reads as zero, so no Rust struct needs it. diff --git a/src/web/classes.rs b/src/web/classes.rs index d88dad2..834598a 100644 --- a/src/web/classes.rs +++ b/src/web/classes.rs @@ -338,7 +338,7 @@ async fn classes_page( (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), - (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran — the class was rolled back, nothing was created", body = ErrorResponse), + (status = 409, description = "The named homeroom teacher was demoted below teacher while the request ran (the class was rolled back, nothing was created), or the named term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -537,7 +537,7 @@ async fn get_class( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), or the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone)", body = ErrorResponse), + (status = 409, description = "The term this update moves the class off changed since the caller read it (nothing was written, re-read and retry), the named homeroom teacher was demoted below teacher while the request ran (the assignment was undone), or the class's own term — or the named one — is archived: past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -548,6 +548,9 @@ async fn update_class( Json(req): Json, ) -> Result, AppError> { let class = class_or_404(&id, &st.db).await?; + // The class's *current* term, so a move off an archived year is refused + // too; `resolve_term` below holds the other end (the term moved onto). + class.require_open(&st.db).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -689,7 +692,7 @@ async fn classes_of( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Students or courses are still on this class", body = ErrorResponse), + (status = 409, description = "Students or courses are still on this class, or its term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_class( @@ -698,6 +701,7 @@ async fn delete_class( Path(id): Path, ) -> Result { let class = class_or_404(&id, &st.db).await?; + class.require_open(&st.db).await?; if !class.delete(&st.db).await? { return Err(AppError::Conflict( "this class still holds students or courses — remove its members and detach its courses first", @@ -726,7 +730,7 @@ async fn delete_class( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Class not found", body = ErrorResponse), - (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), it carries more courses than one add may enroll at once, one of its courses is full, or one of them no longer exists (a stale attachment — detach it). The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full`, `linked_course_missing`", body = ErrorResponse), + (status = 409, description = "Already in this class, the class is at its student ceiling (max_class_members), it carries more courses than one add may enroll at once, one of its courses is full, or one of them no longer exists (a stale attachment — detach it). The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full`, `linked_course_missing`, `term_archived` (the class sits on an archived term — past years are read-only)", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -737,6 +741,7 @@ async fn add_member( Json(req): Json, ) -> Result<(StatusCode, Json), AppError> { let class = class_or_404(&id, &st.db).await?; + class.require_open(&st.db).await?; let target = UserId::from_key(&req.user_id); let Some(target_user) = User::read(&target, &st.db).await? else { @@ -820,6 +825,7 @@ async fn list_members( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse), + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), ), )] async fn remove_member( @@ -828,6 +834,7 @@ async fn remove_member( Path((id, target)): Path<(String, String)>, ) -> Result { let class = class_or_404(&id, &st.db).await?; + class.require_open(&st.db).await?; ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?; Ok(StatusCode::NO_CONTENT) } @@ -853,7 +860,7 @@ async fn remove_member( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Class not found", body = ErrorResponse), - (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), it holds more students than one attach may enroll at once, or the course cannot hold the whole class. The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`", body = ErrorResponse), + (status = 409, description = "Already attached, the class is at its course ceiling (max_class_courses), it holds more students than one attach may enroll at once, or the course cannot hold the whole class. The body carries a machine `code` beside the prose, and this route answers exactly these: `duplicate`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `term_archived` (the class's or the course's term is archived — past years are read-only)", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -875,6 +882,9 @@ async fn attach_course( "only the course creator, an assigned teacher, or a manager/admin can attach this course to a class", )); } + // Both ends: neither a class nor a course on a past year takes a new link. + class.require_open(&st.db).await?; + course.require_open(&st.db).await?; let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; let people = PersonRef::map_of(&[&user]); @@ -939,6 +949,7 @@ async fn list_class_courses( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Class not found, or that course was not attached — a course row that is gone does not refuse the detach, it is the reason for it", body = ErrorResponse), + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), ), )] async fn detach_course( @@ -954,13 +965,20 @@ async fn detach_course( // route answered 404 forever — which also left the class undeletable, its // attachment counter counting a row nothing could sweep. There is no roster // left to protect, and the caller is already teacher+. - if let Some(course) = Course::read(&course, &st.db).await? - && !can_manage_course(&course, &user) + let row = Course::read(&course, &st.db).await?; + if let Some(row) = row.as_ref() + && !can_manage_course(row, &user) { return Err(AppError::Forbidden( "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class", )); } + // Both ends, and only what is still there: a link whose course row is gone + // has no term to read, and sweeping it is the whole point of the route. + class.require_open(&st.db).await?; + if let Some(row) = row.as_ref() { + row.require_open(&st.db).await?; + } ClassCourse::detach(class.get_id(), &course, &st.db).await?; Ok(StatusCode::NO_CONTENT) } @@ -1419,6 +1437,7 @@ async fn blueprint_status( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Class not found, or no blueprint covers its grade", body = ErrorResponse), + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), ), )] async fn apply_blueprint( @@ -1429,6 +1448,15 @@ async fn apply_blueprint( let class = class_or_404(&id, &st.db).await?; let grade = class.get_grade().ok_or(AppError::NotFound)?; let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; + // The pump writes both ends, so both are guarded — the class, and every + // course the template would attach. A course the template names that is + // already gone is the pump's own `skipped` business, not a term refusal. + class.require_open(&st.db).await?; + for id in blueprint.get_courses() { + if let Some(course) = Course::read(id, &st.db).await? { + course.require_open(&st.db).await?; + } + } let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; Ok(Json(ApplyResponse { skipped: skipped.iter().map(SkipResponse::new).collect(), diff --git a/src/web/course_notes.rs b/src/web/course_notes.rs index 8b2754f..c4f7761 100644 --- a/src/web/course_notes.rs +++ b/src/web/course_notes.rs @@ -119,6 +119,7 @@ impl CourseNoteResponse { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -135,6 +136,7 @@ async fn create( "only the course creator, an assigned teacher, or a manager/admin can add a course note", )); } + course.require_open(&st.db).await?; let title = CourseNoteTitle::try_new(&req.title)?; let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; @@ -233,6 +235,7 @@ async fn get_one( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -248,6 +251,7 @@ async fn update( "only the course creator, an assigned teacher, or a manager/admin can edit this course note", )); } + course.require_open(&st.db).await?; let title = req .title @@ -279,6 +283,7 @@ async fn update( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_one( @@ -292,6 +297,7 @@ async fn delete_one( "only the course creator, an assigned teacher, or a manager/admin can delete this course note", )); } + course.require_open(&st.db).await?; // Derived rows first, outside the note's own cascade transaction: they are // disposable, so failing here leaves the note intact and the 500 truthful, // whereas dropping them after the note would strand every blob on an error @@ -352,7 +358,7 @@ impl CourseNoteFileResponse { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Note not found", body = ErrorResponse), - (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), + (status = 409, description = "The note already holds the maximum number of files, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), ), )] @@ -368,6 +374,7 @@ async fn upload_file( "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", )); } + course.require_open(&st.db).await?; // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and // create under one lock) — checking it here too would just race. let limit = Settings::load(&st.db).await?.get_max_file_bytes(); @@ -506,6 +513,7 @@ async fn download_file( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Note or file not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_file( @@ -519,6 +527,7 @@ async fn delete_file( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", )); } + course.require_open(&st.db).await?; let file = CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) .await? @@ -618,6 +627,7 @@ async fn list_rag( (status = 204, description = "Deleted"), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 404, description = "Note or output not found", body = ErrorResponse), ), )] @@ -632,6 +642,7 @@ async fn delete_rag( "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs", )); } + course.require_open(&st.db).await?; // Scoped to the note in the path, like `CourseNoteFile::read_for`: an // output of another note is a 404 here, never a cross-note delete. let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) diff --git a/src/web/courses.rs b/src/web/courses.rs index 21012ff..cfe7e3b 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -293,6 +293,7 @@ fn check_capacity(capacity: Option) -> Result<(), AppError> { (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 409, description = "The named term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -445,7 +446,7 @@ async fn get_course( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "The term this update moves the course off changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse), + (status = 409, description = "The term this update moves the course off changed since the caller read it (nothing was written, re-read and retry), or this course's term (or the named one) is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -463,6 +464,7 @@ async fn update_course( "only the course creator, an assigned teacher, or a manager/admin can edit this course", )); } + course.require_open(&st.db).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -514,7 +516,7 @@ async fn update_course( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Students are still enrolled in this course", body = ErrorResponse), + (status = 409, description = "Students are still enrolled in this course, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_course( @@ -530,6 +532,7 @@ async fn delete_course( "only the course creator or a manager/admin can delete this course", )); } + course.require_open(&st.db).await?; // Writer lease of [`EXAM_LOCK`], for `delete_exam`'s reason: this cascade // sweeps the course's exams *and their attempts*, and an attempt is the one // exam child whose write cannot collide with the sweep (its claim lands on @@ -593,7 +596,7 @@ async fn delete_course( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), - (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone", body = ErrorResponse), + (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone; or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -606,6 +609,7 @@ async fn assign_teacher( let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + course.require_open(&st.db).await?; let target = UserId::from_key(&req.user_id); let Some(target_user) = User::read(&target, &st.db).await? else { @@ -650,6 +654,7 @@ async fn assign_teacher( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Course not found, or that user was not assigned to it", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn unassign_teacher( @@ -660,6 +665,7 @@ async fn unassign_teacher( let course = Course::read(&CourseId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + course.require_open(&st.db).await?; let removed = course .unassign_teacher(&UserId::from_key(&target), &st.db) .await?; @@ -692,7 +698,7 @@ async fn unassign_teacher( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), - (status = 409, description = "The course is full", body = ErrorResponse), + (status = 409, description = "The course is full, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -710,6 +716,7 @@ async fn enroll( "only the course creator, an assigned teacher, or a manager/admin can enroll users", )); } + course.require_open(&st.db).await?; let target = UserId::from_key(&req.user_id); let Some(target_user) = User::read(&target, &st.db).await? else { @@ -800,6 +807,7 @@ async fn list_roster( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn unenroll( @@ -815,6 +823,7 @@ async fn unenroll( "only the course creator, an assigned teacher, or a manager/admin can unenroll users", )); } + course.require_open(&st.db).await?; let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; if removed.is_none() { return Err(AppError::NotFound); @@ -847,6 +856,7 @@ async fn unenroll( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -864,6 +874,7 @@ async fn create_exam_in_course( "only the course creator, an assigned teacher, or a manager/admin can add exams to this course", )); } + course.require_open(&st.db).await?; let title = ExamTitle::try_new(&req.title)?; let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; @@ -976,6 +987,7 @@ struct CreateSubject { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -993,6 +1005,7 @@ async fn create_subject_in_course( "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course", )); } + course.require_open(&st.db).await?; let name = SubjectName::try_new(&req.name)?; let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; @@ -1084,6 +1097,7 @@ struct CreateHomework { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -1101,6 +1115,7 @@ async fn create_homework_in_course( "only the course creator, an assigned teacher, or a manager/admin can add homework to this course", )); } + course.require_open(&st.db).await?; let title = HomeworkTitle::try_new(&req.title)?; let description = match req.description.as_deref() { @@ -1220,6 +1235,7 @@ struct CreateSessionInCourse { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Course not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -1237,6 +1253,7 @@ async fn create_session_in_course( "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course", )); } + course.require_open(&st.db).await?; let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 91afd32..90cc1a5 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -75,8 +75,8 @@ use crate::state::AppState; use crate::validate::validate_required; use crate::web::CurrentUser; use crate::web::exams::{ - EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, - writable_attempt, + EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student, + save_answer_in, writable_attempt, }; use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; @@ -126,7 +126,8 @@ enum ClientMessage { /// unknown or draft exam (404), unscheduled with no mode (409), not a student /// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` /// first), submitted or expired (409), left the room while rejoin is closed -/// (409). +/// (409), the course's term archived (409 `term_archived` — a past year's room +/// is read-only, and the room's whole purpose is writing). /// /// The rejoin gate here is a read-only fast-fail for a proper 409; the /// authoritative clear of `left_at` happens inside the room task, under @@ -148,6 +149,7 @@ pub async fn attempt_ws( ensure_enrolled(&exam, user.get_id(), &st.db).await?; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; check_rejoin(&exam, &attempt)?; + course_of(&exam, &st.db).await?.require_open(&st.db).await?; let user_id = user.get_id().clone(); Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) @@ -441,10 +443,18 @@ async fn handle_message( // Submit the room's own sitting — a stale room must not submit a // retake it never hosted. let finished = match Exam::read(exam_id, db).await { - Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { - Ok(attempt) => attempt.finish(db).await, - Err(err) => Err(err), - }, + Ok(Some(exam)) => { + // Its own archived-term gate: `finish` is the one + // sitting-side write that does not go through + // `save_answer_in`, and the refusal leaves the room by the + // same error frame as every other conflict. + async { + let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; + course_of(&exam, db).await?.require_open(db).await?; + attempt.finish(db).await + } + .await + } Ok(None) => Err(AppError::NotFound), Err(err) => Err(err), }; diff --git a/src/web/exams/attempts.rs b/src/web/exams/attempts.rs index 1566c72..143f22c 100644 --- a/src/web/exams/attempts.rs +++ b/src/web/exams/attempts.rs @@ -156,7 +156,7 @@ pub(crate) async fn attempts_used( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse), - (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse), + (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, no attempts remaining, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] pub(crate) async fn start_attempt( @@ -180,6 +180,7 @@ pub(crate) async fn start_attempt( ensure_sittable(&exam)?; ensure_student(&user)?; ensure_enrolled(&exam, user.get_id(), &st.db).await?; + course_of(&exam, &st.db).await?.require_open(&st.db).await?; let now = Timestamp::now(); if let Some(starts_at) = exam.get_starts_at() && now < starts_at @@ -283,7 +284,7 @@ pub(crate) async fn my_attempt( (status = 200, description = "Attempt submitted", body = AttemptResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse), - (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse), + (status = 409, description = "Already submitted, the deadline passed, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] pub(crate) async fn finish_attempt( @@ -306,6 +307,7 @@ pub(crate) async fn finish_attempt( { return Err(AppError::Conflict("time is up — the attempt has expired")); } + course_of(&exam, &st.db).await?.require_open(&st.db).await?; // Deliberately no rejoin check: a student locked out of the room may // still submit what they saved — finishing answers nothing new. @@ -679,7 +681,13 @@ pub(crate) async fn save_answer_checked( /// The tail of the answer write path, given the sitting to write in: the /// student wall and the enrollment wall (a promotion out of `student` or an /// unenrollment closes the sheet, mid-exam included), the rejoin gate, the -/// question lookup, and the upsert. +/// archived-term gate, the question lookup, and the upsert. +/// +/// The archived-term refusal sits here because this is the single funnel every +/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via +/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room +/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only +/// answer-side writes outside it, and carry their own guard. pub(crate) async fn save_answer_in( exam: &Exam, attempt: &ExamAttempt, @@ -691,6 +699,7 @@ pub(crate) async fn save_answer_in( ensure_student_now(attempt.get_user(), db).await?; ensure_enrolled(exam, attempt.get_user(), db).await?; check_rejoin(exam, attempt)?; + course_of(exam, db).await?.require_open(db).await?; let question = question_of_exam(exam.get_id(), question_id, db).await?; ExamAnswer::save( &question, @@ -849,7 +858,7 @@ pub(crate) async fn attempt_questions( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, rejoin is closed, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] diff --git a/src/web/exams/images.rs b/src/web/exams/images.rs index 6e70e9c..42a90b8 100644 --- a/src/web/exams/images.rs +++ b/src/web/exams/images.rs @@ -81,7 +81,10 @@ pub(crate) async fn images_by_question( // own visibility (author side and sitting side alike). /// The exam, provided the caller may author its questions — the shared front -/// half of every image write. +/// half of every image write. The archived-term refusal lives here rather than +/// in each caller: all four question-image writes (upload/delete of a question +/// illustration and of a choice picture) come through this one door, and none +/// of the reads do. pub(crate) async fn image_managed_exam( st: &AppState, user: &User, @@ -96,6 +99,7 @@ pub(crate) async fn image_managed_exam( "only the course creator, an assigned teacher, or a manager/admin can manage question images", )); } + course.require_open(&st.db).await?; Ok(exam) } @@ -175,7 +179,7 @@ pub(crate) async fn serve_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), ), )] @@ -249,7 +253,7 @@ pub(crate) async fn get_question_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, question, or image", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] pub(crate) async fn delete_question_image( @@ -292,7 +296,7 @@ pub(crate) async fn delete_question_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), ), )] @@ -363,7 +367,7 @@ pub(crate) async fn get_choice_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such exam, question, or image", body = ErrorResponse), - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] pub(crate) async fn delete_choice_image( @@ -440,7 +444,7 @@ pub(crate) async fn store_answer_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, rejoin is closed, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), ), )] @@ -454,6 +458,9 @@ pub(crate) async fn upload_answer_image( .await? .ok_or(AppError::NotFound)?; ensure_student(&user)?; + // Before the body is read: an archived term refuses the upload without + // making the client push its bytes first. + course_of(&exam, &st.db).await?.require_open(&st.db).await?; // The body is consumed before the lock — a client's slow upload must not // stall the exam subsystem (mirrors the question-image upload). let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; @@ -521,7 +528,7 @@ pub(crate) async fn upload_answer_image( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), (status = 404, description = "No such exam, question, attempt, or drawing", body = ErrorResponse), - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), + (status = 409, description = "Attempt already submitted, time is up, rejoin is closed, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] pub(crate) async fn delete_answer_image( @@ -533,6 +540,7 @@ pub(crate) async fn delete_answer_image( .await? .ok_or(AppError::NotFound)?; ensure_student(&user)?; + course_of(&exam, &st.db).await?.require_open(&st.db).await?; let _guard = EXAM_LOCK.read().await; let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; ensure_student_now(attempt.get_user(), &st.db).await?; diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index cd022a3..b022859 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -264,7 +264,7 @@ struct ExamStatisticsResponse { /// The course an exam belongs to. A dangling reference means the course-delete /// cascade was violated — surface it loudly as a 500, not a user-facing 404. -async fn course_of(exam: &Exam, db: &Database) -> Result { +pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result { Course::read(exam.get_course(), db) .await? .ok_or_else(|| AppError::Internal("exam references a missing course".into())) @@ -399,7 +399,7 @@ async fn get_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, or the exam kept changing under concurrent edits", body = ErrorResponse), + (status = 409, description = "Mode change after attempts started, re-drafting an exam that has attempts or results, a kind change on an exam that already carries marks, the exam kept changing under concurrent edits, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -432,6 +432,7 @@ async fn update_exam( "only the course creator, an assigned teacher, or a manager/admin can edit this exam", )); } + course.require_open(&st.db).await?; let title = match req.title { Some(ref title) => ExamTitle::try_new(title)?, @@ -572,6 +573,7 @@ async fn update_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_exam( @@ -588,6 +590,7 @@ async fn delete_exam( "only the course creator, an assigned teacher, or a manager/admin can delete this exam", )); } + course.require_open(&st.db).await?; // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names // included — the lease `delete_homework` has always held, and its absence // here is what made a sitting able to start inside this delete. Every other @@ -645,7 +648,7 @@ async fn delete_exam( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), (status = 404, description = "Exam not found", body = ErrorResponse), - (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse), + (status = 409, description = "The exam is a draft, its kind has been removed from the school's settings, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -671,6 +674,7 @@ async fn grade( "only the course creator, an assigned teacher, or a manager/admin can grade this exam", )); } + course.require_open(&st.db).await?; // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own // transaction, so a re-draft landing after this read cannot leave a mark on // a hidden exam. @@ -860,6 +864,7 @@ async fn my_result( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn remove_result( @@ -876,6 +881,7 @@ async fn remove_result( "only the course creator, an assigned teacher, or a manager/admin can remove results", )); } + course.require_open(&st.db).await?; let removed = ExamResult::remove( exam.get_id(), &UserId::from_key(&target), diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 0ace9c7..1ca8c9a 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -200,7 +200,7 @@ pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result Result Result<(), AppError> { + if let Some(course) = Course::read(homework.get_course(), db).await? { + course.require_open(db).await?; + } + Ok(()) +} + /// One file attached to a submission — metadata only; the bytes download /// separately from `GET /homework/{id}/submission/files/{fid}`. #[derive(Serialize, ToSchema)] @@ -644,7 +661,7 @@ struct SubmitHomework { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse), - (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed", body = ErrorResponse), + (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed, or this course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -669,6 +686,7 @@ async fn submit( // write is what makes the PATCH wait and then see the row. let _guard = HOMEWORK_LOCK.read().await; let homework = gate_own_submission(&id, &user, &st.db).await?; + require_open_term(&homework, &st.db).await?; // The graded gate, twice over. This read answers the common case — graded // minutes ago, and the student who never submitted has no row to carry the // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what @@ -766,7 +784,7 @@ async fn get_submission( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), (status = 404, description = "No such homework, a subset assignment the caller is not part of, or nothing submitted yet", body = ErrorResponse), - (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed", body = ErrorResponse), + (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_submission( @@ -775,6 +793,7 @@ async fn delete_submission( Path(id): Path, ) -> Result { let homework = gate_own_submission(&id, &user, &st.db).await?; + require_open_term(&homework, &st.db).await?; // Reader lease as in `submit` — the audience interlock, not the freeze. let _guard = HOMEWORK_LOCK.read().await; if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) @@ -873,7 +892,7 @@ async fn serve_download(st: &AppState, file: &HomeworkFile) -> Result, ) -> Result { let homework = gate_own_submission(&id, &user, &st.db).await?; + require_open_term(&homework, &st.db).await?; const GRADED: AppError = AppError::Conflict( "this homework has been graded — ask the teacher to remove the grade before deleting files", ); @@ -1100,6 +1123,7 @@ struct GradeHomework { (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), (status = 404, description = "Homework not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -1121,6 +1145,7 @@ async fn grade_homework( "only the course creator, an assigned teacher, or a manager/admin can grade this homework", )); } + course.require_open(&st.db).await?; let status = HomeworkStatus::try_new(&req.status)?; let mark = req.mark.map(Mark::try_new).transpose()?; @@ -1202,6 +1227,7 @@ async fn grade_homework( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "No such homework, or no grade for this user", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn remove_homework_result( @@ -1219,6 +1245,7 @@ async fn remove_homework_result( "only the course creator, an assigned teacher, or a manager/admin can remove grades", )); } + course.require_open(&st.db).await?; let removed = HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; if removed.is_none() { diff --git a/src/web/messages.rs b/src/web/messages.rs index 2342de0..c1c8642 100644 --- a/src/web/messages.rs +++ b/src/web/messages.rs @@ -157,10 +157,11 @@ impl MessageResponse { } } -/// Send a message to another user. Any authenticated user may write to any -/// existing user (parents included — messaging is the one place a parent -/// acts); only messaging yourself is refused. The send is server-stamped and -/// lands in the recipient's inbox unread. +/// Send a message to another user. Messaging is upward only below staff: a +/// student or parent may write to a teacher, manager or admin (parents +/// included — messaging is the one place a parent acts), never to another +/// student or parent; staff write to anyone. Messaging yourself is refused. +/// The send is server-stamped and lands in the recipient's inbox unread. #[utoipa::path( post, path = "/", @@ -171,6 +172,7 @@ impl MessageResponse { (status = 201, description = "Message sent", body = MessageResponse), (status = 400, description = "Invalid subject or body, or the recipient is yourself", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "A student or parent wrote to someone who is not staff", body = ErrorResponse), (status = 404, description = "No such recipient", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), @@ -197,6 +199,11 @@ async fn send_message( let recipient = User::read(&UserId::from_key(&req.recipient_id), &st.db) .await? .ok_or(AppError::NotFound)?; + if !user.get_role().may_message(recipient.get_role()) { + return Err(AppError::Forbidden( + "students and parents may only message staff (teacher or higher)", + )); + } let message = Message::send( user.get_id(), diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 7e0e378..cf8f66f 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -193,6 +193,7 @@ async fn get_session( (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn update_session( @@ -217,6 +218,7 @@ async fn update_session( "only the course creator, an assigned teacher, or a manager/admin can edit this session", )); } + course.require_open(&st.db).await?; let topic = req .topic @@ -260,6 +262,7 @@ async fn update_session( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_session( @@ -273,6 +276,7 @@ async fn delete_session( "only the course creator, an assigned teacher, or a manager/admin can delete this session", )); } + course.require_open(&st.db).await?; session.delete(&st.db).await?; Ok(StatusCode::NO_CONTENT) } @@ -298,6 +302,7 @@ async fn delete_session( (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), (status = 404, description = "Session not found", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn mark_roll_call( @@ -312,6 +317,7 @@ async fn mark_roll_call( "only the session's teacher or a course manager can take roll call", )); } + course.require_open(&st.db).await?; let school = Settings::load(&st.db).await?; let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; @@ -437,6 +443,7 @@ async fn list_roll_call( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the session teacher or a course manager; or removing a staff row without manager+", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn remove_roll_call( @@ -450,6 +457,7 @@ async fn remove_roll_call( "only the session's teacher or a course manager can take roll call", )); } + course.require_open(&st.db).await?; let target = UserId::from_key(&target); // A staff row is management's to remove, keyed on the *target's live role* // rather than on `is_teacher`: reassigning a session's teacher used to hand diff --git a/src/web/subjects.rs b/src/web/subjects.rs index c3604b2..cee5977 100644 --- a/src/web/subjects.rs +++ b/src/web/subjects.rs @@ -125,6 +125,7 @@ async fn get_subject( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -140,6 +141,7 @@ async fn update_subject( "only the course creator, an assigned teacher, or a manager/admin can edit this subject", )); } + course.require_open(&st.db).await?; // Only what the request actually carried is validated and written — an // omitted field stays `None` so the save never re-sends this snapshot's @@ -176,7 +178,7 @@ async fn update_subject( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse), + (status = 409, description = "Exam questions or homework still reference this subject, or this course's term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_subject( @@ -190,6 +192,7 @@ async fn delete_subject( "only the course creator, an assigned teacher, or a manager/admin can delete this subject", )); } + course.require_open(&st.db).await?; // No locks: the two checks *are* the delete's `WHERE`, decided against the // subject's own reference counters inside one statement. This used to be // three process-wide locks (the only site that held more than one) around diff --git a/src/web/terms.rs b/src/web/terms.rs index 196ab19..2b72276 100644 --- a/src/web/terms.rs +++ b/src/web/terms.rs @@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::database::Database; -use crate::domain::term::{Term, TermId, TermName}; +use crate::domain::term::{self, Term, TermId, TermName}; use crate::domain::timestamp::Timestamp; use crate::error::{AppError, ErrorResponse, ValidationError}; use crate::state::AppState; @@ -18,6 +18,8 @@ pub fn routes() -> OpenApiRouter { OpenApiRouter::new() .routes(routes!(create_term, list_terms)) .routes(routes!(get_term, update_term, delete_term)) + .routes(routes!(archive_term)) + .routes(routes!(unarchive_term)) } #[derive(Deserialize, ToSchema)] @@ -50,6 +52,8 @@ struct TermResponse { starts_at: i64, /// Term end, UTC unix-milliseconds. ends_at: i64, + /// Archived at, UTC unix-millis; null while the term is open. + archived_at: Option, } impl TermResponse { @@ -59,13 +63,17 @@ impl TermResponse { name: term.get_name().as_str().to_string(), starts_at: term.get_starts_at().as_millis(), ends_at: term.get_ends_at().as_millis(), + archived_at: term.get_archived_at().map(|at| at.as_millis()), } } } /// Turn an optional request-supplied term id into a validated reference — -/// `None` stays `None`, an unknown id is a `400` naming the field. Shared by -/// the course create/update handlers. +/// `None` stays `None`, an unknown id is a `400` naming the field, and an +/// *archived* one is a `409 term_archived`. That last refusal is here rather +/// than in each handler because this is the single spot every new link to a +/// term passes through — course create/update and class create/update alike: +/// past years take no new structure. pub(crate) async fn resolve_term( id: Option<&str>, db: &Database, @@ -79,6 +87,9 @@ pub(crate) async fn resolve_term( field: "term_id", reason: "term does not exist", }))?; + if term.is_archived() { + return Err(term::archived_error()); + } Ok(Some(term.get_id().clone())) } @@ -177,6 +188,7 @@ async fn get_term( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), + (status = 409, description = "The term is archived — past years are read-only", body = ErrorResponse), (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), ), )] @@ -193,6 +205,9 @@ async fn update_term( let term = Term::read(&TermId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + if term.is_archived() { + return Err(term::archived_error()); + } // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE` // (`Term::update`), so a concurrent move of the end this PATCH omits cannot // slip an inverted range past this snapshot. @@ -220,7 +235,7 @@ async fn update_term( (status = 401, description = "Not authenticated", body = ErrorResponse), (status = 403, description = "Requires manager role or higher", body = ErrorResponse), (status = 404, description = "Not found", body = ErrorResponse), - (status = 409, description = "Courses are still linked to this term", body = ErrorResponse), + (status = 409, description = "Courses are still linked to this term, or the term is archived — past years are read-only", body = ErrorResponse), ), )] async fn delete_term( @@ -231,6 +246,9 @@ async fn delete_term( let term = Term::read(&TermId::from_key(&id), &st.db) .await? .ok_or(AppError::NotFound)?; + if term.is_archived() { + return Err(term::archived_error()); + } if !term.delete(&st.db).await? { return Err(AppError::Conflict( "courses are still linked to this term — unlink them first", @@ -238,3 +256,58 @@ async fn delete_term( } Ok(StatusCode::NO_CONTENT) } + +/// Archive a term. Requires manager+. An archived term is frozen: it takes no +/// edits, no delete, and no new course or class link. Idempotent — archiving an +/// already-archived term answers `200` with the stamp it already had. +#[utoipa::path( + post, + path = "/{id}/archive", + tag = "terms", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Term id")), + responses( + (status = 200, description = "The archived term", body = TermResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn archive_term( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result, AppError> { + let term = Term::read(&TermId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let archived = term.archive(&st.db).await?; + Ok(Json(TermResponse::new(&archived))) +} + +/// Re-open an archived term. Requires manager+. Idempotent the same way as +/// archiving: an already-open term answers `200`. +#[utoipa::path( + post, + path = "/{id}/unarchive", + tag = "terms", + security(("session_cookie" = [])), + params(("id" = String, Path, description = "Term id")), + responses( + (status = 200, description = "The re-opened term", body = TermResponse), + (status = 401, description = "Not authenticated", body = ErrorResponse), + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), + (status = 404, description = "Not found", body = ErrorResponse), + ), +)] +async fn unarchive_term( + State(st): State, + RequireManager(_user): RequireManager, + Path(id): Path, +) -> Result, AppError> { + let term = Term::read(&TermId::from_key(&id), &st.db) + .await? + .ok_or(AppError::NotFound)?; + let reopened = term.unarchive(&st.db).await?; + Ok(Json(TermResponse::new(&reopened))) +} diff --git a/src/web/users.rs b/src/web/users.rs index 6c6a50d..07d43e5 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -28,9 +28,8 @@ use super::courses::visible_courses; use super::dto::AssignableRole; use super::dto::Role as RoleSchema; use super::{ - CurrentUser, Page, PageParams, PersonRef, RequireAdmin, RequireTeacher, UploadFileForm, - UserResponse, ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, - store_blob, + CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, + ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob, }; pub fn routes() -> OpenApiRouter { @@ -197,8 +196,12 @@ struct SearchUsers { } /// Find users by username or name — backs the pickers (enroll, grade, mark -/// attendance). Requires teacher+. `role` narrows to one role (e.g. -/// `role=student` for an enroll picker); a blank `q` with a `role` lists +/// attendance) and, for a student or parent, the one way to find the staff +/// member they are allowed to message. Any authenticated user may ask; a +/// caller below teacher only ever sees the roles they may message (teacher, +/// manager, admin), in the items *and* in `total`. `role` narrows to one role +/// (e.g. `role=student` for an enroll picker) — a student or parent naming a +/// role they may not message is refused; a blank `q` with a `role` lists /// everyone in that role. Paged via `?limit=&offset=` like the other lists /// (omit `limit` for every match); returns a `{items, total, limit, offset}` /// envelope carrying only id/username/display name — no contact details. @@ -212,12 +215,12 @@ struct SearchUsers { (status = 200, description = "A page of matching users (all matches when unpaged)", body = Page), (status = 400, description = "Blank query without a role, unknown role, or invalid limit/offset", body = ErrorResponse), (status = 401, description = "Not authenticated", body = ErrorResponse), - (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), + (status = 403, description = "A student or parent asked for a role they may not message", body = ErrorResponse), ), )] async fn search_users( State(st): State, - _teacher: RequireTeacher, + CurrentUser(user): CurrentUser, Query(req): Query, ) -> Result>, AppError> { if req.q.trim().is_empty() && req.role.is_none() { @@ -232,7 +235,17 @@ async fn search_users( } .resolve()?; let role = req.role.as_deref().map(Role::try_from_str).transpose()?; - let (users, total) = User::search(&req.q, role, limit, offset, &st.db).await?; + // Below staff the caller may only see whom they may write to. Asking for a + // role outside that set is a refusal, not a silently empty page. + let allowed = user.get_role().messageable_roles(); + if let (Some(allowed), Some(role)) = (allowed, role) + && !allowed.contains(&role) + { + return Err(AppError::Forbidden( + "students and parents may only search staff (teacher or higher)", + )); + } + let (users, total) = User::search(&req.q, role, allowed, limit, offset, &st.db).await?; let items = users.iter().map(PersonRef::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } diff --git a/tests/e2e.rs b/tests/e2e.rs index 407fbe0..afb1a40 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -284,10 +284,22 @@ async fn full_user_journey() { .unwrap(); assert!(found["items"].as_array().unwrap().is_empty()); - let res = veli + // A student may search since #24 — and sees staff only: ali the teacher + // comes back, another student never would. + let found: Value = veli .get(format!("{base}/users/search?q=ali")) .send() .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(found["items"].as_array().unwrap().len(), 1); + assert_eq!(found["items"][0]["username"], "ali"); + let res = veli + .get(format!("{base}/users/search?q=vel&role=student")) + .send() + .await .unwrap(); assert_eq!(res.status(), StatusCode::FORBIDDEN); @@ -3302,3 +3314,370 @@ async fn a_demoted_participant_stops_reading_the_canvas_at_once() { ); board_draw(&mut ali, "{\"p\":[5,6]}").await; } + +/// A manager archives an academic year and the whole year turns read-only from +/// the user's seat: every write into its structure answers `409 term_archived`, +/// every read still answers, the live exam room's door refuses the upgrade with +/// a real HTTP 409 (before the WebSocket handshake completes), and unarchiving +/// reopens all of it. The two archive routes are discoverable in the served +/// OpenAPI document Swagger renders. +#[tokio::test] +async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { + let (base, db) = spawn_server().await; + let mudur = client(); + let ogrenci = client(); + let kaan = client(); + register(&mudur, &base, "mudur").await; + register(&ogrenci, &base, "ogrenci").await; + register(&kaan, &base, "kaan").await; + promote(&db, "mudur", "manager").await; + login(&mudur, &base, "mudur").await; + login(&ogrenci, &base, "ogrenci").await; + login(&kaan, &base, "kaan").await; + + let json_of = async |res: reqwest::Response| res.json::().await.unwrap(); + let student_id = + json_of(ogrenci.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"] + .as_str() + .unwrap() + .to_string(); + let kaan_id = json_of(kaan.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"] + .as_str() + .unwrap() + .to_string(); + let now = json_of(mudur.get(format!("{base}/time")).send().await.unwrap()).await["now"] + .as_i64() + .unwrap(); + + // --- a year's worth of structure, all hanging off one term ------------- + let res = mudur + .post(format!("{base}/terms")) + .json(&json!({ "name": "2026 Fall", "starts_at": now - 86_400_000, "ends_at": now + 86_400_000 })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let term: Value = res.json().await.unwrap(); + let term_id = term["id"].as_str().unwrap().to_string(); + assert!( + term["archived_at"].is_null(), + "a fresh term is open: {term}" + ); + + let res = mudur + .post(format!("{base}/courses")) + .json(&json!({ "title": "algebra", "term_id": term_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let course_id = json_of(res).await["id"].as_str().unwrap().to_string(); + + let subject_id = json_of( + mudur + .post(format!("{base}/courses/{course_id}/subjects")) + .json(&json!({ "name": "arithmetic" })) + .send() + .await + .unwrap(), + ) + .await["id"] + .as_str() + .unwrap() + .to_string(); + + let exam: Value = json_of( + mudur + .post(format!("{base}/courses/{course_id}/exams")) + .json(&json!({ "title": "midterm", "kind": "quiz", "mode": "open", "max_attempts": 2 })) + .send() + .await + .unwrap(), + ) + .await; + let exam_id = exam["id"].as_str().unwrap().to_string(); + let question: Value = json_of( + mudur + .post(format!("{base}/exams/{exam_id}/questions")) + .json( + &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", + "points": 10, + "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}], + "correct": "b" }), + ) + .send() + .await + .unwrap(), + ) + .await; + let question_id = question["id"].as_str().unwrap().to_string(); + let opts = choice_ids(&question); + + let res = mudur + .post(format!("{base}/courses/{course_id}/sessions")) + .json(&json!({ "starts_at": now + 3_600_000 })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let session_id = json_of(res).await["id"].as_str().unwrap().to_string(); + + let res = mudur + .post(format!("{base}/courses/{course_id}/homework")) + .json( + &json!({ "title": "read ch3", "subject_id": subject_id, "due_at": now + 604_800_000 }), + ) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let homework_id = json_of(res).await["id"].as_str().unwrap().to_string(); + + let res = mudur + .post(format!("{base}/course-notes")) + .json(&json!({ "course": course_id, "title": "recap", "content": "quadratics" })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let note_id = json_of(res).await["id"].as_str().unwrap().to_string(); + + let res = mudur + .post(format!("{base}/classes")) + .json(&json!({ "name": "9-A", "grade": "9", "term_id": term_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED); + let class_id = json_of(res).await["class"]["id"] + .as_str() + .unwrap() + .to_string(); + + let res = mudur + .post(format!("{base}/courses/{course_id}/enrollments")) + .json(&json!({ "user_id": student_id })) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + + // The student is mid-sitting when the year closes: a live attempt whose + // room door is about to be walled. + let res = ogrenci + .post(format!("{base}/exams/{exam_id}/attempt")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::CREATED, "start the live sitting"); + let student_cookie = raw_session_cookie(&base, "ogrenci").await; + + // --- archive ---------------------------------------------------------- + let res = mudur + .post(format!("{base}/terms/{term_id}/archive")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + let archived: Value = res.json().await.unwrap(); + let stamp = archived["archived_at"].as_i64().expect("archived_at stamp"); + + // Idempotent: a second archive answers 200 with the stamp it already had. + let res = mudur + .post(format!("{base}/terms/{term_id}/archive")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + assert_eq!( + json_of(res).await["archived_at"].as_i64(), + Some(stamp), + "re-archiving must not move the stamp" + ); + + // --- every write into the closed year is a 409 `term_archived` --------- + let refusals: Vec<(&str, reqwest::Response)> = vec![ + ( + "PATCH /terms/{id}", + mudur + .patch(format!("{base}/terms/{term_id}")) + .json(&json!({ "name": "renamed" })) + .send() + .await + .unwrap(), + ), + ( + "PATCH /courses/{id}", + mudur + .patch(format!("{base}/courses/{course_id}")) + .json(&json!({ "title": "renamed" })) + .send() + .await + .unwrap(), + ), + ( + "POST /courses/{id}/enrollments", + mudur + .post(format!("{base}/courses/{course_id}/enrollments")) + .json(&json!({ "user_id": kaan_id })) + .send() + .await + .unwrap(), + ), + ( + "POST /sessions/{id}/attendance", + mudur + .post(format!("{base}/sessions/{session_id}/attendance")) + .json(&json!({ "status": "present", "user_id": student_id })) + .send() + .await + .unwrap(), + ), + ( + "PATCH /exams/{id}", + mudur + .patch(format!("{base}/exams/{exam_id}")) + .json(&json!({ "title": "renamed" })) + .send() + .await + .unwrap(), + ), + ( + "POST /exams/{id}/attempt/answers", + ogrenci + .post(format!("{base}/exams/{exam_id}/attempt/answers")) + .json(&json!({ "question_id": question_id, "selected": opts[1] })) + .send() + .await + .unwrap(), + ), + ( + "POST /homework/{id}/results", + mudur + .post(format!("{base}/homework/{homework_id}/results")) + .json(&json!({ "user": student_id, "status": "done", "mark": 90 })) + .send() + .await + .unwrap(), + ), + ( + "PATCH /course-notes/{id}", + mudur + .patch(format!("{base}/course-notes/{note_id}")) + .json(&json!({ "title": "renamed" })) + .send() + .await + .unwrap(), + ), + ( + "POST /classes/{id}/members", + mudur + .post(format!("{base}/classes/{class_id}/members")) + .json(&json!({ "user_id": kaan_id })) + .send() + .await + .unwrap(), + ), + ]; + for (what, res) in refusals { + let status = res.status(); + let body: Value = res.json().await.unwrap(); + assert_eq!(status, StatusCode::CONFLICT, "{what} status: {body}"); + assert_eq!(body["code"], "term_archived", "{what} code: {body}"); + } + + // --- every read still answers ----------------------------------------- + for url in [ + format!("{base}/terms/{term_id}"), + format!("{base}/courses/{course_id}"), + format!("{base}/exams/{exam_id}"), + format!("{base}/sessions/{session_id}"), + format!("{base}/homework/{homework_id}"), + format!("{base}/course-notes/{note_id}"), + format!("{base}/classes/{class_id}"), + ] { + let res = mudur.get(&url).send().await.unwrap(); + assert_eq!(res.status(), StatusCode::OK, "read stays open: {url}"); + } + + // --- the exam room's door: refused before the upgrade ------------------ + let refused = ws_open(&base, &exam_id, Some(&student_cookie)) + .await + .expect_err("an archived year's room must refuse the handshake"); + assert_eq!(refused, 409, "the room door answers a real HTTP 409"); + + // --- unarchive reopens the year --------------------------------------- + let res = mudur + .post(format!("{base}/terms/{term_id}/unarchive")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + let reopened: Value = res.json().await.unwrap(); + assert!( + reopened["archived_at"].is_null(), + "unarchive clears the stamp: {reopened}" + ); + + // A write that was refused a moment ago now lands. + let res = mudur + .patch(format!("{base}/courses/{course_id}")) + .json(&json!({ "title": "algebra II" })) + .send() + .await + .unwrap(); + assert_eq!( + res.status(), + StatusCode::OK, + "the reopened year takes writes" + ); + + // The room door opens again, and the live sitting is still there. + let mut ws = ws_open(&base, &exam_id, Some(&student_cookie)) + .await + .expect("the reopened year's room"); + let state = ws_next_frame(&mut ws).await.expect("connect state frame"); + assert_eq!(state["type"], "state", "{state}"); + + // Archive under the open socket: `finish` comes back as an error frame + // carrying the archived refusal instead of submitting the sheet. + let res = mudur + .post(format!("{base}/terms/{term_id}/archive")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + ws_send(&mut ws, json!({ "type": "finish" })).await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert!( + error["message"].as_str().unwrap().contains("archived"), + "the room's finish refusal names the archived year: {error}" + ); + + // Reopen once more and the same frame submits the sitting. + let res = mudur + .post(format!("{base}/terms/{term_id}/unarchive")) + .send() + .await + .unwrap(); + assert_eq!(res.status(), StatusCode::OK); + ws_send(&mut ws, json!({ "type": "finish" })).await; + let finished = ws_frame_of_type(&mut ws, "finished").await; + assert!(finished["finished_at"].as_i64().is_some(), "{finished}"); + + // --- discoverable in the document Swagger renders ---------------------- + let spec: Value = json_of( + mudur + .get(format!("{base}/api-docs/openapi.json")) + .send() + .await + .unwrap(), + ) + .await; + for path in ["/terms/{id}/archive", "/terms/{id}/unarchive"] { + assert!( + spec["paths"][path]["post"].is_object(), + "{path} must be a documented POST in the served spec" + ); + } +} diff --git a/tests/integration.rs b/tests/integration.rs index 931a5e9..cac2f2a 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -11063,6 +11063,76 @@ async fn attendance_report_tallies_events_and_sessions_per_course() { assert_eq!(res.status, StatusCode::NOT_FOUND); } +/// Issue #24: a student or parent needs a way to find the teacher they are +/// allowed to write to, so `/users/search` is no longer teacher+ — but below +/// staff it shows staff *only*, in the items and in `total` alike (the +/// restriction is in the query, not a post-filter over one page). +#[tokio::test] +async fn search_below_staff_sees_only_staff() { + let (app, db) = app_and_db().await; + // Both match `q=ay`: one student, one teacher. + let ayse = login(&app, "ayse").await; + let _ayhan = login_as(&app, &db, "ayhan", "teacher").await; + let anne = login_as(&app, &db, "anne", "parent").await; + let mudur = login_as(&app, &db, "mudur", "manager").await; + + for (who, cookie) in [("student", &ayse), ("parent", &anne)] { + let res = send(&app, "GET", "/users/search?q=ay", Some(cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); + let items = common::items(&res.body); + assert_eq!( + items.len(), + 1, + "{who} must see only the teacher: {}", + res.body + ); + assert_eq!(items[0]["username"], "ayhan", "{who}"); + assert_eq!( + res.body["total"], 1, + "{who}: total counts the visible set only" + ); + // Only the picker fields, as before — never contact details. + assert!(items[0].get("email").is_none(), "{who}"); + + // Naming a role they may not message is a refusal, not an empty page. + let res = send( + &app, + "GET", + "/users/search?q=ay&role=student", + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{who}: {}", res.body); + // A staff role they may message filters as usual. + let res = send( + &app, + "GET", + "/users/search?q=ay&role=teacher", + Some(cookie), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{who}: {}", res.body); + assert_eq!(common::items(&res.body).len(), 1, "{who}"); + } + + // Staff keep the unrestricted picker: the student is back in the results. + let res = send(&app, "GET", "/users/search?q=ay", Some(&mudur), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(res.body["total"], 2, "{}", res.body); + let res = send( + &app, + "GET", + "/users/search?q=ay&role=student", + Some(&mudur), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body)[0]["username"], "ayse"); +} + // --- users: search matching semantics -------------------------------------- /// The search fragment is matched with literal `CONTAINS` semantics — never @@ -13337,8 +13407,12 @@ async fn parent_observes_linked_students_and_nothing_else() { ) .await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + // Search is open to a parent since #24, but only onto staff: the linked + // student is a match by name and still must not come back. let res = send(&app, "GET", "/users/search?q=ali", Some(&parent), None).await; - assert_eq!(res.status, StatusCode::FORBIDDEN); + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert_eq!(common::items(&res.body).len(), 0, "{}", res.body); + assert_eq!(res.body["total"], 0); } /// A role change off either end of a tie sweeps it, exactly like promotion @@ -13675,6 +13749,57 @@ async fn messages_remember_the_folder_a_filed_copy_came_from() { assert_eq!(origins, vec![None], "the deleted side keeps no origin"); } +/// Issue #23: messaging is upward only below staff. A student or parent writes +/// to teacher+ and to nobody else; staff write in any direction. +#[tokio::test] +async fn messages_from_below_staff_go_upward_only() { + let (app, db) = app_and_db().await; + let ali = login(&app, "ali").await; // student + let ali_id = me_id(&app, &ali).await; + let veli = login(&app, "veli").await; // student + let veli_id = me_id(&app, &veli).await; + let anne = login_as(&app, &db, "anne", "parent").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; + let mudur = login_as(&app, &db, "mudur", "manager").await; + + let write = async |from: &str, to: &str| { + send( + &app, + "POST", + "/messages", + Some(from), + Some(json!({ "recipient_id": to, "subject": "selam" })), + ) + .await + }; + + // Sideways and downward from below staff: refused, with the rule spelled out. + let res = write(&ali, &veli_id).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + assert!( + res.body["error"] + .as_str() + .unwrap_or_default() + .contains("staff"), + "{}", + res.body + ); + assert_eq!(write(&anne, &ali_id).await.status, StatusCode::FORBIDDEN); + + // Upward: allowed for both. + assert_eq!(write(&ali, &hoca_id).await.status, StatusCode::CREATED); + assert_eq!(write(&anne, &hoca_id).await.status, StatusCode::CREATED); + + // Staff write anywhere — down to a student, sideways to a colleague. + assert_eq!(write(&hoca, &ali_id).await.status, StatusCode::CREATED); + assert_eq!(write(&mudur, &hoca_id).await.status, StatusCode::CREATED); + + // The refused sends left nothing behind. + let inbox = send(&app, "GET", "/messages", Some(&veli), None).await; + assert_eq!(common::items(&inbox.body).len(), 0, "{}", inbox.body); +} + #[tokio::test] async fn messages_guard_parties_recipients_and_folders() { let (app, db) = app_and_db().await; @@ -13682,6 +13807,8 @@ async fn messages_guard_parties_recipients_and_folders() { let ali_id = me_id(&app, &ali).await; let veli = login(&app, "veli").await; let parent = login_as(&app, &db, "anne", "parent").await; + let hoca = login_as(&app, &db, "hoca", "teacher").await; + let hoca_id = me_id(&app, &hoca).await; // Sending to yourself or to nobody fails. let res = send( @@ -13703,7 +13830,8 @@ async fn messages_guard_parties_recipients_and_folders() { .await; assert_eq!(res.status, StatusCode::NOT_FOUND); - // A parent writes like anyone else — messaging is the role's one pen. + // A parent writes — messaging is the role's one pen — but upward only: to + // the teacher, not to the student. let res = send( &app, "POST", @@ -13712,6 +13840,15 @@ async fn messages_guard_parties_recipients_and_folders() { Some(json!({ "recipient_id": ali_id, "subject": "görüşme", "body": "uygun mu?" })), ) .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + let res = send( + &app, + "POST", + "/messages", + Some(&parent), + Some(json!({ "recipient_id": hoca_id, "subject": "görüşme", "body": "uygun mu?" })), + ) + .await; assert_eq!(res.status, StatusCode::CREATED); assert_eq!(res.body["sender_role"], "parent"); assert_eq!( diff --git a/tests/partial_patch_terms.rs b/tests/partial_patch_terms.rs index 2a47ae5..c41d10d 100644 --- a/tests/partial_patch_terms.rs +++ b/tests/partial_patch_terms.rs @@ -110,3 +110,150 @@ async fn concurrent_range_patches_never_invert_the_term() { ); } } + +/// Archiving a term freezes it: the term itself takes no PATCH or DELETE, and +/// no new course or class may link it. Reads stay open — a past year is +/// read-only, not hidden. +#[tokio::test] +async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "archive_manager", "manager").await; + let teacher = login_as(&app, &db, "archive_teacher", "teacher").await; + let student = login_as(&app, &db, "archive_student", "student").await; + + let created = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2024", + "starts_at": 1_700_000_000_000_i64, + "ends_at": 1_710_000_000_000_i64, + })), + ) + .await; + assert_eq!(created.status, StatusCode::CREATED); + assert!(created.body["archived_at"].is_null(), "born open"); + let id = id_of(&created.body); + let uri = format!("/terms/{id}"); + let archive = format!("/terms/{id}/archive"); + + // Only manager+ may flip it. + for (who, cookie) in [("teacher", &teacher), ("student", &student)] { + let res = send(&app, "POST", &archive, Some(cookie), None).await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{who} archive"); + } + + let archived = send(&app, "POST", &archive, Some(&manager), None).await; + assert_eq!(archived.status, StatusCode::OK); + let stamp = archived.body["archived_at"].as_i64().expect("archived_at"); + + // Idempotent: a repeat keeps the original stamp, the year is not re-dated. + let again = send(&app, "POST", &archive, Some(&manager), None).await; + assert_eq!(again.status, StatusCode::OK); + assert_eq!( + again.body["archived_at"].as_i64(), + Some(stamp), + "re-stamped" + ); + + // Frozen: edit and delete both refuse with the coded 409. + for (method, body) in [ + ("PATCH", Some(json!({ "name": "renamed" }))), + ("DELETE", None), + ] { + let res = send(&app, method, &uri, Some(&manager), body).await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "{method} on archived term" + ); + assert_eq!(res.body["code"], "term_archived", "{method} code"); + } + + // No new structure may be hung on a past year — one refusal per link site. + let new_course = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "algebra", "term_id": id })), + ) + .await; + assert_eq!(new_course.status, StatusCode::CONFLICT, "course link"); + assert_eq!(new_course.body["code"], "term_archived"); + let new_class = send( + &app, + "POST", + "/classes", + Some(&manager), + Some(json!({ "name": "9-A", "term_id": id })), + ) + .await; + assert_eq!(new_class.status, StatusCode::CONFLICT, "class link"); + assert_eq!(new_class.body["code"], "term_archived"); + + // Reads keep working and carry the stamp, single and listed. + let one = send(&app, "GET", &uri, Some(&student), None).await; + assert_eq!(one.status, StatusCode::OK); + assert_eq!(one.body["archived_at"].as_i64(), Some(stamp)); + let listed = send(&app, "GET", "/terms", Some(&student), None).await; + assert_eq!(listed.status, StatusCode::OK); + let row = listed.body["items"] + .as_array() + .expect("items") + .iter() + .find(|row| row["id"] == id.as_str()) + .expect("the archived term is still listed"); + assert_eq!(row["archived_at"].as_i64(), Some(stamp)); + + // Re-opening thaws it, and is idempotent too. + let unarchive = format!("/terms/{id}/unarchive"); + let reopened = send(&app, "POST", &unarchive, Some(&manager), None).await; + assert_eq!(reopened.status, StatusCode::OK); + assert!(reopened.body["archived_at"].is_null(), "reopened"); + let twice = send(&app, "POST", &unarchive, Some(&manager), None).await; + assert_eq!(twice.status, StatusCode::OK); + assert!(twice.body["archived_at"].is_null()); + let patched = send( + &app, + "PATCH", + &uri, + Some(&manager), + Some(json!({ "name": "renamed" })), + ) + .await; + assert_eq!(patched.status, StatusCode::OK, "open again, edits land"); + + // An id nobody minted is a 404 on both flips, not a 409. + for route in ["/terms/nope/archive", "/terms/nope/unarchive"] { + let res = send(&app, "POST", route, Some(&manager), None).await; + assert_eq!(res.status, StatusCode::NOT_FOUND, "{route}"); + } +} + +/// A term row written before `archived_at` existed has no such column. It must +/// still decode — as an open term — or the migration would have needed a +/// backfill it deliberately does not have. +#[tokio::test] +async fn a_pre_migration_term_row_still_decodes_as_open() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await; + + db.query("CREATE term:legacy SET name = 'old', starts_at = 100, ends_at = 200") + .await + .expect("legacy term query") + .check() + .expect("legacy term check"); + + let res = send(&app, "GET", "/terms/legacy", Some(&manager), None).await; + assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode"); + assert_eq!(res.body["name"], "old"); + assert!(res.body["archived_at"].is_null(), "absent = open"); + + // And it is still writable, archiving included. + let archived = send(&app, "POST", "/terms/legacy/archive", Some(&manager), None).await; + assert_eq!(archived.status, StatusCode::OK); + assert!(archived.body["archived_at"].as_i64().is_some()); +} diff --git a/tests/regress_appointments.rs b/tests/regress_appointments.rs index fa1828e..31b49f5 100644 --- a/tests/regress_appointments.rs +++ b/tests/regress_appointments.rs @@ -221,9 +221,10 @@ async fn accepting_a_superseded_proposal_is_refused() { /// Not a defect — a pin on a deliberate disclosure, so a future "tightening" /// fails loudly instead of silently killing the booking flow. `GET /// /appointments/slots` hands a parent the slot teacher's `PersonRef`, an -/// identity all three of a parent's direct routes refuse them (`/users/{id}/ -/// profile` 403, `/users/search` teacher+, `/users` admin). It has to: you -/// cannot choose whom to book a conference with from an anonymous calendar. +/// identity a parent's direct routes still refuse them (`/users/{id}/profile` +/// 403, `/users` admin) — `/users/search` names staff since #24, but never says +/// which of them published bookable time. It has to: you cannot choose whom to +/// book a conference with from an anonymous calendar. #[tokio::test] async fn a_parent_reads_the_slot_teachers_identity() { let (app, db) = app_and_db().await; @@ -243,11 +244,7 @@ async fn a_parent_reads_the_slot_teachers_identity() { assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); // The parent is refused that identity everywhere it is asked for directly. - for uri in [ - format!("/users/{ali_id}/profile"), - "/users/search?q=ali".to_string(), - "/users".to_string(), - ] { + for uri in [format!("/users/{ali_id}/profile"), "/users".to_string()] { let res = send(&app, "GET", &uri, Some(&veli), None).await; assert_eq!(res.status, StatusCode::FORBIDDEN, "{uri}: {}", res.body); } diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index 8144b9e..851e898 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -409,3 +409,124 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { "no orphan row was written" ); } + +/// #22, session half: a course sitting in an archived term is a past year — +/// its sessions and their roll call are read-only. The guard runs *after* the +/// authorization check (403 before 409, so a stranger never learns a term's +/// state) and off the `course` the shared session loader already returns, not +/// inside that loader — reads go through it too, and reads stay open. +#[tokio::test] +async fn an_archived_term_freezes_its_sessions_and_roll_call() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "arch_sess_manager", "manager").await; + let ali = login(&app, "arch_sess_ali").await; + let ali_id = me_id(&app, &ali).await; + + let term = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2023", + "starts_at": 1_600_000_000_000_i64, + "ends_at": 1_610_000_000_000_i64, + })), + ) + .await; + assert_eq!(term.status, StatusCode::CREATED, "{}", term.body); + let term_id = common::id_of(&term.body); + + let course = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "Tarih", "term_id": term_id })), + ) + .await; + assert_eq!(course.status, StatusCode::CREATED, "{}", course.body); + let course_id = common::id_of(&course.body); + enroll(&app, &manager, &course_id, &ali_id).await; + let session = create_session(&app, &manager, &course_id, soon()).await; + // A roll-call row exists before the freeze, so the delete route reaches the + // guard rather than a 404 for a missing row. + let marked = send( + &app, + "POST", + &format!("/sessions/{session}/attendance"), + Some(&manager), + Some(json!({ "status": "present", "user_id": ali_id })), + ) + .await; + assert_eq!(marked.status, StatusCode::OK, "{}", marked.body); + + let archived = send( + &app, + "POST", + &format!("/terms/{term_id}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(archived.status, StatusCode::OK, "{}", archived.body); + + // Every write on the session and its roll call refuses with the coded 409. + let writes: [(&str, String, Option); 4] = [ + ( + "PATCH", + format!("/sessions/{session}"), + Some(json!({ "topic": "yeni" })), + ), + ( + "POST", + format!("/sessions/{session}/attendance"), + Some(json!({ "status": "absent", "user_id": ali_id })), + ), + ( + "DELETE", + format!("/sessions/{session}/attendance/{ali_id}"), + None, + ), + ("DELETE", format!("/sessions/{session}"), None), + ]; + for (method, uri, body) in writes { + let res = send(&app, method, &uri, Some(&manager), body).await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "{method} {uri}: {}", + res.body + ); + assert_eq!(res.body["code"], "term_archived", "{method} {uri}"); + } + + // Reads stay open — a past year is read-only, not hidden. + for uri in [ + format!("/sessions/{session}"), + format!("/sessions/{session}/attendance"), + ] { + let res = send(&app, "GET", &uri, Some(&manager), None).await; + assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body); + } + + // Re-opening the year thaws the writes again. + let reopened = send( + &app, + "POST", + &format!("/terms/{term_id}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(reopened.status, StatusCode::OK, "{}", reopened.body); + let res = send( + &app, + "PATCH", + &format!("/sessions/{session}"), + Some(&manager), + Some(json!({ "topic": "yeni" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} diff --git a/tests/regress_classes.rs b/tests/regress_classes.rs index a268bec..5e29c32 100644 --- a/tests/regress_classes.rs +++ b/tests/regress_classes.rs @@ -1818,3 +1818,188 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() { "…and its seat must come back with it" ); } + +/// #22. A class on an archived term is read-only: every write axis it has — +/// the class itself, its roster, its attachments and the blueprint pump — +/// answers the coded 409, while every read stays open. The term the *course* +/// sits on holds the same bar from the other side, and re-opening the year +/// thaws all of it. +#[tokio::test] +async fn an_archived_term_freezes_every_class_write_and_no_read() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "arch_manager", "manager").await; + let student = login_as(&app, &db, "arch_student", "student").await; + let other = login_as(&app, &db, "arch_other", "student").await; + let student_id = me_id(&app, &student).await; + let other_id = me_id(&app, &other).await; + + let term = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2024", + "starts_at": 1_700_000_000_000_i64, + "ends_at": 1_710_000_000_000_i64, + })), + ) + .await; + assert_eq!(term.status, StatusCode::CREATED); + let term_id = common::id_of(&term.body); + + // A course on that same year, and one on no year at all — the second is + // what proves a refusal came from the *class's* side. + let dated = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "algebra", "term_id": term_id })), + ) + .await; + assert_eq!(dated.status, StatusCode::CREATED); + let dated = common::id_of(&dated.body); + let open_course = create_course(&app, &manager, "geometry").await; + + let class = create_class( + &app, + &manager, + json!({ "name": "9-A", "grade": "9", "term_id": term_id }), + ) + .await; + let class = common::id_of(&class.body); + + // Everything the frozen state must already hold: an attachment, a member, + // and a blueprint at this grade for the pump to try. + let attached = send( + &app, + "POST", + &format!("/classes/{class}/courses"), + Some(&manager), + Some(json!({ "course_id": dated })), + ) + .await; + assert_eq!(attached.status, StatusCode::CREATED, "attach while open"); + let joined = send( + &app, + "POST", + &format!("/classes/{class}/members"), + Some(&manager), + Some(json!({ "user_id": student_id })), + ) + .await; + assert_eq!(joined.status, StatusCode::CREATED, "member while open"); + let blueprint = send( + &app, + "POST", + "/classes/blueprints", + Some(&manager), + Some(json!({ "grade": "9", "course_ids": [dated] })), + ) + .await; + assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint"); + + let archived = send( + &app, + "POST", + &format!("/terms/{term_id}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(archived.status, StatusCode::OK); + + // One refusal per write route, each 409 with the machine code — never a + // bare 409, which a client cannot tell from a capacity conflict. + let writes: Vec<(&str, String, Option)> = vec![ + ( + "PATCH", + format!("/classes/{class}"), + Some(json!({ "name": "9-B" })), + ), + ( + "POST", + format!("/classes/{class}/members"), + Some(json!({ "user_id": other_id })), + ), + ( + "DELETE", + format!("/classes/{class}/members/{student_id}"), + None, + ), + ( + "POST", + format!("/classes/{class}/courses"), + // An *open* course: the class's own term is the refusal. + Some(json!({ "course_id": open_course })), + ), + ("DELETE", format!("/classes/{class}/courses/{dated}"), None), + ("POST", format!("/classes/{class}/blueprint"), None), + ("DELETE", format!("/classes/{class}"), None), + ]; + for (method, uri, body) in writes { + let res = send(&app, method, &uri, Some(&manager), body).await; + assert_eq!(res.status, StatusCode::CONFLICT, "{method} {uri}"); + assert_eq!(res.body["code"], "term_archived", "{method} {uri} code"); + } + + // Reads are untouched — a past year is read-only, not hidden. + for uri in [ + format!("/classes/{class}"), + format!("/classes/{class}/members"), + format!("/classes/{class}/courses"), + ] { + let res = send(&app, "GET", &uri, Some(&manager), None).await; + assert_eq!(res.status, StatusCode::OK, "GET {uri}"); + } + let members = send( + &app, + "GET", + &format!("/classes/{class}/members"), + Some(&manager), + None, + ) + .await; + assert_eq!(total(&members.body), 1, "no write landed"); + + // The other side of the attach: an open class may not take a course whose + // own term is archived. + let open_class = create_class(&app, &manager, json!({ "name": "10-A" })).await; + let open_class = common::id_of(&open_class.body); + let cross = send( + &app, + "POST", + &format!("/classes/{open_class}/courses"), + Some(&manager), + Some(json!({ "course_id": dated })), + ) + .await; + assert_eq!( + cross.status, + StatusCode::CONFLICT, + "open class, past course" + ); + assert_eq!(cross.body["code"], "term_archived"); + + // Re-opening the year thaws the whole set; one write is enough to show it. + let reopened = send( + &app, + "POST", + &format!("/terms/{term_id}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(reopened.status, StatusCode::OK); + let patched = send( + &app, + "PATCH", + &format!("/classes/{class}"), + Some(&manager), + Some(json!({ "name": "9-B" })), + ) + .await; + assert_eq!(patched.status, StatusCode::OK, "thawed"); + assert_eq!(patched.body["name"], "9-B"); +} diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index 1ef424e..09b19e8 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -43,6 +43,10 @@ //! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would //! drift out of the real one silently. +mod common; + +use axum::http::StatusCode; +use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; use hezarfen_backend::database::{self, Database}; use hezarfen_backend::domain::course::{ Course, CourseDescription, CourseId, CourseKind, CourseTitle, @@ -58,6 +62,7 @@ use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName use hezarfen_backend::domain::timestamp::Timestamp; use hezarfen_backend::domain::user::UserId; use hezarfen_backend::error::AppError; +use serde_json::json; use tokio::task::JoinHandle; fn teacher() -> UserId { @@ -357,3 +362,173 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { "a refused upload left a row naming a note that is gone" ); } + +/// #22, the course's own children over HTTP: a course in an archived term is a +/// past year, so its subjects and course notes (and note files) refuse every +/// write with the coded 409 while all their reads keep answering. The guard +/// sits in each write handler after its authorization check — 403 before 409 — +/// on the `course` the shared loaders already hand back, never inside those +/// loaders, which the read handlers share. +#[tokio::test] +async fn an_archived_term_freezes_a_course_s_subjects_and_notes() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "arch_child_manager", "manager").await; + + let term = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2022", + "starts_at": 1_500_000_000_000_i64, + "ends_at": 1_510_000_000_000_i64, + })), + ) + .await; + assert_eq!(term.status, StatusCode::CREATED, "{}", term.body); + let term_id = id_of(&term.body); + + let course = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "Fizik", "term_id": term_id })), + ) + .await; + assert_eq!(course.status, StatusCode::CREATED, "{}", course.body); + let course_id = id_of(&course.body); + + let subject = send( + &app, + "POST", + &format!("/courses/{course_id}/subjects"), + Some(&manager), + Some(json!({ "name": "Optik" })), + ) + .await; + assert_eq!(subject.status, StatusCode::CREATED, "{}", subject.body); + let subject_id = id_of(&subject.body); + + let note = send( + &app, + "POST", + "/course-notes", + Some(&manager), + Some(json!({ "course": course_id, "title": "Ders 1" })), + ) + .await; + assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); + let note_id = id_of(¬e.body); + + let file = upload_course_note_file( + &app, + &manager, + ¬e_id, + "plan.pdf", + "application/pdf", + b"pdf bytes", + ) + .await; + assert_eq!(file.status, StatusCode::CREATED, "{}", file.body); + let file_id = id_of(&file.body); + + let archived = send( + &app, + "POST", + &format!("/terms/{term_id}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(archived.status, StatusCode::OK, "{}", archived.body); + + let writes: [(&str, String, Option); 5] = [ + ( + "PATCH", + format!("/subjects/{subject_id}"), + Some(json!({ "name": "Akustik" })), + ), + ("DELETE", format!("/subjects/{subject_id}"), None), + ( + "POST", + "/course-notes".to_string(), + Some(json!({ "course": course_id, "title": "Ders 2" })), + ), + ( + "PATCH", + format!("/course-notes/{note_id}"), + Some(json!({ "title": "Ders 1a" })), + ), + ( + "DELETE", + format!("/course-notes/{note_id}/files/{file_id}"), + None, + ), + ]; + for (method, uri, body) in writes { + let res = send(&app, method, &uri, Some(&manager), body).await; + assert_eq!( + res.status, + StatusCode::CONFLICT, + "{method} {uri}: {}", + res.body + ); + assert_eq!(res.body["code"], "term_archived", "{method} {uri}"); + } + // The multipart upload refuses too, and before its body is buffered. + let refused = upload_course_note_file( + &app, + &manager, + ¬e_id, + "more.pdf", + "application/pdf", + b"more bytes", + ) + .await; + assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.body); + assert_eq!(refused.body["code"], "term_archived"); + // Deleting the note itself is a write as well (it cascades its files). + let res = send( + &app, + "DELETE", + &format!("/course-notes/{note_id}"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); + assert_eq!(res.body["code"], "term_archived"); + + // Reads all stay open. + for uri in [ + format!("/subjects/{subject_id}"), + format!("/course-notes/{note_id}"), + format!("/course-notes/{note_id}/files"), + format!("/course-notes/{note_id}/files/{file_id}"), + ] { + let res = send(&app, "GET", &uri, Some(&manager), None).await; + assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body); + } + + // Re-opening the year thaws them. + let reopened = send( + &app, + "POST", + &format!("/terms/{term_id}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(reopened.status, StatusCode::OK, "{}", reopened.body); + let res = send( + &app, + "PATCH", + &format!("/subjects/{subject_id}"), + Some(&manager), + Some(json!({ "name": "Akustik" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} diff --git a/tests/regress_course_delete.rs b/tests/regress_course_delete.rs index cec189a..b909eca 100644 --- a/tests/regress_course_delete.rs +++ b/tests/regress_course_delete.rs @@ -261,3 +261,179 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { "a sitting outlived the course it was sat under" ); } + +/// An archived term freezes the courses hanging off it: every write route under +/// `/courses/{id}` answers `409 term_archived`, while every read stays open — +/// past years are a read-only archive, not a hidden one. The guard sits *after* +/// each handler's authz check, so a caller who may not write still gets its +/// `403` rather than being told about the term. +#[tokio::test] +async fn an_archived_terms_courses_take_no_writes_but_still_read() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "arsiv_ders_mudur", "manager").await; + let student = login_as(&app, &db, "arsiv_ders_ogrenci", "student").await; + let student_id = me_id(&app, &student).await; + let teacher = login_as(&app, &db, "arsiv_ders_ogretmen", "teacher").await; + let teacher_id = me_id(&app, &teacher).await; + + let res = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2019 güz", + "starts_at": 1_780_000_000_000_i64, + "ends_at": 1_790_000_000_000_i64, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let term = id_of(&res.body); + + let res = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "Coğrafya", "term_id": term })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = id_of(&res.body); + // Both the roster and an assigned teacher have to exist *before* the + // archive: the routes that remove them are themselves frozen. + enroll(&app, &manager, &course, &student_id).await; + let subject = create_subject(&app, &manager, &course, "Iklim").await; + let res = send( + &app, + "POST", + &format!("/courses/{course}/teachers"), + Some(&manager), + Some(json!({ "user_id": teacher_id })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let res = send( + &app, + "POST", + &format!("/terms/{term}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let due = 1_900_000_000_000_i64; + let writes: Vec<(&str, String, Option)> = vec![ + ( + "PATCH", + format!("/courses/{course}"), + Some(json!({ "title": "Yeni" })), + ), + ("DELETE", format!("/courses/{course}"), None), + ( + "POST", + format!("/courses/{course}/teachers"), + Some(json!({ "user_id": teacher_id })), + ), + ( + "DELETE", + format!("/courses/{course}/teachers/{teacher_id}"), + None, + ), + ( + "POST", + format!("/courses/{course}/enrollments"), + Some(json!({ "user_id": student_id })), + ), + ( + "DELETE", + format!("/courses/{course}/enrollments/{student_id}"), + None, + ), + ( + "POST", + format!("/courses/{course}/exams"), + Some(json!({ "title": "Vize", "kind": "midterm" })), + ), + ( + "POST", + format!("/courses/{course}/subjects"), + Some(json!({ "name": "Erozyon" })), + ), + ( + "POST", + format!("/courses/{course}/homework"), + Some(json!({ "title": "Ödev", "subject_id": subject, "due_at": due })), + ), + ( + "POST", + format!("/courses/{course}/sessions"), + Some(json!({ "starts_at": due })), + ), + ]; + for (method, uri, body) in &writes { + let res = send(&app, method, uri, Some(&manager), body.clone()).await; + assert_eq!( + (res.status, res.body["code"].clone()), + (StatusCode::CONFLICT, json!("term_archived")), + "{method} {uri} must be frozen by the archive: {}", + res.body + ); + } + + for uri in [ + format!("/courses/{course}"), + format!("/courses/{course}/enrollments"), + format!("/courses/{course}/exams"), + format!("/courses/{course}/subjects"), + format!("/courses/{course}/homework"), + format!("/courses/{course}/sessions"), + ] { + let res = send(&app, "GET", &uri, Some(&manager), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "GET {uri} must stay readable: {}", + res.body + ); + } + + // A student who cannot write here is still told *that* first — the 403 has + // to precede the 409, or the archive leaks course structure to outsiders. + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&student), + Some(json!({ "name": "Sızıntı" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + let res = send( + &app, + "POST", + &format!("/terms/{term}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "POST", + &format!("/courses/{course}/subjects"), + Some(&manager), + Some(json!({ "name": "Erozyon" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::CREATED, + "the unarchive must give the writes back: {}", + res.body + ); +} diff --git a/tests/regress_exam_delete.rs b/tests/regress_exam_delete.rs index 04a658e..5495cee 100644 --- a/tests/regress_exam_delete.rs +++ b/tests/regress_exam_delete.rs @@ -126,3 +126,283 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() { } assert_eq!(sittings, 0, "a sitting outlived its exam"); } + +/// An archived term freezes the exams hanging off its courses: all nineteen +/// write routes under `/exams/{id}` answer `409 term_archived` — authoring, +/// grading, the images on both sides, and the sitting itself — while every +/// read stays open. Past years are a read-only archive, not a hidden one. +/// +/// The sitting is deliberately *live* when the archive lands: a student mid-exam +/// is the case where a freeze can do real damage, and every one of their write +/// routes has to refuse with the coded 409 rather than a 500 or a silent write. +/// The guards sit after each handler's authz, so a caller who may not write +/// still gets its `403` (asserted below) — the archive never leaks exam +/// structure. +/// +/// Not covered here: the exam-room WebSocket. Its door (`GET +/// /exams/{id}/attempt/ws`) and its `finish` frame carry their own guards, but +/// this binary drives the router through `oneshot` and cannot upgrade — the +/// socket needs the real-TCP harness in `tests/e2e.rs`. The REST +/// `POST /exams/{id}/attempt/answers` below does cover the shared +/// `save_answer_in` funnel that every WS `answer` frame also goes through. +#[tokio::test] +async fn an_archived_terms_exams_take_no_writes_but_still_read() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "arsiv_sinav_mudur", "manager").await; + let student = login_as(&app, &db, "arsiv_sinav_ogrenci", "student").await; + let student_id = me_id(&app, &student).await; + + let res = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2018 bahar", + "starts_at": 1_780_000_000_000_i64, + "ends_at": 1_790_000_000_000_i64, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let term = id_of(&res.body); + + let res = send( + &app, + "POST", + "/courses", + Some(&manager), + Some(json!({ "title": "Tarih", "term_id": term })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let course = id_of(&res.body); + enroll(&app, &manager, &course, &student_id).await; + let subject = common::create_subject(&app, &manager, &course, "Kronoloji").await; + + // `open` mode so the sitting is real: the attempt below has to be running + // when the archive lands. + let res = create_exam_with( + &app, + &manager, + &course, + json!({ "title": "Vize", "kind": "midterm", "mode": "open" }), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let exam = id_of(&res.body); + + // One choice question — it supplies the qid every question route needs and + // the choice id the option-picture routes need. + let res = send( + &app, + "POST", + &format!("/exams/{exam}/questions"), + Some(&manager), + Some(json!({ "subject_id": subject, "text": "Ne zaman?", "kind": "choice", "points": 10, + "choices": [{"id": "c0", "text": "1453"}, {"id": "c1", "text": "1071"}], "correct": "c0" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let question = id_of(&res.body); + let choice = res.body["choices"][0]["id"] + .as_str() + .expect("choice id") + .to_string(); + + let res = send( + &app, + "POST", + &format!("/exams/{exam}/attempt"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + + let res = send( + &app, + "POST", + &format!("/terms/{term}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // The thirteen JSON write routes: exam, results, and the question authoring + // set. `from-bank` takes an id that need not exist — the freeze is judged + // before the bank lookup, and a 404 here would be the bug. + let staff_writes: Vec<(&str, String, Option)> = vec![ + ( + "PATCH", + format!("/exams/{exam}"), + Some(json!({ "title": "Final" })), + ), + ("DELETE", format!("/exams/{exam}"), None), + ( + "POST", + format!("/exams/{exam}/results"), + Some(json!({ "user_id": student_id, "mark": 80 })), + ), + ( + "DELETE", + format!("/exams/{exam}/results/{student_id}"), + None, + ), + ( + "POST", + format!("/exams/{exam}/questions"), + Some(json!({ "subject_id": subject, "text": "Kim?", "kind": "text", "points": 5 })), + ), + ( + "PATCH", + format!("/exams/{exam}/questions/{question}"), + Some(json!({ "text": "Nerede?" })), + ), + ( + "DELETE", + format!("/exams/{exam}/questions/{question}"), + None, + ), + ( + "POST", + format!("/exams/{exam}/questions/from-bank/yok"), + Some(json!({ "subject_id": subject })), + ), + ( + "POST", + format!("/exams/{exam}/questions/{question}/refresh-from-bank"), + None, + ), + ( + "POST", + format!("/exams/{exam}/questions/{question}/to-bank"), + None, + ), + ( + "DELETE", + format!("/exams/{exam}/questions/{question}/image"), + None, + ), + ( + "DELETE", + format!("/exams/{exam}/questions/{question}/choices/{choice}/image"), + None, + ), + ]; + for (method, uri, body) in &staff_writes { + let res = send(&app, method, uri, Some(&manager), body.clone()).await; + assert_eq!( + (res.status, res.body["code"].clone()), + (StatusCode::CONFLICT, json!("term_archived")), + "{method} {uri} must be frozen by the archive: {}", + res.body + ); + } + + // The student's own writes — the live sitting. `save_answer` is the REST + // face of `save_answer_in`, the funnel the WebSocket's `answer` shares. + let sit_writes: Vec<(&str, String, Option)> = vec![ + ("POST", format!("/exams/{exam}/attempt"), None), + ( + "POST", + format!("/exams/{exam}/attempt/answers"), + Some(json!({ "question_id": question, "selected": choice })), + ), + ( + "DELETE", + format!("/exams/{exam}/attempt/answers/{question}/image"), + None, + ), + ("POST", format!("/exams/{exam}/attempt/finish"), None), + ]; + for (method, uri, body) in &sit_writes { + let res = send(&app, method, uri, Some(&student), body.clone()).await; + assert_eq!( + (res.status, res.body["code"].clone()), + (StatusCode::CONFLICT, json!("term_archived")), + "{method} {uri} must be frozen by the archive: {}", + res.body + ); + } + + // The three multipart uploads. The guard runs *before* the body is read, so + // these never touch the blob store. + let uploads = [ + ( + format!("/exams/{exam}/questions/{question}/image"), + manager.clone(), + ), + ( + format!("/exams/{exam}/questions/{question}/choices/{choice}/image"), + manager.clone(), + ), + ( + format!("/exams/{exam}/attempt/answers/{question}/image"), + student.clone(), + ), + ]; + for (uri, cookie) in &uploads { + let res = common::upload_file_at(&app, cookie, uri, "a.png", "image/png", b"png").await; + assert_eq!( + (res.status, res.body["code"].clone()), + (StatusCode::CONFLICT, json!("term_archived")), + "POST {uri} must be frozen by the archive: {}", + res.body + ); + } + + // Reads stay open on both sides of the desk. + for (uri, cookie) in [ + (format!("/exams/{exam}"), &manager), + (format!("/exams/{exam}/questions"), &manager), + (format!("/exams/{exam}/results"), &manager), + ( + format!("/exams/{exam}/attempts/{student_id}/answers"), + &manager, + ), + (format!("/exams/{exam}/attempt"), &student), + (format!("/exams/{exam}/attempt/questions"), &student), + ] { + let res = send(&app, "GET", &uri, Some(cookie), None).await; + assert_eq!( + res.status, + StatusCode::OK, + "GET {uri} must stay readable: {}", + res.body + ); + } + + // A caller who may not write is still told *that* first: the 403 precedes + // the 409, or the archive leaks the exam's structure to outsiders. + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}"), + Some(&student), + Some(json!({ "title": "Sızıntı" })), + ) + .await; + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); + + // Unarchiving thaws them again. + let res = send( + &app, + "POST", + &format!("/terms/{term}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}"), + Some(&manager), + Some(json!({ "title": "Final" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); +} diff --git a/tests/regress_homework_orphans.rs b/tests/regress_homework_orphans.rs index 0560a2f..32d167f 100644 --- a/tests/regress_homework_orphans.rs +++ b/tests/regress_homework_orphans.rs @@ -22,8 +22,8 @@ mod common; use axum::http::StatusCode; use common::{ - app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll, - id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, + Res, app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll, + id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at, }; use hezarfen_backend::database::Database; use serde_json::{Value, json}; @@ -742,3 +742,265 @@ async fn a_file_add_racing_a_file_delete_never_500s() { "the seat counter drifted from the rows" ); } + +/// An archived term freezes every homework write under its courses (#22): the +/// teacher's edit/delete/grade/un-grade and the student's submit, withdraw, +/// file add and file remove all answer `409 term_archived`, while the reads +/// stay open — a past year is browsable, not editable. The student wall sits +/// *after* the audience check, so a student the homework never named still +/// gets the 404 it always did: the archive must not turn a subset assignment +/// into a "this exists" signal. +#[tokio::test] +async fn an_archived_term_freezes_every_homework_write() { + let (app, db) = app_and_db().await; + let manager = login_as(&app, &db, "mudur_arsiv", "manager").await; + let teacher = login_as(&app, &db, "ogretmen_arsiv", "teacher").await; + + let res = send( + &app, + "POST", + "/terms", + Some(&manager), + Some(json!({ + "name": "2025 Guz", + "starts_at": 1_600_000_000_000_i64, + "ends_at": 1_610_000_000_000_i64, + })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create term"); + let term = id_of(&res.body); + + let res = send( + &app, + "POST", + "/courses", + Some(&teacher), + Some(json!({ "title": "tarih", "term_id": term })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create course in term"); + let course = id_of(&res.body); + let subject = create_subject(&app, &teacher, &course, "konu").await; + + let student = login_as(&app, &db, "ogrenci_arsiv", "student").await; + let student_id = me_id(&app, &student).await; + let outsider = login_as(&app, &db, "ogrenci_disarida", "student").await; + let outsider_id = me_id(&app, &outsider).await; + enroll(&app, &teacher, &course, &student_id).await; + enroll(&app, &teacher, &course, &outsider_id).await; + + // A subset assignment: the outsider is enrolled but not named, so their + // 404 is the one the archive must leave alone. + let res = create_homework_with( + &app, + &teacher, + &course, + json!({ + "title": "odev", + "subject_id": subject, + "due_at": far_future(), + "assigned": [student_id], + }), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "create homework"); + let hw = id_of(&res.body); + + // Everything the student owns exists *before* the archive. + let res = send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&student), + Some(json!({ "text": "hazir" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "submit before archiving"); + let res = upload_file_at( + &app, + &student, + &format!("/homework/{hw}/submission/files"), + "odev.pdf", + "application/pdf", + b"homework bytes", + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "upload before archiving"); + let file = id_of(&res.body); + + let res = send( + &app, + "POST", + &format!("/terms/{term}/archive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "archive the term"); + + let frozen = |res: Res, what: &str| { + assert_eq!(res.status, StatusCode::CONFLICT, "{what} after archiving"); + assert_eq!( + res.body["code"], "term_archived", + "{what} carries the machine-readable code: {:?}", + res.body + ); + }; + + frozen( + send( + &app, + "PATCH", + &format!("/homework/{hw}"), + Some(&teacher), + Some(json!({ "title": "yeni" })), + ) + .await, + "PATCH /homework/{id}", + ); + frozen( + send( + &app, + "POST", + &format!("/homework/{hw}/results"), + Some(&teacher), + Some(json!({ "user": student_id, "status": "done" })), + ) + .await, + "POST /homework/{id}/results", + ); + frozen( + send( + &app, + "DELETE", + &format!("/homework/{hw}/results/{student_id}"), + Some(&teacher), + None, + ) + .await, + "DELETE /homework/{id}/results/{user}", + ); + frozen( + send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&student), + Some(json!({ "text": "tekrar" })), + ) + .await, + "POST /homework/{id}/submission", + ); + frozen( + upload_file_at( + &app, + &student, + &format!("/homework/{hw}/submission/files"), + "yeni.pdf", + "application/pdf", + b"more bytes", + ) + .await, + "POST /homework/{id}/submission/files", + ); + frozen( + send( + &app, + "DELETE", + &format!("/homework/{hw}/submission/files/{file}"), + Some(&student), + None, + ) + .await, + "DELETE /homework/{id}/submission/files/{fid}", + ); + frozen( + send( + &app, + "DELETE", + &format!("/homework/{hw}/submission"), + Some(&student), + None, + ) + .await, + "DELETE /homework/{id}/submission", + ); + // The delete goes last: the seven refusals above must have left the rows + // it needs standing. + frozen( + send( + &app, + "DELETE", + &format!("/homework/{hw}"), + Some(&teacher), + None, + ) + .await, + "DELETE /homework/{id}", + ); + + // The past year still reads: the homework and the student's own file. + let res = send( + &app, + "GET", + &format!("/homework/{hw}"), + Some(&student), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "GET /homework/{{id}} archived"); + let (status, _, bytes) = send_raw( + &app, + "GET", + &format!("/homework/{hw}/submission/files/{file}"), + Some(&student), + None, + Vec::new(), + ) + .await; + assert_eq!(status, StatusCode::OK, "download own file while archived"); + assert_eq!(bytes, b"homework bytes", "the stored bytes come back"); + + // Not in the audience: still a 404, never the 409 that would admit the + // homework exists. + let res = send( + &app, + "POST", + &format!("/homework/{hw}/submission"), + Some(&outsider), + Some(json!({ "text": "benim mi" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::NOT_FOUND, + "an unnamed student sees no homework, archived or not: {:?}", + res.body + ); + + // Re-opening the year hands the writes back. + let res = send( + &app, + "POST", + &format!("/terms/{term}/unarchive"), + Some(&manager), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "unarchive the term"); + let res = send( + &app, + "POST", + &format!("/homework/{hw}/results"), + Some(&teacher), + Some(json!({ "user": student_id, "status": "done" })), + ) + .await; + assert_eq!( + res.status, + StatusCode::OK, + "grading works again: {:?}", + res.body + ); +} diff --git a/tests/regress_profile.rs b/tests/regress_profile.rs index 4d9c606..0f029ff 100644 --- a/tests/regress_profile.rs +++ b/tests/regress_profile.rs @@ -254,8 +254,10 @@ async fn display_name_falls_back_to_the_legal_name_then_null() { /// their legal name by every list that embeds a person. #[tokio::test] async fn embedded_person_refs_show_the_chosen_name_like_the_profile() { - let (app, _db) = app_and_db().await; - let ali = login(&app, "ali").await; + let (app, db) = app_and_db().await; + // The sender is staff: messaging is upward-only below teacher, and this + // test needs a send that lands, not the role rule. + let ali = login_as(&app, &db, "ali", "teacher").await; let ayse = login(&app, "ayse").await; let ayse_id = me_id(&app, &ayse).await; diff --git a/tests/spec_bounds.rs b/tests/spec_bounds.rs index d248a3d..6b07f69 100644 --- a/tests/spec_bounds.rs +++ b/tests/spec_bounds.rs @@ -1206,6 +1206,7 @@ async fn the_class_refusal_codes_stay_published() { "class_at_course_ceiling", "class_roster_too_large", "course_full", + "term_archived", ]; let members = [ "duplicate", @@ -1213,7 +1214,12 @@ async fn the_class_refusal_codes_stay_published() { "class_course_list_too_large", "course_full", "linked_course_missing", + "term_archived", ]; + // `term_archived` refuses the whole request up front (the class's or the + // course's term is archived), so no pump ever *skips* an item for it — + // it belongs on the two routes' 409s, never in `SkipResponse.reason`. + let whole_request = ["term_archived"]; for (path, expected) in [ ("/classes/{id}/courses", courses.as_slice()), @@ -1251,6 +1257,7 @@ async fn the_class_refusal_codes_stay_published() { .chain(courses.iter()) .chain(members.iter()) .copied() + .filter(|code| !whole_request.contains(code)) .collect(); assert_eq!( sorted(quoted(reason)),