Archive academic terms
Browse files at this commitc4232e6ac735cc5bc7a12ee5fb64a9778526d290Parent: 1d423c0- feat
- archive academic terms
- an archived year is read-only
27 changed files +2107 -54
- README.md +30 -1
- src/domain/class_group.rs +10 -0
- src/domain/course.rs +10 -0
- src/domain/term.rs +75 -0
- src/lib.rs +2 -2
- src/migration_sql.rs +4 -0
- src/web/classes.rs +35 -7
- src/web/course_notes.rs +10 -1
- src/web/courses.rs +21 -4
- src/web/exam_ws.rs +17 -7
- src/web/exams/attempts.rs +13 -4
- src/web/exams/images.rs +15 -7
- src/web/exams/mod.rs +9 -3
- src/web/exams/questions.rs +12 -5
- src/web/homework.rs +33 -6
- src/web/sessions.rs +8 -0
- src/web/subjects.rs +4 -1
- src/web/terms.rs +77 -4
- tests/e2e.rs +367 -0
- tests/partial_patch_terms.rs +147 -0
- tests/regress_attendance.rs +121 -0
- tests/regress_classes.rs +185 -0
- tests/regress_course_child_orphans.rs +175 -0
- tests/regress_course_delete.rs +176 -0
- tests/regress_exam_delete.rs +280 -0
- tests/regress_homework_orphans.rs +264 -2
- tests/spec_bounds.rs +7 -0
README.mdmodified+30 -1
| @@ -1085,6 +1085,8 @@ window filtering, before paging; negative values are a `400` naming the field. | ||
| 1085 | 1085 | | GET | `/terms/{id}` | student | Fetch a single term by id. | |
| 1086 | 1086 | | PATCH | `/terms/{id}` | manager | Update a term. Requires manager+. Omitted fields keep their value; the merged range must stay ordered. | |
| 1087 | 1087 | | 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. | |
| 1088 | +| 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. | | |
| 1089 | +| POST | `/terms/{id}/unarchive` | manager | Re-open an archived term. Requires manager+. Idempotent the same way as archiving: an already-open term answers `200`. | | |
| 1088 | 1090 | | GET | `/time` | no | Server clock: `{now}` UTC unix-millis, for a frontend to sync against. | |
| 1089 | 1091 | | 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. | |
| 1090 | 1092 | | 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. | |
| @@ -1846,6 +1848,29 @@ under them. Term dates may lie in the past, | ||
| 1846 | 1848 | deliberately: a school adopting the app mid-year backfills its calendar — |
| 1847 | 1849 | unlike exam/lesson/event times, which reject backdating. |
| 1848 | 1850 | |
| 1851 | +A finished year is closed with `POST /terms/{id}/archive` and reopened with | |
| 1852 | +`POST /terms/{id}/unarchive` (manager+). Both are idempotent: archiving an | |
| 1853 | +already-archived term answers `200` with the original `archived_at` stamp, and | |
| 1854 | +unarchiving an open one answers `200` as well. While a term is archived it is | |
| 1855 | +read-only — `PATCH`/`DELETE /terms/{id}` are refused, a new course or class may | |
| 1856 | +not link to it, and every write to a course or class already on it, or to | |
| 1857 | +anything hanging off them, is refused too: enrollment, teacher assignment, | |
| 1858 | +class membership and homeroom, class↔course attach/detach and blueprint apply, | |
| 1859 | +sessions and roll call, subjects, exams with their questions, images, attempts | |
| 1860 | +and answers (the exam-room WebSocket door and its `finish` frame included), | |
| 1861 | +marks and grading, homework and submissions, course notes and files. Each | |
| 1862 | +refusal is a `409` with `code: "term_archived"` and the message "this term is | |
| 1863 | +archived — past years are read-only". Reads stay open throughout, so a past | |
| 1864 | +year is still browsable, and unarchiving restores writes. Deliberately outside | |
| 1865 | +the freeze: personal notes, messages, pomodoro, meals, payments, boards, | |
| 1866 | +appointments, the chatbot, the question pool/bank, events (an event only aims | |
| 1867 | +an audience at a course), class blueprint templates, and the staff work log. | |
| 1868 | +Also exempt are the system integrity sweeps — role demotion stripping homeroom | |
| 1869 | +teachers and course teacher assignments, subject delete clearing bank-question | |
| 1870 | +links — which keep the store consistent rather than edit a past year. The | |
| 1871 | +guard is a pre-flight read of the term row, so an archive and a write landing | |
| 1872 | +in the same instant is an accepted race; see `## Concurrency model`. | |
| 1873 | + | |
| 1849 | 1874 | What stays fixed is deliberate too: the four roles, the `0`–`100` mark scale, |
| 1850 | 1875 | validation bounds, and the UTC time policy are invariants, not preferences |
| 1851 | 1876 | (rename role labels in the frontend if a school says "principal" instead of |
| @@ -4192,7 +4217,7 @@ database itself decides the winner. Three tiers: | ||
| 4192 | 4217 | per (plan, student) — the seat and the row |
| 4193 | 4218 | are claimed in one transaction (`cap::claim_and_create`), so a duplicate |
| 4194 | 4219 | `CREATE` rolls its own seat back instead of costing a stranger their place. |
| 4195 | -3. **Two accepted races**, reviewed and deliberately left open: | |
| 4220 | +3. **Three accepted races**, reviewed and deliberately left open: | |
| 4196 | 4221 | - *Attempt-seq late save* — an exam-room socket writes into the sitting it |
| 4197 | 4222 | joined with, a choice made before any lock is taken, so a save racing a |
| 4198 | 4223 | retake can stamp an answer onto the just-terminal previous sitting. |
| @@ -4201,6 +4226,10 @@ database itself decides the winner. Three tiers: | ||
| 4201 | 4226 | - *Approved-overlap* — two approvals landing in the same instant can |
| 4202 | 4227 | double-book a teacher. Damage: one overlapping half-hour, visible to both |
| 4203 | 4228 | parties, fixable by cancelling either side. |
| 4229 | + - *Archive-vs-write* — the archived-term guard is a pre-flight read on the | |
| 4230 | + term row, so an archive committing in the same instant as a write already | |
| 4231 | + in flight lets that one write through. Damage: one write on a | |
| 4232 | + just-archived term; nothing corrupts, and every later write is refused. | |
| 4204 | 4233 | |
| 4205 | 4234 | In-process locks remain, and they are a *second* line, never the guarantee: |
| 4206 | 4235 | `PRESENCE_LOCK` guards in-process socket state (there is no row to conditional |
src/domain/class_group.rsmodified+10 -0
| @@ -125,6 +125,16 @@ impl ClassGroup { | ||
| 125 | 125 | self.term.as_ref() |
| 126 | 126 | } |
| 127 | 127 | |
| 128 | + /// Refuse the write when this class's term is archived — a pre-flight guard, | |
| 129 | + /// accepted race (see README concurrency model): a term archived after this | |
| 130 | + /// read still lets the write through. | |
| 131 | + pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { | |
| 132 | + match self.get_term() { | |
| 133 | + None => Ok(()), | |
| 134 | + Some(term) => term::Term::require_open(term, db).await, | |
| 135 | + } | |
| 136 | + } | |
| 137 | + | |
| 128 | 138 | /// The homeroom teacher (sınıf öğretmeni), if one is assigned. |
| 129 | 139 | pub fn get_teacher(&self) -> Option<&UserId> { |
| 130 | 140 | self.teacher.as_ref() |
src/domain/course.rsmodified+10 -0
| @@ -144,6 +144,16 @@ impl Course { | ||
| 144 | 144 | self.term.as_ref() |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | + /// Refuse the write when this course's term is archived — a pre-flight guard, | |
| 148 | + /// accepted race (see README concurrency model): a term archived after this | |
| 149 | + /// read still lets the write through. | |
| 150 | + pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { | |
| 151 | + match self.get_term() { | |
| 152 | + None => Ok(()), | |
| 153 | + Some(term) => term::Term::require_open(term, db).await, | |
| 154 | + } | |
| 155 | + } | |
| 156 | + | |
| 147 | 157 | /// The seat cap enforced at enroll time; `None` = unlimited. |
| 148 | 158 | pub fn get_capacity(&self) -> Option<i64> { |
| 149 | 159 | self.capacity |
src/domain/term.rsmodified+75 -0
| @@ -56,6 +56,15 @@ pub fn gone_error() -> AppError { | ||
| 56 | 56 | }) |
| 57 | 57 | } |
| 58 | 58 | |
| 59 | +/// The refusal every write against archived structure gets, coded so a client | |
| 60 | +/// can tell it from the other 409s on the same route. | |
| 61 | +pub fn archived_error() -> AppError { | |
| 62 | + AppError::ConflictCoded { | |
| 63 | + code: "term_archived", | |
| 64 | + message: "this term is archived — past years are read-only".into(), | |
| 65 | + } | |
| 66 | +} | |
| 67 | + | |
| 59 | 68 | /// What a PATCH's `term` field owes the refcounts: the term to claim, and the |
| 60 | 69 | /// one to give back. Covers all three moves — set (none→some), move |
| 61 | 70 | /// (some→other) and clear (some→none) — and moves nothing for a PATCH that |
| @@ -96,6 +105,11 @@ pub struct Term { | ||
| 96 | 105 | name: TermName, |
| 97 | 106 | starts_at: Timestamp, |
| 98 | 107 | ends_at: Timestamp, |
| 108 | + /// When a manager archived this term; `None` = open. `#[surreal(default)]` | |
| 109 | + /// for the same reason `BankQuestion::subject` has one: rows written before | |
| 110 | + /// the column existed still decode, as open terms. | |
| 111 | + #[surreal(default)] | |
| 112 | + archived_at: Option<Timestamp>, | |
| 99 | 113 | } |
| 100 | 114 | |
| 101 | 115 | impl Term { |
| @@ -115,6 +129,14 @@ impl Term { | ||
| 115 | 129 | self.ends_at |
| 116 | 130 | } |
| 117 | 131 | |
| 132 | + pub fn get_archived_at(&self) -> Option<Timestamp> { | |
| 133 | + self.archived_at | |
| 134 | + } | |
| 135 | + | |
| 136 | + pub fn is_archived(&self) -> bool { | |
| 137 | + self.archived_at.is_some() | |
| 138 | + } | |
| 139 | + | |
| 118 | 140 | pub async fn create( |
| 119 | 141 | name: TermName, |
| 120 | 142 | starts_at: Timestamp, |
| @@ -126,6 +148,7 @@ impl Term { | ||
| 126 | 148 | name, |
| 127 | 149 | starts_at, |
| 128 | 150 | ends_at, |
| 151 | + archived_at: None, | |
| 129 | 152 | }; |
| 130 | 153 | let created: Option<Term> = db.create(term.id.record()).content(term).await?; |
| 131 | 154 | created.ok_or_else(|| AppError::Internal("failed to create term".into())) |
| @@ -200,6 +223,58 @@ impl Term { | ||
| 200 | 223 | None => Err(AppError::NotFound), |
| 201 | 224 | } |
| 202 | 225 | } |
| 226 | + | |
| 227 | + /// Freeze the term. Idempotent by construction: the `WHERE` only matches an | |
| 228 | + /// open row, so a repeat archive writes nothing and answers with the | |
| 229 | + /// *original* stamp — the year is not re-dated by a double click. | |
| 230 | + pub async fn archive(self, db: &Database) -> Result<Term, AppError> { | |
| 231 | + self.stamp( | |
| 232 | + "UPDATE $term SET archived_at = $now WHERE archived_at = NONE RETURN AFTER", | |
| 233 | + Some(Timestamp::now()), | |
| 234 | + db, | |
| 235 | + ) | |
| 236 | + .await | |
| 237 | + } | |
| 238 | + | |
| 239 | + /// Re-open the term; idempotent the same way. | |
| 240 | + pub async fn unarchive(self, db: &Database) -> Result<Term, AppError> { | |
| 241 | + self.stamp( | |
| 242 | + "UPDATE $term SET archived_at = NONE WHERE archived_at != NONE RETURN AFTER", | |
| 243 | + None, | |
| 244 | + db, | |
| 245 | + ) | |
| 246 | + .await | |
| 247 | + } | |
| 248 | + | |
| 249 | + /// One conditional write, through [`write_with_retry`] like every other | |
| 250 | + /// guarded single statement here; an empty result is the no-op case, and | |
| 251 | + /// only that path pays for the read that reports the stored row. | |
| 252 | + async fn stamp( | |
| 253 | + self, | |
| 254 | + sql: &str, | |
| 255 | + now: Option<Timestamp>, | |
| 256 | + db: &Database, | |
| 257 | + ) -> Result<Term, AppError> { | |
| 258 | + let mut bindings = vec![("term".into(), self.id.record().into_value())]; | |
| 259 | + if let Some(now) = now { | |
| 260 | + bindings.push(("now".into(), now.as_millis().into_value())); | |
| 261 | + } | |
| 262 | + let written: Vec<Term> = write_with_retry(db, sql, &bindings).await?; | |
| 263 | + if let Some(term) = written.into_iter().next() { | |
| 264 | + return Ok(term); | |
| 265 | + } | |
| 266 | + Self::read(&self.id, db).await?.ok_or(AppError::NotFound) | |
| 267 | + } | |
| 268 | + | |
| 269 | + /// Refuse when the named term is archived. A missing row is `Ok(())`: a | |
| 270 | + /// dangling link is not this guard's error, and the caller that cares | |
| 271 | + /// already answers it (see [`gone_error`]). | |
| 272 | + pub async fn require_open(id: &TermId, db: &Database) -> Result<(), AppError> { | |
| 273 | + match Self::read(id, db).await? { | |
| 274 | + Some(term) if term.is_archived() => Err(archived_error()), | |
| 275 | + _ => Ok(()), | |
| 276 | + } | |
| 277 | + } | |
| 203 | 278 | } |
| 204 | 279 | |
| 205 | 280 | #[cfg(test)] |
src/lib.rsmodified+2 -2
| @@ -58,7 +58,7 @@ use crate::state::AppState; | ||
| 58 | 58 | (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)"), |
| 59 | 59 | (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"), |
| 60 | 60 | (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"), |
| 61 | - (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"), | |
| 61 | + (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"), | |
| 62 | 62 | (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 `<student>_k_<key>`, 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"), |
| 63 | 63 | (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 `<target>_k_<key>` (`_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 `<line>_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"), |
| 64 | 64 | (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; | ||
| 66 | 66 | (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"), |
| 67 | 67 | (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"), |
| 68 | 68 | (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"), |
| 69 | - (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+"), | |
| 69 | + (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+"), | |
| 70 | 70 | ), |
| 71 | 71 | )] |
| 72 | 72 | struct ApiDoc; |
src/migration_sql.rsmodified+4 -0
| @@ -288,6 +288,10 @@ pub const MIGRATION: &str = " | ||
| 288 | 288 | DEFINE FIELD IF NOT EXISTS name ON term TYPE string; |
| 289 | 289 | DEFINE FIELD IF NOT EXISTS starts_at ON term TYPE int; |
| 290 | 290 | DEFINE FIELD IF NOT EXISTS ends_at ON term TYPE int; |
| 291 | + -- When the term was archived; absent = open. `option<int>` and no | |
| 292 | + -- BACKFILL: every term that exists predates archiving and is open, which | |
| 293 | + -- is exactly what an absent stamp already means. | |
| 294 | + DEFINE FIELD IF NOT EXISTS archived_at ON term TYPE option<int>; | |
| 291 | 295 | -- Courses still linking this term, the stored delete guard that closes |
| 292 | 296 | -- write-skew between concurrent request tasks (see `crate::domain::cap`). |
| 293 | 297 | -- Absent reads as zero, so no Rust struct needs it. |
src/web/classes.rsmodified+35 -7
| @@ -338,7 +338,7 @@ async fn classes_page( | ||
| 338 | 338 | (status = 400, description = "Invalid name or grade, an unknown term, or a teacher_id naming nobody or a non-teacher", body = ErrorResponse), |
| 339 | 339 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 340 | 340 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 341 | - (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), | |
| 341 | + (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), | |
| 342 | 342 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 343 | 343 | ), |
| 344 | 344 | )] |
| @@ -537,7 +537,7 @@ async fn get_class( | ||
| 537 | 537 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 538 | 538 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 539 | 539 | (status = 404, description = "Not found", body = ErrorResponse), |
| 540 | - (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), | |
| 540 | + (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), | |
| 541 | 541 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 542 | 542 | ), |
| 543 | 543 | )] |
| @@ -548,6 +548,9 @@ async fn update_class( | ||
| 548 | 548 | Json(req): Json<UpdateClass>, |
| 549 | 549 | ) -> Result<Json<ClassResponse>, AppError> { |
| 550 | 550 | let class = class_or_404(&id, &st.db).await?; |
| 551 | + // The class's *current* term, so a move off an archived year is refused | |
| 552 | + // too; `resolve_term` below holds the other end (the term moved onto). | |
| 553 | + class.require_open(&st.db).await?; | |
| 551 | 554 | |
| 552 | 555 | // Only what the request actually carried is validated and written — an |
| 553 | 556 | // omitted field stays `None` so the save never re-sends this snapshot's |
| @@ -689,7 +692,7 @@ async fn classes_of( | ||
| 689 | 692 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 690 | 693 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 691 | 694 | (status = 404, description = "Not found", body = ErrorResponse), |
| 692 | - (status = 409, description = "Students or courses are still on this class", body = ErrorResponse), | |
| 695 | + (status = 409, description = "Students or courses are still on this class, or its term is archived — past years are read-only", body = ErrorResponse), | |
| 693 | 696 | ), |
| 694 | 697 | )] |
| 695 | 698 | async fn delete_class( |
| @@ -698,6 +701,7 @@ async fn delete_class( | ||
| 698 | 701 | Path(id): Path<String>, |
| 699 | 702 | ) -> Result<StatusCode, AppError> { |
| 700 | 703 | let class = class_or_404(&id, &st.db).await?; |
| 704 | + class.require_open(&st.db).await?; | |
| 701 | 705 | if !class.delete(&st.db).await? { |
| 702 | 706 | return Err(AppError::Conflict( |
| 703 | 707 | "this class still holds students or courses — remove its members and detach its courses first", |
| @@ -726,7 +730,7 @@ async fn delete_class( | ||
| 726 | 730 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 727 | 731 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 728 | 732 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 729 | - (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), | |
| 733 | + (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), | |
| 730 | 734 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 731 | 735 | ), |
| 732 | 736 | )] |
| @@ -737,6 +741,7 @@ async fn add_member( | ||
| 737 | 741 | Json(req): Json<AddMember>, |
| 738 | 742 | ) -> Result<(StatusCode, Json<ClassMemberResponse>), AppError> { |
| 739 | 743 | let class = class_or_404(&id, &st.db).await?; |
| 744 | + class.require_open(&st.db).await?; | |
| 740 | 745 | |
| 741 | 746 | let target = UserId::from_key(&req.user_id); |
| 742 | 747 | let Some(target_user) = User::read(&target, &st.db).await? else { |
| @@ -820,6 +825,7 @@ async fn list_members( | ||
| 820 | 825 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 821 | 826 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 822 | 827 | (status = 404, description = "Class not found, or that student was not in it", body = ErrorResponse), |
| 828 | + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), | |
| 823 | 829 | ), |
| 824 | 830 | )] |
| 825 | 831 | async fn remove_member( |
| @@ -828,6 +834,7 @@ async fn remove_member( | ||
| 828 | 834 | Path((id, target)): Path<(String, String)>, |
| 829 | 835 | ) -> Result<StatusCode, AppError> { |
| 830 | 836 | let class = class_or_404(&id, &st.db).await?; |
| 837 | + class.require_open(&st.db).await?; | |
| 831 | 838 | ClassMember::remove(class.get_id(), &UserId::from_key(&target), &st.db).await?; |
| 832 | 839 | Ok(StatusCode::NO_CONTENT) |
| 833 | 840 | } |
| @@ -853,7 +860,7 @@ async fn remove_member( | ||
| 853 | 860 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 854 | 861 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 855 | 862 | (status = 404, description = "Class not found", body = ErrorResponse), |
| 856 | - (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), | |
| 863 | + (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), | |
| 857 | 864 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 858 | 865 | ), |
| 859 | 866 | )] |
| @@ -875,6 +882,9 @@ async fn attach_course( | ||
| 875 | 882 | "only the course creator, an assigned teacher, or a manager/admin can attach this course to a class", |
| 876 | 883 | )); |
| 877 | 884 | } |
| 885 | + // Both ends: neither a class nor a course on a past year takes a new link. | |
| 886 | + class.require_open(&st.db).await?; | |
| 887 | + course.require_open(&st.db).await?; | |
| 878 | 888 | |
| 879 | 889 | let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; |
| 880 | 890 | let people = PersonRef::map_of(&[&user]); |
| @@ -939,6 +949,7 @@ async fn list_class_courses( | ||
| 939 | 949 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 940 | 950 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 941 | 951 | (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), |
| 952 | + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), | |
| 942 | 953 | ), |
| 943 | 954 | )] |
| 944 | 955 | async fn detach_course( |
| @@ -954,13 +965,20 @@ async fn detach_course( | ||
| 954 | 965 | // route answered 404 forever — which also left the class undeletable, its |
| 955 | 966 | // attachment counter counting a row nothing could sweep. There is no roster |
| 956 | 967 | // left to protect, and the caller is already teacher+. |
| 957 | - if let Some(course) = Course::read(&course, &st.db).await? | |
| 958 | - && !can_manage_course(&course, &user) | |
| 968 | + let row = Course::read(&course, &st.db).await?; | |
| 969 | + if let Some(row) = row.as_ref() | |
| 970 | + && !can_manage_course(row, &user) | |
| 959 | 971 | { |
| 960 | 972 | return Err(AppError::Forbidden( |
| 961 | 973 | "only the course creator, an assigned teacher, or a manager/admin can detach this course from a class", |
| 962 | 974 | )); |
| 963 | 975 | } |
| 976 | + // Both ends, and only what is still there: a link whose course row is gone | |
| 977 | + // has no term to read, and sweeping it is the whole point of the route. | |
| 978 | + class.require_open(&st.db).await?; | |
| 979 | + if let Some(row) = row.as_ref() { | |
| 980 | + row.require_open(&st.db).await?; | |
| 981 | + } | |
| 964 | 982 | ClassCourse::detach(class.get_id(), &course, &st.db).await?; |
| 965 | 983 | Ok(StatusCode::NO_CONTENT) |
| 966 | 984 | } |
| @@ -1419,6 +1437,7 @@ async fn blueprint_status( | ||
| 1419 | 1437 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1420 | 1438 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 1421 | 1439 | (status = 404, description = "Class not found, or no blueprint covers its grade", body = ErrorResponse), |
| 1440 | + (status = 409, description = "The class's (or course's) term is archived — past years are read-only", body = ErrorResponse), | |
| 1422 | 1441 | ), |
| 1423 | 1442 | )] |
| 1424 | 1443 | async fn apply_blueprint( |
| @@ -1429,6 +1448,15 @@ async fn apply_blueprint( | ||
| 1429 | 1448 | let class = class_or_404(&id, &st.db).await?; |
| 1430 | 1449 | let grade = class.get_grade().ok_or(AppError::NotFound)?; |
| 1431 | 1450 | let blueprint = blueprint_or_404(grade.as_str(), &st.db).await?; |
| 1451 | + // The pump writes both ends, so both are guarded — the class, and every | |
| 1452 | + // course the template would attach. A course the template names that is | |
| 1453 | + // already gone is the pump's own `skipped` business, not a term refusal. | |
| 1454 | + class.require_open(&st.db).await?; | |
| 1455 | + for id in blueprint.get_courses() { | |
| 1456 | + if let Some(course) = Course::read(id, &st.db).await? { | |
| 1457 | + course.require_open(&st.db).await?; | |
| 1458 | + } | |
| 1459 | + } | |
| 1432 | 1460 | let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; |
| 1433 | 1461 | Ok(Json(ApplyResponse { |
| 1434 | 1462 | skipped: skipped.iter().map(SkipResponse::new).collect(), |
src/web/course_notes.rsmodified+10 -1
| @@ -115,6 +115,7 @@ impl CourseNoteResponse { | ||
| 115 | 115 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 116 | 116 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 117 | 117 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 118 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 118 | 119 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 119 | 120 | ), |
| 120 | 121 | )] |
| @@ -131,6 +132,7 @@ async fn create( | ||
| 131 | 132 | "only the course creator, an assigned teacher, or a manager/admin can add a course note", |
| 132 | 133 | )); |
| 133 | 134 | } |
| 135 | + course.require_open(&st.db).await?; | |
| 134 | 136 | let title = CourseNoteTitle::try_new(&req.title)?; |
| 135 | 137 | let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; |
| 136 | 138 | let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; |
| @@ -225,6 +227,7 @@ async fn get_one( | ||
| 225 | 227 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 226 | 228 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 227 | 229 | (status = 404, description = "Not found", body = ErrorResponse), |
| 230 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 228 | 231 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 229 | 232 | ), |
| 230 | 233 | )] |
| @@ -240,6 +243,7 @@ async fn update( | ||
| 240 | 243 | "only the course creator, an assigned teacher, or a manager/admin can edit this course note", |
| 241 | 244 | )); |
| 242 | 245 | } |
| 246 | + course.require_open(&st.db).await?; | |
| 243 | 247 | |
| 244 | 248 | let title = req |
| 245 | 249 | .title |
| @@ -269,6 +273,7 @@ async fn update( | ||
| 269 | 273 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 270 | 274 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 271 | 275 | (status = 404, description = "Not found", body = ErrorResponse), |
| 276 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 272 | 277 | ), |
| 273 | 278 | )] |
| 274 | 279 | async fn delete_one( |
| @@ -282,6 +287,7 @@ async fn delete_one( | ||
| 282 | 287 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note", |
| 283 | 288 | )); |
| 284 | 289 | } |
| 290 | + course.require_open(&st.db).await?; | |
| 285 | 291 | // Rows go first (the note delete cascades them), blobs after: a crash in |
| 286 | 292 | // between strands at worst an unreachable blob, never a row whose blob is |
| 287 | 293 | // already gone. The files to unlink come from the delete itself, not a |
| @@ -337,7 +343,7 @@ impl CourseNoteFileResponse { | ||
| 337 | 343 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 338 | 344 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 339 | 345 | (status = 404, description = "Note not found", body = ErrorResponse), |
| 340 | - (status = 409, description = "The note already holds the maximum number of files", body = ErrorResponse), | |
| 346 | + (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), | |
| 341 | 347 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), |
| 342 | 348 | ), |
| 343 | 349 | )] |
| @@ -353,6 +359,7 @@ async fn upload_file( | ||
| 353 | 359 | "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", |
| 354 | 360 | )); |
| 355 | 361 | } |
| 362 | + course.require_open(&st.db).await?; | |
| 356 | 363 | // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and |
| 357 | 364 | // create under one lock) — checking it here too would just race. |
| 358 | 365 | let limit = Settings::load(&st.db).await?.get_max_file_bytes(); |
| @@ -487,6 +494,7 @@ async fn download_file( | ||
| 487 | 494 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 488 | 495 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 489 | 496 | (status = 404, description = "Note or file not found", body = ErrorResponse), |
| 497 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 490 | 498 | ), |
| 491 | 499 | )] |
| 492 | 500 | async fn delete_file( |
| @@ -500,6 +508,7 @@ async fn delete_file( | ||
| 500 | 508 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", |
| 501 | 509 | )); |
| 502 | 510 | } |
| 511 | + course.require_open(&st.db).await?; | |
| 503 | 512 | let file = |
| 504 | 513 | CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) |
| 505 | 514 | .await? |
src/web/courses.rsmodified+21 -4
| @@ -293,6 +293,7 @@ fn check_capacity(capacity: Option<i64>) -> Result<(), AppError> { | ||
| 293 | 293 | (status = 400, description = "Invalid fields, kind, or capacity", body = ErrorResponse), |
| 294 | 294 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 295 | 295 | (status = 403, description = "Requires teacher role or higher", body = ErrorResponse), |
| 296 | + (status = 409, description = "The named term is archived — past years are read-only", body = ErrorResponse), | |
| 296 | 297 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 297 | 298 | ), |
| 298 | 299 | )] |
| @@ -445,7 +446,7 @@ async fn get_course( | ||
| 445 | 446 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 446 | 447 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 447 | 448 | (status = 404, description = "Not found", body = ErrorResponse), |
| 448 | - (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), | |
| 449 | + (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), | |
| 449 | 450 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 450 | 451 | ), |
| 451 | 452 | )] |
| @@ -463,6 +464,7 @@ async fn update_course( | ||
| 463 | 464 | "only the course creator, an assigned teacher, or a manager/admin can edit this course", |
| 464 | 465 | )); |
| 465 | 466 | } |
| 467 | + course.require_open(&st.db).await?; | |
| 466 | 468 | |
| 467 | 469 | // Only what the request actually carried is validated and written — an |
| 468 | 470 | // omitted field stays `None` so the save never re-sends this snapshot's |
| @@ -514,7 +516,7 @@ async fn update_course( | ||
| 514 | 516 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 515 | 517 | (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse), |
| 516 | 518 | (status = 404, description = "Not found", body = ErrorResponse), |
| 517 | - (status = 409, description = "Students are still enrolled in this course", body = ErrorResponse), | |
| 519 | + (status = 409, description = "Students are still enrolled in this course, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 518 | 520 | ), |
| 519 | 521 | )] |
| 520 | 522 | async fn delete_course( |
| @@ -530,6 +532,7 @@ async fn delete_course( | ||
| 530 | 532 | "only the course creator or a manager/admin can delete this course", |
| 531 | 533 | )); |
| 532 | 534 | } |
| 535 | + course.require_open(&st.db).await?; | |
| 533 | 536 | // Writer lease of [`EXAM_LOCK`], for `delete_exam`'s reason: this cascade |
| 534 | 537 | // sweeps the course's exams *and their attempts*, and an attempt is the one |
| 535 | 538 | // exam child whose write cannot collide with the sweep (its claim lands on |
| @@ -593,7 +596,7 @@ async fn delete_course( | ||
| 593 | 596 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 594 | 597 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 595 | 598 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 596 | - (status = 409, description = "That user was demoted below teacher while the request ran — the assignment was undone", body = ErrorResponse), | |
| 599 | + (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), | |
| 597 | 600 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 598 | 601 | ), |
| 599 | 602 | )] |
| @@ -606,6 +609,7 @@ async fn assign_teacher( | ||
| 606 | 609 | let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 607 | 610 | .await? |
| 608 | 611 | .ok_or(AppError::NotFound)?; |
| 612 | + course.require_open(&st.db).await?; | |
| 609 | 613 | |
| 610 | 614 | let target = UserId::from_key(&req.user_id); |
| 611 | 615 | let Some(target_user) = User::read(&target, &st.db).await? else { |
| @@ -650,6 +654,7 @@ async fn assign_teacher( | ||
| 650 | 654 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 651 | 655 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 652 | 656 | (status = 404, description = "Course not found, or that user was not assigned to it", body = ErrorResponse), |
| 657 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 653 | 658 | ), |
| 654 | 659 | )] |
| 655 | 660 | async fn unassign_teacher( |
| @@ -660,6 +665,7 @@ async fn unassign_teacher( | ||
| 660 | 665 | let course = Course::read(&CourseId::from_key(&id), &st.db) |
| 661 | 666 | .await? |
| 662 | 667 | .ok_or(AppError::NotFound)?; |
| 668 | + course.require_open(&st.db).await?; | |
| 663 | 669 | let removed = course |
| 664 | 670 | .unassign_teacher(&UserId::from_key(&target), &st.db) |
| 665 | 671 | .await?; |
| @@ -692,7 +698,7 @@ async fn unassign_teacher( | ||
| 692 | 698 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 693 | 699 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 694 | 700 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 695 | - (status = 409, description = "The course is full", body = ErrorResponse), | |
| 701 | + (status = 409, description = "The course is full, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 696 | 702 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 697 | 703 | ), |
| 698 | 704 | )] |
| @@ -710,6 +716,7 @@ async fn enroll( | ||
| 710 | 716 | "only the course creator, an assigned teacher, or a manager/admin can enroll users", |
| 711 | 717 | )); |
| 712 | 718 | } |
| 719 | + course.require_open(&st.db).await?; | |
| 713 | 720 | |
| 714 | 721 | let target = UserId::from_key(&req.user_id); |
| 715 | 722 | let Some(target_user) = User::read(&target, &st.db).await? else { |
| @@ -800,6 +807,7 @@ async fn list_roster( | ||
| 800 | 807 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 801 | 808 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 802 | 809 | (status = 404, description = "Not found", body = ErrorResponse), |
| 810 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 803 | 811 | ), |
| 804 | 812 | )] |
| 805 | 813 | async fn unenroll( |
| @@ -815,6 +823,7 @@ async fn unenroll( | ||
| 815 | 823 | "only the course creator, an assigned teacher, or a manager/admin can unenroll users", |
| 816 | 824 | )); |
| 817 | 825 | } |
| 826 | + course.require_open(&st.db).await?; | |
| 818 | 827 | let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; |
| 819 | 828 | if removed.is_none() { |
| 820 | 829 | return Err(AppError::NotFound); |
| @@ -847,6 +856,7 @@ async fn unenroll( | ||
| 847 | 856 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 848 | 857 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 849 | 858 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 859 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 850 | 860 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 851 | 861 | ), |
| 852 | 862 | )] |
| @@ -864,6 +874,7 @@ async fn create_exam_in_course( | ||
| 864 | 874 | "only the course creator, an assigned teacher, or a manager/admin can add exams to this course", |
| 865 | 875 | )); |
| 866 | 876 | } |
| 877 | + course.require_open(&st.db).await?; | |
| 867 | 878 | |
| 868 | 879 | let title = ExamTitle::try_new(&req.title)?; |
| 869 | 880 | let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; |
| @@ -976,6 +987,7 @@ struct CreateSubject { | ||
| 976 | 987 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 977 | 988 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 978 | 989 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 990 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 979 | 991 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 980 | 992 | ), |
| 981 | 993 | )] |
| @@ -993,6 +1005,7 @@ async fn create_subject_in_course( | ||
| 993 | 1005 | "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course", |
| 994 | 1006 | )); |
| 995 | 1007 | } |
| 1008 | + course.require_open(&st.db).await?; | |
| 996 | 1009 | |
| 997 | 1010 | let name = SubjectName::try_new(&req.name)?; |
| 998 | 1011 | let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; |
| @@ -1084,6 +1097,7 @@ struct CreateHomework { | ||
| 1084 | 1097 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1085 | 1098 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 1086 | 1099 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 1100 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 1087 | 1101 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1088 | 1102 | ), |
| 1089 | 1103 | )] |
| @@ -1101,6 +1115,7 @@ async fn create_homework_in_course( | ||
| 1101 | 1115 | "only the course creator, an assigned teacher, or a manager/admin can add homework to this course", |
| 1102 | 1116 | )); |
| 1103 | 1117 | } |
| 1118 | + course.require_open(&st.db).await?; | |
| 1104 | 1119 | |
| 1105 | 1120 | let title = HomeworkTitle::try_new(&req.title)?; |
| 1106 | 1121 | let description = match req.description.as_deref() { |
| @@ -1220,6 +1235,7 @@ struct CreateSessionInCourse { | ||
| 1220 | 1235 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1221 | 1236 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 1222 | 1237 | (status = 404, description = "Course not found", body = ErrorResponse), |
| 1238 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 1223 | 1239 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1224 | 1240 | ), |
| 1225 | 1241 | )] |
| @@ -1237,6 +1253,7 @@ async fn create_session_in_course( | ||
| 1237 | 1253 | "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course", |
| 1238 | 1254 | )); |
| 1239 | 1255 | } |
| 1256 | + course.require_open(&st.db).await?; | |
| 1240 | 1257 | |
| 1241 | 1258 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; |
| 1242 | 1259 | let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; |
src/web/exam_ws.rsmodified+17 -7
| @@ -75,8 +75,8 @@ use crate::state::AppState; | ||
| 75 | 75 | use crate::validate::validate_required; |
| 76 | 76 | use crate::web::CurrentUser; |
| 77 | 77 | use crate::web::exams::{ |
| 78 | - EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in, | |
| 79 | - writable_attempt, | |
| 78 | + EXAM_LOCK, check_rejoin, course_of, ensure_enrolled, ensure_sittable, ensure_student, | |
| 79 | + save_answer_in, writable_attempt, | |
| 80 | 80 | }; |
| 81 | 81 | use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; |
| 82 | 82 | |
| @@ -126,7 +126,8 @@ enum ClientMessage { | ||
| 126 | 126 | /// unknown or draft exam (404), unscheduled with no mode (409), not a student |
| 127 | 127 | /// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` |
| 128 | 128 | /// first), submitted or expired (409), left the room while rejoin is closed |
| 129 | -/// (409). | |
| 129 | +/// (409), the course's term archived (409 `term_archived` — a past year's room | |
| 130 | +/// is read-only, and the room's whole purpose is writing). | |
| 130 | 131 | /// |
| 131 | 132 | /// The rejoin gate here is a read-only fast-fail for a proper 409; the |
| 132 | 133 | /// authoritative clear of `left_at` happens inside the room task, under |
| @@ -148,6 +149,7 @@ pub async fn attempt_ws( | ||
| 148 | 149 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 149 | 150 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 150 | 151 | check_rejoin(&exam, &attempt)?; |
| 152 | + course_of(&exam, &st.db).await?.require_open(&st.db).await?; | |
| 151 | 153 | |
| 152 | 154 | let user_id = user.get_id().clone(); |
| 153 | 155 | Ok(ws.on_upgrade(move |socket| room(socket, st, exam, attempt, user_id))) |
| @@ -441,10 +443,18 @@ async fn handle_message( | ||
| 441 | 443 | // Submit the room's own sitting — a stale room must not submit a |
| 442 | 444 | // retake it never hosted. |
| 443 | 445 | let finished = match Exam::read(exam_id, db).await { |
| 444 | - Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { | |
| 445 | - Ok(attempt) => attempt.finish(db).await, | |
| 446 | - Err(err) => Err(err), | |
| 447 | - }, | |
| 446 | + Ok(Some(exam)) => { | |
| 447 | + // Its own archived-term gate: `finish` is the one | |
| 448 | + // sitting-side write that does not go through | |
| 449 | + // `save_answer_in`, and the refusal leaves the room by the | |
| 450 | + // same error frame as every other conflict. | |
| 451 | + async { | |
| 452 | + let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; | |
| 453 | + course_of(&exam, db).await?.require_open(db).await?; | |
| 454 | + attempt.finish(db).await | |
| 455 | + } | |
| 456 | + .await | |
| 457 | + } | |
| 448 | 458 | Ok(None) => Err(AppError::NotFound), |
| 449 | 459 | Err(err) => Err(err), |
| 450 | 460 | }; |
src/web/exams/attempts.rsmodified+13 -4
| @@ -156,7 +156,7 @@ pub(crate) async fn attempts_used( | ||
| 156 | 156 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 157 | 157 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), |
| 158 | 158 | (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse), |
| 159 | - (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse), | |
| 159 | + (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), | |
| 160 | 160 | ), |
| 161 | 161 | )] |
| 162 | 162 | pub(crate) async fn start_attempt( |
| @@ -180,6 +180,7 @@ pub(crate) async fn start_attempt( | ||
| 180 | 180 | ensure_sittable(&exam)?; |
| 181 | 181 | ensure_student(&user)?; |
| 182 | 182 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 183 | + course_of(&exam, &st.db).await?.require_open(&st.db).await?; | |
| 183 | 184 | let now = Timestamp::now(); |
| 184 | 185 | if let Some(starts_at) = exam.get_starts_at() |
| 185 | 186 | && now < starts_at |
| @@ -283,7 +284,7 @@ pub(crate) async fn my_attempt( | ||
| 283 | 284 | (status = 200, description = "Attempt submitted", body = AttemptResponse), |
| 284 | 285 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 285 | 286 | (status = 404, description = "No such exam, or no attempt to finish", body = ErrorResponse), |
| 286 | - (status = 409, description = "Already submitted, or the deadline passed", body = ErrorResponse), | |
| 287 | + (status = 409, description = "Already submitted, the deadline passed, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 287 | 288 | ), |
| 288 | 289 | )] |
| 289 | 290 | pub(crate) async fn finish_attempt( |
| @@ -306,6 +307,7 @@ pub(crate) async fn finish_attempt( | ||
| 306 | 307 | { |
| 307 | 308 | return Err(AppError::Conflict("time is up — the attempt has expired")); |
| 308 | 309 | } |
| 310 | + course_of(&exam, &st.db).await?.require_open(&st.db).await?; | |
| 309 | 311 | |
| 310 | 312 | // Deliberately no rejoin check: a student locked out of the room may |
| 311 | 313 | // still submit what they saved — finishing answers nothing new. |
| @@ -679,7 +681,13 @@ pub(crate) async fn save_answer_checked( | ||
| 679 | 681 | /// The tail of the answer write path, given the sitting to write in: the |
| 680 | 682 | /// student wall and the enrollment wall (a promotion out of `student` or an |
| 681 | 683 | /// unenrollment closes the sheet, mid-exam included), the rejoin gate, the |
| 682 | -/// question lookup, and the upsert. | |
| 684 | +/// archived-term gate, the question lookup, and the upsert. | |
| 685 | +/// | |
| 686 | +/// The archived-term refusal sits here because this is the single funnel every | |
| 687 | +/// answer write passes: REST `POST /exams/{id}/attempt/answers` (via | |
| 688 | +/// [`save_answer_checked`]) *and* every `answer` frame of the exam-room | |
| 689 | +/// WebSocket ([`crate::web::exam_ws`]). The answer-image writes are the only | |
| 690 | +/// answer-side writes outside it, and carry their own guard. | |
| 683 | 691 | pub(crate) async fn save_answer_in( |
| 684 | 692 | exam: &Exam, |
| 685 | 693 | attempt: &ExamAttempt, |
| @@ -691,6 +699,7 @@ pub(crate) async fn save_answer_in( | ||
| 691 | 699 | ensure_student_now(attempt.get_user(), db).await?; |
| 692 | 700 | ensure_enrolled(exam, attempt.get_user(), db).await?; |
| 693 | 701 | check_rejoin(exam, attempt)?; |
| 702 | + course_of(exam, db).await?.require_open(db).await?; | |
| 694 | 703 | let question = question_of_exam(exam.get_id(), question_id, db).await?; |
| 695 | 704 | ExamAnswer::save( |
| 696 | 705 | &question, |
| @@ -849,7 +858,7 @@ pub(crate) async fn attempt_questions( | ||
| 849 | 858 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 850 | 859 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), |
| 851 | 860 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), |
| 852 | - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), | |
| 861 | + (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), | |
| 853 | 862 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 854 | 863 | ), |
| 855 | 864 | )] |
src/web/exams/images.rsmodified+15 -7
| @@ -81,7 +81,10 @@ pub(crate) async fn images_by_question( | ||
| 81 | 81 | // own visibility (author side and sitting side alike). |
| 82 | 82 | |
| 83 | 83 | /// The exam, provided the caller may author its questions — the shared front |
| 84 | -/// half of every image write. | |
| 84 | +/// half of every image write. The archived-term refusal lives here rather than | |
| 85 | +/// in each caller: all four question-image writes (upload/delete of a question | |
| 86 | +/// illustration and of a choice picture) come through this one door, and none | |
| 87 | +/// of the reads do. | |
| 85 | 88 | pub(crate) async fn image_managed_exam( |
| 86 | 89 | st: &AppState, |
| 87 | 90 | user: &User, |
| @@ -96,6 +99,7 @@ pub(crate) async fn image_managed_exam( | ||
| 96 | 99 | "only the course creator, an assigned teacher, or a manager/admin can manage question images", |
| 97 | 100 | )); |
| 98 | 101 | } |
| 102 | + course.require_open(&st.db).await?; | |
| 99 | 103 | Ok(exam) |
| 100 | 104 | } |
| 101 | 105 | |
| @@ -175,7 +179,7 @@ pub(crate) async fn serve_image( | ||
| 175 | 179 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 176 | 180 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 177 | 181 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 178 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 182 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 179 | 183 | (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), |
| 180 | 184 | ), |
| 181 | 185 | )] |
| @@ -249,7 +253,7 @@ pub(crate) async fn get_question_image( | ||
| 249 | 253 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 250 | 254 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 251 | 255 | (status = 404, description = "No such exam, question, or image", body = ErrorResponse), |
| 252 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 256 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 253 | 257 | ), |
| 254 | 258 | )] |
| 255 | 259 | pub(crate) async fn delete_question_image( |
| @@ -292,7 +296,7 @@ pub(crate) async fn delete_question_image( | ||
| 292 | 296 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 293 | 297 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 294 | 298 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 295 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 299 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 296 | 300 | (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), |
| 297 | 301 | ), |
| 298 | 302 | )] |
| @@ -363,7 +367,7 @@ pub(crate) async fn get_choice_image( | ||
| 363 | 367 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 364 | 368 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 365 | 369 | (status = 404, description = "No such exam, question, or image", body = ErrorResponse), |
| 366 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 370 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 367 | 371 | ), |
| 368 | 372 | )] |
| 369 | 373 | pub(crate) async fn delete_choice_image( |
| @@ -440,7 +444,7 @@ pub(crate) async fn store_answer_image( | ||
| 440 | 444 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 441 | 445 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), |
| 442 | 446 | (status = 404, description = "No such exam, question, or attempt", body = ErrorResponse), |
| 443 | - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), | |
| 447 | + (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), | |
| 444 | 448 | (status = 413, description = "Image exceeds the school's size limit", body = ErrorResponse), |
| 445 | 449 | ), |
| 446 | 450 | )] |
| @@ -454,6 +458,9 @@ pub(crate) async fn upload_answer_image( | ||
| 454 | 458 | .await? |
| 455 | 459 | .ok_or(AppError::NotFound)?; |
| 456 | 460 | ensure_student(&user)?; |
| 461 | + // Before the body is read: an archived term refuses the upload without | |
| 462 | + // making the client push its bytes first. | |
| 463 | + course_of(&exam, &st.db).await?.require_open(&st.db).await?; | |
| 457 | 464 | // The body is consumed before the lock — a client's slow upload must not |
| 458 | 465 | // stall the exam subsystem (mirrors the question-image upload). |
| 459 | 466 | let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; |
| @@ -521,7 +528,7 @@ pub(crate) async fn upload_answer_image( | ||
| 521 | 528 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 522 | 529 | (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse), |
| 523 | 530 | (status = 404, description = "No such exam, question, attempt, or drawing", body = ErrorResponse), |
| 524 | - (status = 409, description = "Attempt already submitted, time is up, or rejoin is closed", body = ErrorResponse), | |
| 531 | + (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), | |
| 525 | 532 | ), |
| 526 | 533 | )] |
| 527 | 534 | pub(crate) async fn delete_answer_image( |
| @@ -533,6 +540,7 @@ pub(crate) async fn delete_answer_image( | ||
| 533 | 540 | .await? |
| 534 | 541 | .ok_or(AppError::NotFound)?; |
| 535 | 542 | ensure_student(&user)?; |
| 543 | + course_of(&exam, &st.db).await?.require_open(&st.db).await?; | |
| 536 | 544 | let _guard = EXAM_LOCK.read().await; |
| 537 | 545 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 538 | 546 | ensure_student_now(attempt.get_user(), &st.db).await?; |
src/web/exams/mod.rsmodified+9 -3
| @@ -264,7 +264,7 @@ struct ExamStatisticsResponse { | ||
| 264 | 264 | |
| 265 | 265 | /// The course an exam belongs to. A dangling reference means the course-delete |
| 266 | 266 | /// cascade was violated — surface it loudly as a 500, not a user-facing 404. |
| 267 | -async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { | |
| 267 | +pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { | |
| 268 | 268 | Course::read(exam.get_course(), db) |
| 269 | 269 | .await? |
| 270 | 270 | .ok_or_else(|| AppError::Internal("exam references a missing course".into())) |
| @@ -399,7 +399,7 @@ async fn get_exam( | ||
| 399 | 399 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 400 | 400 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 401 | 401 | (status = 404, description = "Not found", body = ErrorResponse), |
| 402 | - (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), | |
| 402 | + (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), | |
| 403 | 403 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 404 | 404 | ), |
| 405 | 405 | )] |
| @@ -432,6 +432,7 @@ async fn update_exam( | ||
| 432 | 432 | "only the course creator, an assigned teacher, or a manager/admin can edit this exam", |
| 433 | 433 | )); |
| 434 | 434 | } |
| 435 | + course.require_open(&st.db).await?; | |
| 435 | 436 | |
| 436 | 437 | let title = match req.title { |
| 437 | 438 | Some(ref title) => ExamTitle::try_new(title)?, |
| @@ -572,6 +573,7 @@ async fn update_exam( | ||
| 572 | 573 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 573 | 574 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 574 | 575 | (status = 404, description = "Not found", body = ErrorResponse), |
| 576 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 575 | 577 | ), |
| 576 | 578 | )] |
| 577 | 579 | async fn delete_exam( |
| @@ -588,6 +590,7 @@ async fn delete_exam( | ||
| 588 | 590 | "only the course creator, an assigned teacher, or a manager/admin can delete this exam", |
| 589 | 591 | )); |
| 590 | 592 | } |
| 593 | + course.require_open(&st.db).await?; | |
| 591 | 594 | // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names |
| 592 | 595 | // included — the lease `delete_homework` has always held, and its absence |
| 593 | 596 | // here is what made a sitting able to start inside this delete. Every other |
| @@ -645,7 +648,7 @@ async fn delete_exam( | ||
| 645 | 648 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 646 | 649 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 647 | 650 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 648 | - (status = 409, description = "The exam is a draft, or its kind has been removed from the school's settings", body = ErrorResponse), | |
| 651 | + (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), | |
| 649 | 652 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 650 | 653 | ), |
| 651 | 654 | )] |
| @@ -671,6 +674,7 @@ async fn grade( | ||
| 671 | 674 | "only the course creator, an assigned teacher, or a manager/admin can grade this exam", |
| 672 | 675 | )); |
| 673 | 676 | } |
| 677 | + course.require_open(&st.db).await?; | |
| 674 | 678 | // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own |
| 675 | 679 | // transaction, so a re-draft landing after this read cannot leave a mark on |
| 676 | 680 | // a hidden exam. |
| @@ -860,6 +864,7 @@ async fn my_result( | ||
| 860 | 864 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 861 | 865 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 862 | 866 | (status = 404, description = "Not found", body = ErrorResponse), |
| 867 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 863 | 868 | ), |
| 864 | 869 | )] |
| 865 | 870 | async fn remove_result( |
| @@ -876,6 +881,7 @@ async fn remove_result( | ||
| 876 | 881 | "only the course creator, an assigned teacher, or a manager/admin can remove results", |
| 877 | 882 | )); |
| 878 | 883 | } |
| 884 | + course.require_open(&st.db).await?; | |
| 879 | 885 | let removed = ExamResult::remove( |
| 880 | 886 | exam.get_id(), |
| 881 | 887 | &UserId::from_key(&target), |
src/web/exams/questions.rsmodified+12 -5
| @@ -200,7 +200,7 @@ pub(crate) fn choice_slot(question: &ExamQuestion, choice_id: &str) -> Result<Ch | ||
| 200 | 200 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 201 | 201 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 202 | 202 | (status = 404, description = "Exam not found", body = ErrorResponse), |
| 203 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 203 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 204 | 204 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 205 | 205 | ), |
| 206 | 206 | )] |
| @@ -219,6 +219,7 @@ pub(crate) async fn create_question( | ||
| 219 | 219 | "only the course creator, an assigned teacher, or a manager/admin can author questions", |
| 220 | 220 | )); |
| 221 | 221 | } |
| 222 | + course.require_open(&st.db).await?; | |
| 222 | 223 | // No lease: the subject check below is only a pre-flight for the message, |
| 223 | 224 | // and the insert takes the subject's reference counter in the same breath — |
| 224 | 225 | // a subject delete lands either wholly before it (400) or is refused. The |
| @@ -338,7 +339,7 @@ pub(crate) async fn question_page( | ||
| 338 | 339 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 339 | 340 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 340 | 341 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 341 | - (status = 409, description = "Attempts have started — questions are frozen, or the subject the question was read on changed since — nothing was written, re-read and retry", body = ErrorResponse), | |
| 342 | + (status = 409, description = "Attempts have started — questions are frozen, the subject the question was read on changed since — nothing was written, re-read and retry — or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 342 | 343 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 343 | 344 | ), |
| 344 | 345 | )] |
| @@ -357,6 +358,7 @@ pub(crate) async fn update_question( | ||
| 357 | 358 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", |
| 358 | 359 | )); |
| 359 | 360 | } |
| 361 | + course.require_open(&st.db).await?; | |
| 360 | 362 | // No lease — see `create_question`; a re-tag moves the subject's reference |
| 361 | 363 | // counter, and the freeze gate rides in the update's transaction. |
| 362 | 364 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -427,7 +429,7 @@ pub(crate) async fn update_question( | ||
| 427 | 429 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 428 | 430 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 429 | 431 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 430 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 432 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 431 | 433 | ), |
| 432 | 434 | )] |
| 433 | 435 | pub(crate) async fn delete_question( |
| @@ -444,6 +446,7 @@ pub(crate) async fn delete_question( | ||
| 444 | 446 | "only the course creator, an assigned teacher, or a manager/admin can delete questions", |
| 445 | 447 | )); |
| 446 | 448 | } |
| 449 | + course.require_open(&st.db).await?; | |
| 447 | 450 | // No lock: the freeze gate is part of the delete's own transaction, and |
| 448 | 451 | // this path checks no subject. The pre-flight below is the fast 409. |
| 449 | 452 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -496,7 +499,7 @@ pub(crate) struct InstantiateFromBank { | ||
| 496 | 499 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 497 | 500 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 498 | 501 | (status = 404, description = "No such exam, or no bank template the caller may see", body = ErrorResponse), |
| 499 | - (status = 409, description = "Attempts have started — questions are frozen", body = ErrorResponse), | |
| 502 | + (status = 409, description = "Attempts have started — questions are frozen, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 500 | 503 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 501 | 504 | ), |
| 502 | 505 | )] |
| @@ -515,6 +518,7 @@ pub(crate) async fn question_from_bank( | ||
| 515 | 518 | "only the course creator, an assigned teacher, or a manager/admin can author questions", |
| 516 | 519 | )); |
| 517 | 520 | } |
| 521 | + course.require_open(&st.db).await?; | |
| 518 | 522 | // No lease — same reasoning as `create_question`. The freeze gate rides in |
| 519 | 523 | // the insert's transaction. |
| 520 | 524 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -628,7 +632,7 @@ pub(crate) async fn question_from_bank( | ||
| 628 | 632 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 629 | 633 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 630 | 634 | (status = 404, description = "No such exam, no such question in it, or no bank template the caller may see", body = ErrorResponse), |
| 631 | - (status = 409, description = "Attempts have started — questions are frozen, or the question's subject was re-tagged since the caller read it — nothing was written, re-read and retry", body = ErrorResponse), | |
| 635 | + (status = 409, description = "Attempts have started — questions are frozen, the question's subject was re-tagged since the caller read it — nothing was written, re-read and retry — or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 632 | 636 | ), |
| 633 | 637 | )] |
| 634 | 638 | pub(crate) async fn question_refresh_from_bank( |
| @@ -645,6 +649,7 @@ pub(crate) async fn question_refresh_from_bank( | ||
| 645 | 649 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", |
| 646 | 650 | )); |
| 647 | 651 | } |
| 652 | + course.require_open(&st.db).await?; | |
| 648 | 653 | // No lock: the question keeps its own subject here, so there is nothing to |
| 649 | 654 | // pair with a subject delete, and the freeze gate rides in the overwrite's |
| 650 | 655 | // transaction. |
| @@ -752,6 +757,7 @@ pub(crate) async fn question_refresh_from_bank( | ||
| 752 | 757 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 753 | 758 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 754 | 759 | (status = 404, description = "No such exam, or no such question in it", body = ErrorResponse), |
| 760 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 755 | 761 | ), |
| 756 | 762 | )] |
| 757 | 763 | pub(crate) async fn question_to_bank( |
| @@ -768,6 +774,7 @@ pub(crate) async fn question_to_bank( | ||
| 768 | 774 | "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", |
| 769 | 775 | )); |
| 770 | 776 | } |
| 777 | + course.require_open(&st.db).await?; | |
| 771 | 778 | // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and |
| 772 | 779 | // a template left holding a deleted subject reads as an empty |
| 773 | 780 | // `subject_name` either way (see [`crate::web::bank_questions`]). |
src/web/homework.rsmodified+33 -6
| @@ -328,7 +328,7 @@ struct UpdateHomework { | ||
| 328 | 328 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 329 | 329 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 330 | 330 | (status = 404, description = "Not found", body = ErrorResponse), |
| 331 | - (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result, or the subject this update re-tags from changed since the caller read it — nothing was written, re-read and retry", body = ErrorResponse), | |
| 331 | + (status = 409, description = "Narrowing the assigned list would orphan an existing submission or result, or the subject this update re-tags from changed since the caller read it — nothing was written, re-read and retry; or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 332 | 332 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 333 | 333 | ), |
| 334 | 334 | )] |
| @@ -344,6 +344,7 @@ async fn update_homework( | ||
| 344 | 344 | "only the course creator, an assigned teacher, or a manager/admin can edit this homework", |
| 345 | 345 | )); |
| 346 | 346 | } |
| 347 | + course.require_open(&st.db).await?; | |
| 347 | 348 | |
| 348 | 349 | // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the |
| 349 | 350 | // live submissions and results, and the row write depends on what it saw — |
| @@ -449,6 +450,7 @@ async fn ensure_no_orphans( | ||
| 449 | 450 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 450 | 451 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 451 | 452 | (status = 404, description = "Not found", body = ErrorResponse), |
| 453 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 452 | 454 | ), |
| 453 | 455 | )] |
| 454 | 456 | async fn delete_homework( |
| @@ -462,6 +464,7 @@ async fn delete_homework( | ||
| 462 | 464 | "only the course creator, an assigned teacher, or a manager/admin can delete this homework", |
| 463 | 465 | )); |
| 464 | 466 | } |
| 467 | + course.require_open(&st.db).await?; | |
| 465 | 468 | let _guard = HOMEWORK_LOCK.write().await; |
| 466 | 469 | let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; |
| 467 | 470 | homework.delete(&st.db).await?; |
| @@ -512,6 +515,20 @@ async fn gate_own_submission(id: &str, user: &User, db: &Database) -> Result<Hom | ||
| 512 | 515 | Ok(homework) |
| 513 | 516 | } |
| 514 | 517 | |
| 518 | +/// The term wall of the student side: an archived term makes past years | |
| 519 | +/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate | |
| 520 | +/// also fronts the download read, and an archived year is still browsable. So | |
| 521 | +/// every student *write* calls this right after the gate, which keeps the | |
| 522 | +/// order that matters: a student the homework never named is refused by the | |
| 523 | +/// audience check with a 404 and never learns the homework exists. A course | |
| 524 | +/// that vanished under us is the gates' own business, not this one's. | |
| 525 | +async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { | |
| 526 | + if let Some(course) = Course::read(homework.get_course(), db).await? { | |
| 527 | + course.require_open(db).await?; | |
| 528 | + } | |
| 529 | + Ok(()) | |
| 530 | +} | |
| 531 | + | |
| 515 | 532 | /// One file attached to a submission — metadata only; the bytes download |
| 516 | 533 | /// separately from `GET /homework/{id}/submission/files/{fid}`. |
| 517 | 534 | #[derive(Serialize, ToSchema)] |
| @@ -644,7 +661,7 @@ struct SubmitHomework { | ||
| 644 | 661 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 645 | 662 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), |
| 646 | 663 | (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse), |
| 647 | - (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed", body = ErrorResponse), | |
| 664 | + (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), | |
| 648 | 665 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 649 | 666 | ), |
| 650 | 667 | )] |
| @@ -669,6 +686,7 @@ async fn submit( | ||
| 669 | 686 | // write is what makes the PATCH wait and then see the row. |
| 670 | 687 | let _guard = HOMEWORK_LOCK.read().await; |
| 671 | 688 | let homework = gate_own_submission(&id, &user, &st.db).await?; |
| 689 | + require_open_term(&homework, &st.db).await?; | |
| 672 | 690 | // The graded gate, twice over. This read answers the common case — graded |
| 673 | 691 | // minutes ago, and the student who never submitted has no row to carry the |
| 674 | 692 | // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what |
| @@ -766,7 +784,7 @@ async fn get_submission( | ||
| 766 | 784 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 767 | 785 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), |
| 768 | 786 | (status = 404, description = "No such homework, a subset assignment the caller is not part of, or nothing submitted yet", body = ErrorResponse), |
| 769 | - (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed", body = ErrorResponse), | |
| 787 | + (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), | |
| 770 | 788 | ), |
| 771 | 789 | )] |
| 772 | 790 | async fn delete_submission( |
| @@ -775,6 +793,7 @@ async fn delete_submission( | ||
| 775 | 793 | Path(id): Path<String>, |
| 776 | 794 | ) -> Result<StatusCode, AppError> { |
| 777 | 795 | let homework = gate_own_submission(&id, &user, &st.db).await?; |
| 796 | + require_open_term(&homework, &st.db).await?; | |
| 778 | 797 | // Reader lease as in `submit` — the audience interlock, not the freeze. |
| 779 | 798 | let _guard = HOMEWORK_LOCK.read().await; |
| 780 | 799 | 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<Response, | ||
| 873 | 892 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 874 | 893 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), |
| 875 | 894 | (status = 404, description = "No such homework (or a subset assignment the caller is not part of)", body = ErrorResponse), |
| 876 | - (status = 409, description = "The homework has been graded, or the submission already holds the maximum of 10 files", body = ErrorResponse), | |
| 895 | + (status = 409, description = "The homework has been graded, or the submission already holds the maximum of 10 files, or this course's term is archived — past years are read-only", body = ErrorResponse), | |
| 877 | 896 | (status = 413, description = "File exceeds the school's size limit", body = ErrorResponse), |
| 878 | 897 | ), |
| 879 | 898 | )] |
| @@ -886,7 +905,8 @@ async fn upload_submission_file( | ||
| 886 | 905 | // Pre-flight, so a caller with no business here is refused before uploading |
| 887 | 906 | // 25 MiB; the gate that *licenses the write* is the one under the lease |
| 888 | 907 | // below, because this snapshot goes stale while the body streams. |
| 889 | - gate_own_submission(&id, &user, &st.db).await?; | |
| 908 | + let preflight = gate_own_submission(&id, &user, &st.db).await?; | |
| 909 | + require_open_term(&preflight, &st.db).await?; | |
| 890 | 910 | let limit = Settings::load(&st.db).await?.get_max_file_bytes(); |
| 891 | 911 | // Consume the body before taking the lock — a slow upload must not stall the |
| 892 | 912 | // homework subsystem (mirrors the exam/note image uploads). |
| @@ -909,6 +929,8 @@ async fn upload_submission_file( | ||
| 909 | 929 | // under it, all unreachable afterwards. A gate read before the body is a |
| 910 | 930 | // pre-flight; a gate read after it is the decision. |
| 911 | 931 | let homework = gate_own_submission(&id, &user, &st.db).await?; |
| 932 | + // Re-walled too: the term can be archived while the body streams. | |
| 933 | + require_open_term(&homework, &st.db).await?; | |
| 912 | 934 | // The common-case gate; the freeze itself rides on the writes below. |
| 913 | 935 | if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) |
| 914 | 936 | .await? |
| @@ -1029,7 +1051,7 @@ async fn download_submission_file( | ||
| 1029 | 1051 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1030 | 1052 | (status = 403, description = "Not a student, or not enrolled in the homework's course", body = ErrorResponse), |
| 1031 | 1053 | (status = 404, description = "No such homework or file (or a subset assignment the caller is not part of)", body = ErrorResponse), |
| 1032 | - (status = 409, description = "The homework has been graded — the submission is frozen until the grade is removed", body = ErrorResponse), | |
| 1054 | + (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), | |
| 1033 | 1055 | ), |
| 1034 | 1056 | )] |
| 1035 | 1057 | async fn delete_submission_file( |
| @@ -1038,6 +1060,7 @@ async fn delete_submission_file( | ||
| 1038 | 1060 | Path((id, fid)): Path<(String, String)>, |
| 1039 | 1061 | ) -> Result<StatusCode, AppError> { |
| 1040 | 1062 | let homework = gate_own_submission(&id, &user, &st.db).await?; |
| 1063 | + require_open_term(&homework, &st.db).await?; | |
| 1041 | 1064 | const GRADED: AppError = AppError::Conflict( |
| 1042 | 1065 | "this homework has been graded — ask the teacher to remove the grade before deleting files", |
| 1043 | 1066 | ); |
| @@ -1100,6 +1123,7 @@ struct GradeHomework { | ||
| 1100 | 1123 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1101 | 1124 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse), |
| 1102 | 1125 | (status = 404, description = "Homework not found", body = ErrorResponse), |
| 1126 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 1103 | 1127 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 1104 | 1128 | ), |
| 1105 | 1129 | )] |
| @@ -1121,6 +1145,7 @@ async fn grade_homework( | ||
| 1121 | 1145 | "only the course creator, an assigned teacher, or a manager/admin can grade this homework", |
| 1122 | 1146 | )); |
| 1123 | 1147 | } |
| 1148 | + course.require_open(&st.db).await?; | |
| 1124 | 1149 | |
| 1125 | 1150 | let status = HomeworkStatus::try_new(&req.status)?; |
| 1126 | 1151 | let mark = req.mark.map(Mark::try_new).transpose()?; |
| @@ -1202,6 +1227,7 @@ async fn grade_homework( | ||
| 1202 | 1227 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 1203 | 1228 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 1204 | 1229 | (status = 404, description = "No such homework, or no grade for this user", body = ErrorResponse), |
| 1230 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 1205 | 1231 | ), |
| 1206 | 1232 | )] |
| 1207 | 1233 | async fn remove_homework_result( |
| @@ -1219,6 +1245,7 @@ async fn remove_homework_result( | ||
| 1219 | 1245 | "only the course creator, an assigned teacher, or a manager/admin can remove grades", |
| 1220 | 1246 | )); |
| 1221 | 1247 | } |
| 1248 | + course.require_open(&st.db).await?; | |
| 1222 | 1249 | let removed = |
| 1223 | 1250 | HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; |
| 1224 | 1251 | if removed.is_none() { |
src/web/sessions.rsmodified+8 -0
| @@ -193,6 +193,7 @@ async fn get_session( | ||
| 193 | 193 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 194 | 194 | (status = 404, description = "Not found", body = ErrorResponse), |
| 195 | 195 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 196 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 196 | 197 | ), |
| 197 | 198 | )] |
| 198 | 199 | async fn update_session( |
| @@ -217,6 +218,7 @@ async fn update_session( | ||
| 217 | 218 | "only the course creator, an assigned teacher, or a manager/admin can edit this session", |
| 218 | 219 | )); |
| 219 | 220 | } |
| 221 | + course.require_open(&st.db).await?; | |
| 220 | 222 | |
| 221 | 223 | let topic = req |
| 222 | 224 | .topic |
| @@ -260,6 +262,7 @@ async fn update_session( | ||
| 260 | 262 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 261 | 263 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 262 | 264 | (status = 404, description = "Not found", body = ErrorResponse), |
| 265 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 263 | 266 | ), |
| 264 | 267 | )] |
| 265 | 268 | async fn delete_session( |
| @@ -273,6 +276,7 @@ async fn delete_session( | ||
| 273 | 276 | "only the course creator, an assigned teacher, or a manager/admin can delete this session", |
| 274 | 277 | )); |
| 275 | 278 | } |
| 279 | + course.require_open(&st.db).await?; | |
| 276 | 280 | session.delete(&st.db).await?; |
| 277 | 281 | Ok(StatusCode::NO_CONTENT) |
| 278 | 282 | } |
| @@ -298,6 +302,7 @@ async fn delete_session( | ||
| 298 | 302 | (status = 403, description = "Not the session teacher or a course manager; or marking the teacher without manager+", body = ErrorResponse), |
| 299 | 303 | (status = 404, description = "Session not found", body = ErrorResponse), |
| 300 | 304 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 305 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 301 | 306 | ), |
| 302 | 307 | )] |
| 303 | 308 | async fn mark_roll_call( |
| @@ -312,6 +317,7 @@ async fn mark_roll_call( | ||
| 312 | 317 | "only the session's teacher or a course manager can take roll call", |
| 313 | 318 | )); |
| 314 | 319 | } |
| 320 | + course.require_open(&st.db).await?; | |
| 315 | 321 | |
| 316 | 322 | let school = Settings::load(&st.db).await?; |
| 317 | 323 | let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; |
| @@ -437,6 +443,7 @@ async fn list_roll_call( | ||
| 437 | 443 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 438 | 444 | (status = 403, description = "Not the session teacher or a course manager; or removing a staff row without manager+", body = ErrorResponse), |
| 439 | 445 | (status = 404, description = "Not found", body = ErrorResponse), |
| 446 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 440 | 447 | ), |
| 441 | 448 | )] |
| 442 | 449 | async fn remove_roll_call( |
| @@ -450,6 +457,7 @@ async fn remove_roll_call( | ||
| 450 | 457 | "only the session's teacher or a course manager can take roll call", |
| 451 | 458 | )); |
| 452 | 459 | } |
| 460 | + course.require_open(&st.db).await?; | |
| 453 | 461 | let target = UserId::from_key(&target); |
| 454 | 462 | // A staff row is management's to remove, keyed on the *target's live role* |
| 455 | 463 | // rather than on `is_teacher`: reassigning a session's teacher used to hand |
src/web/subjects.rsmodified+4 -1
| @@ -125,6 +125,7 @@ async fn get_subject( | ||
| 125 | 125 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 126 | 126 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 127 | 127 | (status = 404, description = "Not found", body = ErrorResponse), |
| 128 | + (status = 409, description = "This course's term is archived — past years are read-only", body = ErrorResponse), | |
| 128 | 129 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 129 | 130 | ), |
| 130 | 131 | )] |
| @@ -140,6 +141,7 @@ async fn update_subject( | ||
| 140 | 141 | "only the course creator, an assigned teacher, or a manager/admin can edit this subject", |
| 141 | 142 | )); |
| 142 | 143 | } |
| 144 | + course.require_open(&st.db).await?; | |
| 143 | 145 | |
| 144 | 146 | // Only what the request actually carried is validated and written — an |
| 145 | 147 | // omitted field stays `None` so the save never re-sends this snapshot's |
| @@ -176,7 +178,7 @@ async fn update_subject( | ||
| 176 | 178 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 177 | 179 | (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), |
| 178 | 180 | (status = 404, description = "Not found", body = ErrorResponse), |
| 179 | - (status = 409, description = "Exam questions or homework still reference this subject", body = ErrorResponse), | |
| 181 | + (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), | |
| 180 | 182 | ), |
| 181 | 183 | )] |
| 182 | 184 | async fn delete_subject( |
| @@ -190,6 +192,7 @@ async fn delete_subject( | ||
| 190 | 192 | "only the course creator, an assigned teacher, or a manager/admin can delete this subject", |
| 191 | 193 | )); |
| 192 | 194 | } |
| 195 | + course.require_open(&st.db).await?; | |
| 193 | 196 | // No locks: the two checks *are* the delete's `WHERE`, decided against the |
| 194 | 197 | // subject's own reference counters inside one statement. This used to be |
| 195 | 198 | // three process-wide locks (the only site that held more than one) around |
src/web/terms.rsmodified+77 -4
| @@ -7,7 +7,7 @@ use utoipa_axum::router::OpenApiRouter; | ||
| 7 | 7 | use utoipa_axum::routes; |
| 8 | 8 | |
| 9 | 9 | use crate::database::Database; |
| 10 | -use crate::domain::term::{Term, TermId, TermName}; | |
| 10 | +use crate::domain::term::{self, Term, TermId, TermName}; | |
| 11 | 11 | use crate::domain::timestamp::Timestamp; |
| 12 | 12 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 13 | 13 | use crate::state::AppState; |
| @@ -18,6 +18,8 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 18 | 18 | OpenApiRouter::new() |
| 19 | 19 | .routes(routes!(create_term, list_terms)) |
| 20 | 20 | .routes(routes!(get_term, update_term, delete_term)) |
| 21 | + .routes(routes!(archive_term)) | |
| 22 | + .routes(routes!(unarchive_term)) | |
| 21 | 23 | } |
| 22 | 24 | |
| 23 | 25 | #[derive(Deserialize, ToSchema)] |
| @@ -50,6 +52,8 @@ struct TermResponse { | ||
| 50 | 52 | starts_at: i64, |
| 51 | 53 | /// Term end, UTC unix-milliseconds. |
| 52 | 54 | ends_at: i64, |
| 55 | + /// Archived at, UTC unix-millis; null while the term is open. | |
| 56 | + archived_at: Option<i64>, | |
| 53 | 57 | } |
| 54 | 58 | |
| 55 | 59 | impl TermResponse { |
| @@ -59,13 +63,17 @@ impl TermResponse { | ||
| 59 | 63 | name: term.get_name().as_str().to_string(), |
| 60 | 64 | starts_at: term.get_starts_at().as_millis(), |
| 61 | 65 | ends_at: term.get_ends_at().as_millis(), |
| 66 | + archived_at: term.get_archived_at().map(|at| at.as_millis()), | |
| 62 | 67 | } |
| 63 | 68 | } |
| 64 | 69 | } |
| 65 | 70 | |
| 66 | 71 | /// Turn an optional request-supplied term id into a validated reference — |
| 67 | -/// `None` stays `None`, an unknown id is a `400` naming the field. Shared by | |
| 68 | -/// the course create/update handlers. | |
| 72 | +/// `None` stays `None`, an unknown id is a `400` naming the field, and an | |
| 73 | +/// *archived* one is a `409 term_archived`. That last refusal is here rather | |
| 74 | +/// than in each handler because this is the single spot every new link to a | |
| 75 | +/// term passes through — course create/update and class create/update alike: | |
| 76 | +/// past years take no new structure. | |
| 69 | 77 | pub(crate) async fn resolve_term( |
| 70 | 78 | id: Option<&str>, |
| 71 | 79 | db: &Database, |
| @@ -79,6 +87,9 @@ pub(crate) async fn resolve_term( | ||
| 79 | 87 | field: "term_id", |
| 80 | 88 | reason: "term does not exist", |
| 81 | 89 | }))?; |
| 90 | + if term.is_archived() { | |
| 91 | + return Err(term::archived_error()); | |
| 92 | + } | |
| 82 | 93 | Ok(Some(term.get_id().clone())) |
| 83 | 94 | } |
| 84 | 95 | |
| @@ -177,6 +188,7 @@ async fn get_term( | ||
| 177 | 188 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 178 | 189 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 179 | 190 | (status = 404, description = "Not found", body = ErrorResponse), |
| 191 | + (status = 409, description = "The term is archived — past years are read-only", body = ErrorResponse), | |
| 180 | 192 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 181 | 193 | ), |
| 182 | 194 | )] |
| @@ -193,6 +205,9 @@ async fn update_term( | ||
| 193 | 205 | let term = Term::read(&TermId::from_key(&id), &st.db) |
| 194 | 206 | .await? |
| 195 | 207 | .ok_or(AppError::NotFound)?; |
| 208 | + if term.is_archived() { | |
| 209 | + return Err(term::archived_error()); | |
| 210 | + } | |
| 196 | 211 | // Pre-flight only: the range check is re-made inside the UPDATE's `WHERE` |
| 197 | 212 | // (`Term::update`), so a concurrent move of the end this PATCH omits cannot |
| 198 | 213 | // slip an inverted range past this snapshot. |
| @@ -220,7 +235,7 @@ async fn update_term( | ||
| 220 | 235 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 221 | 236 | (status = 403, description = "Requires manager role or higher", body = ErrorResponse), |
| 222 | 237 | (status = 404, description = "Not found", body = ErrorResponse), |
| 223 | - (status = 409, description = "Courses are still linked to this term", body = ErrorResponse), | |
| 238 | + (status = 409, description = "Courses are still linked to this term, or the term is archived — past years are read-only", body = ErrorResponse), | |
| 224 | 239 | ), |
| 225 | 240 | )] |
| 226 | 241 | async fn delete_term( |
| @@ -231,6 +246,9 @@ async fn delete_term( | ||
| 231 | 246 | let term = Term::read(&TermId::from_key(&id), &st.db) |
| 232 | 247 | .await? |
| 233 | 248 | .ok_or(AppError::NotFound)?; |
| 249 | + if term.is_archived() { | |
| 250 | + return Err(term::archived_error()); | |
| 251 | + } | |
| 234 | 252 | if !term.delete(&st.db).await? { |
| 235 | 253 | return Err(AppError::Conflict( |
| 236 | 254 | "courses are still linked to this term — unlink them first", |
| @@ -238,3 +256,58 @@ async fn delete_term( | ||
| 238 | 256 | } |
| 239 | 257 | Ok(StatusCode::NO_CONTENT) |
| 240 | 258 | } |
| 259 | + | |
| 260 | +/// Archive a term. Requires manager+. An archived term is frozen: it takes no | |
| 261 | +/// edits, no delete, and no new course or class link. Idempotent — archiving an | |
| 262 | +/// already-archived term answers `200` with the stamp it already had. | |
| 263 | +#[utoipa::path( | |
| 264 | + post, | |
| 265 | + path = "/{id}/archive", | |
| 266 | + tag = "terms", | |
| 267 | + security(("session_cookie" = [])), | |
| 268 | + params(("id" = String, Path, description = "Term id")), | |
| 269 | + responses( | |
| 270 | + (status = 200, description = "The archived term", body = TermResponse), | |
| 271 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 272 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 273 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 274 | + ), | |
| 275 | +)] | |
| 276 | +async fn archive_term( | |
| 277 | + State(st): State<AppState>, | |
| 278 | + RequireManager(_user): RequireManager, | |
| 279 | + Path(id): Path<String>, | |
| 280 | +) -> Result<Json<TermResponse>, AppError> { | |
| 281 | + let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 282 | + .await? | |
| 283 | + .ok_or(AppError::NotFound)?; | |
| 284 | + let archived = term.archive(&st.db).await?; | |
| 285 | + Ok(Json(TermResponse::new(&archived))) | |
| 286 | +} | |
| 287 | + | |
| 288 | +/// Re-open an archived term. Requires manager+. Idempotent the same way as | |
| 289 | +/// archiving: an already-open term answers `200`. | |
| 290 | +#[utoipa::path( | |
| 291 | + post, | |
| 292 | + path = "/{id}/unarchive", | |
| 293 | + tag = "terms", | |
| 294 | + security(("session_cookie" = [])), | |
| 295 | + params(("id" = String, Path, description = "Term id")), | |
| 296 | + responses( | |
| 297 | + (status = 200, description = "The re-opened term", body = TermResponse), | |
| 298 | + (status = 401, description = "Not authenticated", body = ErrorResponse), | |
| 299 | + (status = 403, description = "Requires manager role or higher", body = ErrorResponse), | |
| 300 | + (status = 404, description = "Not found", body = ErrorResponse), | |
| 301 | + ), | |
| 302 | +)] | |
| 303 | +async fn unarchive_term( | |
| 304 | + State(st): State<AppState>, | |
| 305 | + RequireManager(_user): RequireManager, | |
| 306 | + Path(id): Path<String>, | |
| 307 | +) -> Result<Json<TermResponse>, AppError> { | |
| 308 | + let term = Term::read(&TermId::from_key(&id), &st.db) | |
| 309 | + .await? | |
| 310 | + .ok_or(AppError::NotFound)?; | |
| 311 | + let reopened = term.unarchive(&st.db).await?; | |
| 312 | + Ok(Json(TermResponse::new(&reopened))) | |
| 313 | +} |
tests/e2e.rsmodified+367 -0
| @@ -3314,3 +3314,370 @@ async fn a_demoted_participant_stops_reading_the_canvas_at_once() { | ||
| 3314 | 3314 | ); |
| 3315 | 3315 | board_draw(&mut ali, "{\"p\":[5,6]}").await; |
| 3316 | 3316 | } |
| 3317 | + | |
| 3318 | +/// A manager archives an academic year and the whole year turns read-only from | |
| 3319 | +/// the user's seat: every write into its structure answers `409 term_archived`, | |
| 3320 | +/// every read still answers, the live exam room's door refuses the upgrade with | |
| 3321 | +/// a real HTTP 409 (before the WebSocket handshake completes), and unarchiving | |
| 3322 | +/// reopens all of it. The two archive routes are discoverable in the served | |
| 3323 | +/// OpenAPI document Swagger renders. | |
| 3324 | +#[tokio::test] | |
| 3325 | +async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() { | |
| 3326 | + let (base, db) = spawn_server().await; | |
| 3327 | + let mudur = client(); | |
| 3328 | + let ogrenci = client(); | |
| 3329 | + let kaan = client(); | |
| 3330 | + register(&mudur, &base, "mudur").await; | |
| 3331 | + register(&ogrenci, &base, "ogrenci").await; | |
| 3332 | + register(&kaan, &base, "kaan").await; | |
| 3333 | + promote(&db, "mudur", "manager").await; | |
| 3334 | + login(&mudur, &base, "mudur").await; | |
| 3335 | + login(&ogrenci, &base, "ogrenci").await; | |
| 3336 | + login(&kaan, &base, "kaan").await; | |
| 3337 | + | |
| 3338 | + let json_of = async |res: reqwest::Response| res.json::<Value>().await.unwrap(); | |
| 3339 | + let student_id = | |
| 3340 | + json_of(ogrenci.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"] | |
| 3341 | + .as_str() | |
| 3342 | + .unwrap() | |
| 3343 | + .to_string(); | |
| 3344 | + let kaan_id = json_of(kaan.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"] | |
| 3345 | + .as_str() | |
| 3346 | + .unwrap() | |
| 3347 | + .to_string(); | |
| 3348 | + let now = json_of(mudur.get(format!("{base}/time")).send().await.unwrap()).await["now"] | |
| 3349 | + .as_i64() | |
| 3350 | + .unwrap(); | |
| 3351 | + | |
| 3352 | + // --- a year's worth of structure, all hanging off one term ------------- | |
| 3353 | + let res = mudur | |
| 3354 | + .post(format!("{base}/terms")) | |
| 3355 | + .json(&json!({ "name": "2026 Fall", "starts_at": now - 86_400_000, "ends_at": now + 86_400_000 })) | |
| 3356 | + .send() | |
| 3357 | + .await | |
| 3358 | + .unwrap(); | |
| 3359 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3360 | + let term: Value = res.json().await.unwrap(); | |
| 3361 | + let term_id = term["id"].as_str().unwrap().to_string(); | |
| 3362 | + assert!( | |
| 3363 | + term["archived_at"].is_null(), | |
| 3364 | + "a fresh term is open: {term}" | |
| 3365 | + ); | |
| 3366 | + | |
| 3367 | + let res = mudur | |
| 3368 | + .post(format!("{base}/courses")) | |
| 3369 | + .json(&json!({ "title": "algebra", "term_id": term_id })) | |
| 3370 | + .send() | |
| 3371 | + .await | |
| 3372 | + .unwrap(); | |
| 3373 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3374 | + let course_id = json_of(res).await["id"].as_str().unwrap().to_string(); | |
| 3375 | + | |
| 3376 | + let subject_id = json_of( | |
| 3377 | + mudur | |
| 3378 | + .post(format!("{base}/courses/{course_id}/subjects")) | |
| 3379 | + .json(&json!({ "name": "arithmetic" })) | |
| 3380 | + .send() | |
| 3381 | + .await | |
| 3382 | + .unwrap(), | |
| 3383 | + ) | |
| 3384 | + .await["id"] | |
| 3385 | + .as_str() | |
| 3386 | + .unwrap() | |
| 3387 | + .to_string(); | |
| 3388 | + | |
| 3389 | + let exam: Value = json_of( | |
| 3390 | + mudur | |
| 3391 | + .post(format!("{base}/courses/{course_id}/exams")) | |
| 3392 | + .json(&json!({ "title": "midterm", "kind": "quiz", "mode": "open", "max_attempts": 2 })) | |
| 3393 | + .send() | |
| 3394 | + .await | |
| 3395 | + .unwrap(), | |
| 3396 | + ) | |
| 3397 | + .await; | |
| 3398 | + let exam_id = exam["id"].as_str().unwrap().to_string(); | |
| 3399 | + let question: Value = json_of( | |
| 3400 | + mudur | |
| 3401 | + .post(format!("{base}/exams/{exam_id}/questions")) | |
| 3402 | + .json( | |
| 3403 | + &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice", | |
| 3404 | + "points": 10, | |
| 3405 | + "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}], | |
| 3406 | + "correct": "b" }), | |
| 3407 | + ) | |
| 3408 | + .send() | |
| 3409 | + .await | |
| 3410 | + .unwrap(), | |
| 3411 | + ) | |
| 3412 | + .await; | |
| 3413 | + let question_id = question["id"].as_str().unwrap().to_string(); | |
| 3414 | + let opts = choice_ids(&question); | |
| 3415 | + | |
| 3416 | + let res = mudur | |
| 3417 | + .post(format!("{base}/courses/{course_id}/sessions")) | |
| 3418 | + .json(&json!({ "starts_at": now + 3_600_000 })) | |
| 3419 | + .send() | |
| 3420 | + .await | |
| 3421 | + .unwrap(); | |
| 3422 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3423 | + let session_id = json_of(res).await["id"].as_str().unwrap().to_string(); | |
| 3424 | + | |
| 3425 | + let res = mudur | |
| 3426 | + .post(format!("{base}/courses/{course_id}/homework")) | |
| 3427 | + .json( | |
| 3428 | + &json!({ "title": "read ch3", "subject_id": subject_id, "due_at": now + 604_800_000 }), | |
| 3429 | + ) | |
| 3430 | + .send() | |
| 3431 | + .await | |
| 3432 | + .unwrap(); | |
| 3433 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3434 | + let homework_id = json_of(res).await["id"].as_str().unwrap().to_string(); | |
| 3435 | + | |
| 3436 | + let res = mudur | |
| 3437 | + .post(format!("{base}/course-notes")) | |
| 3438 | + .json(&json!({ "course": course_id, "title": "recap", "content": "quadratics" })) | |
| 3439 | + .send() | |
| 3440 | + .await | |
| 3441 | + .unwrap(); | |
| 3442 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3443 | + let note_id = json_of(res).await["id"].as_str().unwrap().to_string(); | |
| 3444 | + | |
| 3445 | + let res = mudur | |
| 3446 | + .post(format!("{base}/classes")) | |
| 3447 | + .json(&json!({ "name": "9-A", "grade": "9", "term_id": term_id })) | |
| 3448 | + .send() | |
| 3449 | + .await | |
| 3450 | + .unwrap(); | |
| 3451 | + assert_eq!(res.status(), StatusCode::CREATED); | |
| 3452 | + let class_id = json_of(res).await["class"]["id"] | |
| 3453 | + .as_str() | |
| 3454 | + .unwrap() | |
| 3455 | + .to_string(); | |
| 3456 | + | |
| 3457 | + let res = mudur | |
| 3458 | + .post(format!("{base}/courses/{course_id}/enrollments")) | |
| 3459 | + .json(&json!({ "user_id": student_id })) | |
| 3460 | + .send() | |
| 3461 | + .await | |
| 3462 | + .unwrap(); | |
| 3463 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3464 | + | |
| 3465 | + // The student is mid-sitting when the year closes: a live attempt whose | |
| 3466 | + // room door is about to be walled. | |
| 3467 | + let res = ogrenci | |
| 3468 | + .post(format!("{base}/exams/{exam_id}/attempt")) | |
| 3469 | + .send() | |
| 3470 | + .await | |
| 3471 | + .unwrap(); | |
| 3472 | + assert_eq!(res.status(), StatusCode::CREATED, "start the live sitting"); | |
| 3473 | + let student_cookie = raw_session_cookie(&base, "ogrenci").await; | |
| 3474 | + | |
| 3475 | + // --- archive ---------------------------------------------------------- | |
| 3476 | + let res = mudur | |
| 3477 | + .post(format!("{base}/terms/{term_id}/archive")) | |
| 3478 | + .send() | |
| 3479 | + .await | |
| 3480 | + .unwrap(); | |
| 3481 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3482 | + let archived: Value = res.json().await.unwrap(); | |
| 3483 | + let stamp = archived["archived_at"].as_i64().expect("archived_at stamp"); | |
| 3484 | + | |
| 3485 | + // Idempotent: a second archive answers 200 with the stamp it already had. | |
| 3486 | + let res = mudur | |
| 3487 | + .post(format!("{base}/terms/{term_id}/archive")) | |
| 3488 | + .send() | |
| 3489 | + .await | |
| 3490 | + .unwrap(); | |
| 3491 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3492 | + assert_eq!( | |
| 3493 | + json_of(res).await["archived_at"].as_i64(), | |
| 3494 | + Some(stamp), | |
| 3495 | + "re-archiving must not move the stamp" | |
| 3496 | + ); | |
| 3497 | + | |
| 3498 | + // --- every write into the closed year is a 409 `term_archived` --------- | |
| 3499 | + let refusals: Vec<(&str, reqwest::Response)> = vec![ | |
| 3500 | + ( | |
| 3501 | + "PATCH /terms/{id}", | |
| 3502 | + mudur | |
| 3503 | + .patch(format!("{base}/terms/{term_id}")) | |
| 3504 | + .json(&json!({ "name": "renamed" })) | |
| 3505 | + .send() | |
| 3506 | + .await | |
| 3507 | + .unwrap(), | |
| 3508 | + ), | |
| 3509 | + ( | |
| 3510 | + "PATCH /courses/{id}", | |
| 3511 | + mudur | |
| 3512 | + .patch(format!("{base}/courses/{course_id}")) | |
| 3513 | + .json(&json!({ "title": "renamed" })) | |
| 3514 | + .send() | |
| 3515 | + .await | |
| 3516 | + .unwrap(), | |
| 3517 | + ), | |
| 3518 | + ( | |
| 3519 | + "POST /courses/{id}/enrollments", | |
| 3520 | + mudur | |
| 3521 | + .post(format!("{base}/courses/{course_id}/enrollments")) | |
| 3522 | + .json(&json!({ "user_id": kaan_id })) | |
| 3523 | + .send() | |
| 3524 | + .await | |
| 3525 | + .unwrap(), | |
| 3526 | + ), | |
| 3527 | + ( | |
| 3528 | + "POST /sessions/{id}/attendance", | |
| 3529 | + mudur | |
| 3530 | + .post(format!("{base}/sessions/{session_id}/attendance")) | |
| 3531 | + .json(&json!({ "status": "present", "user_id": student_id })) | |
| 3532 | + .send() | |
| 3533 | + .await | |
| 3534 | + .unwrap(), | |
| 3535 | + ), | |
| 3536 | + ( | |
| 3537 | + "PATCH /exams/{id}", | |
| 3538 | + mudur | |
| 3539 | + .patch(format!("{base}/exams/{exam_id}")) | |
| 3540 | + .json(&json!({ "title": "renamed" })) | |
| 3541 | + .send() | |
| 3542 | + .await | |
| 3543 | + .unwrap(), | |
| 3544 | + ), | |
| 3545 | + ( | |
| 3546 | + "POST /exams/{id}/attempt/answers", | |
| 3547 | + ogrenci | |
| 3548 | + .post(format!("{base}/exams/{exam_id}/attempt/answers")) | |
| 3549 | + .json(&json!({ "question_id": question_id, "selected": opts[1] })) | |
| 3550 | + .send() | |
| 3551 | + .await | |
| 3552 | + .unwrap(), | |
| 3553 | + ), | |
| 3554 | + ( | |
| 3555 | + "POST /homework/{id}/results", | |
| 3556 | + mudur | |
| 3557 | + .post(format!("{base}/homework/{homework_id}/results")) | |
| 3558 | + .json(&json!({ "user": student_id, "status": "done", "mark": 90 })) | |
| 3559 | + .send() | |
| 3560 | + .await | |
| 3561 | + .unwrap(), | |
| 3562 | + ), | |
| 3563 | + ( | |
| 3564 | + "PATCH /course-notes/{id}", | |
| 3565 | + mudur | |
| 3566 | + .patch(format!("{base}/course-notes/{note_id}")) | |
| 3567 | + .json(&json!({ "title": "renamed" })) | |
| 3568 | + .send() | |
| 3569 | + .await | |
| 3570 | + .unwrap(), | |
| 3571 | + ), | |
| 3572 | + ( | |
| 3573 | + "POST /classes/{id}/members", | |
| 3574 | + mudur | |
| 3575 | + .post(format!("{base}/classes/{class_id}/members")) | |
| 3576 | + .json(&json!({ "user_id": kaan_id })) | |
| 3577 | + .send() | |
| 3578 | + .await | |
| 3579 | + .unwrap(), | |
| 3580 | + ), | |
| 3581 | + ]; | |
| 3582 | + for (what, res) in refusals { | |
| 3583 | + let status = res.status(); | |
| 3584 | + let body: Value = res.json().await.unwrap(); | |
| 3585 | + assert_eq!(status, StatusCode::CONFLICT, "{what} status: {body}"); | |
| 3586 | + assert_eq!(body["code"], "term_archived", "{what} code: {body}"); | |
| 3587 | + } | |
| 3588 | + | |
| 3589 | + // --- every read still answers ----------------------------------------- | |
| 3590 | + for url in [ | |
| 3591 | + format!("{base}/terms/{term_id}"), | |
| 3592 | + format!("{base}/courses/{course_id}"), | |
| 3593 | + format!("{base}/exams/{exam_id}"), | |
| 3594 | + format!("{base}/sessions/{session_id}"), | |
| 3595 | + format!("{base}/homework/{homework_id}"), | |
| 3596 | + format!("{base}/course-notes/{note_id}"), | |
| 3597 | + format!("{base}/classes/{class_id}"), | |
| 3598 | + ] { | |
| 3599 | + let res = mudur.get(&url).send().await.unwrap(); | |
| 3600 | + assert_eq!(res.status(), StatusCode::OK, "read stays open: {url}"); | |
| 3601 | + } | |
| 3602 | + | |
| 3603 | + // --- the exam room's door: refused before the upgrade ------------------ | |
| 3604 | + let refused = ws_open(&base, &exam_id, Some(&student_cookie)) | |
| 3605 | + .await | |
| 3606 | + .expect_err("an archived year's room must refuse the handshake"); | |
| 3607 | + assert_eq!(refused, 409, "the room door answers a real HTTP 409"); | |
| 3608 | + | |
| 3609 | + // --- unarchive reopens the year --------------------------------------- | |
| 3610 | + let res = mudur | |
| 3611 | + .post(format!("{base}/terms/{term_id}/unarchive")) | |
| 3612 | + .send() | |
| 3613 | + .await | |
| 3614 | + .unwrap(); | |
| 3615 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3616 | + let reopened: Value = res.json().await.unwrap(); | |
| 3617 | + assert!( | |
| 3618 | + reopened["archived_at"].is_null(), | |
| 3619 | + "unarchive clears the stamp: {reopened}" | |
| 3620 | + ); | |
| 3621 | + | |
| 3622 | + // A write that was refused a moment ago now lands. | |
| 3623 | + let res = mudur | |
| 3624 | + .patch(format!("{base}/courses/{course_id}")) | |
| 3625 | + .json(&json!({ "title": "algebra II" })) | |
| 3626 | + .send() | |
| 3627 | + .await | |
| 3628 | + .unwrap(); | |
| 3629 | + assert_eq!( | |
| 3630 | + res.status(), | |
| 3631 | + StatusCode::OK, | |
| 3632 | + "the reopened year takes writes" | |
| 3633 | + ); | |
| 3634 | + | |
| 3635 | + // The room door opens again, and the live sitting is still there. | |
| 3636 | + let mut ws = ws_open(&base, &exam_id, Some(&student_cookie)) | |
| 3637 | + .await | |
| 3638 | + .expect("the reopened year's room"); | |
| 3639 | + let state = ws_next_frame(&mut ws).await.expect("connect state frame"); | |
| 3640 | + assert_eq!(state["type"], "state", "{state}"); | |
| 3641 | + | |
| 3642 | + // Archive under the open socket: `finish` comes back as an error frame | |
| 3643 | + // carrying the archived refusal instead of submitting the sheet. | |
| 3644 | + let res = mudur | |
| 3645 | + .post(format!("{base}/terms/{term_id}/archive")) | |
| 3646 | + .send() | |
| 3647 | + .await | |
| 3648 | + .unwrap(); | |
| 3649 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3650 | + ws_send(&mut ws, json!({ "type": "finish" })).await; | |
| 3651 | + let error = ws_frame_of_type(&mut ws, "error").await; | |
| 3652 | + assert!( | |
| 3653 | + error["message"].as_str().unwrap().contains("archived"), | |
| 3654 | + "the room's finish refusal names the archived year: {error}" | |
| 3655 | + ); | |
| 3656 | + | |
| 3657 | + // Reopen once more and the same frame submits the sitting. | |
| 3658 | + let res = mudur | |
| 3659 | + .post(format!("{base}/terms/{term_id}/unarchive")) | |
| 3660 | + .send() | |
| 3661 | + .await | |
| 3662 | + .unwrap(); | |
| 3663 | + assert_eq!(res.status(), StatusCode::OK); | |
| 3664 | + ws_send(&mut ws, json!({ "type": "finish" })).await; | |
| 3665 | + let finished = ws_frame_of_type(&mut ws, "finished").await; | |
| 3666 | + assert!(finished["finished_at"].as_i64().is_some(), "{finished}"); | |
| 3667 | + | |
| 3668 | + // --- discoverable in the document Swagger renders ---------------------- | |
| 3669 | + let spec: Value = json_of( | |
| 3670 | + mudur | |
| 3671 | + .get(format!("{base}/api-docs/openapi.json")) | |
| 3672 | + .send() | |
| 3673 | + .await | |
| 3674 | + .unwrap(), | |
| 3675 | + ) | |
| 3676 | + .await; | |
| 3677 | + for path in ["/terms/{id}/archive", "/terms/{id}/unarchive"] { | |
| 3678 | + assert!( | |
| 3679 | + spec["paths"][path]["post"].is_object(), | |
| 3680 | + "{path} must be a documented POST in the served spec" | |
| 3681 | + ); | |
| 3682 | + } | |
| 3683 | +} |
tests/partial_patch_terms.rsmodified+147 -0
| @@ -110,3 +110,150 @@ async fn concurrent_range_patches_never_invert_the_term() { | ||
| 110 | 110 | ); |
| 111 | 111 | } |
| 112 | 112 | } |
| 113 | + | |
| 114 | +/// Archiving a term freezes it: the term itself takes no PATCH or DELETE, and | |
| 115 | +/// no new course or class may link it. Reads stay open — a past year is | |
| 116 | +/// read-only, not hidden. | |
| 117 | +#[tokio::test] | |
| 118 | +async fn an_archived_term_is_frozen_for_writes_and_open_for_reads() { | |
| 119 | + let (app, db) = app_and_db().await; | |
| 120 | + let manager = login_as(&app, &db, "archive_manager", "manager").await; | |
| 121 | + let teacher = login_as(&app, &db, "archive_teacher", "teacher").await; | |
| 122 | + let student = login_as(&app, &db, "archive_student", "student").await; | |
| 123 | + | |
| 124 | + let created = send( | |
| 125 | + &app, | |
| 126 | + "POST", | |
| 127 | + "/terms", | |
| 128 | + Some(&manager), | |
| 129 | + Some(json!({ | |
| 130 | + "name": "2024", | |
| 131 | + "starts_at": 1_700_000_000_000_i64, | |
| 132 | + "ends_at": 1_710_000_000_000_i64, | |
| 133 | + })), | |
| 134 | + ) | |
| 135 | + .await; | |
| 136 | + assert_eq!(created.status, StatusCode::CREATED); | |
| 137 | + assert!(created.body["archived_at"].is_null(), "born open"); | |
| 138 | + let id = id_of(&created.body); | |
| 139 | + let uri = format!("/terms/{id}"); | |
| 140 | + let archive = format!("/terms/{id}/archive"); | |
| 141 | + | |
| 142 | + // Only manager+ may flip it. | |
| 143 | + for (who, cookie) in [("teacher", &teacher), ("student", &student)] { | |
| 144 | + let res = send(&app, "POST", &archive, Some(cookie), None).await; | |
| 145 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{who} archive"); | |
| 146 | + } | |
| 147 | + | |
| 148 | + let archived = send(&app, "POST", &archive, Some(&manager), None).await; | |
| 149 | + assert_eq!(archived.status, StatusCode::OK); | |
| 150 | + let stamp = archived.body["archived_at"].as_i64().expect("archived_at"); | |
| 151 | + | |
| 152 | + // Idempotent: a repeat keeps the original stamp, the year is not re-dated. | |
| 153 | + let again = send(&app, "POST", &archive, Some(&manager), None).await; | |
| 154 | + assert_eq!(again.status, StatusCode::OK); | |
| 155 | + assert_eq!( | |
| 156 | + again.body["archived_at"].as_i64(), | |
| 157 | + Some(stamp), | |
| 158 | + "re-stamped" | |
| 159 | + ); | |
| 160 | + | |
| 161 | + // Frozen: edit and delete both refuse with the coded 409. | |
| 162 | + for (method, body) in [ | |
| 163 | + ("PATCH", Some(json!({ "name": "renamed" }))), | |
| 164 | + ("DELETE", None), | |
| 165 | + ] { | |
| 166 | + let res = send(&app, method, &uri, Some(&manager), body).await; | |
| 167 | + assert_eq!( | |
| 168 | + res.status, | |
| 169 | + StatusCode::CONFLICT, | |
| 170 | + "{method} on archived term" | |
| 171 | + ); | |
| 172 | + assert_eq!(res.body["code"], "term_archived", "{method} code"); | |
| 173 | + } | |
| 174 | + | |
| 175 | + // No new structure may be hung on a past year — one refusal per link site. | |
| 176 | + let new_course = send( | |
| 177 | + &app, | |
| 178 | + "POST", | |
| 179 | + "/courses", | |
| 180 | + Some(&manager), | |
| 181 | + Some(json!({ "title": "algebra", "term_id": id })), | |
| 182 | + ) | |
| 183 | + .await; | |
| 184 | + assert_eq!(new_course.status, StatusCode::CONFLICT, "course link"); | |
| 185 | + assert_eq!(new_course.body["code"], "term_archived"); | |
| 186 | + let new_class = send( | |
| 187 | + &app, | |
| 188 | + "POST", | |
| 189 | + "/classes", | |
| 190 | + Some(&manager), | |
| 191 | + Some(json!({ "name": "9-A", "term_id": id })), | |
| 192 | + ) | |
| 193 | + .await; | |
| 194 | + assert_eq!(new_class.status, StatusCode::CONFLICT, "class link"); | |
| 195 | + assert_eq!(new_class.body["code"], "term_archived"); | |
| 196 | + | |
| 197 | + // Reads keep working and carry the stamp, single and listed. | |
| 198 | + let one = send(&app, "GET", &uri, Some(&student), None).await; | |
| 199 | + assert_eq!(one.status, StatusCode::OK); | |
| 200 | + assert_eq!(one.body["archived_at"].as_i64(), Some(stamp)); | |
| 201 | + let listed = send(&app, "GET", "/terms", Some(&student), None).await; | |
| 202 | + assert_eq!(listed.status, StatusCode::OK); | |
| 203 | + let row = listed.body["items"] | |
| 204 | + .as_array() | |
| 205 | + .expect("items") | |
| 206 | + .iter() | |
| 207 | + .find(|row| row["id"] == id.as_str()) | |
| 208 | + .expect("the archived term is still listed"); | |
| 209 | + assert_eq!(row["archived_at"].as_i64(), Some(stamp)); | |
| 210 | + | |
| 211 | + // Re-opening thaws it, and is idempotent too. | |
| 212 | + let unarchive = format!("/terms/{id}/unarchive"); | |
| 213 | + let reopened = send(&app, "POST", &unarchive, Some(&manager), None).await; | |
| 214 | + assert_eq!(reopened.status, StatusCode::OK); | |
| 215 | + assert!(reopened.body["archived_at"].is_null(), "reopened"); | |
| 216 | + let twice = send(&app, "POST", &unarchive, Some(&manager), None).await; | |
| 217 | + assert_eq!(twice.status, StatusCode::OK); | |
| 218 | + assert!(twice.body["archived_at"].is_null()); | |
| 219 | + let patched = send( | |
| 220 | + &app, | |
| 221 | + "PATCH", | |
| 222 | + &uri, | |
| 223 | + Some(&manager), | |
| 224 | + Some(json!({ "name": "renamed" })), | |
| 225 | + ) | |
| 226 | + .await; | |
| 227 | + assert_eq!(patched.status, StatusCode::OK, "open again, edits land"); | |
| 228 | + | |
| 229 | + // An id nobody minted is a 404 on both flips, not a 409. | |
| 230 | + for route in ["/terms/nope/archive", "/terms/nope/unarchive"] { | |
| 231 | + let res = send(&app, "POST", route, Some(&manager), None).await; | |
| 232 | + assert_eq!(res.status, StatusCode::NOT_FOUND, "{route}"); | |
| 233 | + } | |
| 234 | +} | |
| 235 | + | |
| 236 | +/// A term row written before `archived_at` existed has no such column. It must | |
| 237 | +/// still decode — as an open term — or the migration would have needed a | |
| 238 | +/// backfill it deliberately does not have. | |
| 239 | +#[tokio::test] | |
| 240 | +async fn a_pre_migration_term_row_still_decodes_as_open() { | |
| 241 | + let (app, db) = app_and_db().await; | |
| 242 | + let manager = login_as(&app, &db, "archive_legacy_manager", "manager").await; | |
| 243 | + | |
| 244 | + db.query("CREATE term:legacy SET name = 'old', starts_at = 100, ends_at = 200") | |
| 245 | + .await | |
| 246 | + .expect("legacy term query") | |
| 247 | + .check() | |
| 248 | + .expect("legacy term check"); | |
| 249 | + | |
| 250 | + let res = send(&app, "GET", "/terms/legacy", Some(&manager), None).await; | |
| 251 | + assert_eq!(res.status, StatusCode::OK, "pre-migration row must decode"); | |
| 252 | + assert_eq!(res.body["name"], "old"); | |
| 253 | + assert!(res.body["archived_at"].is_null(), "absent = open"); | |
| 254 | + | |
| 255 | + // And it is still writable, archiving included. | |
| 256 | + let archived = send(&app, "POST", "/terms/legacy/archive", Some(&manager), None).await; | |
| 257 | + assert_eq!(archived.status, StatusCode::OK); | |
| 258 | + assert!(archived.body["archived_at"].as_i64().is_some()); | |
| 259 | +} |
tests/regress_attendance.rsmodified+121 -0
| @@ -409,3 +409,124 @@ async fn an_event_mark_writes_its_event_and_is_refused_once_it_is_gone() { | ||
| 409 | 409 | "no orphan row was written" |
| 410 | 410 | ); |
| 411 | 411 | } |
| 412 | + | |
| 413 | +/// #22, session half: a course sitting in an archived term is a past year — | |
| 414 | +/// its sessions and their roll call are read-only. The guard runs *after* the | |
| 415 | +/// authorization check (403 before 409, so a stranger never learns a term's | |
| 416 | +/// state) and off the `course` the shared session loader already returns, not | |
| 417 | +/// inside that loader — reads go through it too, and reads stay open. | |
| 418 | +#[tokio::test] | |
| 419 | +async fn an_archived_term_freezes_its_sessions_and_roll_call() { | |
| 420 | + let (app, db) = app_and_db().await; | |
| 421 | + let manager = login_as(&app, &db, "arch_sess_manager", "manager").await; | |
| 422 | + let ali = login(&app, "arch_sess_ali").await; | |
| 423 | + let ali_id = me_id(&app, &ali).await; | |
| 424 | + | |
| 425 | + let term = send( | |
| 426 | + &app, | |
| 427 | + "POST", | |
| 428 | + "/terms", | |
| 429 | + Some(&manager), | |
| 430 | + Some(json!({ | |
| 431 | + "name": "2023", | |
| 432 | + "starts_at": 1_600_000_000_000_i64, | |
| 433 | + "ends_at": 1_610_000_000_000_i64, | |
| 434 | + })), | |
| 435 | + ) | |
| 436 | + .await; | |
| 437 | + assert_eq!(term.status, StatusCode::CREATED, "{}", term.body); | |
| 438 | + let term_id = common::id_of(&term.body); | |
| 439 | + | |
| 440 | + let course = send( | |
| 441 | + &app, | |
| 442 | + "POST", | |
| 443 | + "/courses", | |
| 444 | + Some(&manager), | |
| 445 | + Some(json!({ "title": "Tarih", "term_id": term_id })), | |
| 446 | + ) | |
| 447 | + .await; | |
| 448 | + assert_eq!(course.status, StatusCode::CREATED, "{}", course.body); | |
| 449 | + let course_id = common::id_of(&course.body); | |
| 450 | + enroll(&app, &manager, &course_id, &ali_id).await; | |
| 451 | + let session = create_session(&app, &manager, &course_id, soon()).await; | |
| 452 | + // A roll-call row exists before the freeze, so the delete route reaches the | |
| 453 | + // guard rather than a 404 for a missing row. | |
| 454 | + let marked = send( | |
| 455 | + &app, | |
| 456 | + "POST", | |
| 457 | + &format!("/sessions/{session}/attendance"), | |
| 458 | + Some(&manager), | |
| 459 | + Some(json!({ "status": "present", "user_id": ali_id })), | |
| 460 | + ) | |
| 461 | + .await; | |
| 462 | + assert_eq!(marked.status, StatusCode::OK, "{}", marked.body); | |
| 463 | + | |
| 464 | + let archived = send( | |
| 465 | + &app, | |
| 466 | + "POST", | |
| 467 | + &format!("/terms/{term_id}/archive"), | |
| 468 | + Some(&manager), | |
| 469 | + None, | |
| 470 | + ) | |
| 471 | + .await; | |
| 472 | + assert_eq!(archived.status, StatusCode::OK, "{}", archived.body); | |
| 473 | + | |
| 474 | + // Every write on the session and its roll call refuses with the coded 409. | |
| 475 | + let writes: [(&str, String, Option<serde_json::Value>); 4] = [ | |
| 476 | + ( | |
| 477 | + "PATCH", | |
| 478 | + format!("/sessions/{session}"), | |
| 479 | + Some(json!({ "topic": "yeni" })), | |
| 480 | + ), | |
| 481 | + ( | |
| 482 | + "POST", | |
| 483 | + format!("/sessions/{session}/attendance"), | |
| 484 | + Some(json!({ "status": "absent", "user_id": ali_id })), | |
| 485 | + ), | |
| 486 | + ( | |
| 487 | + "DELETE", | |
| 488 | + format!("/sessions/{session}/attendance/{ali_id}"), | |
| 489 | + None, | |
| 490 | + ), | |
| 491 | + ("DELETE", format!("/sessions/{session}"), None), | |
| 492 | + ]; | |
| 493 | + for (method, uri, body) in writes { | |
| 494 | + let res = send(&app, method, &uri, Some(&manager), body).await; | |
| 495 | + assert_eq!( | |
| 496 | + res.status, | |
| 497 | + StatusCode::CONFLICT, | |
| 498 | + "{method} {uri}: {}", | |
| 499 | + res.body | |
| 500 | + ); | |
| 501 | + assert_eq!(res.body["code"], "term_archived", "{method} {uri}"); | |
| 502 | + } | |
| 503 | + | |
| 504 | + // Reads stay open — a past year is read-only, not hidden. | |
| 505 | + for uri in [ | |
| 506 | + format!("/sessions/{session}"), | |
| 507 | + format!("/sessions/{session}/attendance"), | |
| 508 | + ] { | |
| 509 | + let res = send(&app, "GET", &uri, Some(&manager), None).await; | |
| 510 | + assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body); | |
| 511 | + } | |
| 512 | + | |
| 513 | + // Re-opening the year thaws the writes again. | |
| 514 | + let reopened = send( | |
| 515 | + &app, | |
| 516 | + "POST", | |
| 517 | + &format!("/terms/{term_id}/unarchive"), | |
| 518 | + Some(&manager), | |
| 519 | + None, | |
| 520 | + ) | |
| 521 | + .await; | |
| 522 | + assert_eq!(reopened.status, StatusCode::OK, "{}", reopened.body); | |
| 523 | + let res = send( | |
| 524 | + &app, | |
| 525 | + "PATCH", | |
| 526 | + &format!("/sessions/{session}"), | |
| 527 | + Some(&manager), | |
| 528 | + Some(json!({ "topic": "yeni" })), | |
| 529 | + ) | |
| 530 | + .await; | |
| 531 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 532 | +} |
tests/regress_classes.rsmodified+185 -0
| @@ -1818,3 +1818,188 @@ async fn a_detach_never_hands_a_row_to_a_class_that_is_gone() { | ||
| 1818 | 1818 | "…and its seat must come back with it" |
| 1819 | 1819 | ); |
| 1820 | 1820 | } |
| 1821 | + | |
| 1822 | +/// #22. A class on an archived term is read-only: every write axis it has — | |
| 1823 | +/// the class itself, its roster, its attachments and the blueprint pump — | |
| 1824 | +/// answers the coded 409, while every read stays open. The term the *course* | |
| 1825 | +/// sits on holds the same bar from the other side, and re-opening the year | |
| 1826 | +/// thaws all of it. | |
| 1827 | +#[tokio::test] | |
| 1828 | +async fn an_archived_term_freezes_every_class_write_and_no_read() { | |
| 1829 | + let (app, db) = app_and_db().await; | |
| 1830 | + let manager = login_as(&app, &db, "arch_manager", "manager").await; | |
| 1831 | + let student = login_as(&app, &db, "arch_student", "student").await; | |
| 1832 | + let other = login_as(&app, &db, "arch_other", "student").await; | |
| 1833 | + let student_id = me_id(&app, &student).await; | |
| 1834 | + let other_id = me_id(&app, &other).await; | |
| 1835 | + | |
| 1836 | + let term = send( | |
| 1837 | + &app, | |
| 1838 | + "POST", | |
| 1839 | + "/terms", | |
| 1840 | + Some(&manager), | |
| 1841 | + Some(json!({ | |
| 1842 | + "name": "2024", | |
| 1843 | + "starts_at": 1_700_000_000_000_i64, | |
| 1844 | + "ends_at": 1_710_000_000_000_i64, | |
| 1845 | + })), | |
| 1846 | + ) | |
| 1847 | + .await; | |
| 1848 | + assert_eq!(term.status, StatusCode::CREATED); | |
| 1849 | + let term_id = common::id_of(&term.body); | |
| 1850 | + | |
| 1851 | + // A course on that same year, and one on no year at all — the second is | |
| 1852 | + // what proves a refusal came from the *class's* side. | |
| 1853 | + let dated = send( | |
| 1854 | + &app, | |
| 1855 | + "POST", | |
| 1856 | + "/courses", | |
| 1857 | + Some(&manager), | |
| 1858 | + Some(json!({ "title": "algebra", "term_id": term_id })), | |
| 1859 | + ) | |
| 1860 | + .await; | |
| 1861 | + assert_eq!(dated.status, StatusCode::CREATED); | |
| 1862 | + let dated = common::id_of(&dated.body); | |
| 1863 | + let open_course = create_course(&app, &manager, "geometry").await; | |
| 1864 | + | |
| 1865 | + let class = create_class( | |
| 1866 | + &app, | |
| 1867 | + &manager, | |
| 1868 | + json!({ "name": "9-A", "grade": "9", "term_id": term_id }), | |
| 1869 | + ) | |
| 1870 | + .await; | |
| 1871 | + let class = common::id_of(&class.body); | |
| 1872 | + | |
| 1873 | + // Everything the frozen state must already hold: an attachment, a member, | |
| 1874 | + // and a blueprint at this grade for the pump to try. | |
| 1875 | + let attached = send( | |
| 1876 | + &app, | |
| 1877 | + "POST", | |
| 1878 | + &format!("/classes/{class}/courses"), | |
| 1879 | + Some(&manager), | |
| 1880 | + Some(json!({ "course_id": dated })), | |
| 1881 | + ) | |
| 1882 | + .await; | |
| 1883 | + assert_eq!(attached.status, StatusCode::CREATED, "attach while open"); | |
| 1884 | + let joined = send( | |
| 1885 | + &app, | |
| 1886 | + "POST", | |
| 1887 | + &format!("/classes/{class}/members"), | |
| 1888 | + Some(&manager), | |
| 1889 | + Some(json!({ "user_id": student_id })), | |
| 1890 | + ) | |
| 1891 | + .await; | |
| 1892 | + assert_eq!(joined.status, StatusCode::CREATED, "member while open"); | |
| 1893 | + let blueprint = send( | |
| 1894 | + &app, | |
| 1895 | + "POST", | |
| 1896 | + "/classes/blueprints", | |
| 1897 | + Some(&manager), | |
| 1898 | + Some(json!({ "grade": "9", "course_ids": [dated] })), | |
| 1899 | + ) | |
| 1900 | + .await; | |
| 1901 | + assert_eq!(blueprint.status, StatusCode::CREATED, "blueprint"); | |
| 1902 | + | |
| 1903 | + let archived = send( | |
| 1904 | + &app, | |
| 1905 | + "POST", | |
| 1906 | + &format!("/terms/{term_id}/archive"), | |
| 1907 | + Some(&manager), | |
| 1908 | + None, | |
| 1909 | + ) | |
| 1910 | + .await; | |
| 1911 | + assert_eq!(archived.status, StatusCode::OK); | |
| 1912 | + | |
| 1913 | + // One refusal per write route, each 409 with the machine code — never a | |
| 1914 | + // bare 409, which a client cannot tell from a capacity conflict. | |
| 1915 | + let writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![ | |
| 1916 | + ( | |
| 1917 | + "PATCH", | |
| 1918 | + format!("/classes/{class}"), | |
| 1919 | + Some(json!({ "name": "9-B" })), | |
| 1920 | + ), | |
| 1921 | + ( | |
| 1922 | + "POST", | |
| 1923 | + format!("/classes/{class}/members"), | |
| 1924 | + Some(json!({ "user_id": other_id })), | |
| 1925 | + ), | |
| 1926 | + ( | |
| 1927 | + "DELETE", | |
| 1928 | + format!("/classes/{class}/members/{student_id}"), | |
| 1929 | + None, | |
| 1930 | + ), | |
| 1931 | + ( | |
| 1932 | + "POST", | |
| 1933 | + format!("/classes/{class}/courses"), | |
| 1934 | + // An *open* course: the class's own term is the refusal. | |
| 1935 | + Some(json!({ "course_id": open_course })), | |
| 1936 | + ), | |
| 1937 | + ("DELETE", format!("/classes/{class}/courses/{dated}"), None), | |
| 1938 | + ("POST", format!("/classes/{class}/blueprint"), None), | |
| 1939 | + ("DELETE", format!("/classes/{class}"), None), | |
| 1940 | + ]; | |
| 1941 | + for (method, uri, body) in writes { | |
| 1942 | + let res = send(&app, method, &uri, Some(&manager), body).await; | |
| 1943 | + assert_eq!(res.status, StatusCode::CONFLICT, "{method} {uri}"); | |
| 1944 | + assert_eq!(res.body["code"], "term_archived", "{method} {uri} code"); | |
| 1945 | + } | |
| 1946 | + | |
| 1947 | + // Reads are untouched — a past year is read-only, not hidden. | |
| 1948 | + for uri in [ | |
| 1949 | + format!("/classes/{class}"), | |
| 1950 | + format!("/classes/{class}/members"), | |
| 1951 | + format!("/classes/{class}/courses"), | |
| 1952 | + ] { | |
| 1953 | + let res = send(&app, "GET", &uri, Some(&manager), None).await; | |
| 1954 | + assert_eq!(res.status, StatusCode::OK, "GET {uri}"); | |
| 1955 | + } | |
| 1956 | + let members = send( | |
| 1957 | + &app, | |
| 1958 | + "GET", | |
| 1959 | + &format!("/classes/{class}/members"), | |
| 1960 | + Some(&manager), | |
| 1961 | + None, | |
| 1962 | + ) | |
| 1963 | + .await; | |
| 1964 | + assert_eq!(total(&members.body), 1, "no write landed"); | |
| 1965 | + | |
| 1966 | + // The other side of the attach: an open class may not take a course whose | |
| 1967 | + // own term is archived. | |
| 1968 | + let open_class = create_class(&app, &manager, json!({ "name": "10-A" })).await; | |
| 1969 | + let open_class = common::id_of(&open_class.body); | |
| 1970 | + let cross = send( | |
| 1971 | + &app, | |
| 1972 | + "POST", | |
| 1973 | + &format!("/classes/{open_class}/courses"), | |
| 1974 | + Some(&manager), | |
| 1975 | + Some(json!({ "course_id": dated })), | |
| 1976 | + ) | |
| 1977 | + .await; | |
| 1978 | + assert_eq!( | |
| 1979 | + cross.status, | |
| 1980 | + StatusCode::CONFLICT, | |
| 1981 | + "open class, past course" | |
| 1982 | + ); | |
| 1983 | + assert_eq!(cross.body["code"], "term_archived"); | |
| 1984 | + | |
| 1985 | + // Re-opening the year thaws the whole set; one write is enough to show it. | |
| 1986 | + let reopened = send( | |
| 1987 | + &app, | |
| 1988 | + "POST", | |
| 1989 | + &format!("/terms/{term_id}/unarchive"), | |
| 1990 | + Some(&manager), | |
| 1991 | + None, | |
| 1992 | + ) | |
| 1993 | + .await; | |
| 1994 | + assert_eq!(reopened.status, StatusCode::OK); | |
| 1995 | + let patched = send( | |
| 1996 | + &app, | |
| 1997 | + "PATCH", | |
| 1998 | + &format!("/classes/{class}"), | |
| 1999 | + Some(&manager), | |
| 2000 | + Some(json!({ "name": "9-B" })), | |
| 2001 | + ) | |
| 2002 | + .await; | |
| 2003 | + assert_eq!(patched.status, StatusCode::OK, "thawed"); | |
| 2004 | + assert_eq!(patched.body["name"], "9-B"); | |
| 2005 | +} |
tests/regress_course_child_orphans.rsmodified+175 -0
| @@ -43,6 +43,10 @@ | ||
| 43 | 43 | //! `RACE_LOCK` that serializes them, and a hand-copied bootstrap here would |
| 44 | 44 | //! drift out of the real one silently. |
| 45 | 45 | |
| 46 | +mod common; | |
| 47 | + | |
| 48 | +use axum::http::StatusCode; | |
| 49 | +use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; | |
| 46 | 50 | use hezarfen_backend::database::{self, Database}; |
| 47 | 51 | use hezarfen_backend::domain::course::{ |
| 48 | 52 | Course, CourseDescription, CourseId, CourseKind, CourseTitle, |
| @@ -58,6 +62,7 @@ use hezarfen_backend::domain::subject::{Subject, SubjectDescription, SubjectName | ||
| 58 | 62 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 59 | 63 | use hezarfen_backend::domain::user::UserId; |
| 60 | 64 | use hezarfen_backend::error::AppError; |
| 65 | +use serde_json::json; | |
| 61 | 66 | use tokio::task::JoinHandle; |
| 62 | 67 | |
| 63 | 68 | fn teacher() -> UserId { |
| @@ -357,3 +362,173 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { | ||
| 357 | 362 | "a refused upload left a row naming a note that is gone" |
| 358 | 363 | ); |
| 359 | 364 | } |
| 365 | + | |
| 366 | +/// #22, the course's own children over HTTP: a course in an archived term is a | |
| 367 | +/// past year, so its subjects and course notes (and note files) refuse every | |
| 368 | +/// write with the coded 409 while all their reads keep answering. The guard | |
| 369 | +/// sits in each write handler after its authorization check — 403 before 409 — | |
| 370 | +/// on the `course` the shared loaders already hand back, never inside those | |
| 371 | +/// loaders, which the read handlers share. | |
| 372 | +#[tokio::test] | |
| 373 | +async fn an_archived_term_freezes_a_course_s_subjects_and_notes() { | |
| 374 | + let (app, db) = app_and_db().await; | |
| 375 | + let manager = login_as(&app, &db, "arch_child_manager", "manager").await; | |
| 376 | + | |
| 377 | + let term = send( | |
| 378 | + &app, | |
| 379 | + "POST", | |
| 380 | + "/terms", | |
| 381 | + Some(&manager), | |
| 382 | + Some(json!({ | |
| 383 | + "name": "2022", | |
| 384 | + "starts_at": 1_500_000_000_000_i64, | |
| 385 | + "ends_at": 1_510_000_000_000_i64, | |
| 386 | + })), | |
| 387 | + ) | |
| 388 | + .await; | |
| 389 | + assert_eq!(term.status, StatusCode::CREATED, "{}", term.body); | |
| 390 | + let term_id = id_of(&term.body); | |
| 391 | + | |
| 392 | + let course = send( | |
| 393 | + &app, | |
| 394 | + "POST", | |
| 395 | + "/courses", | |
| 396 | + Some(&manager), | |
| 397 | + Some(json!({ "title": "Fizik", "term_id": term_id })), | |
| 398 | + ) | |
| 399 | + .await; | |
| 400 | + assert_eq!(course.status, StatusCode::CREATED, "{}", course.body); | |
| 401 | + let course_id = id_of(&course.body); | |
| 402 | + | |
| 403 | + let subject = send( | |
| 404 | + &app, | |
| 405 | + "POST", | |
| 406 | + &format!("/courses/{course_id}/subjects"), | |
| 407 | + Some(&manager), | |
| 408 | + Some(json!({ "name": "Optik" })), | |
| 409 | + ) | |
| 410 | + .await; | |
| 411 | + assert_eq!(subject.status, StatusCode::CREATED, "{}", subject.body); | |
| 412 | + let subject_id = id_of(&subject.body); | |
| 413 | + | |
| 414 | + let note = send( | |
| 415 | + &app, | |
| 416 | + "POST", | |
| 417 | + "/course-notes", | |
| 418 | + Some(&manager), | |
| 419 | + Some(json!({ "course": course_id, "title": "Ders 1" })), | |
| 420 | + ) | |
| 421 | + .await; | |
| 422 | + assert_eq!(note.status, StatusCode::CREATED, "{}", note.body); | |
| 423 | + let note_id = id_of(¬e.body); | |
| 424 | + | |
| 425 | + let file = upload_course_note_file( | |
| 426 | + &app, | |
| 427 | + &manager, | |
| 428 | + ¬e_id, | |
| 429 | + "plan.pdf", | |
| 430 | + "application/pdf", | |
| 431 | + b"pdf bytes", | |
| 432 | + ) | |
| 433 | + .await; | |
| 434 | + assert_eq!(file.status, StatusCode::CREATED, "{}", file.body); | |
| 435 | + let file_id = id_of(&file.body); | |
| 436 | + | |
| 437 | + let archived = send( | |
| 438 | + &app, | |
| 439 | + "POST", | |
| 440 | + &format!("/terms/{term_id}/archive"), | |
| 441 | + Some(&manager), | |
| 442 | + None, | |
| 443 | + ) | |
| 444 | + .await; | |
| 445 | + assert_eq!(archived.status, StatusCode::OK, "{}", archived.body); | |
| 446 | + | |
| 447 | + let writes: [(&str, String, Option<serde_json::Value>); 5] = [ | |
| 448 | + ( | |
| 449 | + "PATCH", | |
| 450 | + format!("/subjects/{subject_id}"), | |
| 451 | + Some(json!({ "name": "Akustik" })), | |
| 452 | + ), | |
| 453 | + ("DELETE", format!("/subjects/{subject_id}"), None), | |
| 454 | + ( | |
| 455 | + "POST", | |
| 456 | + "/course-notes".to_string(), | |
| 457 | + Some(json!({ "course": course_id, "title": "Ders 2" })), | |
| 458 | + ), | |
| 459 | + ( | |
| 460 | + "PATCH", | |
| 461 | + format!("/course-notes/{note_id}"), | |
| 462 | + Some(json!({ "title": "Ders 1a" })), | |
| 463 | + ), | |
| 464 | + ( | |
| 465 | + "DELETE", | |
| 466 | + format!("/course-notes/{note_id}/files/{file_id}"), | |
| 467 | + None, | |
| 468 | + ), | |
| 469 | + ]; | |
| 470 | + for (method, uri, body) in writes { | |
| 471 | + let res = send(&app, method, &uri, Some(&manager), body).await; | |
| 472 | + assert_eq!( | |
| 473 | + res.status, | |
| 474 | + StatusCode::CONFLICT, | |
| 475 | + "{method} {uri}: {}", | |
| 476 | + res.body | |
| 477 | + ); | |
| 478 | + assert_eq!(res.body["code"], "term_archived", "{method} {uri}"); | |
| 479 | + } | |
| 480 | + // The multipart upload refuses too, and before its body is buffered. | |
| 481 | + let refused = upload_course_note_file( | |
| 482 | + &app, | |
| 483 | + &manager, | |
| 484 | + ¬e_id, | |
| 485 | + "more.pdf", | |
| 486 | + "application/pdf", | |
| 487 | + b"more bytes", | |
| 488 | + ) | |
| 489 | + .await; | |
| 490 | + assert_eq!(refused.status, StatusCode::CONFLICT, "{}", refused.body); | |
| 491 | + assert_eq!(refused.body["code"], "term_archived"); | |
| 492 | + // Deleting the note itself is a write as well (it cascades its files). | |
| 493 | + let res = send( | |
| 494 | + &app, | |
| 495 | + "DELETE", | |
| 496 | + &format!("/course-notes/{note_id}"), | |
| 497 | + Some(&manager), | |
| 498 | + None, | |
| 499 | + ) | |
| 500 | + .await; | |
| 501 | + assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | |
| 502 | + assert_eq!(res.body["code"], "term_archived"); | |
| 503 | + | |
| 504 | + // Reads all stay open. | |
| 505 | + for uri in [ | |
| 506 | + format!("/subjects/{subject_id}"), | |
| 507 | + format!("/course-notes/{note_id}"), | |
| 508 | + format!("/course-notes/{note_id}/files"), | |
| 509 | + format!("/course-notes/{note_id}/files/{file_id}"), | |
| 510 | + ] { | |
| 511 | + let res = send(&app, "GET", &uri, Some(&manager), None).await; | |
| 512 | + assert_eq!(res.status, StatusCode::OK, "GET {uri}: {}", res.body); | |
| 513 | + } | |
| 514 | + | |
| 515 | + // Re-opening the year thaws them. | |
| 516 | + let reopened = send( | |
| 517 | + &app, | |
| 518 | + "POST", | |
| 519 | + &format!("/terms/{term_id}/unarchive"), | |
| 520 | + Some(&manager), | |
| 521 | + None, | |
| 522 | + ) | |
| 523 | + .await; | |
| 524 | + assert_eq!(reopened.status, StatusCode::OK, "{}", reopened.body); | |
| 525 | + let res = send( | |
| 526 | + &app, | |
| 527 | + "PATCH", | |
| 528 | + &format!("/subjects/{subject_id}"), | |
| 529 | + Some(&manager), | |
| 530 | + Some(json!({ "name": "Akustik" })), | |
| 531 | + ) | |
| 532 | + .await; | |
| 533 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 534 | +} |
tests/regress_course_delete.rsmodified+176 -0
| @@ -261,3 +261,179 @@ async fn an_attempt_started_inside_a_course_delete_never_outlives_it() { | ||
| 261 | 261 | "a sitting outlived the course it was sat under" |
| 262 | 262 | ); |
| 263 | 263 | } |
| 264 | + | |
| 265 | +/// An archived term freezes the courses hanging off it: every write route under | |
| 266 | +/// `/courses/{id}` answers `409 term_archived`, while every read stays open — | |
| 267 | +/// past years are a read-only archive, not a hidden one. The guard sits *after* | |
| 268 | +/// each handler's authz check, so a caller who may not write still gets its | |
| 269 | +/// `403` rather than being told about the term. | |
| 270 | +#[tokio::test] | |
| 271 | +async fn an_archived_terms_courses_take_no_writes_but_still_read() { | |
| 272 | + let (app, db) = app_and_db().await; | |
| 273 | + let manager = login_as(&app, &db, "arsiv_ders_mudur", "manager").await; | |
| 274 | + let student = login_as(&app, &db, "arsiv_ders_ogrenci", "student").await; | |
| 275 | + let student_id = me_id(&app, &student).await; | |
| 276 | + let teacher = login_as(&app, &db, "arsiv_ders_ogretmen", "teacher").await; | |
| 277 | + let teacher_id = me_id(&app, &teacher).await; | |
| 278 | + | |
| 279 | + let res = send( | |
| 280 | + &app, | |
| 281 | + "POST", | |
| 282 | + "/terms", | |
| 283 | + Some(&manager), | |
| 284 | + Some(json!({ | |
| 285 | + "name": "2019 güz", | |
| 286 | + "starts_at": 1_780_000_000_000_i64, | |
| 287 | + "ends_at": 1_790_000_000_000_i64, | |
| 288 | + })), | |
| 289 | + ) | |
| 290 | + .await; | |
| 291 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 292 | + let term = id_of(&res.body); | |
| 293 | + | |
| 294 | + let res = send( | |
| 295 | + &app, | |
| 296 | + "POST", | |
| 297 | + "/courses", | |
| 298 | + Some(&manager), | |
| 299 | + Some(json!({ "title": "Coğrafya", "term_id": term })), | |
| 300 | + ) | |
| 301 | + .await; | |
| 302 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 303 | + let course = id_of(&res.body); | |
| 304 | + // Both the roster and an assigned teacher have to exist *before* the | |
| 305 | + // archive: the routes that remove them are themselves frozen. | |
| 306 | + enroll(&app, &manager, &course, &student_id).await; | |
| 307 | + let subject = create_subject(&app, &manager, &course, "Iklim").await; | |
| 308 | + let res = send( | |
| 309 | + &app, | |
| 310 | + "POST", | |
| 311 | + &format!("/courses/{course}/teachers"), | |
| 312 | + Some(&manager), | |
| 313 | + Some(json!({ "user_id": teacher_id })), | |
| 314 | + ) | |
| 315 | + .await; | |
| 316 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 317 | + | |
| 318 | + let res = send( | |
| 319 | + &app, | |
| 320 | + "POST", | |
| 321 | + &format!("/terms/{term}/archive"), | |
| 322 | + Some(&manager), | |
| 323 | + None, | |
| 324 | + ) | |
| 325 | + .await; | |
| 326 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 327 | + | |
| 328 | + let due = 1_900_000_000_000_i64; | |
| 329 | + let writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![ | |
| 330 | + ( | |
| 331 | + "PATCH", | |
| 332 | + format!("/courses/{course}"), | |
| 333 | + Some(json!({ "title": "Yeni" })), | |
| 334 | + ), | |
| 335 | + ("DELETE", format!("/courses/{course}"), None), | |
| 336 | + ( | |
| 337 | + "POST", | |
| 338 | + format!("/courses/{course}/teachers"), | |
| 339 | + Some(json!({ "user_id": teacher_id })), | |
| 340 | + ), | |
| 341 | + ( | |
| 342 | + "DELETE", | |
| 343 | + format!("/courses/{course}/teachers/{teacher_id}"), | |
| 344 | + None, | |
| 345 | + ), | |
| 346 | + ( | |
| 347 | + "POST", | |
| 348 | + format!("/courses/{course}/enrollments"), | |
| 349 | + Some(json!({ "user_id": student_id })), | |
| 350 | + ), | |
| 351 | + ( | |
| 352 | + "DELETE", | |
| 353 | + format!("/courses/{course}/enrollments/{student_id}"), | |
| 354 | + None, | |
| 355 | + ), | |
| 356 | + ( | |
| 357 | + "POST", | |
| 358 | + format!("/courses/{course}/exams"), | |
| 359 | + Some(json!({ "title": "Vize", "kind": "midterm" })), | |
| 360 | + ), | |
| 361 | + ( | |
| 362 | + "POST", | |
| 363 | + format!("/courses/{course}/subjects"), | |
| 364 | + Some(json!({ "name": "Erozyon" })), | |
| 365 | + ), | |
| 366 | + ( | |
| 367 | + "POST", | |
| 368 | + format!("/courses/{course}/homework"), | |
| 369 | + Some(json!({ "title": "Ödev", "subject_id": subject, "due_at": due })), | |
| 370 | + ), | |
| 371 | + ( | |
| 372 | + "POST", | |
| 373 | + format!("/courses/{course}/sessions"), | |
| 374 | + Some(json!({ "starts_at": due })), | |
| 375 | + ), | |
| 376 | + ]; | |
| 377 | + for (method, uri, body) in &writes { | |
| 378 | + let res = send(&app, method, uri, Some(&manager), body.clone()).await; | |
| 379 | + assert_eq!( | |
| 380 | + (res.status, res.body["code"].clone()), | |
| 381 | + (StatusCode::CONFLICT, json!("term_archived")), | |
| 382 | + "{method} {uri} must be frozen by the archive: {}", | |
| 383 | + res.body | |
| 384 | + ); | |
| 385 | + } | |
| 386 | + | |
| 387 | + for uri in [ | |
| 388 | + format!("/courses/{course}"), | |
| 389 | + format!("/courses/{course}/enrollments"), | |
| 390 | + format!("/courses/{course}/exams"), | |
| 391 | + format!("/courses/{course}/subjects"), | |
| 392 | + format!("/courses/{course}/homework"), | |
| 393 | + format!("/courses/{course}/sessions"), | |
| 394 | + ] { | |
| 395 | + let res = send(&app, "GET", &uri, Some(&manager), None).await; | |
| 396 | + assert_eq!( | |
| 397 | + res.status, | |
| 398 | + StatusCode::OK, | |
| 399 | + "GET {uri} must stay readable: {}", | |
| 400 | + res.body | |
| 401 | + ); | |
| 402 | + } | |
| 403 | + | |
| 404 | + // A student who cannot write here is still told *that* first — the 403 has | |
| 405 | + // to precede the 409, or the archive leaks course structure to outsiders. | |
| 406 | + let res = send( | |
| 407 | + &app, | |
| 408 | + "POST", | |
| 409 | + &format!("/courses/{course}/subjects"), | |
| 410 | + Some(&student), | |
| 411 | + Some(json!({ "name": "Sızıntı" })), | |
| 412 | + ) | |
| 413 | + .await; | |
| 414 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | |
| 415 | + | |
| 416 | + let res = send( | |
| 417 | + &app, | |
| 418 | + "POST", | |
| 419 | + &format!("/terms/{term}/unarchive"), | |
| 420 | + Some(&manager), | |
| 421 | + None, | |
| 422 | + ) | |
| 423 | + .await; | |
| 424 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 425 | + let res = send( | |
| 426 | + &app, | |
| 427 | + "POST", | |
| 428 | + &format!("/courses/{course}/subjects"), | |
| 429 | + Some(&manager), | |
| 430 | + Some(json!({ "name": "Erozyon" })), | |
| 431 | + ) | |
| 432 | + .await; | |
| 433 | + assert_eq!( | |
| 434 | + res.status, | |
| 435 | + StatusCode::CREATED, | |
| 436 | + "the unarchive must give the writes back: {}", | |
| 437 | + res.body | |
| 438 | + ); | |
| 439 | +} |
tests/regress_exam_delete.rsmodified+280 -0
| @@ -126,3 +126,283 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() { | ||
| 126 | 126 | } |
| 127 | 127 | assert_eq!(sittings, 0, "a sitting outlived its exam"); |
| 128 | 128 | } |
| 129 | + | |
| 130 | +/// An archived term freezes the exams hanging off its courses: all nineteen | |
| 131 | +/// write routes under `/exams/{id}` answer `409 term_archived` — authoring, | |
| 132 | +/// grading, the images on both sides, and the sitting itself — while every | |
| 133 | +/// read stays open. Past years are a read-only archive, not a hidden one. | |
| 134 | +/// | |
| 135 | +/// The sitting is deliberately *live* when the archive lands: a student mid-exam | |
| 136 | +/// is the case where a freeze can do real damage, and every one of their write | |
| 137 | +/// routes has to refuse with the coded 409 rather than a 500 or a silent write. | |
| 138 | +/// The guards sit after each handler's authz, so a caller who may not write | |
| 139 | +/// still gets its `403` (asserted below) — the archive never leaks exam | |
| 140 | +/// structure. | |
| 141 | +/// | |
| 142 | +/// Not covered here: the exam-room WebSocket. Its door (`GET | |
| 143 | +/// /exams/{id}/attempt/ws`) and its `finish` frame carry their own guards, but | |
| 144 | +/// this binary drives the router through `oneshot` and cannot upgrade — the | |
| 145 | +/// socket needs the real-TCP harness in `tests/e2e.rs`. The REST | |
| 146 | +/// `POST /exams/{id}/attempt/answers` below does cover the shared | |
| 147 | +/// `save_answer_in` funnel that every WS `answer` frame also goes through. | |
| 148 | +#[tokio::test] | |
| 149 | +async fn an_archived_terms_exams_take_no_writes_but_still_read() { | |
| 150 | + let (app, db) = app_and_db().await; | |
| 151 | + let manager = login_as(&app, &db, "arsiv_sinav_mudur", "manager").await; | |
| 152 | + let student = login_as(&app, &db, "arsiv_sinav_ogrenci", "student").await; | |
| 153 | + let student_id = me_id(&app, &student).await; | |
| 154 | + | |
| 155 | + let res = send( | |
| 156 | + &app, | |
| 157 | + "POST", | |
| 158 | + "/terms", | |
| 159 | + Some(&manager), | |
| 160 | + Some(json!({ | |
| 161 | + "name": "2018 bahar", | |
| 162 | + "starts_at": 1_780_000_000_000_i64, | |
| 163 | + "ends_at": 1_790_000_000_000_i64, | |
| 164 | + })), | |
| 165 | + ) | |
| 166 | + .await; | |
| 167 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 168 | + let term = id_of(&res.body); | |
| 169 | + | |
| 170 | + let res = send( | |
| 171 | + &app, | |
| 172 | + "POST", | |
| 173 | + "/courses", | |
| 174 | + Some(&manager), | |
| 175 | + Some(json!({ "title": "Tarih", "term_id": term })), | |
| 176 | + ) | |
| 177 | + .await; | |
| 178 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 179 | + let course = id_of(&res.body); | |
| 180 | + enroll(&app, &manager, &course, &student_id).await; | |
| 181 | + let subject = common::create_subject(&app, &manager, &course, "Kronoloji").await; | |
| 182 | + | |
| 183 | + // `open` mode so the sitting is real: the attempt below has to be running | |
| 184 | + // when the archive lands. | |
| 185 | + let res = create_exam_with( | |
| 186 | + &app, | |
| 187 | + &manager, | |
| 188 | + &course, | |
| 189 | + json!({ "title": "Vize", "kind": "midterm", "mode": "open" }), | |
| 190 | + ) | |
| 191 | + .await; | |
| 192 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 193 | + let exam = id_of(&res.body); | |
| 194 | + | |
| 195 | + // One choice question — it supplies the qid every question route needs and | |
| 196 | + // the choice id the option-picture routes need. | |
| 197 | + let res = send( | |
| 198 | + &app, | |
| 199 | + "POST", | |
| 200 | + &format!("/exams/{exam}/questions"), | |
| 201 | + Some(&manager), | |
| 202 | + Some(json!({ "subject_id": subject, "text": "Ne zaman?", "kind": "choice", "points": 10, | |
| 203 | + "choices": [{"id": "c0", "text": "1453"}, {"id": "c1", "text": "1071"}], "correct": "c0" })), | |
| 204 | + ) | |
| 205 | + .await; | |
| 206 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 207 | + let question = id_of(&res.body); | |
| 208 | + let choice = res.body["choices"][0]["id"] | |
| 209 | + .as_str() | |
| 210 | + .expect("choice id") | |
| 211 | + .to_string(); | |
| 212 | + | |
| 213 | + let res = send( | |
| 214 | + &app, | |
| 215 | + "POST", | |
| 216 | + &format!("/exams/{exam}/attempt"), | |
| 217 | + Some(&student), | |
| 218 | + None, | |
| 219 | + ) | |
| 220 | + .await; | |
| 221 | + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); | |
| 222 | + | |
| 223 | + let res = send( | |
| 224 | + &app, | |
| 225 | + "POST", | |
| 226 | + &format!("/terms/{term}/archive"), | |
| 227 | + Some(&manager), | |
| 228 | + None, | |
| 229 | + ) | |
| 230 | + .await; | |
| 231 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 232 | + | |
| 233 | + // The thirteen JSON write routes: exam, results, and the question authoring | |
| 234 | + // set. `from-bank` takes an id that need not exist — the freeze is judged | |
| 235 | + // before the bank lookup, and a 404 here would be the bug. | |
| 236 | + let staff_writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![ | |
| 237 | + ( | |
| 238 | + "PATCH", | |
| 239 | + format!("/exams/{exam}"), | |
| 240 | + Some(json!({ "title": "Final" })), | |
| 241 | + ), | |
| 242 | + ("DELETE", format!("/exams/{exam}"), None), | |
| 243 | + ( | |
| 244 | + "POST", | |
| 245 | + format!("/exams/{exam}/results"), | |
| 246 | + Some(json!({ "user_id": student_id, "mark": 80 })), | |
| 247 | + ), | |
| 248 | + ( | |
| 249 | + "DELETE", | |
| 250 | + format!("/exams/{exam}/results/{student_id}"), | |
| 251 | + None, | |
| 252 | + ), | |
| 253 | + ( | |
| 254 | + "POST", | |
| 255 | + format!("/exams/{exam}/questions"), | |
| 256 | + Some(json!({ "subject_id": subject, "text": "Kim?", "kind": "text", "points": 5 })), | |
| 257 | + ), | |
| 258 | + ( | |
| 259 | + "PATCH", | |
| 260 | + format!("/exams/{exam}/questions/{question}"), | |
| 261 | + Some(json!({ "text": "Nerede?" })), | |
| 262 | + ), | |
| 263 | + ( | |
| 264 | + "DELETE", | |
| 265 | + format!("/exams/{exam}/questions/{question}"), | |
| 266 | + None, | |
| 267 | + ), | |
| 268 | + ( | |
| 269 | + "POST", | |
| 270 | + format!("/exams/{exam}/questions/from-bank/yok"), | |
| 271 | + Some(json!({ "subject_id": subject })), | |
| 272 | + ), | |
| 273 | + ( | |
| 274 | + "POST", | |
| 275 | + format!("/exams/{exam}/questions/{question}/refresh-from-bank"), | |
| 276 | + None, | |
| 277 | + ), | |
| 278 | + ( | |
| 279 | + "POST", | |
| 280 | + format!("/exams/{exam}/questions/{question}/to-bank"), | |
| 281 | + None, | |
| 282 | + ), | |
| 283 | + ( | |
| 284 | + "DELETE", | |
| 285 | + format!("/exams/{exam}/questions/{question}/image"), | |
| 286 | + None, | |
| 287 | + ), | |
| 288 | + ( | |
| 289 | + "DELETE", | |
| 290 | + format!("/exams/{exam}/questions/{question}/choices/{choice}/image"), | |
| 291 | + None, | |
| 292 | + ), | |
| 293 | + ]; | |
| 294 | + for (method, uri, body) in &staff_writes { | |
| 295 | + let res = send(&app, method, uri, Some(&manager), body.clone()).await; | |
| 296 | + assert_eq!( | |
| 297 | + (res.status, res.body["code"].clone()), | |
| 298 | + (StatusCode::CONFLICT, json!("term_archived")), | |
| 299 | + "{method} {uri} must be frozen by the archive: {}", | |
| 300 | + res.body | |
| 301 | + ); | |
| 302 | + } | |
| 303 | + | |
| 304 | + // The student's own writes — the live sitting. `save_answer` is the REST | |
| 305 | + // face of `save_answer_in`, the funnel the WebSocket's `answer` shares. | |
| 306 | + let sit_writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![ | |
| 307 | + ("POST", format!("/exams/{exam}/attempt"), None), | |
| 308 | + ( | |
| 309 | + "POST", | |
| 310 | + format!("/exams/{exam}/attempt/answers"), | |
| 311 | + Some(json!({ "question_id": question, "selected": choice })), | |
| 312 | + ), | |
| 313 | + ( | |
| 314 | + "DELETE", | |
| 315 | + format!("/exams/{exam}/attempt/answers/{question}/image"), | |
| 316 | + None, | |
| 317 | + ), | |
| 318 | + ("POST", format!("/exams/{exam}/attempt/finish"), None), | |
| 319 | + ]; | |
| 320 | + for (method, uri, body) in &sit_writes { | |
| 321 | + let res = send(&app, method, uri, Some(&student), body.clone()).await; | |
| 322 | + assert_eq!( | |
| 323 | + (res.status, res.body["code"].clone()), | |
| 324 | + (StatusCode::CONFLICT, json!("term_archived")), | |
| 325 | + "{method} {uri} must be frozen by the archive: {}", | |
| 326 | + res.body | |
| 327 | + ); | |
| 328 | + } | |
| 329 | + | |
| 330 | + // The three multipart uploads. The guard runs *before* the body is read, so | |
| 331 | + // these never touch the blob store. | |
| 332 | + let uploads = [ | |
| 333 | + ( | |
| 334 | + format!("/exams/{exam}/questions/{question}/image"), | |
| 335 | + manager.clone(), | |
| 336 | + ), | |
| 337 | + ( | |
| 338 | + format!("/exams/{exam}/questions/{question}/choices/{choice}/image"), | |
| 339 | + manager.clone(), | |
| 340 | + ), | |
| 341 | + ( | |
| 342 | + format!("/exams/{exam}/attempt/answers/{question}/image"), | |
| 343 | + student.clone(), | |
| 344 | + ), | |
| 345 | + ]; | |
| 346 | + for (uri, cookie) in &uploads { | |
| 347 | + let res = common::upload_file_at(&app, cookie, uri, "a.png", "image/png", b"png").await; | |
| 348 | + assert_eq!( | |
| 349 | + (res.status, res.body["code"].clone()), | |
| 350 | + (StatusCode::CONFLICT, json!("term_archived")), | |
| 351 | + "POST {uri} must be frozen by the archive: {}", | |
| 352 | + res.body | |
| 353 | + ); | |
| 354 | + } | |
| 355 | + | |
| 356 | + // Reads stay open on both sides of the desk. | |
| 357 | + for (uri, cookie) in [ | |
| 358 | + (format!("/exams/{exam}"), &manager), | |
| 359 | + (format!("/exams/{exam}/questions"), &manager), | |
| 360 | + (format!("/exams/{exam}/results"), &manager), | |
| 361 | + ( | |
| 362 | + format!("/exams/{exam}/attempts/{student_id}/answers"), | |
| 363 | + &manager, | |
| 364 | + ), | |
| 365 | + (format!("/exams/{exam}/attempt"), &student), | |
| 366 | + (format!("/exams/{exam}/attempt/questions"), &student), | |
| 367 | + ] { | |
| 368 | + let res = send(&app, "GET", &uri, Some(cookie), None).await; | |
| 369 | + assert_eq!( | |
| 370 | + res.status, | |
| 371 | + StatusCode::OK, | |
| 372 | + "GET {uri} must stay readable: {}", | |
| 373 | + res.body | |
| 374 | + ); | |
| 375 | + } | |
| 376 | + | |
| 377 | + // A caller who may not write is still told *that* first: the 403 precedes | |
| 378 | + // the 409, or the archive leaks the exam's structure to outsiders. | |
| 379 | + let res = send( | |
| 380 | + &app, | |
| 381 | + "PATCH", | |
| 382 | + &format!("/exams/{exam}"), | |
| 383 | + Some(&student), | |
| 384 | + Some(json!({ "title": "Sızıntı" })), | |
| 385 | + ) | |
| 386 | + .await; | |
| 387 | + assert_eq!(res.status, StatusCode::FORBIDDEN, "{}", res.body); | |
| 388 | + | |
| 389 | + // Unarchiving thaws them again. | |
| 390 | + let res = send( | |
| 391 | + &app, | |
| 392 | + "POST", | |
| 393 | + &format!("/terms/{term}/unarchive"), | |
| 394 | + Some(&manager), | |
| 395 | + None, | |
| 396 | + ) | |
| 397 | + .await; | |
| 398 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 399 | + let res = send( | |
| 400 | + &app, | |
| 401 | + "PATCH", | |
| 402 | + &format!("/exams/{exam}"), | |
| 403 | + Some(&manager), | |
| 404 | + Some(json!({ "title": "Final" })), | |
| 405 | + ) | |
| 406 | + .await; | |
| 407 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | |
| 408 | +} |
tests/regress_homework_orphans.rsmodified+264 -2
| @@ -22,8 +22,8 @@ mod common; | ||
| 22 | 22 | |
| 23 | 23 | use axum::http::StatusCode; |
| 24 | 24 | use common::{ |
| 25 | - app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll, | |
| 26 | - id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, | |
| 25 | + Res, app_and_db, create_course, create_homework, create_homework_with, create_subject, enroll, | |
| 26 | + id_of, items, login_as, me_id, multipart_file, send, send_raw, unenroll, upload_file_at, | |
| 27 | 27 | }; |
| 28 | 28 | use hezarfen_backend::database::Database; |
| 29 | 29 | use serde_json::{Value, json}; |
| @@ -742,3 +742,265 @@ async fn a_file_add_racing_a_file_delete_never_500s() { | ||
| 742 | 742 | "the seat counter drifted from the rows" |
| 743 | 743 | ); |
| 744 | 744 | } |
| 745 | + | |
| 746 | +/// An archived term freezes every homework write under its courses (#22): the | |
| 747 | +/// teacher's edit/delete/grade/un-grade and the student's submit, withdraw, | |
| 748 | +/// file add and file remove all answer `409 term_archived`, while the reads | |
| 749 | +/// stay open — a past year is browsable, not editable. The student wall sits | |
| 750 | +/// *after* the audience check, so a student the homework never named still | |
| 751 | +/// gets the 404 it always did: the archive must not turn a subset assignment | |
| 752 | +/// into a "this exists" signal. | |
| 753 | +#[tokio::test] | |
| 754 | +async fn an_archived_term_freezes_every_homework_write() { | |
| 755 | + let (app, db) = app_and_db().await; | |
| 756 | + let manager = login_as(&app, &db, "mudur_arsiv", "manager").await; | |
| 757 | + let teacher = login_as(&app, &db, "ogretmen_arsiv", "teacher").await; | |
| 758 | + | |
| 759 | + let res = send( | |
| 760 | + &app, | |
| 761 | + "POST", | |
| 762 | + "/terms", | |
| 763 | + Some(&manager), | |
| 764 | + Some(json!({ | |
| 765 | + "name": "2025 Guz", | |
| 766 | + "starts_at": 1_600_000_000_000_i64, | |
| 767 | + "ends_at": 1_610_000_000_000_i64, | |
| 768 | + })), | |
| 769 | + ) | |
| 770 | + .await; | |
| 771 | + assert_eq!(res.status, StatusCode::CREATED, "create term"); | |
| 772 | + let term = id_of(&res.body); | |
| 773 | + | |
| 774 | + let res = send( | |
| 775 | + &app, | |
| 776 | + "POST", | |
| 777 | + "/courses", | |
| 778 | + Some(&teacher), | |
| 779 | + Some(json!({ "title": "tarih", "term_id": term })), | |
| 780 | + ) | |
| 781 | + .await; | |
| 782 | + assert_eq!(res.status, StatusCode::CREATED, "create course in term"); | |
| 783 | + let course = id_of(&res.body); | |
| 784 | + let subject = create_subject(&app, &teacher, &course, "konu").await; | |
| 785 | + | |
| 786 | + let student = login_as(&app, &db, "ogrenci_arsiv", "student").await; | |
| 787 | + let student_id = me_id(&app, &student).await; | |
| 788 | + let outsider = login_as(&app, &db, "ogrenci_disarida", "student").await; | |
| 789 | + let outsider_id = me_id(&app, &outsider).await; | |
| 790 | + enroll(&app, &teacher, &course, &student_id).await; | |
| 791 | + enroll(&app, &teacher, &course, &outsider_id).await; | |
| 792 | + | |
| 793 | + // A subset assignment: the outsider is enrolled but not named, so their | |
| 794 | + // 404 is the one the archive must leave alone. | |
| 795 | + let res = create_homework_with( | |
| 796 | + &app, | |
| 797 | + &teacher, | |
| 798 | + &course, | |
| 799 | + json!({ | |
| 800 | + "title": "odev", | |
| 801 | + "subject_id": subject, | |
| 802 | + "due_at": far_future(), | |
| 803 | + "assigned": [student_id], | |
| 804 | + }), | |
| 805 | + ) | |
| 806 | + .await; | |
| 807 | + assert_eq!(res.status, StatusCode::CREATED, "create homework"); | |
| 808 | + let hw = id_of(&res.body); | |
| 809 | + | |
| 810 | + // Everything the student owns exists *before* the archive. | |
| 811 | + let res = send( | |
| 812 | + &app, | |
| 813 | + "POST", | |
| 814 | + &format!("/homework/{hw}/submission"), | |
| 815 | + Some(&student), | |
| 816 | + Some(json!({ "text": "hazir" })), | |
| 817 | + ) | |
| 818 | + .await; | |
| 819 | + assert_eq!(res.status, StatusCode::CREATED, "submit before archiving"); | |
| 820 | + let res = upload_file_at( | |
| 821 | + &app, | |
| 822 | + &student, | |
| 823 | + &format!("/homework/{hw}/submission/files"), | |
| 824 | + "odev.pdf", | |
| 825 | + "application/pdf", | |
| 826 | + b"homework bytes", | |
| 827 | + ) | |
| 828 | + .await; | |
| 829 | + assert_eq!(res.status, StatusCode::CREATED, "upload before archiving"); | |
| 830 | + let file = id_of(&res.body); | |
| 831 | + | |
| 832 | + let res = send( | |
| 833 | + &app, | |
| 834 | + "POST", | |
| 835 | + &format!("/terms/{term}/archive"), | |
| 836 | + Some(&manager), | |
| 837 | + None, | |
| 838 | + ) | |
| 839 | + .await; | |
| 840 | + assert_eq!(res.status, StatusCode::OK, "archive the term"); | |
| 841 | + | |
| 842 | + let frozen = |res: Res, what: &str| { | |
| 843 | + assert_eq!(res.status, StatusCode::CONFLICT, "{what} after archiving"); | |
| 844 | + assert_eq!( | |
| 845 | + res.body["code"], "term_archived", | |
| 846 | + "{what} carries the machine-readable code: {:?}", | |
| 847 | + res.body | |
| 848 | + ); | |
| 849 | + }; | |
| 850 | + | |
| 851 | + frozen( | |
| 852 | + send( | |
| 853 | + &app, | |
| 854 | + "PATCH", | |
| 855 | + &format!("/homework/{hw}"), | |
| 856 | + Some(&teacher), | |
| 857 | + Some(json!({ "title": "yeni" })), | |
| 858 | + ) | |
| 859 | + .await, | |
| 860 | + "PATCH /homework/{id}", | |
| 861 | + ); | |
| 862 | + frozen( | |
| 863 | + send( | |
| 864 | + &app, | |
| 865 | + "POST", | |
| 866 | + &format!("/homework/{hw}/results"), | |
| 867 | + Some(&teacher), | |
| 868 | + Some(json!({ "user": student_id, "status": "done" })), | |
| 869 | + ) | |
| 870 | + .await, | |
| 871 | + "POST /homework/{id}/results", | |
| 872 | + ); | |
| 873 | + frozen( | |
| 874 | + send( | |
| 875 | + &app, | |
| 876 | + "DELETE", | |
| 877 | + &format!("/homework/{hw}/results/{student_id}"), | |
| 878 | + Some(&teacher), | |
| 879 | + None, | |
| 880 | + ) | |
| 881 | + .await, | |
| 882 | + "DELETE /homework/{id}/results/{user}", | |
| 883 | + ); | |
| 884 | + frozen( | |
| 885 | + send( | |
| 886 | + &app, | |
| 887 | + "POST", | |
| 888 | + &format!("/homework/{hw}/submission"), | |
| 889 | + Some(&student), | |
| 890 | + Some(json!({ "text": "tekrar" })), | |
| 891 | + ) | |
| 892 | + .await, | |
| 893 | + "POST /homework/{id}/submission", | |
| 894 | + ); | |
| 895 | + frozen( | |
| 896 | + upload_file_at( | |
| 897 | + &app, | |
| 898 | + &student, | |
| 899 | + &format!("/homework/{hw}/submission/files"), | |
| 900 | + "yeni.pdf", | |
| 901 | + "application/pdf", | |
| 902 | + b"more bytes", | |
| 903 | + ) | |
| 904 | + .await, | |
| 905 | + "POST /homework/{id}/submission/files", | |
| 906 | + ); | |
| 907 | + frozen( | |
| 908 | + send( | |
| 909 | + &app, | |
| 910 | + "DELETE", | |
| 911 | + &format!("/homework/{hw}/submission/files/{file}"), | |
| 912 | + Some(&student), | |
| 913 | + None, | |
| 914 | + ) | |
| 915 | + .await, | |
| 916 | + "DELETE /homework/{id}/submission/files/{fid}", | |
| 917 | + ); | |
| 918 | + frozen( | |
| 919 | + send( | |
| 920 | + &app, | |
| 921 | + "DELETE", | |
| 922 | + &format!("/homework/{hw}/submission"), | |
| 923 | + Some(&student), | |
| 924 | + None, | |
| 925 | + ) | |
| 926 | + .await, | |
| 927 | + "DELETE /homework/{id}/submission", | |
| 928 | + ); | |
| 929 | + // The delete goes last: the seven refusals above must have left the rows | |
| 930 | + // it needs standing. | |
| 931 | + frozen( | |
| 932 | + send( | |
| 933 | + &app, | |
| 934 | + "DELETE", | |
| 935 | + &format!("/homework/{hw}"), | |
| 936 | + Some(&teacher), | |
| 937 | + None, | |
| 938 | + ) | |
| 939 | + .await, | |
| 940 | + "DELETE /homework/{id}", | |
| 941 | + ); | |
| 942 | + | |
| 943 | + // The past year still reads: the homework and the student's own file. | |
| 944 | + let res = send( | |
| 945 | + &app, | |
| 946 | + "GET", | |
| 947 | + &format!("/homework/{hw}"), | |
| 948 | + Some(&student), | |
| 949 | + None, | |
| 950 | + ) | |
| 951 | + .await; | |
| 952 | + assert_eq!(res.status, StatusCode::OK, "GET /homework/{{id}} archived"); | |
| 953 | + let (status, _, bytes) = send_raw( | |
| 954 | + &app, | |
| 955 | + "GET", | |
| 956 | + &format!("/homework/{hw}/submission/files/{file}"), | |
| 957 | + Some(&student), | |
| 958 | + None, | |
| 959 | + Vec::new(), | |
| 960 | + ) | |
| 961 | + .await; | |
| 962 | + assert_eq!(status, StatusCode::OK, "download own file while archived"); | |
| 963 | + assert_eq!(bytes, b"homework bytes", "the stored bytes come back"); | |
| 964 | + | |
| 965 | + // Not in the audience: still a 404, never the 409 that would admit the | |
| 966 | + // homework exists. | |
| 967 | + let res = send( | |
| 968 | + &app, | |
| 969 | + "POST", | |
| 970 | + &format!("/homework/{hw}/submission"), | |
| 971 | + Some(&outsider), | |
| 972 | + Some(json!({ "text": "benim mi" })), | |
| 973 | + ) | |
| 974 | + .await; | |
| 975 | + assert_eq!( | |
| 976 | + res.status, | |
| 977 | + StatusCode::NOT_FOUND, | |
| 978 | + "an unnamed student sees no homework, archived or not: {:?}", | |
| 979 | + res.body | |
| 980 | + ); | |
| 981 | + | |
| 982 | + // Re-opening the year hands the writes back. | |
| 983 | + let res = send( | |
| 984 | + &app, | |
| 985 | + "POST", | |
| 986 | + &format!("/terms/{term}/unarchive"), | |
| 987 | + Some(&manager), | |
| 988 | + None, | |
| 989 | + ) | |
| 990 | + .await; | |
| 991 | + assert_eq!(res.status, StatusCode::OK, "unarchive the term"); | |
| 992 | + let res = send( | |
| 993 | + &app, | |
| 994 | + "POST", | |
| 995 | + &format!("/homework/{hw}/results"), | |
| 996 | + Some(&teacher), | |
| 997 | + Some(json!({ "user": student_id, "status": "done" })), | |
| 998 | + ) | |
| 999 | + .await; | |
| 1000 | + assert_eq!( | |
| 1001 | + res.status, | |
| 1002 | + StatusCode::OK, | |
| 1003 | + "grading works again: {:?}", | |
| 1004 | + res.body | |
| 1005 | + ); | |
| 1006 | +} |
tests/spec_bounds.rsmodified+7 -0
| @@ -1206,6 +1206,7 @@ async fn the_class_refusal_codes_stay_published() { | ||
| 1206 | 1206 | "class_at_course_ceiling", |
| 1207 | 1207 | "class_roster_too_large", |
| 1208 | 1208 | "course_full", |
| 1209 | + "term_archived", | |
| 1209 | 1210 | ]; |
| 1210 | 1211 | let members = [ |
| 1211 | 1212 | "duplicate", |
| @@ -1213,7 +1214,12 @@ async fn the_class_refusal_codes_stay_published() { | ||
| 1213 | 1214 | "class_course_list_too_large", |
| 1214 | 1215 | "course_full", |
| 1215 | 1216 | "linked_course_missing", |
| 1217 | + "term_archived", | |
| 1216 | 1218 | ]; |
| 1219 | + // `term_archived` refuses the whole request up front (the class's or the | |
| 1220 | + // course's term is archived), so no pump ever *skips* an item for it — | |
| 1221 | + // it belongs on the two routes' 409s, never in `SkipResponse.reason`. | |
| 1222 | + let whole_request = ["term_archived"]; | |
| 1217 | 1223 | |
| 1218 | 1224 | for (path, expected) in [ |
| 1219 | 1225 | ("/classes/{id}/courses", courses.as_slice()), |
| @@ -1251,6 +1257,7 @@ async fn the_class_refusal_codes_stay_published() { | ||
| 1251 | 1257 | .chain(courses.iter()) |
| 1252 | 1258 | .chain(members.iter()) |
| 1253 | 1259 | .copied() |
| 1260 | + .filter(|code| !whole_request.contains(code)) | |
| 1254 | 1261 | .collect(); |
| 1255 | 1262 | assert_eq!( |
| 1256 | 1263 | sorted(quoted(reason)), |