forge
Explore
Log in

Don't you dare go Hollow

Announce an exam to sibling instances (shared-exam write surface)

Browse files at this commit

1824c341d54d4bf1c412fb27be54da7dda3fa904Ahmet Kaan GümüşParent: b3f7395
  • feat
    • announce an exam to sibling instances (shared-exam write surface)
Show full message
✨ feat: announce an exam to sibling instances (shared-exam write surface)

b3f7395 gave `exam_audience` a read role; this gives it its writes. An exam
is owned by the instance it was created on and can now be addressed to
further instances — one sitting, one mark, standing in every addressed
section's exam list, marks report and the report card.

- `POST /exams/{id}/audience` announces the exam to another instance: the
  target must teach the exam's own catalog course and sit under the same
  academic year (400 otherwise), the owner itself is refused (400), an
  archived target year is a 409, and a repeat announce is a no-op 200.
  The write needs management rights over the exam's **owner** instance —
  the target instance's teachers have no say.
- `GET /exams/{id}/audience` lists the set (owner first, then announcement
  order), visible exactly as the exam is; drafts stay a 404 to everyone but
  an addressed instance's manager. `DELETE /exams/{id}/audience/{instance}`
  withdraws one; the owner's pair is not withdrawable (400) and a pair that
  holds no row is a 404.
- Grading, statistics, results and the live monitor now accept teacher+
  rights over any instance the exam is addressed to, so an announced-to
  section's teacher grades its own students; the monitor's roster read is
  deduped by student and ordered, so a sitter in two addressed sections
  appears once.
- `sweep_instance_subtree` clears both directions of `exam_audience` before
  the rows they name — an exam a sibling announced *here* referenced the
  `class_course` row the caller deletes and refused the delete with a 23503.

Tests: regress_exam_delete.rs pins the announce/withdraw surface end to end
(owner-first order, the same-year and same-course 400s, the 409, the no-op)
and the sweep's answer-image blobs — the drawing row's bytes land on disk
and are gone with the row, with a mutation witness.

Gates: prepare_db, SQLX_OFFLINE=true check --all-targets (cache: 1 dropped,
7 added, all audience-shaped), doc_sync, spec_bounds, limits_completeness,
clippy -D warnings all green; cargo nextest run 1385/1385 across 47 binaries.
.sqlx/query-05651fea73df39aad458cf27fe791dc62dbd5a9933e4e3cd3b66fb9e15c545bf.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT exam AS \"exam: ExamId\" FROM exam_audience\n WHERE class_course = $1 ORDER BY exam",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "exam: ExamId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "exam_audience",
13+ "name": "exam"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "05651fea73df39aad458cf27fe791dc62dbd5a9933e4e3cd3b66fb9e15c545bf"
28+}
.sqlx/query-2d5355e3d1705a624bd1cba4d208036072113705cb5dc8e70b1009d332f2cbbb.jsonadded+52 -0
@@ -0,0 +1,52 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT a.class_course AS \"class_course: ClassCourseId\",\n c.class AS \"class: ClassGroupId\",\n c.course AS \"course: CourseId\"\n FROM exam_audience a\n JOIN class_course c ON c.id = a.class_course\n WHERE a.exam = $1\n ORDER BY a.class_course",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "class_course: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "exam_audience",
13+ "name": "class_course"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "class: ClassGroupId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "class_course",
24+ "name": "class"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "course: CourseId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "class_course",
35+ "name": "course"
36+ }
37+ }
38+ }
39+ ],
40+ "parameters": {
41+ "Left": [
42+ "Uuid"
43+ ]
44+ },
45+ "nullable": [
46+ false,
47+ false,
48+ false
49+ ]
50+ },
51+ "hash": "2d5355e3d1705a624bd1cba4d208036072113705cb5dc8e70b1009d332f2cbbb"
52+}
.sqlx/query-5df20b5a3c54f189ee0acad7b4967004fdf228e3a2611e575f354f3d89f2a98c.jsonadded+76 -0
@@ -0,0 +1,76 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT DISTINCT ON (e.app_user)\n e.class_course AS \"class_course: ClassCourseId\",\n e.app_user AS \"user: UserId\",\n e.enrolled_by AS \"enrolled_by: UserId\",\n e.source AS \"source: ClassGroupId\",\n e.created_at AS \"created_at: Timestamp\"\n FROM enrollment e\n JOIN exam_audience a ON a.class_course = e.class_course\n WHERE a.exam = $1\n ORDER BY e.app_user, e.created_at, e.class_course",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "class_course: ClassCourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "enrollment",
13+ "name": "class_course"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "user: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "enrollment",
24+ "name": "app_user"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "enrolled_by: UserId",
31+ "type_info": "Uuid",
32+ "origin": {
33+ "Table": {
34+ "table": "enrollment",
35+ "name": "enrolled_by"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "source: ClassGroupId",
42+ "type_info": "Uuid",
43+ "origin": {
44+ "Table": {
45+ "table": "enrollment",
46+ "name": "source"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "created_at: Timestamp",
53+ "type_info": "Int8",
54+ "origin": {
55+ "Table": {
56+ "table": "enrollment",
57+ "name": "created_at"
58+ }
59+ }
60+ }
61+ ],
62+ "parameters": {
63+ "Left": [
64+ "Uuid"
65+ ]
66+ },
67+ "nullable": [
68+ false,
69+ false,
70+ false,
71+ true,
72+ false
73+ ]
74+ },
75+ "hash": "5df20b5a3c54f189ee0acad7b4967004fdf228e3a2611e575f354f3d89f2a98c"
76+}
.sqlx/query-9453e4503e168e41af8373a64021940018d9be6e553ab939cfaeec6c642dceba.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM exam_audience WHERE class_course = $1 OR exam = ANY($2)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "9453e4503e168e41af8373a64021940018d9be6e553ab939cfaeec6c642dceba"
15+}
.sqlx/query-9a38964a74d388732b4b9a951bebd1aab284e36ae8fd84f02c58d6926f1db327.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)\n ON CONFLICT ON CONSTRAINT exam_audience_pk DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "9a38964a74d388732b4b9a951bebd1aab284e36ae8fd84f02c58d6926f1db327"
15+}
.sqlx/query-b2e2ab6d10204ac50cac62111cda053eb4d23f6eadc6630cc294134096955e20.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM exam_audience WHERE exam = $1 AND class_course = $2",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "b2e2ab6d10204ac50cac62111cda053eb4d23f6eadc6630cc294134096955e20"
15+}
.sqlx/query-bbed0d6dd708685f1c3c55c3b1041e3d8038c393bdac87ea4a636239427f19d5.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT EXISTS(\n SELECT 1 FROM exam_audience a\n JOIN enrollment e ON e.class_course = a.class_course\n WHERE a.exam = $1 AND e.app_user = $2) AS \"enrolled!\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "enrolled!",
9+ "type_info": "Bool",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "Uuid"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "bbed0d6dd708685f1c3c55c3b1041e3d8038c393bdac87ea4a636239427f19d5"
24+}
.sqlx/query-ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM exam_audience WHERE class_course = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "ca6514056875c3acd3cf79f227cfb3b09093a0bf5c7708c65504e3fc60c7f118"
14-}
README.mdmodified+51 -8
@@ -36,7 +36,10 @@ weight in the karne average), `counts_toward_karne` flag, teachers, roster,
36 exams, lesson sessions and homework. Two sections that attach Matematik get36 exams, lesson sessions and homework. Two sections that attach Matematik get
37 **two** instances and share nothing: adding a student to 5-A enrolls them in37 **two** instances and share nothing: adding a student to 5-A enrolls them in
38 5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to38 5-A's Matematik only, and an exam written on 5-A's Matematik is invisible to
39-5-B. The catalog row is office-owned (creator or manager+; clubs and etüt are39+5-B — unless the exam is **announced** to 5-B as an *ortak sınav*
40+(`POST /exams/{id}/audience`): one sitting, one mark, standing in every
41+addressed section's exam list, marks report and karne (see "Exam modes…").
42+The catalog row is office-owned (creator or manager+; clubs and etüt are
40 the exception — see "Courses (catalog)"), while an instance is run by the43 the exception — see "Courses (catalog)"), while an instance is run by the
41 teachers a **manager assigns** to it (`POST /instances/{id}/teachers`) plus the44 teachers a **manager assigns** to it (`POST /instances/{id}/teachers`) plus the
42 section's homeroom teacher: an assigned teacher manages everything inside the45 section's homeroom teacher: an assigned teacher manages everything inside the
@@ -1259,7 +1262,7 @@ window filtering, before paging; negative values are a `400` naming the field.
1259 | DELETE | `/events/{id}/register/{user}` | teacher | Take a user off the signup list — the register rules mirrored: teacher+, students' seats or your own (another *staff* member's seat only if their account no longer exists), and only while the list is open (the event hasn't started or, ends_at-only, passed). A seat held by a `parent` is freeable by any teacher+ as well: no route lets that account free it itself, so a stranded seat needs a door. Attendance already marked stays recorded. |1262 | DELETE | `/events/{id}/register/{user}` | teacher | Take a user off the signup list — the register rules mirrored: teacher+, students' seats or your own (another *staff* member's seat only if their account no longer exists), and only while the list is open (the event hasn't started or, ends_at-only, passed). A seat held by a `parent` is freeable by any teacher+ as well: no route lets that account free it itself, so a stranded seat needs a door. Attendance already marked stays recorded. |
1260 | GET | `/events/{id}/roster` | teacher | The event's expected-attendee roster joined with its attendance marks — the who-came/who-missed report. Resolved live from the audience (today's role holders, current enrollment, the current class roster, the current signup list), so it always reflects the present roster; attendance rows for people no longer in the audience are omitted here (they remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via `?limit=&offset=` (omit `limit` for the whole roster). |1263 | GET | `/events/{id}/roster` | teacher | The event's expected-attendee roster joined with its attendance marks — the who-came/who-missed report. Resolved live from the audience (today's role holders, current enrollment, the current class roster, the current signup list), so it always reflects the present roster; attendance rows for people no longer in the audience are omitted here (they remain in `GET /events/{id}/attendance`). Requires teacher+. Paged via `?limit=&offset=` (omit `limit` for the whole roster). |
1261 | GET | `/exams` | student | List the exams visible to the caller: every exam for manager+, otherwise the exams of the instances they teach or are enrolled in — minus other people's drafts (a draft shows only to its instance's managers). Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |1264 | GET | `/exams` | student | List the exams visible to the caller: every exam for manager+, otherwise the exams of the instances they teach or are enrolled in — minus other people's drafts (a draft shows only to its instance's managers). Paged via `?limit=&offset=` (omit `limit` for the full list); returns a `{items, total, limit, offset}` envelope. |
1262-| GET | `/exams/{id}` | student | Fetch a single exam by id. Visible to its instance's enrolled students, its teachers (or its class's homeroom teacher), and managers/admins — except drafts, which only the instance's managers see (everyone else gets a `404`, as if the exam doesn't exist yet — because it doesn't, officially). |1265+| GET | `/exams/{id}` | student | Fetch a single exam by id. Visible to **any instance the exam is addressed to** — its owner's enrolled students and teachers, and, for an announced exam (ortak sınav), each addressed section's alike — plus managers/admins; drafts only show to the managers of an addressed instance (everyone else gets a `404`, as if the exam doesn't exist yet — because it doesn't, officially). |
1263 | PATCH | `/exams/{id}` | teacher | Update an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Omitted fields keep their value; an explicit `null` clears a schedule field; the instance an exam hangs off is not updatable here. The schedule must stay consistent as a whole (see the create endpoint), and `mode` is frozen once anyone has started an attempt — times, duration, `max_attempts`, and `allow_rejoin` stay editable so a running exam can be extended, granted retakes, or have its rejoin door opened live. `draft: false` publishes a draft; `draft: true` re-hides an exam, but only while it has no attempts and no results (`409` otherwise) — students never lose sight of an exam they've already sat or been graded on. |1266 | PATCH | `/exams/{id}` | teacher | Update an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Omitted fields keep their value; an explicit `null` clears a schedule field; the instance an exam hangs off is not updatable here. The schedule must stay consistent as a whole (see the create endpoint), and `mode` is frozen once anyone has started an attempt — times, duration, `max_attempts`, and `allow_rejoin` stay editable so a running exam can be extended, granted retakes, or have its rejoin door opened live. `draft: false` publishes a draft; `draft: true` re-hides an exam, but only while it has no attempts and no results (`409` otherwise) — students never lose sight of an exam they've already sat or been graded on. |
1264 | DELETE | `/exams/{id}` | teacher | Delete an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Cascades the exam's results, attempts, questions, answers, and question + answer images (blobs included). |1267 | DELETE | `/exams/{id}` | teacher | Delete an exam. Requires teacher+ and management rights over the exam's instance (an assigned teacher, its class's homeroom teacher, or a manager/admin). Cascades the exam's results, attempts, questions, answers, and question + answer images (blobs included). |
1265 | GET | `/exams/{id}/attempt` | student | The caller's own (latest) attempt: status, deadline, remaining time, and mark once graded — everything a student's live exam screen needs, judged by the server clock. `404` until an attempt is started. |1268 | GET | `/exams/{id}/attempt` | student | The caller's own (latest) attempt: status, deadline, remaining time, and mark once graded — everything a student's live exam screen needs, judged by the server clock. `404` until an attempt is started. |
@@ -1273,7 +1276,10 @@ window filtering, before paging; negative values are a `400` naming the field.
1273 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |1276 | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") |
1274 | GET | `/exams/{id}/attempts/{user}/answers` | teacher | One student's answer sheet with correctness flags — always the *latest* sitting's answers (a retake starts from a blank sheet). Every row carries the saved answer plus `is_correct` (`null` for text questions — those are the grader's call), and the machine's `auto_score` over the choice questions is attached as a *suggestion*: the final mark stays human, via `POST /exams/{id}/results`. Requires teacher+ and management rights over the exam's instance. |1277 | GET | `/exams/{id}/attempts/{user}/answers` | teacher | One student's answer sheet with correctness flags — always the *latest* sitting's answers (a retake starts from a blank sheet). Every row carries the saved answer plus `is_correct` (`null` for text questions — those are the grader's call), and the machine's `auto_score` over the choice questions is attached as a *suggestion*: the final mark stays human, via `POST /exams/{id}/results`. Requires teacher+ and management rights over the exam's instance. |
1275 | GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | One student's drawn-answer bytes, for the grader. Requires teacher+ and management rights over the exam's instance — the `attempt_answers` gate. |1278 | GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | One student's drawn-answer bytes, for the grader. Requires teacher+ and management rights over the exam's instance — the `attempt_answers` gate. |
1276-| GET | `/exams/{id}/live` | teacher | A one-shot live snapshot of the exam: who's in, who's still writing (and on which sitting), who walked out of the room (`left_at`), who never showed at all (`absent`, once the window is over), time each student has left, and marks as they land. Requires teacher+ and management rights over the exam's instance. Poll it to keep a monitor up to date. |1279+| GET | `/exams/{id}/audience` | student | List the instances an exam is announced to, its owner included — the read behind the announce routes' answer, useful on its own to a client that wants to show where else an exam is sat. Visible to the exam's own audience: an addressed instance's enrolled students, its teachers (or its şube's homeroom teacher), and managers/admins — except drafts, which stay a `404` to everyone but an addressed instance's managers. |
1280+| POST | `/exams/{id}/audience` | teacher | Announce an exam to another instance — the **ortak sınav** write: one exam addressed to a sibling şube, so it and its marks stand in that section's exam list, marks report and karne. Requires teacher+ and management rights over the exam's **owner** instance (an assigned teacher, its şube's homeroom teacher, or a manager/admin) — the target instance's teachers have no say. The target must teach the exam's own catalog course and sit under the same academic year (`400` otherwise), the owner itself is refused (`400`), and an archived target year is a `409`. Announcing a pair that already stands is a no-op answering `200` with the audience unchanged. |
1281+| DELETE | `/exams/{id}/audience/{instance}` | teacher | Withdraw an exam from one instance's audience. Requires teacher+ and management rights over the exam's **owner** instance, like the announce itself. The owner's own pair is not withdrawable (`400`) — that is the instance the exam belongs to, and deleting the exam is what ends it; an archived year refuses the withdrawal with the same `409` its other writes answer. A pair that holds no audience row is a `404`. |
1282+| GET | `/exams/{id}/live` | teacher | A one-shot live snapshot of the exam: who's in, who's still writing (and on which sitting), who walked out of the room (`left_at`), who never showed at all (`absent`, once the window is over), time each student has left, and marks as they land — the roster of every instance the exam is addressed to, so an announced-to section's sitters are here too. Requires teacher+ and management rights over the exam's instance. Poll it to keep a monitor up to date. |
1277 | GET | `/exams/{id}/questions` | teacher | The exam's question list, `correct` choice ids included — the answer key, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and management rights over the exam's instance. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. |1283 | GET | `/exams/{id}/questions` | teacher | The exam's question list, `correct` choice ids included — the answer key, paged via `?limit=&offset=` (omit `limit` for the whole list). Requires teacher+ and management rights over the exam's instance. Students read questions through `GET /exams/{id}/attempt/questions`. Returns a `{items, total, limit, offset}` envelope. |
1278 | POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's instance. `subject_id` must name one of the subjects of that instance's catalog course (`GET /courses/{id}/subjects`) — every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. |1284 | POST | `/exams/{id}/questions` | teacher | Add a question to an exam. Requires teacher+ and management rights over the exam's instance. `subject_id` must name one of the subjects of that instance's catalog course (`GET /courses/{id}/subjects`) — every question belongs to a subject. `choice` questions carry 2–10 `choices` plus `correct` naming one of them by id; `text` questions carry neither. Locked once attempts exist. |
1279 | POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a bank template into this exam as a fresh question. Requires teacher+, management rights over the exam's instance, and a template the caller may see (their own, or one published to the school) — anything else is a 404. `subject_id` must name one of the subjects of the instance's catalog course — the template's own subject is origin metadata and does not carry over. The template (and its blobs) stay untouched; a full copy — text, points, spec, illustration, and option pictures — lands under a new question id. Locked once attempts exist. |1285 | POST | `/exams/{id}/questions/from-bank/{bid}` | teacher | Instantiate a bank template into this exam as a fresh question. Requires teacher+, management rights over the exam's instance, and a template the caller may see (their own, or one published to the school) — anything else is a 404. `subject_id` must name one of the subjects of the instance's catalog course — the template's own subject is origin metadata and does not carry over. The template (and its blobs) stay untouched; a full copy — text, points, spec, illustration, and option pictures — lands under a new question id. Locked once attempts exist. |
@@ -1288,14 +1294,14 @@ window filtering, before paging; negative values are a `400` naming the field.
1288 | POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy a bank template's *current* content over the exam question that was instantiated from it — the escape hatch for the divergence a deep copy creates: fixing a typo in the template does not reach the copies, so this is how a copy is brought back in line, explicitly and per question. Requires teacher+, management rights over the exam's instance, and a template the caller may still see. |1294 | POST | `/exams/{id}/questions/{qid}/refresh-from-bank` | teacher | Re-copy a bank template's *current* content over the exam question that was instantiated from it — the escape hatch for the divergence a deep copy creates: fixing a typo in the template does not reach the copies, so this is how a copy is brought back in line, explicitly and per question. Requires teacher+, management rights over the exam's instance, and a template the caller may still see. |
1289 | POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save one of this exam's questions into the school-wide bank as a reusable template. Requires teacher+ and management rights over the exam's instance. The caller becomes the template's owner; the question's subject rides along as origin metadata. A full copy — text, points, spec, illustration, and option pictures — lands under a new bank id. Provenance rides both ways: the origin exam is recorded on the template as `source_exam`, and the exam question's `banked_as` is pointed at the new template (a repeat save is allowed and repoints it at the newest one). `from_bank` is left alone — it records the other direction and a save never changes where a question came from. |1295 | POST | `/exams/{id}/questions/{qid}/to-bank` | teacher | Save one of this exam's questions into the school-wide bank as a reusable template. Requires teacher+ and management rights over the exam's instance. The caller becomes the template's owner; the question's subject rides along as origin metadata. A full copy — text, points, spec, illustration, and option pictures — lands under a new bank id. Provenance rides both ways: the origin exam is recorded on the template as `source_exam`, and the exam question's `banked_as` is pointed at the new template (a repeat save is allowed and repoints it at the newest one). `from_bank` is left alone — it records the other direction and a save never changes where a question came from. |
1290 | GET | `/exams/{id}/result` | student | The current user's own result for an exam. Any authenticated user may read their own mark; `404` while ungraded (or when the exam doesn't exist). |1296 | GET | `/exams/{id}/result` | student | The current user's own result for an exam. Any authenticated user may read their own mark; `404` while ungraded (or when the exam doesn't exist). |
1291-| GET | `/exams/{id}/results` | teacher | List an exam's results, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+ and management rights over the exam's instance — students read only their own via `GET /exams/{id}/result`. Returns a `{items, total, limit, offset}` envelope. |1297+| GET | `/exams/{id}/results` | teacher | List an exam's results, paged via `?limit=&offset=` (omit `limit` for all of them). Requires teacher+ and management rights over an instance the exam is addressed to — students read only their own via `GET /exams/{id}/result`. Returns a `{items, total, limit, offset}` envelope. |
1292-| POST | `/exams/{id}/results` | teacher | Record (or overwrite) a student's mark for an exam. Requires teacher+ and management rights over the exam's instance; the target must be a student and enrolled. Only students carry marks; students never grade — and nobody grades themselves. A draft can't be graded (`409`) — a mark would point at an exam its student can't see. |1298+| POST | `/exams/{id}/results` | teacher | Record (or overwrite) a student's mark for an exam. Requires teacher+ and management rights over **an instance the exam is addressed to** (the announced-to section's teacher grades its own students on an ortak sınav); the target must be a student enrolled in one of them. Only students carry marks; students never grade — and nobody grades themselves. A draft can't be graded (`409`) — a mark would point at an exam its student can't see. |
1293-| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over the exam's instance. |1299+| DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result from an exam. Requires teacher+ and management rights over an instance the exam is addressed to. |
1294 | GET | `/exams/{id}/review/attempts` | student | The caller's own sitting numbers at an exam — every seq that carries answers or a mark, ascending. Own-scoped review view; opens once the teacher enables review and has marked the caller, and closes again (409) while the caller can still sit the exam. |1300 | GET | `/exams/{id}/review/attempts` | student | The caller's own sitting numbers at an exam — every seq that carries answers or a mark, ascending. Own-scoped review view; opens once the teacher enables review and has marked the caller, and closes again (409) while the caller can still sit the exam. |
1295 | GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's own sittings, judged — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Own-scoped review view; 409 while the caller can still sit the exam, so a retake can't read its own correctness off an earlier seq. |1301 | GET | `/exams/{id}/review/attempts/{seq}/answers` | student | One of the caller's own sittings, judged — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Own-scoped review view; 409 while the caller can still sit the exam, so a retake can't read its own correctness off an earlier seq. |
1296 | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's own drawn-answer bytes for one of their sittings — the seq-scoped, own-scoped mirror of the grader's drawing read. Same 409 while a sitting is still available. |1302 | GET | `/exams/{id}/review/attempts/{seq}/answers/{qid}/image` | student | The caller's own drawn-answer bytes for one of their sittings — the seq-scoped, own-scoped mirror of the grader's drawing read. Same 409 while a sitting is still available. |
1297 | GET | `/exams/{id}/review/questions` | student | The exam's full question list, `correct` choice ids included — the answer key the caller reviews their own sheet against. Same review gate as the other self-review reads; revealing `correct` is the point (the gate already proves the caller was marked and can no longer sit the exam). Paged via `?limit=&offset=`. |1303 | GET | `/exams/{id}/review/questions` | student | The exam's full question list, `correct` choice ids included — the answer key the caller reviews their own sheet against. Same review gate as the other self-review reads; revealing `correct` is the point (the gate already proves the caller was marked and can no longer sit the exam). Paged via `?limit=&offset=`. |
1298-| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over the exam's instance. |1304+| GET | `/exams/{id}/statistics` | teacher | Summary statistics for an exam's graded results. Requires teacher+ and management rights over an instance the exam is addressed to. |
1299 | GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left at an exam — every seq that carries answers or a mark, ascending. Requires teacher+ and management rights over the exam's instance. Drives the FE's attempt-by-attempt picker. |1305 | GET | `/exams/{id}/students/{user}/attempts` | teacher | The sitting numbers a student has left at an exam — every seq that carries answers or a mark, ascending. Requires teacher+ and management rights over the exam's instance. Drives the FE's attempt-by-attempt picker. |
1300 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's judged answer sheet — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Requires teacher+ and management rights over the exam's instance. Serves an empty sheet for a seq the student never wrote in. |1306 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers` | teacher | One prior sitting's judged answer sheet — the `seq`th attempt's answers, drawing refs, correctness flags, and auto-score suggestion. Requires teacher+ and management rights over the exam's instance. Serves an empty sheet for a seq the student never wrote in. |
1301 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | A prior sitting's drawn-answer bytes. Requires teacher+ and management rights over the exam's instance — the seq-scoped mirror of the grader's latest-sitting drawing read. |1307 | GET | `/exams/{id}/students/{user}/attempts/{seq}/answers/{qid}/image` | teacher | A prior sitting's drawn-answer bytes. Requires teacher+ and management rights over the exam's instance — the seq-scoped mirror of the grader's latest-sitting drawing read. |
@@ -2950,10 +2956,47 @@ records one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to
2950 keep a monitor current — attendance, ticking clocks, submissions, and marks all2956 keep a monitor current — attendance, ticking clocks, submissions, and marks all
2951 ride in each snapshot.2957 ride in each snapshot.
2952 2958
2959+### Ortak sınav: one exam, several sections
2960+
2961+An exam belongs to the instance it was created on (`exam.class_course`), and
2962+that owner's audience row is written with it — every exam read goes through
2963+`exam_audience`, so the owner is always in the set. A **sibling instance** can
2964+be added to that set (`POST /exams/{id}/audience` with
2965+`{"instance": "<class_course id>"}`): the ortak sınav — one exam, one mark
2966+per student, standing in every addressed section's exam list, marks report
2967+and karne, so a single mark stands on each of their lines. An announcement is
2968+also what **admits a section**: an addressed instance's students read the exam
2969+(`GET /exams/{id}`), start and answer it (`POST /exams/{id}/attempt`, the
2970+answer routes, the exam room), and are graded on it exactly like the owner's —
2971+the sitting, answering and grading gates ask "enrolled in any instance the
2972+exam is addressed to", not only the owner's roster — and `GET
2973+`/exams/{id}/live` monitors every addressed section's sitters, not only the
2974+owner's, and the teacher side of the exam — grading, the results and
2975+statistics reads, the monitor — opens to a teacher of **any** addressed
2976+instance, so the section that sits the exam also runs it there (authoring,
2977+`PATCH`/`DELETE` and the question/image routes, stays the owner's). Two rules
2978+make the announcement legal: the target must teach the **same catalog course**
2979+and sit under the **same academic year** as the owner (an exam's mark has to
2980+land in a report that teaches the subject, in the year it is sat), and the owner itself
2981+cannot be announced to — its row is always there, and deleting the exam is
2982+what ends it. The target's year must still be open, so announcing into an
2983+archived year is the usual `409`. The gate is the **owner** instance's
2984+(`manager`+, its assigned teachers, its şube's homeroom teacher): the section
2985+that runs the exam decides who else sits it; a teacher of the receiving
2986+section may grade there, not re-announce. `GET /exams/{id}/audience` lists the
2987+set (owner first, then announcement order), visible exactly as the exam is;
2988+`DELETE /exams/{id}/audience/{instance}` withdraws one — a repeat announce is
2989+a no-op `200`, a pair that was never announced a `404`, and the owner's own
2990+pair a `400`.
2991+
2953 Deleting an exam (or its course) cascades attempts, questions, answers, and2992 Deleting an exam (or its course) cascades attempts, questions, answers, and
2954 question + answer images (blobs included) along with results; unenrolling mid-exam2993 question + answer images (blobs included) along with results; unenrolling mid-exam
2955 hides the student from the monitor roster but keeps the attempt and mark2994 hides the student from the monitor roster but keeps the attempt and mark
2956-rows, mirroring the marks report.2995+rows, mirroring the marks report. Detaching the instance that carries an exam
2996+sweeps it the same way, and the sweep takes every audience row that names the
2997+detaching instance — the ones addressed **to** it (an exam a sibling owns) and
2998+the rows of the exams it **owns** (announcements out to siblings) — so an
2999+ortak sınav never blocks a detach on a foreign key.
2957 3000
2958 > **Schema changes are migrations, not boot batches.** The sqlx migrator3001 > **Schema changes are migrations, not boot batches.** The sqlx migrator
2959 > applies `migrations/control` to the control database at boot and3002 > applies `migrations/control` to the control database at boot and
src/db/course.rsmodified+23 -2
@@ -462,9 +462,30 @@ pub(crate) async fn sweep_instance_subtree(
462 )462 )
463 .fetch_all(&mut *tx)463 .fetch_all(&mut *tx)
464 .await?;464 .await?;
465+ // Both directions of the audience table, and each has to go before the
466+ // row it names. The rows *addressed to* this instance (an exam owned by
467+ // another instance may be announced here — an ortak sınav) reference the
468+ // `class_course` row the caller deletes right after this sweep and would
469+ // otherwise refuse it with a `23503`. The rows *of* the exams this sweep
470+ // deletes reference *those* exams the same way (`exam_audience.exam` is
471+ // `NO ACTION` too), so they block the `DELETE FROM exam` below wherever
472+ // they point — an audience of a swept exam in a şube that is *not* being
473+ // detached included.
474+ //
475+ // The instance row is held `FOR UPDATE` by the caller from before this
476+ // sweep, and an insert into `exam_audience` takes that row's
477+ // `FOR KEY SHARE` through its foreign key, so no audience *addressed to*
478+ // this instance can land under the sweep: the `add` blocks behind the
479+ // detach and, on the settled state, finds the instance gone (`404`). An
480+ // audience of one of the swept *exams* rides that exam's own key-share
481+ // lock instead; if it commits between this delete and the exam delete
482+ // below, the `exam_audience_exam_fkey` refusal that follows is what the
483+ // detach's `cascade` retry re-runs on — the second round sees the
484+ // settled row and takes it.
465 sqlx::query!(485 sqlx::query!(
466- r#"DELETE FROM exam_audience WHERE class_course = $1"#,486+ r#"DELETE FROM exam_audience WHERE class_course = $1 OR exam = ANY($2)"#,
467- instance487+ instance,
488+ &exams,
468 )489 )
469 .execute(&mut *tx)490 .execute(&mut *tx)
470 .await?;491 .await?;
src/db/enrollment.rsmodified+33 -0
@@ -16,6 +16,7 @@ use crate::domain::class_course::ClassCourseId;
16 use crate::domain::class_group::ClassGroupId;16 use crate::domain::class_group::ClassGroupId;
17 use crate::domain::course::CourseId;17 use crate::domain::course::CourseId;
18 use crate::domain::enrollment::Enrollment;18 use crate::domain::enrollment::Enrollment;
19+use crate::domain::exam::ExamId;
19 use crate::domain::role::Role;20 use crate::domain::role::Role;
20 use crate::domain::timestamp::Timestamp;21 use crate::domain::timestamp::Timestamp;
21 use crate::domain::user::UserId;22 use crate::domain::user::UserId;
@@ -223,6 +224,38 @@ pub async fn read_for_user(
223 Ok(row)224 Ok(row)
224 }225 }
225 226
227+/// The roster an exam is sat by: every enrollment of every instance the exam
228+/// is addressed to (`exam_audience`, D2), deduped by student — the live
229+/// monitor's roster read, and the one that makes an announced-to section's
230+/// sitters visible to it. For an exam nobody was announced to this is the
231+/// owner instance's roster, row for row.
232+///
233+/// `DISTINCT ON (app_user)` because a student enrolled in two addressed
234+/// instances sits once: the roster is a set of people, and the monitor joins
235+/// it with one attempt/mark map per person.
236+pub async fn list_for_exam_audience(
237+ db: &Database,
238+ exam: &ExamId,
239+) -> Result<Vec<Enrollment>, AppError> {
240+ let rows = sqlx::query_as!(
241+ Enrollment,
242+ r#"SELECT DISTINCT ON (e.app_user)
243+ e.class_course AS "class_course: ClassCourseId",
244+ e.app_user AS "user: UserId",
245+ e.enrolled_by AS "enrolled_by: UserId",
246+ e.source AS "source: ClassGroupId",
247+ e.created_at AS "created_at: Timestamp"
248+ FROM enrollment e
249+ JOIN exam_audience a ON a.class_course = e.class_course
250+ WHERE a.exam = $1
251+ ORDER BY e.app_user, e.created_at, e.class_course"#,
252+ exam.uuid(),
253+ )
254+ .fetch_all(db)
255+ .await?;
256+ Ok(rows)
257+}
258+
226 /// Whether `user` is one of `course`'s students right now — the point probe259 /// Whether `user` is one of `course`'s students right now — the point probe
227 /// behind an event addressed at a course.260 /// behind an event addressed at a course.
228 ///261 ///
src/db/exam_audience.rsadded+157 -0
@@ -0,0 +1,157 @@
1+//! The `exam_audience` junction: which instances one exam is announced to.
2+//!
3+//! Every exam is *owned* by exactly one instance — the `class_course` column
4+//! on its own row — and [`crate::db::exam::insert_in`] writes that owner's
5+//! audience row in the same transaction as the exam. The rows beyond it are
6+//! the **ortak sınav**'s (D2): one exam announced to another şube's instance,
7+//! sat and graded once, standing in every addressed instance's marks and
8+//! karne. Every exam read goes through this table
9+//! ([`crate::db::exam::list_for_class_course`] and the marks reports' joins),
10+//! so the audience set is the single answer to "which instances does this
11+//! exam belong to" and the owner column is only the join's tie-break.
12+//!
13+//! The owner's row is never removed from here: [`crate::service::exam`]
14+//! refuses that pair on both routes, and deleting the exam is what ends its
15+//! audience — [`crate::db::exam::delete`] and the instance sweep each clear
16+//! the rows in their own transaction. The audience a detach may *not* leave
17+//! behind is the one pointing at the detaching instance: an exam owned by
18+//! another instance would block the `class_course` delete with a `23503`, so
19+//! [`crate::db::course::sweep_instance_subtree`] clears both directions.
20+
21+use crate::database::{Database, foreign_key_violation};
22+use crate::domain::class_course::ClassCourseId;
23+use crate::domain::class_group::ClassGroupId;
24+use crate::domain::course::CourseId;
25+use crate::domain::exam::ExamId;
26+use crate::domain::user::UserId;
27+use crate::error::AppError;
28+
29+/// One audience row, resolved to what a client needs to name it: the
30+/// instance, the şube it belongs to and the catalog course it teaches.
31+#[derive(Debug, sqlx::FromRow)]
32+pub struct Audience {
33+ class_course: ClassCourseId,
34+ class: ClassGroupId,
35+ course: CourseId,
36+}
37+
38+impl Audience {
39+ /// The instance the exam is announced to.
40+ pub fn get_instance(&self) -> &ClassCourseId {
41+ &self.class_course
42+ }
43+
44+ /// The şube that instance belongs to.
45+ pub fn get_class(&self) -> &ClassGroupId {
46+ &self.class
47+ }
48+
49+ /// The catalog course that instance teaches — the exam's own, by the
50+ /// announcement's rule.
51+ pub fn get_course(&self) -> &CourseId {
52+ &self.course
53+ }
54+}
55+
56+/// Announce `exam` to `class_course`. An audience the exam already carries is
57+/// success, not a refusal: the announcement is idempotent, exactly like a
58+/// teacher assignment ([`crate::db::class_course_teacher::assign`]), and the
59+/// route answers the resulting set either way.
60+///
61+/// Both foreign keys answer a gone parent with `NotFound`: an exam swept by a
62+/// concurrent detach and an instance that never existed are the same answer
63+/// to the caller, and neither may read as a `500`.
64+pub async fn add(
65+ db: &Database,
66+ exam: &ExamId,
67+ class_course: &ClassCourseId,
68+) -> Result<(), AppError> {
69+ match sqlx::query!(
70+ r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)
71+ ON CONFLICT ON CONSTRAINT exam_audience_pk DO NOTHING"#,
72+ exam.uuid(),
73+ class_course.uuid(),
74+ )
75+ .execute(db)
76+ .await
77+ {
78+ Ok(_) => Ok(()),
79+ Err(e) if foreign_key_violation(&e) => Err(AppError::NotFound),
80+ Err(e) => Err(e.into()),
81+ }
82+}
83+
84+/// Drop an audience row. `false` when the pair held none, so the web layer
85+/// can answer 404 instead of pretending it removed one — the shape
86+/// [`crate::db::class_course_teacher::unassign`] has.
87+pub async fn remove(
88+ db: &Database,
89+ exam: &ExamId,
90+ class_course: &ClassCourseId,
91+) -> Result<bool, AppError> {
92+ let deleted = sqlx::query!(
93+ r#"DELETE FROM exam_audience WHERE exam = $1 AND class_course = $2"#,
94+ exam.uuid(),
95+ class_course.uuid(),
96+ )
97+ .execute(db)
98+ .await?;
99+ Ok(deleted.rows_affected() > 0)
100+}
101+
102+/// Every instance `exam` is announced to, in the order they were announced —
103+/// uuidv7 is creation order — the read behind `GET /exams/{id}/audience`.
104+pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<Audience>, AppError> {
105+ let rows = sqlx::query_as!(
106+ Audience,
107+ r#"SELECT a.class_course AS "class_course: ClassCourseId",
108+ c.class AS "class: ClassGroupId",
109+ c.course AS "course: CourseId"
110+ FROM exam_audience a
111+ JOIN class_course c ON c.id = a.class_course
112+ WHERE a.exam = $1
113+ ORDER BY a.class_course"#,
114+ exam.uuid(),
115+ )
116+ .fetch_all(db)
117+ .await?;
118+ Ok(rows)
119+}
120+
121+/// The exams addressed to one instance — the reverse read, for a caller that
122+/// starts from the instance rather than the exam (`exam_audience`'s
123+/// `class_course` index is the side it walks).
124+pub async fn list_for_instance(
125+ db: &Database,
126+ class_course: &ClassCourseId,
127+) -> Result<Vec<ExamId>, AppError> {
128+ let rows = sqlx::query!(
129+ r#"SELECT exam AS "exam: ExamId" FROM exam_audience
130+ WHERE class_course = $1 ORDER BY exam"#,
131+ class_course.uuid(),
132+ )
133+ .fetch_all(db)
134+ .await?;
135+ Ok(rows.into_iter().map(|row| row.exam).collect())
136+}
137+
138+/// Whether `user` is enrolled in any instance `exam` is addressed to — the
139+/// owner included, its audience row always standing.
140+///
141+/// The enrollment predicate the sitting and grading gates ask once one exam
142+/// can be announced to several instances (D2): for an exam nobody was
143+/// announced to this is the owner-only check those gates used to run, row for
144+/// row, and for an ortak sınav it admits the addressed sections' students —
145+/// who sit and are graded at their own instance exactly like the owner's.
146+pub async fn enrolled(db: &Database, exam: &ExamId, user: &UserId) -> Result<bool, AppError> {
147+ Ok(sqlx::query_scalar!(
148+ r#"SELECT EXISTS(
149+ SELECT 1 FROM exam_audience a
150+ JOIN enrollment e ON e.class_course = a.class_course
151+ WHERE a.exam = $1 AND e.app_user = $2) AS "enrolled!""#,
152+ exam.uuid(),
153+ user.uuid(),
154+ )
155+ .fetch_one(db)
156+ .await?)
157+}
src/db/mod.rsmodified+1 -0
@@ -30,6 +30,7 @@ pub mod event;
30 pub mod exam;30 pub mod exam;
31 pub mod exam_answer;31 pub mod exam_answer;
32 pub mod exam_attempt;32 pub mod exam_attempt;
33+pub mod exam_audience;
33 pub mod exam_question;34 pub mod exam_question;
34 pub mod exam_result;35 pub mod exam_result;
35 pub mod fee_plan;36 pub mod fee_plan;
src/lib.rsmodified+1 -1
@@ -71,7 +71,7 @@ use crate::web::module_gate::gate;
71 (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)"),71 (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)"),
72 (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"),72 (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"),
73 (name = "attendance", description = "Attendance summary reports: event tallies, lesson roll-call tallies per instance with rates, and the **devamsızlık** block a Turkish school reads — per dönem, how many distinct school-days the student was away, split `absent` (unexcused) and `excused`, against the school's configured day limits (`max_excused_absent_days` / `max_unexcused_absent_days` on `/settings`) with an `over_limit` flag. Days are counted in the school's timezone (`settings.timezone`) and deduplicated: two missed lessons in one day are one absent day, and the day is the *lesson's* (`course_session.starts_at`), never when the teacher marked it. Own report at `/me`; another user's needs teacher+ (teachers narrowed to the instances they run — blocks, tallies and absence days alike) or a parent link to that student"),73 (name = "attendance", description = "Attendance summary reports: event tallies, lesson roll-call tallies per instance with rates, and the **devamsızlık** block a Turkish school reads — per dönem, how many distinct school-days the student was away, split `absent` (unexcused) and `excused`, against the school's configured day limits (`max_excused_absent_days` / `max_unexcused_absent_days` on `/settings`) with an `over_limit` flag. Days are counted in the school's timezone (`settings.timezone`) and deduplicated: two missed lessons in one day are one absent day, and the day is the *lesson's* (`course_session.starts_at`), never when the teacher marked it. Own report at `/me`; another user's needs teacher+ (teachers narrowed to the instances they run — blocks, tallies and absence days alike) or a parent link to that student"),
74- (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"),74+ (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). An exam is owned by the instance it was created on, and it can be announced to **sibling instances** — the ortak sınav: `POST /exams/{id}/audience` adds an instance that teaches the same catalog course in the same academic year, `GET /exams/{id}/audience` lists the set (owner first), and `DELETE /exams/{id}/audience/{instance}` withdraws one — the owner's own pair never, that is the exam's own instance and deleting the exam is what ends it. An announcement is what *attributes* and what *admits*: every addressed instance's students read the exam (`GET /exams/{id}`), sit it (attempts and answers), and are graded on it exactly like the owner's — the sitting/answering/grading enrollment gates ask \"enrolled in any addressed instance\", and the live monitor's roster spans the audience — while every addressed instance's exam list, marks report and karne carry the exam and its marks (one sitting, one mark, standing in each addressed instance's report). The announce/withdraw gate is the owner instance's (`manager`+, its assigned teachers, its şube's homeroom teacher) — the section that runs the exam decides who else sits it — while the **teacher side of the exam itself** (grading, the results and statistics reads, the live monitor) opens to a teacher of *any* addressed instance, so the section that sits it also runs it there; exam authoring (PATCH/DELETE, questions, images) stays the owner's. 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"),
75 (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"),75 (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"),
76 (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"),76 (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"),
77 (name = "marks", description = "Weighted mark reports per class×course instance 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 the instances they run) or a parent link to that student. `GET /marks/karne?term=` is the dönem's karne — every karne-counting instance of the student's şubeler with its average and band, the `ders_saati`-weighted dönem average, and the pass/fail verdict read off the bands (never hardcoded); `GET /marks/karne/{user}` is the same for another student, narrowed for an exactly-teacher caller to their own instances (the dönem average recomputed over those, no verdict — a partially-seen karne states none). An archived dönem serves the snapshot the school froze when it closed; an open one computes live"),77 (name = "marks", description = "Weighted mark reports per class×course instance 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 the instances they run) or a parent link to that student. `GET /marks/karne?term=` is the dönem's karne — every karne-counting instance of the student's şubeler with its average and band, the `ders_saati`-weighted dönem average, and the pass/fail verdict read off the bands (never hardcoded); `GET /marks/karne/{user}` is the same for another student, narrowed for an exactly-teacher caller to their own instances (the dönem average recomputed over those, no verdict — a partially-seen karne states none). An archived dönem serves the snapshot the school froze when it closed; an open one computes live"),
src/service/exam.rsmodified+484 -1
@@ -10,6 +10,7 @@ use crate::constant::CAS_UPDATE_RETRIES;
10 use crate::database::Database;10 use crate::database::Database;
11 use crate::db::exam;11 use crate::db::exam;
12 use crate::db::exam_attempt::any_for_exam;12 use crate::db::exam_attempt::any_for_exam;
13+use crate::db::exam_audience;
13 use crate::db::exam_result;14 use crate::db::exam_result;
14 use crate::domain::class_course::ClassCourseId;15 use crate::domain::class_course::ClassCourseId;
15 use crate::domain::course::CourseId;16 use crate::domain::course::CourseId;
@@ -19,7 +20,7 @@ use crate::domain::exam::{
19 };20 };
20 use crate::domain::term::TermId;21 use crate::domain::term::TermId;
21 use crate::domain::timestamp::Timestamp;22 use crate::domain::timestamp::Timestamp;
22-use crate::domain::user::UserId;23+use crate::domain::user::{User, UserId};
23 use crate::error::{AppError, ValidationError};24 use crate::error::{AppError, ValidationError};
24 use crate::service::exam_attempt::require_open;25 use crate::service::exam_attempt::require_open;
25 26
@@ -140,6 +141,174 @@ pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec
140 exam::list_for_courses(db, courses).await141 exam::list_for_courses(db, courses).await
141 }142 }
142 143
144+// ---- audience: the ortak sınav (D2) ---------------------------------------
145+
146+/// The exam, or the `404` a gone id deserves — and the caller's right to act
147+/// on the exam's **owner** instance, or the `403` D10 answers
148+/// ([`crate::service::class_course::ensure_instance_teacher`]: manager+, an
149+/// assigned teacher, or the şube's homeroom teacher).
150+///
151+/// The audience routes never move the exam, they announce it, so the gate is
152+/// the owner's and not the target's: the section that runs the exam decides
153+/// who else it is addressed to, and a teacher of the receiving section has no
154+/// say in the announcement.
155+async fn managed_exam(db: &Database, user: &User, id: &ExamId) -> Result<Exam, AppError> {
156+ let exam = exam::read(db, id).await?.ok_or(AppError::NotFound)?;
157+ crate::service::class_course::ensure_instance_teacher(db, user, exam.get_class_course())
158+ .await?;
159+ Ok(exam)
160+}
161+
162+/// Announce `exam` to another instance — the ortak sınav write (D2).
163+///
164+/// The exam stays owned by the instance it was created on; an audience row is
165+/// what makes a second (third, …) şube sit the same sitting and carry the
166+/// mark in its own marks and karne ([`crate::db::exam_result`] reads through
167+/// `exam_audience`). Three rules keep the announcement from filing academic
168+/// work where it cannot be graded:
169+///
170+/// - the target must teach the **same catalog course** — a mark on an algebra
171+/// exam standing in a geometry instance's report is a subject that report
172+/// never taught;
173+/// - both instances must sit under the **same academic year** — a karne is
174+/// computed over one year, so an announcement across years would file the
175+/// mark into a year the exam is not taught in (the rule [`create`] already
176+/// applies to the dönem);
177+/// - the target may not be the owner itself: the owner's audience row always
178+/// exists, and the owner cannot be withdrawn (see [`remove_audience`]) —
179+/// deleting the exam is what ends it.
180+///
181+/// The target's year must still be open ([`crate::service::class_course::require_open`]):
182+/// announcing into an archived year is a write into a read-only year like
183+/// every other one. A repeat announcement is success, not a conflict — the
184+/// store treats the existing row as a no-op — and the answer is the audience
185+/// the exam holds after the call.
186+///
187+/// Every refusal is coded: `404` for a gone exam or target instance, `403`
188+/// for a caller with no right over the owner, `400` for the three shape
189+/// rules, and the archived year's `409`.
190+pub async fn add_audience(
191+ db: &Database,
192+ user: &User,
193+ id: &ExamId,
194+ target: &ClassCourseId,
195+) -> Result<Vec<exam_audience::Audience>, AppError> {
196+ let exam = managed_exam(db, user, id).await?;
197+ let owner = crate::db::class_course::read(db, exam.get_class_course())
198+ .await?
199+ // A foreign key names the owner, so only a concurrent detach — which
200+ // sweeps the exam in the same transaction — could have taken it;
201+ // either way the exam is gone, and 404 is that answer.
202+ .ok_or(AppError::NotFound)?;
203+ let target_row = crate::db::class_course::read(db, target)
204+ .await?
205+ .ok_or(AppError::NotFound)?;
206+ if target_row.get_id() == owner.get_id() {
207+ return Err(AppError::Validation(ValidationError::Invalid {
208+ field: "instance",
209+ reason: "this instance owns the exam — an audience is another instance, and \
210+ deleting the exam is what ends the owner's",
211+ }));
212+ }
213+ if target_row.get_course() != owner.get_course() {
214+ return Err(AppError::Validation(ValidationError::Invalid {
215+ field: "instance",
216+ reason: "the instance teaches another course than the exam's",
217+ }));
218+ }
219+ let owner_year = crate::service::class_course::year_of(db, owner.get_id()).await?;
220+ if owner_year != crate::service::class_course::year_of(db, target).await? {
221+ return Err(AppError::Validation(ValidationError::Invalid {
222+ field: "instance",
223+ reason: "the instance belongs to another academic year than the exam's",
224+ }));
225+ }
226+ crate::service::class_course::require_open(db, target).await?;
227+ exam_audience::add(db, id, target).await?;
228+ list_audience(db, id).await
229+}
230+
231+/// Withdraw `exam` from one instance's audience. The same **gate** as
232+/// [`add_audience`] (management rights over the exam's owner instance), and
233+/// none of its shape rules re-run: the row was validated when it was
234+/// announced, and taking it back is cleanup — a stale announcement (an
235+/// instance whose section moved years, say) can always be withdrawn.
236+///
237+/// One pair is the exception, and it is the route's whole safety property:
238+/// the **owner's** row is not withdrawable. Removing it would leave an exam
239+/// belonging to no instance — every audience read is the `exam_audience`
240+/// join, so the exam, its marks and its attempts would vanish from every
241+/// report while their rows stood — which is why the owner pair is a `400`
242+/// here and not a delete.
243+///
244+/// A pair that holds no audience row is the `404`
245+/// [`crate::db::exam_audience::remove`]'s boolean carries — never a silent
246+/// success. The exam's own year must still be open, like every other write
247+/// against the exam's structure ([`update`] and [`delete`]): withdrawing from
248+/// an archived year's ortak sınav is a `409`, not a silent edit of a past
249+/// year's record. The answer is the audience the exam holds after the call.
250+pub async fn remove_audience(
251+ db: &Database,
252+ user: &User,
253+ id: &ExamId,
254+ target: &ClassCourseId,
255+) -> Result<Vec<exam_audience::Audience>, AppError> {
256+ let exam = managed_exam(db, user, id).await?;
257+ if exam.get_class_course() == target {
258+ return Err(AppError::Validation(ValidationError::Invalid {
259+ field: "instance",
260+ reason: "the owner instance is not an audience — an exam cannot lose the \
261+ instance it belongs to; delete the exam instead",
262+ }));
263+ }
264+ require_open(db, &exam).await?;
265+ if !exam_audience::remove(db, id, target).await? {
266+ return Err(AppError::NotFound);
267+ }
268+ list_audience(db, id).await
269+}
270+
271+/// The audience of one exam: the instances it is announced to, its owner
272+/// included — the read behind `GET /exams/{id}/audience`. Read-only, so the
273+/// web layer gates it with the exam's own view rule.
274+pub async fn list_audience(
275+ db: &Database,
276+ id: &ExamId,
277+) -> Result<Vec<exam_audience::Audience>, AppError> {
278+ exam_audience::list_for_exam(db, id).await
279+}
280+
281+/// Whether `user` is enrolled in any instance `exam` is addressed to — its
282+/// owner or an announced sibling (D2).
283+///
284+/// This is the enrollment predicate every *student* door at an exam asks
285+/// (sitting, answering, grading), and announcing an exam is what moves it:
286+/// the addressed sections' students sit and are graded at their own instance.
287+/// An exam nobody was announced to answers exactly what the owner-only check
288+/// these doors used to run answered.
289+pub async fn enrolled_anywhere(
290+ db: &Database,
291+ exam: &Exam,
292+ user: &UserId,
293+) -> Result<bool, AppError> {
294+ exam_audience::enrolled(db, exam.get_id(), user).await
295+}
296+
297+/// A `403` unless [`enrolled_anywhere`] — the refusal the sit paths answer,
298+/// kept byte-for-byte from the owner-only check it replaces.
299+pub async fn ensure_enrolled_anywhere(
300+ db: &Database,
301+ exam: &Exam,
302+ user: &UserId,
303+) -> Result<(), AppError> {
304+ if enrolled_anywhere(db, exam, user).await? {
305+ return Ok(());
306+ }
307+ Err(AppError::Forbidden(
308+ "you are not enrolled in this exam's course",
309+ ))
310+}
311+
143 /// A `PATCH /exams/{id}` request after field validation: every value the312 /// A `PATCH /exams/{id}` request after field validation: every value the
144 /// request *set* is already validated (title, description, mode, duration,313 /// request *set* is already validated (title, description, mode, duration,
145 /// and attempt limit by their newtypes; the kind against the school's314 /// and attempt limit by their newtypes; the kind against the school's
@@ -338,3 +507,317 @@ pub async fn delete(db: &Database, target: &Exam) -> Result<DeleteOutcome, AppEr
338 answer_image_files: deleted.answer_image_files,507 answer_image_files: deleted.answer_image_files,
339 })508 })
340 }509 }
510+
511+#[cfg(test)]
512+mod tests {
513+ use super::*;
514+ use crate::domain::academic_year::AcademicYearId;
515+ use crate::domain::class_course::ClassCourse;
516+ use crate::domain::class_group::ClassName;
517+ use crate::domain::role::Role;
518+ use crate::domain::settings::Settings;
519+ use crate::domain::user::Username;
520+
521+ /// A real account at a role — the announcement gate judges the live row,
522+ /// so a raw fixture id would not do.
523+ async fn staff(db: &Database, username: &str, role: Role) -> User {
524+ let account = crate::db::user::create(db, Username::try_new(username).unwrap(), None)
525+ .await
526+ .unwrap();
527+ crate::service::user::set_role(db, account.get_id(), role)
528+ .await
529+ .unwrap();
530+ crate::db::user::read(db, account.get_id())
531+ .await
532+ .unwrap()
533+ .unwrap()
534+ }
535+
536+ /// An instance of `course` inside a fresh şube of `year` — one side of an
537+ /// announcement.
538+ async fn instance_in(
539+ db: &Database,
540+ manager: &UserId,
541+ name: &str,
542+ course: &CourseId,
543+ year: Option<&AcademicYearId>,
544+ ) -> ClassCourse {
545+ let class = crate::db::class_group::create(
546+ db,
547+ manager,
548+ ClassName::try_new(name).unwrap(),
549+ None,
550+ year.cloned(),
551+ None,
552+ )
553+ .await
554+ .unwrap();
555+ crate::service::class_course::attach(db, class.get_id(), course, manager)
556+ .await
557+ .unwrap()
558+ }
559+
560+ /// A published, unscheduled exam on `instance` — the parent an audience
561+ /// row hangs off.
562+ async fn exam_on(db: &Database, instance: &ClassCourse) -> Exam {
563+ let creator = crate::db::class_member::tests::fixture_user(db, "audience-author").await;
564+ let term = crate::db::term::a_test_term(db).await;
565+ let allowed = Settings::defaults().get_exam_kinds().to_vec();
566+ crate::db::exam::create(
567+ db,
568+ &creator,
569+ instance.get_id(),
570+ &term,
571+ ExamTitle::try_new("1. Yazılı").unwrap(),
572+ ExamDescription::try_new("").unwrap(),
573+ ExamKind::try_new("yazili", &allowed).unwrap(),
574+ ExamSchedule::try_new(None, None, None, None).unwrap(),
575+ ExamAttemptLimit::try_new(1).unwrap(),
576+ true,
577+ false,
578+ false,
579+ )
580+ .await
581+ .unwrap()
582+ }
583+
584+ /// The announcement's shape rules: same catalog course, same academic
585+ /// year, another instance — each violation a coded `400`, the pair that
586+ /// satisfies all three a row the audience read (and so the marks reports)
587+ /// sees, and a repeat a no-op rather than a conflict.
588+ #[tokio::test]
589+ async fn an_announcement_needs_the_same_course_and_year() {
590+ let (db, _leases) = crate::database::init_test_db().await;
591+ let manager = staff(&db, "audience-mudur", Role::Manager).await;
592+ let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
593+ let geometry = crate::db::class_member::tests::a_course("geometry", &db).await;
594+ let year = crate::db::academic_year::a_test_year(&db).await;
595+ let other_year = crate::db::academic_year::a_test_year(&db).await;
596+
597+ let owner = instance_in(&db, manager.get_id(), "5-A", &algebra, Some(&year)).await;
598+ let sibling = instance_in(&db, manager.get_id(), "5-B", &algebra, Some(&year)).await;
599+ let wrong_course = instance_in(&db, manager.get_id(), "5-C", &geometry, Some(&year)).await;
600+ let wrong_year =
601+ instance_in(&db, manager.get_id(), "6-A", &algebra, Some(&other_year)).await;
602+ let exam = exam_on(&db, &owner).await;
603+
604+ let audience = add_audience(&db, &manager, exam.get_id(), sibling.get_id())
605+ .await
606+ .unwrap();
607+ assert_eq!(audience.len(), 2, "owner + announcement");
608+ assert_eq!(
609+ audience[0].get_instance(),
610+ owner.get_id(),
611+ "the owner stands first — announcement order is creation order"
612+ );
613+ assert_eq!(audience[1].get_instance(), sibling.get_id());
614+ assert_eq!(audience[1].get_class(), sibling.get_class());
615+ assert_eq!(audience[1].get_course(), &algebra);
616+ // The sibling's own exam list carries it — the join the marks reports
617+ // and the instance page read.
618+ assert_eq!(
619+ list_for_class_course(&db, sibling.get_id())
620+ .await
621+ .unwrap()
622+ .len(),
623+ 1,
624+ "the announcement is one exam, addressed here"
625+ );
626+
627+ for (bad, why) in [
628+ (&wrong_course, "another course"),
629+ (&wrong_year, "another year"),
630+ ] {
631+ let refused = add_audience(&db, &manager, exam.get_id(), bad.get_id()).await;
632+ assert!(
633+ matches!(refused, Err(AppError::Validation(_))),
634+ "{why} must be a coded 400: {refused:?}"
635+ );
636+ }
637+ let owned = add_audience(&db, &manager, exam.get_id(), owner.get_id()).await;
638+ assert!(
639+ matches!(owned, Err(AppError::Validation(_))),
640+ "the owner is not an audience: {owned:?}"
641+ );
642+ let ghost = ClassCourseId::generate();
643+ assert!(
644+ matches!(
645+ add_audience(&db, &manager, exam.get_id(), &ghost).await,
646+ Err(AppError::NotFound)
647+ ),
648+ "a minted instance id names nothing"
649+ );
650+ assert!(matches!(
651+ add_audience(&db, &manager, &ExamId::generate(), sibling.get_id()).await,
652+ Err(AppError::NotFound)
653+ ));
654+
655+ add_audience(&db, &manager, exam.get_id(), sibling.get_id())
656+ .await
657+ .unwrap();
658+ assert_eq!(
659+ exam_audience::list_for_exam(&db, exam.get_id())
660+ .await
661+ .unwrap()
662+ .len(),
663+ 2,
664+ "a repeat announcement is a no-op, not a second row"
665+ );
666+ }
667+
668+ /// The gate is the **owner** instance's: its assigned teacher and a
669+ /// manager+ may announce and withdraw; the target instance's own teacher
670+ /// may not — running the receiving section is not running the exam — and
671+ /// a student may not either.
672+ #[tokio::test]
673+ async fn an_announcement_is_gated_on_the_owner_instance() {
674+ let (db, _leases) = crate::database::init_test_db().await;
675+ let manager = staff(&db, "audience-mudur-2", Role::Manager).await;
676+ let owner_teacher = staff(&db, "audience-ogretmen-a", Role::Teacher).await;
677+ let target_teacher = staff(&db, "audience-ogretmen-b", Role::Teacher).await;
678+ let student = staff(&db, "audience-ogrenci", Role::Student).await;
679+ let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
680+ let owner = instance_in(&db, manager.get_id(), "7-A", &algebra, None).await;
681+ let target = instance_in(&db, manager.get_id(), "7-B", &algebra, None).await;
682+ crate::service::class_course::assign_teacher(
683+ &db,
684+ owner.get_id(),
685+ owner_teacher.get_id(),
686+ manager.get_id(),
687+ )
688+ .await
689+ .unwrap();
690+ crate::service::class_course::assign_teacher(
691+ &db,
692+ target.get_id(),
693+ target_teacher.get_id(),
694+ manager.get_id(),
695+ )
696+ .await
697+ .unwrap();
698+ let exam = exam_on(&db, &owner).await;
699+
700+ assert!(
701+ add_audience(&db, &owner_teacher, exam.get_id(), target.get_id())
702+ .await
703+ .is_ok(),
704+ "an assigned teacher of the owner instance announces"
705+ );
706+ assert!(
707+ remove_audience(&db, &owner_teacher, exam.get_id(), target.get_id())
708+ .await
709+ .is_ok(),
710+ "…and withdraws"
711+ );
712+ for (user, who) in [
713+ (&target_teacher, "the target's teacher"),
714+ (&student, "a student"),
715+ ] {
716+ let refused = add_audience(&db, user, exam.get_id(), target.get_id()).await;
717+ assert!(
718+ matches!(refused, Err(AppError::Forbidden(_))),
719+ "{who} must be a 403: {refused:?}"
720+ );
721+ }
722+ }
723+
724+ /// Withdrawal: the owner's own pair is a coded `400` (an exam cannot lose
725+ /// the instance it belongs to), a pair holding no row is a `404`, and the
726+ /// row the instance's read joins on is gone afterwards.
727+ #[tokio::test]
728+ async fn withdrawing_an_audience_leaves_the_owner_alone() {
729+ let (db, _leases) = crate::database::init_test_db().await;
730+ let manager = staff(&db, "audience-mudur-3", Role::Manager).await;
731+ let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
732+ let owner = instance_in(&db, manager.get_id(), "8-A", &algebra, None).await;
733+ let target = instance_in(&db, manager.get_id(), "8-B", &algebra, None).await;
734+ let exam = exam_on(&db, &owner).await;
735+ add_audience(&db, &manager, exam.get_id(), target.get_id())
736+ .await
737+ .unwrap();
738+
739+ let audience = remove_audience(&db, &manager, exam.get_id(), target.get_id())
740+ .await
741+ .unwrap();
742+ assert_eq!(audience.len(), 1);
743+ assert_eq!(audience[0].get_instance(), owner.get_id());
744+ assert!(
745+ list_for_class_course(&db, target.get_id())
746+ .await
747+ .unwrap()
748+ .is_empty(),
749+ "the withdrawn instance no longer carries the exam"
750+ );
751+
752+ assert!(
753+ matches!(
754+ remove_audience(&db, &manager, exam.get_id(), target.get_id()).await,
755+ Err(AppError::NotFound)
756+ ),
757+ "a pair holding no row is a 404, never a silent success"
758+ );
759+ let owner_pair = remove_audience(&db, &manager, exam.get_id(), owner.get_id()).await;
760+ assert!(
761+ matches!(owner_pair, Err(AppError::Validation(_))),
762+ "the owner pair is refused: {owner_pair:?}"
763+ );
764+ assert_eq!(
765+ exam_audience::list_for_exam(&db, exam.get_id())
766+ .await
767+ .unwrap()
768+ .len(),
769+ 1,
770+ "the owner's row stands"
771+ );
772+ }
773+
774+ /// The archived-year posture of both routes: announcing into an archived
775+ /// year and withdrawing from one are the coded `409` every other write
776+ /// against the year answers, and neither writes — an announcement row
777+ /// predating the archive is no loophole for more of them.
778+ #[tokio::test]
779+ async fn an_archived_year_refuses_the_announcement_and_the_withdrawal() {
780+ let (db, _leases) = crate::database::init_test_db().await;
781+ let manager = staff(&db, "audience-mudur-4", Role::Manager).await;
782+ let algebra = crate::db::class_member::tests::a_course("algebra", &db).await;
783+ let year = crate::db::academic_year::a_test_year(&db).await;
784+ let owner = instance_in(&db, manager.get_id(), "9-A", &algebra, Some(&year)).await;
785+ let announced = instance_in(&db, manager.get_id(), "9-B", &algebra, Some(&year)).await;
786+ let later = instance_in(&db, manager.get_id(), "9-C", &algebra, Some(&year)).await;
787+ let exam = exam_on(&db, &owner).await;
788+ add_audience(&db, &manager, exam.get_id(), announced.get_id())
789+ .await
790+ .unwrap();
791+
792+ crate::service::academic_year::archive(&db, &year)
793+ .await
794+ .unwrap();
795+
796+ for (result, route) in [
797+ (
798+ add_audience(&db, &manager, exam.get_id(), later.get_id()).await,
799+ "the announcement",
800+ ),
801+ (
802+ remove_audience(&db, &manager, exam.get_id(), announced.get_id()).await,
803+ "the withdrawal",
804+ ),
805+ ] {
806+ assert!(
807+ matches!(
808+ result,
809+ Err(AppError::ConflictCoded { code, .. }) if code == "academic_year_archived"
810+ ),
811+ "{route} into an archived year must be the coded 409: {result:?}"
812+ );
813+ }
814+ assert_eq!(
815+ exam_audience::list_for_exam(&db, exam.get_id())
816+ .await
817+ .unwrap()
818+ .len(),
819+ 2,
820+ "neither refusal wrote"
821+ );
822+ }
823+}
src/service/exam_attempt.rsmodified+3 -10
@@ -73,21 +73,14 @@ pub async fn ensure_student_now(user: &UserId, db: &Database) -> Result<(), AppE
73 ensure_student(&user)73 ensure_student(&user)
74 }74 }
75 75
76-/// A 403 unless `user` is enrolled in the instance the exam belongs to — the76+/// A 403 unless `user` is enrolled in an instance the exam is addressed to —
77+/// its owner, or any sibling it was announced to (an ortak sınav, D2). The
77 /// same wall the exam room checks at its door, re-applied to the sitting's78 /// same wall the exam room checks at its door, re-applied to the sitting's
78 /// content paths so an unenrollment mid-exam cuts them too. Finishing stays79 /// content paths so an unenrollment mid-exam cuts them too. Finishing stays
79 /// exempt: like the rejoin lock, submitting what's already saved writes80 /// exempt: like the rejoin lock, submitting what's already saved writes
80 /// nothing new.81 /// nothing new.
81 pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {82 pub async fn ensure_enrolled(exam: &Exam, user: &UserId, db: &Database) -> Result<(), AppError> {
82- if crate::db::enrollment::read_for_user(db, exam.get_class_course(), user)83+ crate::service::exam::ensure_enrolled_anywhere(db, exam, user).await
83- .await?
84- .is_none()
85- {
86- return Err(AppError::Forbidden(
87- "you are not enrolled in this exam's course",
88- ));
89- }
90- Ok(())
91 }84 }
92 85
93 /// A 409 when the student has walked out of the exam room and the exam's86 /// A 409 when the student has walked out of the exam room and the exam's
src/service/exam_result.rsmodified+4 -5
@@ -91,11 +91,10 @@ pub async fn grade(
91 }));91 }));
92 }92 }
93 93
94- // ... and be enrolled in the instance the exam belongs to.94+ // ... and be enrolled in an instance the exam is addressed to — the
95- if crate::service::enrollment::read_for_user(db, exam.get_class_course(), target)95+ // owner's or an announced sibling's (an ortak sınav, D2): an addressed
96- .await?96+ // section's student is graded exactly like the owner's.
97- .is_none()97+ if !crate::service::exam::enrolled_anywhere(db, &exam, target).await? {
98- {
99 return Err(AppError::Validation(ValidationError::Invalid {98 return Err(AppError::Validation(ValidationError::Invalid {
100 field: "user_id",99 field: "user_id",
101 reason: "target user is not enrolled in this course",100 reason: "target user is not enrolled in this course",
src/web/exams/attempts.rsmodified+12 -10
@@ -321,15 +321,15 @@ pub(crate) struct ExamLiveResponse {
321 321
322 /// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.322 /// Build the monitor snapshot: roster ⋈ attempts ⋈ marks at one instant.
323 /// Students unenrolled mid-exam drop off the roster view (their attempt and323 /// Students unenrolled mid-exam drop off the roster view (their attempt and
324-/// mark rows survive, exactly like the marks report).324+/// mark rows survive, exactly like the marks report). The roster is the
325+/// exam's whole audience (D2), so an announced-to section's sitters appear
326+/// here exactly like the owner's — deduped by student, one row per person.
325 pub(crate) async fn live_snapshot(327 pub(crate) async fn live_snapshot(
326 exam: &Exam,328 exam: &Exam,
327 db: &Database,329 db: &Database,
328 ) -> Result<ExamLiveResponse, AppError> {330 ) -> Result<ExamLiveResponse, AppError> {
329 let now = Timestamp::now();331 let now = Timestamp::now();
330- let (roster, _) =332+ let roster = crate::db::enrollment::list_for_exam_audience(db, exam.get_id()).await?;
331- crate::service::enrollment::list_for_class_course(db, exam.get_class_course(), None, 0)
332- .await?;
333 // Per student: their latest sitting (the one the monitor shows) plus how333 // Per student: their latest sitting (the one the monitor shows) plus how
334 // many they've used.334 // many they've used.
335 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();335 let mut attempts: HashMap<String, ExamAttempt> = HashMap::new();
@@ -439,8 +439,10 @@ pub(crate) async fn live_snapshot(
439 /// A one-shot live snapshot of the exam: who's in, who's still writing (and439 /// A one-shot live snapshot of the exam: who's in, who's still writing (and
440 /// on which sitting), who walked out of the room (`left_at`), who never440 /// on which sitting), who walked out of the room (`left_at`), who never
441 /// showed at all (`absent`, once the window is over), time each student has441 /// showed at all (`absent`, once the window is over), time each student has
442-/// left, and marks as they land. Requires teacher+ and management rights442+/// left, and marks as they land — the roster of every instance the exam is
443-/// over the exam's instance. Poll it to keep a monitor up to date.443+/// addressed to, so an announced-to section's sitters are here too. Requires
444+/// teacher+ and management rights over the exam's instance. Poll it to keep a
445+/// monitor up to date.
444 #[utoipa::path(446 #[utoipa::path(
445 get,447 get,
446 path = "/{id}/live",448 path = "/{id}/live",
@@ -450,7 +452,7 @@ pub(crate) async fn live_snapshot(
450 responses(452 responses(
451 (status = 200, description = "Live snapshot", body = ExamLiveResponse),453 (status = 200, description = "Live snapshot", body = ExamLiveResponse),
452 (status = 401, description = "Not authenticated", body = ErrorResponse),454 (status = 401, description = "Not authenticated", body = ErrorResponse),
453- (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),455+ (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
454 (status = 404, description = "Exam not found", body = ErrorResponse),456 (status = 404, description = "Exam not found", body = ErrorResponse),
455 ),457 ),
456 )]458 )]
@@ -462,10 +464,10 @@ pub(crate) async fn exam_live(
462 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))464 let exam = crate::service::exam::read(&st.db, &ExamId::from_key(&id))
463 .await?465 .await?
464 .ok_or(AppError::NotFound)?;466 .ok_or(AppError::NotFound)?;
465- let instance = exam_attempt::class_course_of(&exam, &st.db).await?;467+ let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
466- if !can_manage_instance(&st.db, instance.get_id(), &user).await? {468+ if !manages {
467 return Err(AppError::Forbidden(469 return Err(AppError::Forbidden(
468- "only this instance's teachers, its class's homeroom teacher, or a manager/admin can monitor this exam",470+ "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can monitor this exam",
469 ));471 ));
470 }472 }
471 Ok(Json(live_snapshot(&exam, &st.db).await?))473 Ok(Json(live_snapshot(&exam, &st.db).await?))
src/web/exams/audience.rsadded+207 -0
@@ -0,0 +1,207 @@
1+use super::*;
2+
3+use crate::domain::class_course::ClassCourseId;
4+
5+// ---- audience: the ortak sınav ---------------------------------------------
6+// An exam is owned by the instance it was created on, but it can be announced
7+// to other instances of the same course in the same academic year: one
8+// sitting, one mark, standing in every addressed instance's marks and karne.
9+// The gate is the owner instance's (a manager+, its assigned teachers, its
10+// şube's homeroom teacher) — the instance that runs the exam decides who else
11+// sits it.
12+
13+/// One instance an exam is announced to.
14+#[derive(Serialize, ToSchema)]
15+pub(crate) struct ExamAudienceResponse {
16+ /// The class×course instance the exam is announced to.
17+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
18+ instance: String,
19+ /// The şube (class section) that instance belongs to.
20+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
21+ class: String,
22+ /// The catalog course that instance teaches — the exam's own course, by
23+ /// the announcement's rule.
24+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
25+ course: String,
26+}
27+
28+impl ExamAudienceResponse {
29+ fn new(audience: &crate::db::exam_audience::Audience) -> Self {
30+ Self {
31+ instance: audience.get_instance().key().to_string(),
32+ class: audience.get_class().key().to_string(),
33+ course: audience.get_course().key().to_string(),
34+ }
35+ }
36+
37+ fn list(audience: &[crate::db::exam_audience::Audience]) -> Vec<Self> {
38+ audience.iter().map(Self::new).collect()
39+ }
40+}
41+
42+/// `(may_view, may_manage)` over the instances an exam is addressed to — the
43+/// pair of questions every exam-level gate asks (D2).
44+///
45+/// A caller *sees* the exam when any addressed instance admits them as a
46+/// viewer (its enrolled students, its teachers, its şube's homeroom teacher,
47+/// manager+), and *acts* on it — grading, the results readers, the live
48+/// monitor — when they manage one of them. Both are exactly the predicates
49+/// that instance's own routes apply
50+/// ([`super::instances::list_instance_exams`], `POST /instances/{id}/exams`),
51+/// so an announced-to section's teacher runs the exam there like the owner's.
52+/// One walk: an audience is one or two rows.
53+pub(crate) async fn audience_rights(
54+ db: &Database,
55+ exam: &Exam,
56+ user: &User,
57+) -> Result<(bool, bool), AppError> {
58+ let mut may_view = false;
59+ let mut may_manage = false;
60+ for row in crate::service::exam::list_audience(db, exam.get_id()).await? {
61+ if !may_view && can_view_instance(db, row.get_instance(), user).await? {
62+ may_view = true;
63+ }
64+ if !may_manage && can_manage_instance(db, row.get_instance(), user).await? {
65+ may_manage = true;
66+ }
67+ if may_view && may_manage {
68+ break;
69+ }
70+ }
71+ Ok((may_view, may_manage))
72+}
73+
74+#[derive(Deserialize, ToSchema)]
75+pub(crate) struct AddAudience {
76+ /// The class×course instance to announce the exam to (`GET /instances/me`,
77+ /// `GET /classes/{id}/instances`). It must teach the exam's own catalog
78+ /// course, sit under the same academic year, and be a *different*
79+ /// instance — the owner is refused with a `400`.
80+ #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
81+ instance: String,
82+}
83+
84+/// Announce an exam to another instance — the **ortak sınav** write: one exam
85+/// addressed to a sibling şube, so it and its marks stand in that section's
86+/// exam list, marks report and karne. Requires teacher+ and management rights
87+/// over the exam's **owner** instance (an assigned teacher, its şube's
88+/// homeroom teacher, or a manager/admin) — the target instance's teachers
89+/// have no say.
90+/// The target must teach the exam's own catalog course and sit under the same
91+/// academic year (`400` otherwise), the owner itself is refused (`400`), and
92+/// an archived target year is a `409`. Announcing a pair that already stands
93+/// is a no-op answering `200` with the audience unchanged.
94+#[utoipa::path(
95+ post,
96+ path = "/{id}/audience",
97+ tag = "exams",
98+ security(("session_cookie" = [])),
99+ params(("id" = String, Path, description = "Exam id")),
100+ request_body = AddAudience,
101+ responses(
102+ (status = 200, description = "The exam's audience after the announcement", body = [ExamAudienceResponse]),
103+ (status = 400, description = "The instance is the exam's own, teaches another course, or belongs to another academic year", body = ErrorResponse),
104+ (status = 401, description = "Not authenticated", body = ErrorResponse),
105+ (status = 403, description = "Not this exam's owner instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
106+ (status = 404, description = "The exam or the instance does not exist", body = ErrorResponse),
107+ (status = 409, description = "The instance's academic year is archived (read-only)", body = ErrorResponse),
108+ (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
109+ ),
110+)]
111+pub(crate) async fn add_audience(
112+ State(st): State<AppState>,
113+ RequireTeacher(user): RequireTeacher,
114+ Path(id): Path<String>,
115+ Json(req): Json<AddAudience>,
116+) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
117+ let audience = service::exam::add_audience(
118+ &st.db,
119+ &user,
120+ &ExamId::from_key(&id),
121+ &ClassCourseId::from_key(&req.instance),
122+ )
123+ .await?;
124+ Ok(Json(ExamAudienceResponse::list(&audience)))
125+}
126+
127+/// List the instances an exam is announced to, its owner included — the read
128+/// behind the announce routes' answer, useful on its own to a client that
129+/// wants to show where else an exam is sat. Visible to the exam's own
130+/// audience: an addressed instance's enrolled students, its teachers (or its
131+/// şube's homeroom teacher), and managers/admins — except drafts, which stay
132+/// a `404` to everyone but an addressed instance's managers.
133+#[utoipa::path(
134+ get,
135+ path = "/{id}/audience",
136+ tag = "exams",
137+ security(("session_cookie" = [])),
138+ params(("id" = String, Path, description = "Exam id")),
139+ responses(
140+ (status = 200, description = "The instances the exam is announced to (the owner first, then in announcement order)", body = [ExamAudienceResponse]),
141+ (status = 401, description = "Not authenticated", body = ErrorResponse),
142+ (status = 403, description = "Not enrolled and not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
143+ (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
144+ ),
145+)]
146+pub(crate) async fn list_audience(
147+ State(st): State<AppState>,
148+ CurrentUser(user): CurrentUser,
149+ Path(id): Path<String>,
150+) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
151+ let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
152+ .await?
153+ .ok_or(AppError::NotFound)?;
154+ let (may_view, may_manage) = audience_rights(&st.db, &exam, &user).await?;
155+ if !may_view {
156+ return Err(AppError::Forbidden(
157+ "only an addressed instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view this exam",
158+ ));
159+ }
160+ // A draft doesn't exist for anyone but an addressed instance's managers —
161+ // 404, not 403, so its existence never leaks to the students it's hidden
162+ // from.
163+ if exam.is_draft() && !may_manage {
164+ return Err(AppError::NotFound);
165+ }
166+ let audience = service::exam::list_audience(&st.db, exam.get_id()).await?;
167+ Ok(Json(ExamAudienceResponse::list(&audience)))
168+}
169+
170+/// Withdraw an exam from one instance's audience. Requires teacher+ and
171+/// management rights over the exam's **owner** instance, like the announce
172+/// itself. The owner's own pair is not withdrawable (`400`) — that is the
173+/// instance the exam belongs to, and deleting the exam is what ends it; an
174+/// archived year refuses the withdrawal with the same `409` its other writes
175+/// answer. A pair that holds no audience row is a `404`.
176+#[utoipa::path(
177+ delete,
178+ path = "/{id}/audience/{instance}",
179+ tag = "exams",
180+ security(("session_cookie" = [])),
181+ params(
182+ ("id" = String, Path, description = "Exam id"),
183+ ("instance" = String, Path, description = "Instance id"),
184+ ),
185+ responses(
186+ (status = 200, description = "The exam's audience after the withdrawal", body = [ExamAudienceResponse]),
187+ (status = 400, description = "The pair names the exam's owner instance", body = ErrorResponse),
188+ (status = 401, description = "Not authenticated", body = ErrorResponse),
189+ (status = 403, description = "Not this exam's owner instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),
190+ (status = 404, description = "The exam does not exist, or the pair holds no audience row", body = ErrorResponse),
191+ (status = 409, description = "The exam's academic year is archived (read-only)", body = ErrorResponse),
192+ ),
193+)]
194+pub(crate) async fn remove_audience(
195+ State(st): State<AppState>,
196+ RequireTeacher(user): RequireTeacher,
197+ Path((id, instance)): Path<(String, String)>,
198+) -> Result<Json<Vec<ExamAudienceResponse>>, AppError> {
199+ let audience = service::exam::remove_audience(
200+ &st.db,
201+ &user,
202+ &ExamId::from_key(&id),
203+ &ClassCourseId::from_key(&instance),
204+ )
205+ .await?;
206+ Ok(Json(ExamAudienceResponse::list(&audience)))
207+}
src/web/exams/mod.rsmodified+48 -38
@@ -40,11 +40,13 @@ use super::{
40 };40 };
41 41
42 pub(crate) mod attempts;42 pub(crate) mod attempts;
43+pub(crate) mod audience;
43 pub(crate) mod images;44 pub(crate) mod images;
44 pub(crate) mod questions;45 pub(crate) mod questions;
45 pub(crate) mod review;46 pub(crate) mod review;
46 47
47 pub(crate) use attempts::*;48 pub(crate) use attempts::*;
49+pub(crate) use audience::*;
48 pub(crate) use images::*;50 pub(crate) use images::*;
49 pub(crate) use questions::*;51 pub(crate) use questions::*;
50 pub(crate) use review::*;52 pub(crate) use review::*;
@@ -74,6 +76,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
74 )76 )
75 .routes(routes!(list_exams))77 .routes(routes!(list_exams))
76 .routes(routes!(get_exam, update_exam, delete_exam))78 .routes(routes!(get_exam, update_exam, delete_exam))
79+ .routes(routes!(add_audience, list_audience, remove_audience))
77 .routes(routes!(grade, list_results))80 .routes(routes!(grade, list_results))
78 .routes(routes!(my_result))81 .routes(routes!(my_result))
79 .routes(routes!(remove_result))82 .routes(routes!(remove_result))
@@ -286,17 +289,20 @@ async fn list_exams(
286 Ok(Json(Page::new(items, total, limit, offset)))289 Ok(Json(Page::new(items, total, limit, offset)))
287 }290 }
288 291
289-/// Fetch a single exam by id. Visible to its instance's enrolled students, its292+/// Fetch a single exam by id. Visible to **any instance the exam is addressed
290-/// teachers (or its class's homeroom teacher), and managers/admins — except293+/// to** — its owner's enrolled students and teachers, and, for an announced
291-/// drafts, which only the instance's managers see (everyone else gets a `404`,294+/// exam (ortak sınav), each addressed section's alike — plus managers/admins;
292-/// as if the exam doesn't exist yet — because it doesn't, officially).295+/// drafts only show to the managers of an addressed instance (everyone else
296+/// gets a `404`, as if the exam doesn't exist yet — because it doesn't,
297+/// officially).
293 ///298 ///
294 /// Gate order is deliberate and must stay as written: a caller with no view of299 /// Gate order is deliberate and must stay as written: a caller with no view of
295-/// the instance is refused by the *view* gate (`403`) before the draft gate is300+/// any addressed instance is refused by the *view* gate (`403`) before the
296-/// reached, so the `404` rule covers only callers who can see the instance — a301+/// draft gate is reached, so the `404` rule covers only callers who can see an
297-/// teacher since removed from it, for instance, gets the `403` unless they are302+/// instance the exam reaches — a teacher since removed from it, for instance,
298-/// enrolled. Moving the draft check above the view check to "make the 404303+/// gets the `403` unless they are enrolled. Moving the draft check above the
299-/// universal" would hand every unenrolled caller a probe for which exams exist.304+/// view check to "make the 404 universal" would hand every unenrolled caller a
305+/// probe for which exams exist.
300 #[utoipa::path(306 #[utoipa::path(
301 get,307 get,
302 path = "/{id}",308 path = "/{id}",
@@ -306,7 +312,7 @@ async fn list_exams(
306 responses(312 responses(
307 (status = 200, description = "The exam", body = ExamResponse),313 (status = 200, description = "The exam", body = ExamResponse),
308 (status = 401, description = "Not authenticated", body = ErrorResponse),314 (status = 401, description = "Not authenticated", body = ErrorResponse),
309- (status = 403, description = "Not enrolled, and not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),315+ (status = 403, description = "Not enrolled and not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
310 (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),316 (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
311 ),317 ),
312 )]318 )]
@@ -318,15 +324,16 @@ async fn get_exam(
318 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))324 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
319 .await?325 .await?
320 .ok_or(AppError::NotFound)?;326 .ok_or(AppError::NotFound)?;
321- let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;327+ let (may_view, may_manage) = audience_rights(&st.db, &exam, &user).await?;
322- if !can_view_instance(&st.db, instance.get_id(), &user).await? {328+ if !may_view {
323 return Err(AppError::Forbidden(329 return Err(AppError::Forbidden(
324- "only this instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view this exam",330+ "only an addressed instance's enrolled students, its teachers, its class's homeroom teacher, or a manager/admin can view this exam",
325 ));331 ));
326 }332 }
327- // A draft doesn't exist for anyone but its instance's managers — 404, not333+ // A draft doesn't exist for anyone but an addressed instance's managers —
328- // 403, so its existence never leaks to the students it's hidden from.334+ // 404, not 403, so its existence never leaks to the students it's hidden
329- if exam.is_draft() && !can_manage_instance(&st.db, instance.get_id(), &user).await? {335+ // from.
336+ if exam.is_draft() && !may_manage {
330 return Err(AppError::NotFound);337 return Err(AppError::NotFound);
331 }338 }
332 Ok(Json(ExamResponse::new(&exam)))339 Ok(Json(ExamResponse::new(&exam)))
@@ -494,8 +501,10 @@ async fn delete_exam(
494 // ---- results ------------------------------------------------------------501 // ---- results ------------------------------------------------------------
495 502
496 /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and503 /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and
497-/// management rights over the exam's instance; the target must be a student504+/// management rights over **an instance the exam is addressed to** (the
498-/// and enrolled. Only students carry marks; students never grade — and nobody505+/// announced-to section's teacher grades its own students on an ortak sınav);
506+/// the target must be a student enrolled in one of them. Only students carry
507+/// marks; students never grade — and nobody
499 /// grades themselves. A draft can't be graded (`409`) — a mark would point at508 /// grades themselves. A draft can't be graded (`409`) — a mark would point at
500 /// an exam its student can't see.509 /// an exam its student can't see.
501 #[utoipa::path(510 #[utoipa::path(
@@ -509,7 +518,7 @@ async fn delete_exam(
509 (status = 200, description = "Result recorded", body = ExamResultResponse),518 (status = 200, description = "Result recorded", body = ExamResultResponse),
510 (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),519 (status = 400, description = "Invalid mark, unknown user, user not a student, or not enrolled", body = ErrorResponse),
511 (status = 401, description = "Not authenticated", body = ErrorResponse),520 (status = 401, description = "Not authenticated", body = ErrorResponse),
512- (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin, or attempted to grade yourself", body = ErrorResponse),521+ (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin, or attempted to grade yourself", body = ErrorResponse),
513 (status = 404, description = "Exam not found", body = ErrorResponse),522 (status = 404, description = "Exam not found", body = ErrorResponse),
514 (status = 409, description = "The exam is a draft, its kind has been removed from the school's settings, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),523 (status = 409, description = "The exam is a draft, its kind has been removed from the school's settings, or this instance's academic year is archived — past years are read-only", body = ErrorResponse),
515 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),524 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
@@ -527,10 +536,10 @@ async fn grade(
527 let exam = service::exam::read(&st.db, &exam_id)536 let exam = service::exam::read(&st.db, &exam_id)
528 .await?537 .await?
529 .ok_or(AppError::NotFound)?;538 .ok_or(AppError::NotFound)?;
530- let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;539+ let (_, manages) = audience_rights(&st.db, &exam, &teacher).await?;
531- if !can_manage_instance(&st.db, instance.get_id(), &teacher).await? {540+ if !manages {
532 return Err(AppError::Forbidden(541 return Err(AppError::Forbidden(
533- "only this instance's teachers, its class's homeroom teacher, or a manager/admin can grade this exam",542+ "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can grade this exam",
534 ));543 ));
535 }544 }
536 let target = UserId::from_key(&req.user_id);545 let target = UserId::from_key(&req.user_id);
@@ -550,8 +559,9 @@ async fn grade(
550 }559 }
551 560
552 /// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all561 /// List an exam's results, paged via `?limit=&offset=` (omit `limit` for all
553-/// of them). Requires teacher+ and management rights over the exam's instance562+/// of them). Requires teacher+ and management rights over an instance the
554-/// — students read only their own via `GET /exams/{id}/result`. Returns a563+/// exam is addressed to — students read only their own via
564+/// `GET /exams/{id}/result`. Returns a
555 /// `{items, total, limit, offset}` envelope.565 /// `{items, total, limit, offset}` envelope.
556 #[utoipa::path(566 #[utoipa::path(
557 get,567 get,
@@ -563,7 +573,7 @@ async fn grade(
563 (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),573 (status = 200, description = "A page of results (all of them when unpaged)", body = Page<ExamResultResponse>),
564 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),574 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
565 (status = 401, description = "Not authenticated", body = ErrorResponse),575 (status = 401, description = "Not authenticated", body = ErrorResponse),
566- (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),576+ (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
567 (status = 404, description = "Exam not found", body = ErrorResponse),577 (status = 404, description = "Exam not found", body = ErrorResponse),
568 ),578 ),
569 )]579 )]
@@ -578,10 +588,10 @@ async fn list_results(
578 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))588 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
579 .await?589 .await?
580 .ok_or(AppError::NotFound)?;590 .ok_or(AppError::NotFound)?;
581- let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;591+ let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
582- if !can_manage_instance(&st.db, instance.get_id(), &user).await? {592+ if !manages {
583 return Err(AppError::Forbidden(593 return Err(AppError::Forbidden(
584- "only this instance's teachers, its class's homeroom teacher, or a manager/admin can list results",594+ "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can list results",
585 ));595 ));
586 }596 }
587 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;597 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;
@@ -630,7 +640,7 @@ async fn my_result(
630 }640 }
631 641
632 /// Remove a student's result from an exam. Requires teacher+ and management642 /// Remove a student's result from an exam. Requires teacher+ and management
633-/// rights over the exam's instance.643+/// rights over an instance the exam is addressed to.
634 #[utoipa::path(644 #[utoipa::path(
635 delete,645 delete,
636 path = "/{id}/results/{user}",646 path = "/{id}/results/{user}",
@@ -643,7 +653,7 @@ async fn my_result(
643 responses(653 responses(
644 (status = 204, description = "Removed"),654 (status = 204, description = "Removed"),
645 (status = 401, description = "Not authenticated", body = ErrorResponse),655 (status = 401, description = "Not authenticated", body = ErrorResponse),
646- (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),656+ (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
647 (status = 404, description = "Not found", body = ErrorResponse),657 (status = 404, description = "Not found", body = ErrorResponse),
648 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),658 (status = 409, description = "This instance's academic year is archived — past years are read-only", body = ErrorResponse),
649 ),659 ),
@@ -656,10 +666,10 @@ async fn remove_result(
656 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))666 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
657 .await?667 .await?
658 .ok_or(AppError::NotFound)?;668 .ok_or(AppError::NotFound)?;
659- let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;669+ let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
660- if !can_manage_instance(&st.db, instance.get_id(), &user).await? {670+ if !manages {
661 return Err(AppError::Forbidden(671 return Err(AppError::Forbidden(
662- "only this instance's teachers, its class's homeroom teacher, or a manager/admin can remove results",672+ "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can remove results",
663 ));673 ));
664 }674 }
665 // The archived-term gate and the refunding delete are675 // The archived-term gate and the refunding delete are
@@ -672,7 +682,7 @@ async fn remove_result(
672 }682 }
673 683
674 /// Summary statistics for an exam's graded results. Requires teacher+ and684 /// Summary statistics for an exam's graded results. Requires teacher+ and
675-/// management rights over the exam's instance.685+/// management rights over an instance the exam is addressed to.
676 #[utoipa::path(686 #[utoipa::path(
677 get,687 get,
678 path = "/{id}/statistics",688 path = "/{id}/statistics",
@@ -682,7 +692,7 @@ async fn remove_result(
682 responses(692 responses(
683 (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),693 (status = 200, description = "The exam's mark statistics", body = ExamStatisticsResponse),
684 (status = 401, description = "Not authenticated", body = ErrorResponse),694 (status = 401, description = "Not authenticated", body = ErrorResponse),
685- (status = 403, description = "Not this instance's teacher, its şube's homeroom teacher, or a manager/admin", body = ErrorResponse),695+ (status = 403, description = "Not a teacher of any instance the exam is addressed to, nor its şube's homeroom teacher, nor a manager/admin", body = ErrorResponse),
686 (status = 404, description = "Exam not found", body = ErrorResponse),696 (status = 404, description = "Exam not found", body = ErrorResponse),
687 ),697 ),
688 )]698 )]
@@ -695,10 +705,10 @@ async fn exam_statistics(
695 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))705 let exam = service::exam::read(&st.db, &ExamId::from_key(&id))
696 .await?706 .await?
697 .ok_or(AppError::NotFound)?;707 .ok_or(AppError::NotFound)?;
698- let instance = service::exam_attempt::class_course_of(&exam, &st.db).await?;708+ let (_, manages) = audience_rights(&st.db, &exam, &user).await?;
699- if !can_manage_instance(&st.db, instance.get_id(), &user).await? {709+ if !manages {
700 return Err(AppError::Forbidden(710 return Err(AppError::Forbidden(
701- "only this instance's teachers, its class's homeroom teacher, or a manager/admin can view statistics",711+ "only a teacher of an instance the exam is addressed to, that instance's class's homeroom teacher, or a manager/admin can view statistics",
702 ));712 ));
703 }713 }
704 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;714 let results = service::exam_result::list_for_exam(&st.db, exam.get_id()).await?;
tests/regress_course_delete.rsmodified+114 -2
@@ -24,8 +24,8 @@ mod common;
24 24
25 use axum::http::StatusCode;25 use axum::http::StatusCode;
26 use common::{26 use common::{
27- Res, app_and_db, create_exam, create_exam_with, create_subject, enroll, id_of, login, login_as,27+ Res, app_and_db, blob_dir, create_exam, create_exam_with, create_subject, enroll, id_of, login,
28- me_id, send, taught, unenroll,28+ login_as, me_id, send, taught, unenroll, upload_file_at,
29 };29 };
30 use hezarfen_backend::db::course;30 use hezarfen_backend::db::course;
31 use hezarfen_backend::db::exam_attempt::list_for_exam;31 use hezarfen_backend::db::exam_attempt::list_for_exam;
@@ -280,6 +280,118 @@ async fn the_sweep_that_takes_an_instances_exams_gives_its_term_the_count_back()
280 );280 );
281 }281 }
282 282
283+/// The third blob collection the instance sweep hands back is the students'
284+/// answer images — the exam questions' illustrations and the homework
285+/// submissions were already pinned, the started sitting's drawing was not.
286+/// The row is written only through the sitting wall (an in-progress attempt
287+/// plus a live enrollment), so the fixture has to actually sit the exam: the
288+/// upload is the student's own route and its bytes land on disk under the
289+/// row's file name.
290+///
291+/// The detach is the shipped sweep that takes the row, and the route is what
292+/// unlinks the bytes — a route that drops that list strands the drawing on
293+/// disk with nothing left pointing at it, which is the leak this pins closed.
294+#[tokio::test]
295+async fn the_detach_unlinks_a_swept_instances_answer_drawing_bytes() {
296+ let (app, db) = app_and_db().await;
297+ let mudur = login_as(&app, &db, "cizim_ders_sil", "manager").await;
298+ let student = login_as(&app, &db, "cizim_ogrenci", "student").await;
299+ let student_id = me_id(&app, &student).await;
300+
301+ let t = taught(&app, &mudur, "Resim").await;
302+ enroll(&app, &mudur, &t.instance, &student_id).await;
303+ // `open` mode, as next door: an unscheduled exam answers the start with a
304+ // 409 before it ever writes, and there would be no sitting to draw under.
305+ let res = create_exam_with(
306+ &app,
307+ &mudur,
308+ &t.instance,
309+ json!({ "title": "Vize", "kind": "yazili", "mode": "open", "term": t.term.clone() }),
310+ )
311+ .await;
312+ assert_eq!(res.status, StatusCode::CREATED, "create exam: {}", res.body);
313+ let exam = id_of(&res.body);
314+ let subject = create_subject(&app, &mudur, &t.course, "Natürmort").await;
315+ let res = send(
316+ &app,
317+ "POST",
318+ &format!("/exams/{exam}/questions"),
319+ Some(&mudur),
320+ Some(json!({ "subject_id": subject, "text": "elma çiz", "kind": "text", "points": 5 })),
321+ )
322+ .await;
323+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
324+ let question = id_of(&res.body);
325+
326+ // The drawing rides a started sitting: the upload 404s without an attempt.
327+ let sat = send(
328+ &app,
329+ "POST",
330+ &format!("/exams/{exam}/attempt"),
331+ Some(&student),
332+ None,
333+ )
334+ .await;
335+ assert_eq!(sat.status, StatusCode::CREATED, "sit: {}", sat.body);
336+ let drawn = upload_file_at(
337+ &app,
338+ &student,
339+ &format!("/exams/{exam}/attempt/answers/{question}/image"),
340+ "elma.png",
341+ "image/png",
342+ b"png-drawing",
343+ )
344+ .await;
345+ assert_eq!(drawn.status, StatusCode::CREATED, "draw: {}", drawn.body);
346+
347+ // The blob name straight out of the store: the bytes on disk are keyed by
348+ // the row's own file name.
349+ let file: String = sqlx::query_scalar("SELECT file FROM answer_image WHERE exam = $1")
350+ .bind(uuid::Uuid::parse_str(&exam).expect("a uuid exam id"))
351+ .fetch_one(&db)
352+ .await
353+ .expect("the answer-image row");
354+ assert!(
355+ blob_dir().join(&file).exists(),
356+ "the fixture's drawing blob {file} never landed on disk"
357+ );
358+
359+ let detached = detach_instance(&app, &mudur, &t).await;
360+ assert_eq!(
361+ detached.status,
362+ StatusCode::NO_CONTENT,
363+ "the instance detaches: {}",
364+ detached.body
365+ );
366+
367+ // Stored state is the verdict: the drawing's row, its sitting and its exam
368+ // are gone, and so are the bytes the row named.
369+ let exam_id = uuid::Uuid::parse_str(&exam).expect("a uuid exam id");
370+ let drawings: i64 = sqlx::query_scalar("SELECT count(*) FROM answer_image WHERE exam = $1")
371+ .bind(exam_id)
372+ .fetch_one(&db)
373+ .await
374+ .expect("the answer-image count");
375+ assert_eq!(drawings, 0, "the sweep must take the drawing's row");
376+ let sittings: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_attempt WHERE exam = $1")
377+ .bind(exam_id)
378+ .fetch_one(&db)
379+ .await
380+ .expect("the attempt count");
381+ assert_eq!(sittings, 0, "the swept exam must take its sitting rows");
382+ let exams: i64 = sqlx::query_scalar("SELECT count(*) FROM exam WHERE id = $1")
383+ .bind(exam_id)
384+ .fetch_one(&db)
385+ .await
386+ .expect("the exam count");
387+ assert_eq!(exams, 0, "the sweep must take the exam row itself");
388+ assert!(
389+ !blob_dir().join(&file).exists(),
390+ "the swept drawing's blob {file} lingers on disk with nothing pointing \
391+ at it"
392+ );
393+}
394+
283 /// The sitting's own write is held open, every gate already cleared, and the395 /// The sitting's own write is held open, every gate already cleared, and the
284 /// sweep that takes its exam fires into that window: an `AFTER INSERT` trigger396 /// sweep that takes its exam fires into that window: an `AFTER INSERT` trigger
285 /// on `exam_attempt` sleeps *inside* the create's own transaction, after the397 /// on `exam_attempt` sleeps *inside* the create's own transaction, after the
tests/regress_exam_delete.rsmodified+622 -7
@@ -19,7 +19,9 @@ mod common;
19 19
20 use axum::http::StatusCode;20 use axum::http::StatusCode;
21 use common::{21 use common::{
22- app_and_db, create_exam_with, enroll, id_of, login_as, me_id, send, taught, taught_under,22+ add_member, app_and_db, attach_instance, create_class, create_course, create_exam,
23+ create_exam_with, create_term, enroll, ensure_year, id_of, items, login_as, me_id, send,
24+ taught, taught_under, total,
23 };25 };
24 use hezarfen_backend::db::exam_attempt::list_for_exam;26 use hezarfen_backend::db::exam_attempt::list_for_exam;
25 use hezarfen_backend::domain::exam::ExamId;27 use hezarfen_backend::domain::exam::ExamId;
@@ -139,10 +141,10 @@ async fn an_attempt_started_inside_a_delete_never_outlives_the_exam() {
139 }141 }
140 142
141 /// An archived academic year freezes the exams hanging off its şubeler'143 /// An archived academic year freezes the exams hanging off its şubeler'
142-/// instances: all nineteen write routes under `/exams/{id}` answer144+/// instances: every write route under `/exams/{id}` (the lists below) answers
143 /// `409 academic_year_archived` — authoring, grading, the images on both sides,145 /// `409 academic_year_archived` — authoring, grading, the images on both sides,
144-/// and the sitting itself — while every read stays open. Past years are a146+/// the ortak-sınav audience pair, and the sitting itself — while every read
145-/// read-only archive, not a hidden one.147+/// stays open. Past years are a read-only archive, not a hidden one.
146 ///148 ///
147 /// The sitting is deliberately *live* when the archive lands: a student mid-exam149 /// The sitting is deliberately *live* when the archive lands: a student mid-exam
148 /// is the case where a freeze can do real damage, and every one of their write150 /// is the case where a freeze can do real damage, and every one of their write
@@ -183,6 +185,24 @@ async fn an_archived_years_exams_take_no_writes_but_still_read() {
183 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);185 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
184 let exam = id_of(&res.body);186 let exam = id_of(&res.body);
185 187
188+ let sibling_class =
189+ create_class(&app, &manager, "Tarih 2", json!({ "year": t.year.clone() })).await;
190+ let sibling = attach_instance(&app, &manager, &sibling_class, &t.course).await;
191+ let announced = send(
192+ &app,
193+ "POST",
194+ &format!("/exams/{exam}/audience"),
195+ Some(&manager),
196+ Some(json!({ "instance": sibling })),
197+ )
198+ .await;
199+ assert_eq!(
200+ announced.status,
201+ StatusCode::OK,
202+ "the announcement predating the archive: {}",
203+ announced.body
204+ );
205+
186 // One choice question — it supplies the qid every question route needs and206 // One choice question — it supplies the qid every question route needs and
187 // the choice id the option-picture routes need.207 // the choice id the option-picture routes need.
188 let res = send(208 let res = send(
@@ -226,9 +246,11 @@ async fn an_archived_years_exams_take_no_writes_but_still_read() {
226 "the fixture's year is archived"246 "the fixture's year is archived"
227 );247 );
228 248
229- // The thirteen JSON write routes: exam, results, and the question authoring249+ // The JSON write routes: exam, results, the question authoring set, and
230- // set. `from-bank` takes an id that need not exist — the freeze is judged250+ // the ortak-sınav audience pair (its announcement is re-sent — a no-op
231- // before the bank lookup, and a 404 here would be the bug.251+ // against an open year, which the archive must still refuse). `from-bank`
252+ // takes an id that need not exist — the freeze is judged before the bank
253+ // lookup, and a 404 here would be the bug.
232 let staff_writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![254 let staff_writes: Vec<(&str, String, Option<serde_json::Value>)> = vec![
233 (255 (
234 "PATCH",256 "PATCH",
@@ -236,6 +258,12 @@ async fn an_archived_years_exams_take_no_writes_but_still_read() {
236 Some(json!({ "title": "Final" })),258 Some(json!({ "title": "Final" })),
237 ),259 ),
238 ("DELETE", format!("/exams/{exam}"), None),260 ("DELETE", format!("/exams/{exam}"), None),
261+ (
262+ "POST",
263+ format!("/exams/{exam}/audience"),
264+ Some(json!({ "instance": sibling })),
265+ ),
266+ ("DELETE", format!("/exams/{exam}/audience/{sibling}"), None),
239 (267 (
240 "POST",268 "POST",
241 format!("/exams/{exam}/results"),269 format!("/exams/{exam}/results"),
@@ -399,3 +427,590 @@ async fn an_archived_years_exams_take_no_writes_but_still_read() {
399 .await;427 .await;
400 assert_eq!(res.status, StatusCode::OK, "{}", res.body);428 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
401 }429 }
430+
431+/// One instance's line out of a `?term=` karne report.
432+fn karne_line<'a>(body: &'a serde_json::Value, instance: &str) -> &'a serde_json::Value {
433+ body["instances"]
434+ .as_array()
435+ .unwrap_or_else(|| panic!("a karne report with an instances array: {body}"))
436+ .iter()
437+ .find(|line| line["class_course"] == instance)
438+ .unwrap_or_else(|| panic!("a karne line for {instance}: {body}"))
439+}
440+
441+/// The ortak sınav round trip over HTTP: 5-A and 5-B teach the same course in
442+/// the same year (two instances), an exam written on 5-A is announced to 5-B,
443+/// and the **same mark** then stands in 5-B's karne — the per-instance read
444+/// joins `exam_audience`, so the announcement is what attributes it there.
445+/// 5-B's own exam list carries it while the announcement stands; withdrawal
446+/// takes both back out. The student is enrolled by hand on 5-A's instance too
447+/// (an operator may place anyone), which is what makes one mark readable from
448+/// both sides without a second grade.
449+#[tokio::test]
450+async fn an_ortak_sinav_lands_in_the_targets_karne_until_withdrawn() {
451+ let (app, db) = app_and_db().await;
452+ let mudur = login_as(&app, &db, "mudur_ortak", "manager").await;
453+ let teacher = login_as(&app, &db, "ogretmen_ortak", "teacher").await;
454+ let student = login_as(&app, &db, "ogrenci_ortak_b", "student").await;
455+ let student_id = me_id(&app, &student).await;
456+ let teacher_id = me_id(&app, &teacher).await;
457+
458+ let year = ensure_year(&app, &mudur).await;
459+ let term = create_term(&app, &mudur, &year, "1. Dönem").await;
460+ let course = create_course(&app, &teacher, "Matematik").await;
461+ let a_class = create_class(
462+ &app,
463+ &mudur,
464+ "5-A",
465+ json!({ "year": year, "teacher_id": teacher_id }),
466+ )
467+ .await;
468+ let b_class = create_class(&app, &mudur, "5-B", json!({ "year": year })).await;
469+ let a_inst = attach_instance(&app, &mudur, &a_class, &course).await;
470+ let b_inst = attach_instance(&app, &mudur, &b_class, &course).await;
471+
472+ // 5-B's roster carries the student; the hand enrollment on 5-A's instance
473+ // is the operator's row the grader's enrollment gate reads.
474+ add_member(&app, &mudur, &b_class, &student_id).await;
475+ enroll(&app, &mudur, &a_inst, &student_id).await;
476+
477+ let exam = create_exam(&app, &teacher, &a_inst, &term, "Ortak Yazılı", "yazili").await;
478+ let graded = send(
479+ &app,
480+ "POST",
481+ &format!("/exams/{exam}/results"),
482+ Some(&mudur),
483+ Some(json!({ "user_id": student_id, "mark": 85 })),
484+ )
485+ .await;
486+ assert_eq!(graded.status, StatusCode::OK, "grade: {}", graded.body);
487+
488+ // A karne line exists per instance the student's şubeler carry — 5-B's is
489+ // the only one here — and before the announcement the mark is not
490+ // attributed to it: nothing addresses the exam to 5-B's instance.
491+ let before = send(
492+ &app,
493+ "GET",
494+ &format!("/marks/karne?term={term}"),
495+ Some(&student),
496+ None,
497+ )
498+ .await;
499+ assert_eq!(before.status, StatusCode::OK, "karne: {}", before.body);
500+ assert_eq!(
501+ karne_line(&before.body, &b_inst)["average"],
502+ serde_json::Value::Null,
503+ "5-B's line carries nothing before the announcement: {}",
504+ before.body
505+ );
506+
507+ // Announce. The answer is the audience, owner first.
508+ let announced = send(
509+ &app,
510+ "POST",
511+ &format!("/exams/{exam}/audience"),
512+ Some(&mudur),
513+ Some(json!({ "instance": b_inst })),
514+ )
515+ .await;
516+ assert_eq!(
517+ announced.status,
518+ StatusCode::OK,
519+ "announce: {}",
520+ announced.body
521+ );
522+ assert_eq!(
523+ announced.body.as_array().map(Vec::len),
524+ Some(2),
525+ "{}",
526+ announced.body
527+ );
528+ assert_eq!(announced.body[0]["instance"], json!(a_inst));
529+ assert_eq!(announced.body[1]["instance"], json!(b_inst));
530+ assert_eq!(announced.body[1]["class"], json!(b_class));
531+ assert_eq!(announced.body[1]["course"], json!(course));
532+
533+ // 5-B's own list carries the exam now, and the mark is attributed to its
534+ // line — the whole point of the announcement.
535+ let listed = send(
536+ &app,
537+ "GET",
538+ &format!("/instances/{b_inst}/exams"),
539+ Some(&mudur),
540+ None,
541+ )
542+ .await;
543+ assert_eq!(listed.status, StatusCode::OK, "{}", listed.body);
544+ assert_eq!(
545+ total(&listed.body),
546+ 1,
547+ "5-B carries the exam: {}",
548+ listed.body
549+ );
550+ assert_eq!(id_of(&items(&listed.body)[0]), exam);
551+
552+ let during = send(
553+ &app,
554+ "GET",
555+ &format!("/marks/karne?term={term}"),
556+ Some(&student),
557+ None,
558+ )
559+ .await;
560+ assert_eq!(during.status, StatusCode::OK, "karne: {}", during.body);
561+ assert_eq!(
562+ karne_line(&during.body, &b_inst)["average"],
563+ json!(85.0),
564+ "the announcement puts the mark on 5-B's line: {}",
565+ during.body
566+ );
567+
568+ // Withdrawal: the audience is back to the owner, 5-B drops the exam, and
569+ // the mark leaves its line — the announcement was the only attribution.
570+ let withdrawn = send(
571+ &app,
572+ "DELETE",
573+ &format!("/exams/{exam}/audience/{b_inst}"),
574+ Some(&mudur),
575+ None,
576+ )
577+ .await;
578+ assert_eq!(
579+ withdrawn.status,
580+ StatusCode::OK,
581+ "withdraw: {}",
582+ withdrawn.body
583+ );
584+ assert_eq!(
585+ withdrawn.body.as_array().map(Vec::len),
586+ Some(1),
587+ "{}",
588+ withdrawn.body
589+ );
590+ assert_eq!(withdrawn.body[0]["instance"], json!(a_inst));
591+
592+ let relay = send(
593+ &app,
594+ "GET",
595+ &format!("/instances/{b_inst}/exams"),
596+ Some(&mudur),
597+ None,
598+ )
599+ .await;
600+ assert_eq!(total(&relay.body), 0, "5-B dropped it: {}", relay.body);
601+ let after = send(
602+ &app,
603+ "GET",
604+ &format!("/marks/karne?term={term}"),
605+ Some(&student),
606+ None,
607+ )
608+ .await;
609+ assert_eq!(
610+ karne_line(&after.body, &b_inst)["average"],
611+ serde_json::Value::Null,
612+ "the withdrawal takes the mark off 5-B's line: {}",
613+ after.body
614+ );
615+}
616+
617+/// Detaching an instance an exam is announced *to* (one it does not own) is
618+/// not a foreign-key failure: the audience row naming it is swept with the
619+/// instance, and the exam — owned by a sibling — stands with its owner's row.
620+#[tokio::test]
621+async fn detaching_an_audience_instance_sweeps_its_row() {
622+ let (app, db) = app_and_db().await;
623+ let mudur = login_as(&app, &db, "mudur_ortak_detach_a", "manager").await;
624+ let teacher = login_as(&app, &db, "ogretmen_ortak_detach_a", "teacher").await;
625+
626+ let year = ensure_year(&app, &mudur).await;
627+ let term = create_term(&app, &mudur, &year, "1. Dönem").await;
628+ let course = create_course(&app, &teacher, "Fizik").await;
629+ let a_class = create_class(&app, &mudur, "6-A", json!({ "year": year })).await;
630+ let b_class = create_class(&app, &mudur, "6-B", json!({ "year": year })).await;
631+ let a_inst = attach_instance(&app, &mudur, &a_class, &course).await;
632+ let b_inst = attach_instance(&app, &mudur, &b_class, &course).await;
633+ let exam = create_exam(&app, &mudur, &a_inst, &term, "Ortak Vize", "yazili").await;
634+ let announced = send(
635+ &app,
636+ "POST",
637+ &format!("/exams/{exam}/audience"),
638+ Some(&mudur),
639+ Some(json!({ "instance": b_inst })),
640+ )
641+ .await;
642+ assert_eq!(announced.status, StatusCode::OK, "{}", announced.body);
643+
644+ let detached = send(
645+ &app,
646+ "DELETE",
647+ &format!("/classes/{b_class}/instances/{b_inst}"),
648+ Some(&mudur),
649+ None,
650+ )
651+ .await;
652+ assert_eq!(
653+ detached.status,
654+ StatusCode::NO_CONTENT,
655+ "detaching an announced-to instance must not 500: {}",
656+ detached.body
657+ );
658+
659+ let rows: i64 =
660+ sqlx::query_scalar("SELECT count(*) FROM exam_audience WHERE class_course = $1")
661+ .bind(sqlx::types::Uuid::parse_str(&b_inst).unwrap())
662+ .fetch_one(&db)
663+ .await
664+ .unwrap();
665+ assert_eq!(rows, 0, "the row naming the detached instance is gone");
666+ // The exam is a sibling's: it stands, addressed to its owner alone.
667+ let read = send(&app, "GET", &format!("/exams/{exam}"), Some(&mudur), None).await;
668+ assert_eq!(
669+ read.status,
670+ StatusCode::OK,
671+ "the exam stands: {}",
672+ read.body
673+ );
674+ let audience = send(
675+ &app,
676+ "GET",
677+ &format!("/exams/{exam}/audience"),
678+ Some(&mudur),
679+ None,
680+ )
681+ .await;
682+ assert_eq!(
683+ audience.body.as_array().map(Vec::len),
684+ Some(1),
685+ "{}",
686+ audience.body
687+ );
688+ assert_eq!(audience.body[0]["instance"], json!(a_inst));
689+}
690+
691+/// Detaching the instance that **owns** an exam which is announced to a
692+/// sibling: the audience rows of the exams being swept go with them, wherever
693+/// they point. Without that sweep the `exam` delete trips
694+/// `exam_audience_exam_fkey` (`NO ACTION`) and the detach is a `500` — the
695+/// probe is mutation-tested, dropping `exam = ANY(...)` from the sweep's
696+/// delete turns this red.
697+#[tokio::test]
698+async fn detaching_the_owner_instance_sweeps_its_exams_audiences() {
699+ let (app, db) = app_and_db().await;
700+ let mudur = login_as(&app, &db, "mudur_ortak_detach_b", "manager").await;
701+ let teacher = login_as(&app, &db, "ogretmen_ortak_detach_b", "teacher").await;
702+
703+ let year = ensure_year(&app, &mudur).await;
704+ let term = create_term(&app, &mudur, &year, "1. Dönem").await;
705+ let course = create_course(&app, &teacher, "Kimya").await;
706+ let a_class = create_class(&app, &mudur, "7-A", json!({ "year": year })).await;
707+ let b_class = create_class(&app, &mudur, "7-B", json!({ "year": year })).await;
708+ let a_inst = attach_instance(&app, &mudur, &a_class, &course).await;
709+ let b_inst = attach_instance(&app, &mudur, &b_class, &course).await;
710+ let exam = create_exam(&app, &mudur, &a_inst, &term, "Ortak Final", "yazili").await;
711+ let announced = send(
712+ &app,
713+ "POST",
714+ &format!("/exams/{exam}/audience"),
715+ Some(&mudur),
716+ Some(json!({ "instance": b_inst })),
717+ )
718+ .await;
719+ assert_eq!(announced.status, StatusCode::OK, "{}", announced.body);
720+
721+ let detached = send(
722+ &app,
723+ "DELETE",
724+ &format!("/classes/{a_class}/instances/{a_inst}"),
725+ Some(&mudur),
726+ None,
727+ )
728+ .await;
729+ assert_eq!(
730+ detached.status,
731+ StatusCode::NO_CONTENT,
732+ "detaching the owner must not 500: {}",
733+ detached.body
734+ );
735+
736+ let rows: i64 = sqlx::query_scalar("SELECT count(*) FROM exam_audience WHERE exam = $1")
737+ .bind(sqlx::types::Uuid::parse_str(&exam).unwrap())
738+ .fetch_one(&db)
739+ .await
740+ .unwrap();
741+ assert_eq!(rows, 0, "the swept exam left no audience behind");
742+ // The sibling no longer carries it.
743+ let listed = send(
744+ &app,
745+ "GET",
746+ &format!("/instances/{b_inst}/exams"),
747+ Some(&mudur),
748+ None,
749+ )
750+ .await;
751+ assert_eq!(total(&listed.body), 0, "{}", listed.body);
752+ // And 7-B itself is untouched.
753+ let read = send(
754+ &app,
755+ "GET",
756+ &format!("/instances/{b_inst}"),
757+ Some(&mudur),
758+ None,
759+ )
760+ .await;
761+ assert_eq!(
762+ read.status,
763+ StatusCode::OK,
764+ "7-B's instance stands: {}",
765+ read.body
766+ );
767+}
768+
769+/// The cutover: a student enrolled **only** in an instance the exam is
770+/// announced to can see the exam, sit it, and be graded on it — the
771+/// announcement is what admits them (`exam_audience`), not a roster row on the
772+/// owner's instance. Both read and write doors were owner-only before this;
773+/// an unrelated student stays refused on every one of them.
774+#[tokio::test]
775+async fn an_announced_student_can_see_sit_and_be_graded() {
776+ let (app, db) = app_and_db().await;
777+ let mudur = login_as(&app, &db, "mudur_ortak_sit", "manager").await;
778+ let teacher = login_as(&app, &db, "ogretmen_ortak_sit", "teacher").await;
779+ let b_teacher = login_as(&app, &db, "ogretmen_ortak_sit_b", "teacher").await;
780+ let x_teacher = login_as(&app, &db, "ogretmen_ortak_sit_x", "teacher").await;
781+ let b_student = login_as(&app, &db, "ogrenci_ortak_sit_b", "student").await;
782+ let outsider = login_as(&app, &db, "ogrenci_ortak_sit_x", "student").await;
783+ let b_student_id = me_id(&app, &b_student).await;
784+ let outsider_id = me_id(&app, &outsider).await;
785+ let teacher_id = me_id(&app, &teacher).await;
786+ let b_teacher_id = me_id(&app, &b_teacher).await;
787+
788+ let year = ensure_year(&app, &mudur).await;
789+ let term = create_term(&app, &mudur, &year, "1. Dönem").await;
790+ let course = create_course(&app, &teacher, "Biyoloji").await;
791+ let a_class = create_class(
792+ &app,
793+ &mudur,
794+ "10-A",
795+ json!({ "year": year, "teacher_id": teacher_id }),
796+ )
797+ .await;
798+ let b_class = create_class(&app, &mudur, "10-B", json!({ "year": year })).await;
799+ let a_inst = attach_instance(&app, &mudur, &a_class, &course).await;
800+ let b_inst = attach_instance(&app, &mudur, &b_class, &course).await;
801+ // Only 10-B's roster carries the student; nobody is enrolled on 10-A's
802+ // instance, where the exam is written.
803+ add_member(&app, &mudur, &b_class, &b_student_id).await;
804+
805+ let created = create_exam_with(
806+ &app,
807+ &teacher,
808+ &a_inst,
809+ json!({ "title": "Ortak Sınav", "kind": "yazili", "mode": "open", "term": term }),
810+ )
811+ .await;
812+ assert_eq!(created.status, StatusCode::CREATED, "{}", created.body);
813+ let exam = id_of(&created.body);
814+
815+ // Before the announcement the 10-B student is nobody to this exam.
816+ let pre_read = send(
817+ &app,
818+ "GET",
819+ &format!("/exams/{exam}"),
820+ Some(&b_student),
821+ None,
822+ )
823+ .await;
824+ assert_eq!(pre_read.status, StatusCode::FORBIDDEN, "{}", pre_read.body);
825+ let pre_sit = send(
826+ &app,
827+ "POST",
828+ &format!("/exams/{exam}/attempt"),
829+ Some(&b_student),
830+ None,
831+ )
832+ .await;
833+ assert_eq!(pre_sit.status, StatusCode::FORBIDDEN, "{}", pre_sit.body);
834+
835+ let announced = send(
836+ &app,
837+ "POST",
838+ &format!("/exams/{exam}/audience"),
839+ Some(&mudur),
840+ Some(json!({ "instance": b_inst })),
841+ )
842+ .await;
843+ assert_eq!(announced.status, StatusCode::OK, "{}", announced.body);
844+
845+ // The announced section's own teacher now runs the exam's teacher side:
846+ // grading its students, reading the results and statistics, and watching
847+ // the monitor.
848+ let assigned = send(
849+ &app,
850+ "POST",
851+ &format!("/instances/{b_inst}/teachers"),
852+ Some(&mudur),
853+ Some(json!({ "user_id": b_teacher_id })),
854+ )
855+ .await;
856+ assert_eq!(
857+ assigned.status,
858+ StatusCode::OK,
859+ "assign 10-B's teacher: {}",
860+ assigned.body
861+ );
862+
863+ // (a) The read door opens for a student of an addressed instance.
864+ let read = send(
865+ &app,
866+ "GET",
867+ &format!("/exams/{exam}"),
868+ Some(&b_student),
869+ None,
870+ )
871+ .await;
872+ assert_eq!(
873+ read.status,
874+ StatusCode::OK,
875+ "the announcement admits them: {}",
876+ read.body
877+ );
878+
879+ // (b) The sitting door opens too.
880+ let sat = send(
881+ &app,
882+ "POST",
883+ &format!("/exams/{exam}/attempt"),
884+ Some(&b_student),
885+ None,
886+ )
887+ .await;
888+ assert_eq!(sat.status, StatusCode::CREATED, "sitting: {}", sat.body);
889+
890+ // …and the teacher's monitor sees them: the roster is the exam's whole
891+ // audience, so an announced-to section's sitter is not a blind spot.
892+ let live = send(
893+ &app,
894+ "GET",
895+ &format!("/exams/{exam}/live"),
896+ Some(&mudur),
897+ None,
898+ )
899+ .await;
900+ assert_eq!(live.status, StatusCode::OK, "monitor: {}", live.body);
901+ let names: Vec<&str> = live.body["students"]
902+ .as_array()
903+ .unwrap_or_else(|| panic!("a live snapshot with students: {}", live.body))
904+ .iter()
905+ .filter_map(|row| row["user"]["id"].as_str())
906+ .collect();
907+ assert!(
908+ names.contains(&b_student_id.as_str()),
909+ "the monitor lists the announced-to section's sitter ({}): {}",
910+ b_student_id,
911+ live.body
912+ );
913+
914+ // (c) And the mark can be recorded — by the **announced section's own
915+ // teacher** — standing on their own instance's line.
916+ let graded = send(
917+ &app,
918+ "POST",
919+ &format!("/exams/{exam}/results"),
920+ Some(&b_teacher),
921+ Some(json!({ "user_id": b_student_id, "mark": 90 })),
922+ )
923+ .await;
924+ assert_eq!(graded.status, StatusCode::OK, "grading: {}", graded.body);
925+ let karne = send(
926+ &app,
927+ "GET",
928+ &format!("/marks/karne?term={term}"),
929+ Some(&b_student),
930+ None,
931+ )
932+ .await;
933+ assert_eq!(
934+ karne_line(&karne.body, &b_inst)["average"],
935+ json!(90.0),
936+ "the mark stands on 10-B's line: {}",
937+ karne.body
938+ );
939+
940+ // The results readers and the monitor, from that teacher's cookie too.
941+ for (uri, what) in [
942+ (format!("/exams/{exam}/results"), "results"),
943+ (format!("/exams/{exam}/statistics"), "statistics"),
944+ (format!("/exams/{exam}/live"), "the monitor"),
945+ (format!("/exams/{exam}/audience"), "the audience"),
946+ ] {
947+ let res = send(&app, "GET", &uri, Some(&b_teacher), None).await;
948+ assert_eq!(
949+ res.status,
950+ StatusCode::OK,
951+ "10-B's teacher reads {what}: {}",
952+ res.body
953+ );
954+ }
955+
956+ // An unrelated teacher manages no addressed instance: refused at every
957+ // teacher-side door, grading included.
958+ for (method, uri, body, what) in [
959+ (
960+ "POST",
961+ format!("/exams/{exam}/results"),
962+ Some(json!({ "user_id": b_student_id, "mark": 60 })),
963+ "grading",
964+ ),
965+ ("GET", format!("/exams/{exam}/results"), None, "results"),
966+ (
967+ "GET",
968+ format!("/exams/{exam}/statistics"),
969+ None,
970+ "statistics",
971+ ),
972+ ("GET", format!("/exams/{exam}/live"), None, "the monitor"),
973+ ] {
974+ let res = send(&app, method, &uri, Some(&x_teacher), body).await;
975+ assert_eq!(
976+ res.status,
977+ StatusCode::FORBIDDEN,
978+ "an unrelated teacher on {what}: {}",
979+ res.body
980+ );
981+ }
982+
983+ // An unrelated student is refused at every door.
984+ let f_read = send(
985+ &app,
986+ "GET",
987+ &format!("/exams/{exam}"),
988+ Some(&outsider),
989+ None,
990+ )
991+ .await;
992+ assert_eq!(f_read.status, StatusCode::FORBIDDEN, "{}", f_read.body);
993+ let f_sit = send(
994+ &app,
995+ "POST",
996+ &format!("/exams/{exam}/attempt"),
997+ Some(&outsider),
998+ None,
999+ )
1000+ .await;
1001+ assert_eq!(f_sit.status, StatusCode::FORBIDDEN, "{}", f_sit.body);
1002+ let f_grade = send(
1003+ &app,
1004+ "POST",
1005+ &format!("/exams/{exam}/results"),
1006+ Some(&mudur),
1007+ Some(json!({ "user_id": outsider_id, "mark": 50 })),
1008+ )
1009+ .await;
1010+ assert_eq!(
1011+ f_grade.status,
1012+ StatusCode::BAD_REQUEST,
1013+ "grading a student outside every addressed instance: {}",
1014+ f_grade.body
1015+ );
1016+}